From d3d920a5ec0a2388d6ea59f3afc5426b35cd0e0f Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 6 Jan 2018 18:07:16 +0200 Subject: [PATCH 01/50] Update for newer cabal-hel Subject to https://github.com/DanielG/cabal-helper/pull/39 --- core/GhcMod/Target.hs | 4 ++-- test/CabalHelperSpec.hs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index 0523fc674..3f169fd49 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -367,8 +367,8 @@ resolveEntrypoint Cradle {..} c@GmComponent {..} = do -- ghc do the warning about it. Right now we run that module through -- resolveModule like any other resolveChEntrypoints :: FilePath -> ChEntrypoint -> IO [CompilationUnit] -resolveChEntrypoints _ (ChLibEntrypoint em om) = - return $ map (Right . chModToMod) (em ++ om) +resolveChEntrypoints _ (ChLibEntrypoint em om sm) = + return $ map (Right . chModToMod) (em ++ om ++ sm) resolveChEntrypoints _ (ChExeEntrypoint main om) = return $ [Left main] ++ map (Right . chModToMod) om diff --git a/test/CabalHelperSpec.hs b/test/CabalHelperSpec.hs index c14ed3881..ebbe31969 100644 --- a/test/CabalHelperSpec.hs +++ b/test/CabalHelperSpec.hs @@ -3,7 +3,7 @@ module CabalHelperSpec where import Control.Arrow import Control.Applicative -import Distribution.Helper +import Distribution.Helper hiding ( (<.>)) import GhcMod.CabalHelper import GhcMod.PathsAndFiles import GhcMod.Error @@ -86,7 +86,7 @@ spec = do opts <- map gmcGhcOpts <$> runD' tdir getComponents let ghcOpts = head opts pkgs = pkgOptions ghcOpts - pkgs `shouldBe` ["Cabal","base"] + sort pkgs `shouldBe` ["Cabal","base"] test From b62c558cadeda55ad5a6ef79a62bca603ead48d8 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 7 Jan 2018 21:59:39 +0200 Subject: [PATCH 02/50] Switch to 8.2.2 image for gitlab ci --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4a8c8df32..e9914bc83 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -38,7 +38,7 @@ after_script: when: always job-ghc802: - image: registry.gitlab.com/dxld/ghc-mod:ghc8.2.1-cabal-install2.0.0.0 + image: registry.gitlab.com/dxld/ghc-mod:ghc8.2.2-cabal-install2.0.0.0 stage: build <<: *common_before_script <<: *common_script From 6b04d9b6cb18a4679f3c2c1959c3b372af40885f Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 20 Jan 2018 18:19:22 +0200 Subject: [PATCH 03/50] Explicitly turn off -Wmissing-home-modules This is because when a component makes use of another internal one, the modules are added to the options. This then mismatches the cabal file representation, but is not an error in the cabal file for normal compilation. --- core/GhcMod/Target.hs | 10 ++++++---- core/GhcMod/Types.hs | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index 3f169fd49..907c4f9a3 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -200,7 +200,7 @@ targetGhcOptions crdl sefnmn = do where zipMap f l = l `zip` (f `map` l) - cabalOpts :: Cradle -> GhcModT m [String] + cabalOpts :: Cradle -> GhcModT m [GHCOption] cabalOpts Cradle{..} = do mcs <- cabalResolvedComponents @@ -216,13 +216,15 @@ targetGhcOptions crdl sefnmn = do let cns = filter (/= ChSetupHsName) $ Map.keys mcs gmLog GmDebug "" $ strDoc $ "Could not find a component assignment, falling back to picking library component in cabal file." - return $ gmcGhcOpts $ fromJustNote "targetGhcOptions, no-assignment" $ Map.lookup (head cns) mcs + return $ gmcGhcOpts (fromJustNote "targetGhcOptions, no-assignment" $ Map.lookup (head cns) mcs) + ++ ["-Wno-missing-home-modules"] else do when noCandidates $ throwError $ GMECabalCompAssignment mdlcs let cn = pickComponent candidates - return $ gmcGhcOpts $ fromJustNote "targetGhcOptions" $ Map.lookup cn mcs + return $ gmcGhcOpts (fromJustNote "targetGhcOptions" $ Map.lookup cn mcs) + ++ ["-Wno-missing-home-modules"] resolvedComponentsCache :: IOish m => FilePath -> Cached (GhcModT m) GhcModState @@ -311,7 +313,7 @@ packageGhcOptions = do | otherwise -> sandboxOpts crdl -- also works for plain projects! -sandboxOpts :: (IOish m, GmEnv m) => Cradle -> m [String] +sandboxOpts :: (IOish m, GmEnv m) => Cradle -> m [GHCOption] sandboxOpts crdl = do mCusPkgDb <- getCustomPkgDbStack pkgDbStack <- liftIO $ getSandboxPackageDbStack diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index 06d3a625a..ecaf5911b 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -291,7 +291,7 @@ data GmComponent (t :: GmComponentType) eps = GmComponent { , gmcRawEntrypoints :: ChEntrypoint , gmcEntrypoints :: eps , gmcSourceDirs :: [FilePath] - , gmcName :: ChComponentName + , gmcName :: ChComponentName } deriving (Eq, Ord, Show, Read, Generic, Functor) instance Binary eps => Binary (GmComponent t eps) where From 26382275a946d037d0593a50302d49ab167e24be Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 20 Jan 2018 19:40:06 +0200 Subject: [PATCH 04/50] Add runV to run tests with vomit logging --- test/TestUtils.hs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/TestUtils.hs b/test/TestUtils.hs index 3d252f151..92dde65d3 100644 --- a/test/TestUtils.hs +++ b/test/TestUtils.hs @@ -2,6 +2,7 @@ module TestUtils ( run , runD + , runV , runD' , runE , runNullLog @@ -73,6 +74,11 @@ runD :: GhcModT IO a -> IO a runD = extract . runGhcModTSpec (setLogLevel testLogLevel defaultOptions) +-- | Run GhcMod with default options, and vomit log level +runV :: GhcModT IO a -> IO a +runV = + extract . runGhcModTSpec (setLogLevel GmVomit defaultOptions) + runD' :: FilePath -> GhcModT IO a -> IO a runD' dir = extract . runGhcModTSpec' dir (setLogLevel testLogLevel defaultOptions) From 11280966fa2d51ccc702fdd428a3811c39d5cf9d Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Mon, 25 Sep 2017 15:22:27 +0200 Subject: [PATCH 05/50] Move the core functionality into new package ghc-mod-core --- cabal.project | 2 + core/COPYING.AGPL3 | 661 ++++++++++++++++++ core/COPYING.BSD3 | 29 + core/GhcMod/CabalHelper.hs | 2 +- core/GhcMod/Caching.hs | 2 +- core/GhcMod/Error.hs | 2 +- core/GhcMod/Utils.hs | 2 +- core/GhcModCore.hs | 51 ++ core/Setup.hs | 8 + core/ghc-mod-core.cabal | 262 +++++++ .../shared}/System/Directory/ModTime.hs | 0 {shared => core/shared}/Utils.hs | 0 ghc-mod.cabal | 120 ++-- 13 files changed, 1080 insertions(+), 61 deletions(-) create mode 100644 cabal.project create mode 100644 core/COPYING.AGPL3 create mode 100644 core/COPYING.BSD3 create mode 100644 core/GhcModCore.hs create mode 100755 core/Setup.hs create mode 100644 core/ghc-mod-core.cabal rename {shared => core/shared}/System/Directory/ModTime.hs (100%) rename {shared => core/shared}/Utils.hs (100%) diff --git a/cabal.project b/cabal.project new file mode 100644 index 000000000..0d3711349 --- /dev/null +++ b/cabal.project @@ -0,0 +1,2 @@ +packages: . + ./core diff --git a/core/COPYING.AGPL3 b/core/COPYING.AGPL3 new file mode 100644 index 000000000..dba13ed2d --- /dev/null +++ b/core/COPYING.AGPL3 @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/core/COPYING.BSD3 b/core/COPYING.BSD3 new file mode 100644 index 000000000..542219308 --- /dev/null +++ b/core/COPYING.BSD3 @@ -0,0 +1,29 @@ +Copyright (c) 2009, IIJ Innovation Institute Inc. +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 the copyright holders nor the names of its + 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/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index e47d60290..1e82c39e9 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -48,7 +48,7 @@ import System.Process import System.Exit import Prelude hiding ((.)) -import Paths_ghc_mod as GhcMod +import Paths_ghc_mod_core as GhcMod -- | Only package related GHC options, sufficient for things that don't need to -- access home modules diff --git a/core/GhcMod/Caching.hs b/core/GhcMod/Caching.hs index 2f58929a6..9b0b9f280 100644 --- a/core/GhcMod/Caching.hs +++ b/core/GhcMod/Caching.hs @@ -35,7 +35,7 @@ import qualified Data.ByteString.Char8 as BS8 import System.FilePath import System.Directory.ModTime import Utils (TimedFile(..), timeMaybe, mightExist) -import Paths_ghc_mod (version) +import Paths_ghc_mod_core (version) import Prelude import GhcMod.Monad.Types diff --git a/core/GhcMod/Error.hs b/core/GhcMod/Error.hs index 18e5fc861..968c357b0 100644 --- a/core/GhcMod/Error.hs +++ b/core/GhcMod/Error.hs @@ -45,7 +45,7 @@ import Exception import Panic import Pretty import Config (cProjectVersion, cHostPlatformString) -import Paths_ghc_mod (version) +import Paths_ghc_mod_core (version) import GhcMod.Types import GhcMod.Pretty diff --git a/core/GhcMod/Utils.hs b/core/GhcMod/Utils.hs index 38062b6f4..7c282357b 100644 --- a/core/GhcMod/Utils.hs +++ b/core/GhcMod/Utils.hs @@ -40,7 +40,7 @@ import System.IO.Temp (createTempDirectory) import System.Process (readProcess) import Text.Printf -import Paths_ghc_mod (getLibexecDir, getBinDir) +import Paths_ghc_mod_core (getLibexecDir, getBinDir) import Utils import Prelude diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs new file mode 100644 index 000000000..a7ba32d13 --- /dev/null +++ b/core/GhcModCore.hs @@ -0,0 +1,51 @@ +-- | The ghc-mod library. + +module GhcModCore ( + -- * Cradle + Cradle(..) + , Project(..) + , findCradle + -- * Options + , Options(..) + , LineSeparator(..) + , OutputStyle(..) + , FileMapping(..) + , defaultOptions + -- * Logging + , GmLogLevel + , increaseLogLevel + , decreaseLogLevel + , gmSetLogLevel + , gmLog + -- * Types + , ModuleString + , Expression(..) + , GhcPkgDb + -- , Symbol + -- , SymbolDb + , GhcModError(..) + -- * Monad Types + , GhcModT + , IOish + -- * Monad utilities + , runGhcModT + , withOptions + , dropSession + -- * Output + , gmPutStr + , gmErrStr + , gmPutStrLn + , gmErrStrLn + -- * FileMapping + , loadMappedFile + , loadMappedFileSource + , unloadMappedFile + ) where + +import GhcMod.Cradle +import GhcMod.FileMapping +import GhcMod.Logging +import GhcMod.Monad +import GhcMod.Output +import GhcMod.Target +import GhcMod.Types diff --git a/core/Setup.hs b/core/Setup.hs new file mode 100755 index 000000000..47b0bd564 --- /dev/null +++ b/core/Setup.hs @@ -0,0 +1,8 @@ + +import Distribution.Simple +import Distribution.Simple.Program + +main :: IO () +main = defaultMainWithHooks $ simpleUserHooks { + hookedPrograms = [ simpleProgram "shelltest" ] + } diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal new file mode 100644 index 000000000..751e3cbf9 --- /dev/null +++ b/core/ghc-mod-core.cabal @@ -0,0 +1,262 @@ +Name: ghc-mod-core +Version: 5.9.0.0 +Author: Kazu Yamamoto , + Daniel Gröber , + Alejandro Serrano , + Nikolay Yakimov +Maintainer: Daniel Gröber +License: AGPL-3 +License-File: LICENSE +License-Files: COPYING.BSD3 COPYING.AGPL3 +Homepage: https://github.com/DanielG/ghc-mod +Synopsis: Happy Haskell Hacking +Description: + ghc-mod is a backend program to enrich Haskell programming in editors. It + strives to offer most of the features one has come to expect from modern IDEs + in any editor. + + ghc-mod provides a library for other haskell programs to use as well as a + standalone program for easy editor integration. All of the fundamental + functionality of the frontend program can be accessed through the library + however many implementation details are hidden and if you want to + significantly extend ghc-mod you should submit these changes upstream instead + of implementing them on top of the library. + + +Category: GHC, Development +Cabal-Version: >= 1.18 +Build-Type: Custom +-- Data-Files: elisp/Makefile +-- elisp/*.el +-- Extra-Source-Files: ChangeLog + + +Custom-Setup + Setup-Depends: base + , Cabal >= 1.18 && < 2.1 + , containers + , filepath + , directory + , process + , template-haskell + , transformers + + +Library + Default-Language: Haskell2010 + GHC-Options: -Wall -fno-warn-deprecations + Default-Extensions: ScopedTypeVariables, RecordWildCards, NamedFieldPuns, + ConstraintKinds, FlexibleContexts, + DataKinds, KindSignatures, TypeOperators, ViewPatterns + HS-Source-Dirs: . shared + Exposed-Modules: + GhcModCore + GhcMod.CabalHelper + GhcMod.Caching + GhcMod.Caching.Types + GhcMod.Convert + GhcMod.Cradle + GhcMod.CustomPackageDb + GhcMod.DebugLogger + GhcMod.Doc + GhcMod.DynFlags + GhcMod.DynFlagsTH + GhcMod.Error + GhcMod.FileMapping + GhcMod.Gap + GhcMod.GhcPkg + GhcMod.HomeModuleGraph + GhcMod.LightGhc + GhcMod.Logger + GhcMod.Logging + GhcMod.Monad + GhcMod.Monad.Env + GhcMod.Monad.Log + GhcMod.Monad.Newtypes + GhcMod.Monad.Orphans + GhcMod.Monad.Out + GhcMod.Monad.State + GhcMod.Monad.Types + GhcMod.Options.DocUtils + GhcMod.Options.Help + GhcMod.Options.Options + GhcMod.Output + GhcMod.PathsAndFiles + GhcMod.Pretty + GhcMod.Read + GhcMod.SrcUtils + GhcMod.Stack + GhcMod.Target + GhcMod.Types + GhcMod.Utils + GhcMod.World + Utils + Data.Binary.Generic + System.Directory.ModTime + Other-Modules: Paths_ghc_mod_core + Build-Depends: + -- See Note [GHC Boot libraries] + binary + , bytestring + , containers + , deepseq + , directory + , filepath + , mtl + , old-time + , process + , template-haskell + , time + , transformers + + , base < 4.11 && >= 4.6.0.1 + , djinn-ghc < 0.1 && >= 0.0.2.2 + , extra < 1.7 && >= 1.4 + , fclabels < 2.1 && >= 2.0 + , fingertree < 0.2 && >= 0.1.1.0 + , ghc-paths < 0.2 && >= 0.1.0.9 + , ghc-syb-utils < 0.3 && >= 0.2.3 + , haskell-src-exts < 1.20 && >= 1.18 + , hlint < 3.0 && >= 2.0.8 + , monad-control < 1.1 && >= 1 + , monad-journal < 0.9 && >= 0.4 + , optparse-applicative < 0.15 && >= 0.13.0.0 + , pipes < 4.4 && >= 4.1 + , safe < 0.4 && >= 0.3.9 + , semigroups < 0.19 && >= 0.10.0 + , split < 0.3 && >= 0.2.2 + , syb < 0.8 && >= 0.5.1 + , temporary < 1.3 && >= 1.2.0.3 + , text < 1.3 && >= 1.2.1.3 + , transformers-base < 0.5 && >= 0.4.4 + + , cabal-helper < 0.9 && >= 0.8 + , ghc < 8.4 && >= 7.6 + + if impl(ghc >= 8.0) + Build-Depends: ghc-boot + if impl(ghc < 7.8) + Build-Depends: convertible < 1.2 && >= 1.1.0.0 + + + +-- Test-Suite doctest +-- Type: exitcode-stdio-1.0 +-- Default-Language: Haskell2010 +-- HS-Source-Dirs: test +-- Ghc-Options: -Wall +-- Default-Extensions: ConstraintKinds, FlexibleContexts +-- Main-Is: doctests.hs +-- Build-Depends: base < 4.10 && >= 4.6.0.1 +-- , doctest < 0.12 && >= 0.9.3 + + +-- Test-Suite spec +-- Default-Language: Haskell2010 +-- Default-Extensions: ScopedTypeVariables, RecordWildCards, NamedFieldPuns, +-- ConstraintKinds, FlexibleContexts, +-- DataKinds, KindSignatures, TypeOperators, ViewPatterns +-- Main-Is: Main.hs +-- Hs-Source-Dirs: test, src +-- Ghc-Options: -Wall -fno-warn-deprecations -threaded +-- Type: exitcode-stdio-1.0 +-- Other-Modules: Paths_ghc_mod +-- Dir +-- TestUtils + +-- -- $ ls test/*Spec.hs | sed 's_^.*/\(.*\)\.hs$_\1_' | sort +-- BrowseSpec +-- CabalHelperSpec +-- CaseSplitSpec +-- CheckSpec +-- CradleSpec +-- CustomPackageDbSpec +-- FileMappingSpec +-- FindSpec +-- FlagSpec +-- GhcPkgSpec +-- HomeModuleGraphSpec +-- InfoSpec +-- LangSpec +-- LintSpec +-- ListSpec +-- MonadSpec +-- PathsAndFilesSpec +-- ShellParseSpec +-- TargetSpec + +-- Build-Depends: +-- -- See Note [GHC Boot libraries] +-- containers +-- , directory +-- , filepath +-- , mtl +-- , process +-- , transformers + +-- , base < 4.10 && >= 4.6.0.1 +-- , fclabels < 2.1 && >= 2.0 +-- , hspec < 2.4 && >= 2.0.0 +-- , monad-journal < 0.8 && >= 0.4 +-- , split < 0.3 && >= 0.2.2 +-- , temporary < 1.3 && >= 1.2.0.3 + + +-- if impl(ghc < 7.8) +-- Build-Depends: convertible < 1.2 && >= 1.1.0.0 +-- if impl(ghc >= 8.0) +-- Build-Depends: ghc-boot + +-- Build-Depends: +-- cabal-helper < 0.8 && >= 0.7.1.0 +-- , ghc < 8.2 && >= 7.6 +-- , ghc-mod + + +-- Test-Suite shelltest +-- Default-Language: Haskell2010 +-- Main-Is: ShellTest.hs +-- Hs-Source-Dirs: shelltest +-- Type: exitcode-stdio-1.0 +-- Build-Tools: shelltest +-- Build-Depends: base < 4.10 && >= 4.6.0.1 +-- , process < 1.5 +-- -- , shelltestrunner >= 1.3.5 +-- if !flag(shelltest) +-- Buildable: False + + +-- Benchmark criterion +-- Type: exitcode-stdio-1.0 +-- Default-Language: Haskell2010 +-- Default-Extensions: ScopedTypeVariables, RecordWildCards, NamedFieldPuns, +-- ConstraintKinds, FlexibleContexts, +-- DataKinds, KindSignatures, TypeOperators, ViewPatterns +-- HS-Source-Dirs: bench, test +-- Main-Is: Bench.hs +-- Build-Depends: +-- -- See Note [GHC Boot libraries] +-- directory +-- , filepath + +-- , base < 4.10 && >= 4.6.0.1 +-- , criterion < 1.2 && >= 1.1.1.0 +-- , temporary < 1.3 && >= 1.2.0.3 + +-- , ghc-mod +-- Buildable: False + +Flag shelltest + Description: Enable/disable shelltest test-suite + Default: False + Manual: True + + +Source-Repository head + Type: git + Location: https://github.com/DanielG/ghc-mod.git + +-- Note [GHC Boot libraries] +-- +-- We don't give bounds to GHC boot libraries as our dependency on 'ghc' already +-- constrains these packages to the version that shipped with GHC. diff --git a/shared/System/Directory/ModTime.hs b/core/shared/System/Directory/ModTime.hs similarity index 100% rename from shared/System/Directory/ModTime.hs rename to core/shared/System/Directory/ModTime.hs diff --git a/shared/Utils.hs b/core/shared/Utils.hs similarity index 100% rename from shared/Utils.hs rename to core/shared/Utils.hs diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 713cbe5bf..87b0e4543 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -1,5 +1,5 @@ Name: ghc-mod -Version: 5.8.0.0 +Version: 5.9.0.0 Author: Kazu Yamamoto , Daniel Gröber , Alejandro Serrano , @@ -30,7 +30,7 @@ Data-Files: elisp/Makefile elisp/*.el Extra-Source-Files: ChangeLog README.md - core/GhcMod/Monad/Compat.hs_h + -- core/GhcMod/Monad/Compat.hs_h test/data/annotations/*.hs test/data/broken-cabal/*.cabal test/data/broken-sandbox/cabal.sandbox.config @@ -108,7 +108,7 @@ Library Default-Extensions: ScopedTypeVariables, RecordWildCards, NamedFieldPuns, ConstraintKinds, FlexibleContexts, DataKinds, KindSignatures, TypeOperators, ViewPatterns - HS-Source-Dirs: ., core, shared + HS-Source-Dirs: . Exposed-Modules: GhcMod GhcMod.Exe.Boot @@ -126,49 +126,49 @@ Library GhcMod.Exe.Modules GhcMod.Exe.PkgDoc GhcMod.Exe.Test - GhcMod.CabalHelper - GhcMod.Caching - GhcMod.Caching.Types - GhcMod.Convert - GhcMod.Cradle - GhcMod.CustomPackageDb - GhcMod.DebugLogger - GhcMod.Doc - GhcMod.DynFlags - GhcMod.DynFlagsTH - GhcMod.Error - GhcMod.FileMapping - GhcMod.Gap - GhcMod.GhcPkg - GhcMod.HomeModuleGraph - GhcMod.LightGhc - GhcMod.Logger - GhcMod.Logging - GhcMod.Monad - GhcMod.Monad.Env - GhcMod.Monad.Log - GhcMod.Monad.Newtypes - GhcMod.Monad.Orphans - GhcMod.Monad.Out - GhcMod.Monad.State - GhcMod.Monad.Types - GhcMod.Options.DocUtils - GhcMod.Options.Help - GhcMod.Options.Options - GhcMod.Output - GhcMod.PathsAndFiles - GhcMod.Pretty - GhcMod.Read - GhcMod.SrcUtils - GhcMod.Stack - GhcMod.Target - GhcMod.Types - GhcMod.Utils - GhcMod.World + -- GhcMod.CabalHelper + -- GhcMod.Caching + -- GhcMod.Caching.Types + -- GhcMod.Convert + -- GhcMod.Cradle + -- GhcMod.CustomPackageDb + -- GhcMod.DebugLogger + -- GhcMod.Doc + -- GhcMod.DynFlags + -- GhcMod.DynFlagsTH + -- GhcMod.Error + -- GhcMod.FileMapping + -- GhcMod.Gap + -- GhcMod.GhcPkg + -- GhcMod.HomeModuleGraph + -- GhcMod.LightGhc + -- GhcMod.Logger + -- GhcMod.Logging + -- GhcMod.Monad + -- GhcMod.Monad.Env + -- GhcMod.Monad.Log + -- GhcMod.Monad.Newtypes + -- GhcMod.Monad.Orphans + -- GhcMod.Monad.Out + -- GhcMod.Monad.State + -- GhcMod.Monad.Types + -- GhcMod.Options.DocUtils + -- GhcMod.Options.Help + -- GhcMod.Options.Options + -- GhcMod.Output + -- GhcMod.PathsAndFiles + -- GhcMod.Pretty + -- GhcMod.Read + -- GhcMod.SrcUtils + -- GhcMod.Stack + -- GhcMod.Target + -- GhcMod.Types + -- GhcMod.Utils + -- GhcMod.World Other-Modules: Paths_ghc_mod - Utils - Data.Binary.Generic - System.Directory.ModTime + -- Utils + -- Data.Binary.Generic + -- System.Directory.ModTime Build-Depends: -- See Note [GHC Boot libraries] binary @@ -186,15 +186,16 @@ Library , base < 4.11 && >= 4.6.0.1 , djinn-ghc < 0.1 && >= 0.0.2.2 - , extra < 1.6 && >= 1.4 + , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 , ghc-syb-utils < 0.3 && >= 0.2.3 + , ghc-mod-core == 5.9.0.0 , haskell-src-exts < 1.20 && >= 1.18 - , hlint < 2.1 && >= 2.0.8 + , hlint < 3.0 && >= 2.0.8 , monad-control < 1.1 && >= 1 - , monad-journal < 0.8 && >= 0.4 - , optparse-applicative < 0.14 && >= 0.13.0.0 + , monad-journal < 0.9 && >= 0.4 + , optparse-applicative < 0.15 && >= 0.13.0.0 , pipes < 4.4 && >= 4.1 , safe < 0.4 && >= 0.3.9 , semigroups < 0.19 && >= 0.10.0 @@ -206,6 +207,7 @@ Library , cabal-helper < 0.9 && >= 0.8.0.0 , ghc < 8.4 && >= 7.8 + , ghc-mod-core if impl(ghc >= 8.0) Build-Depends: ghc-boot @@ -220,7 +222,8 @@ Executable ghc-mod , GhcMod.Exe.Options.ShellParse GHC-Options: -Wall -fno-warn-deprecations -threaded Default-Extensions: ConstraintKinds, FlexibleContexts - HS-Source-Dirs: src, shared + HS-Source-Dirs: src + X-Internal: True Build-Depends: -- See Note [GHC Boot libraries] directory @@ -231,25 +234,26 @@ Executable ghc-mod , base < 4.11 && >= 4.6.0.1 , fclabels < 2.1 && >= 2.0 , monad-control < 1.1 && >= 1 - , optparse-applicative < 0.14 && >= 0.13.0.0 + , optparse-applicative < 0.15 && >= 0.13.0.0 , semigroups < 0.19 && >= 0.10.0 , split < 0.3 && >= 0.2.2 , ghc < 8.4 && >= 7.8 , ghc-mod + , ghc-mod-core Executable ghc-modi Default-Language: Haskell2010 Main-Is: GhcModi.hs Other-Modules: Paths_ghc_mod - Utils - System.Directory.ModTime + -- Utils + -- System.Directory.ModTime GHC-Options: -Wall -threaded -fno-warn-deprecations if os(windows) Cpp-Options: -DWINDOWS Default-Extensions: ConstraintKinds, FlexibleContexts - HS-Source-Dirs: ., src, shared + HS-Source-Dirs: ., src Build-Depends: -- See Note [GHC Boot libraries] binary @@ -263,6 +267,7 @@ Executable ghc-modi , base < 4.11 && >= 4.6.0.1 , ghc-mod + , ghc-mod-core Test-Suite doctest @@ -326,11 +331,10 @@ Test-Suite spec , base < 4.11 && >= 4.6.0.1 , fclabels < 2.1 && >= 2.0 , hspec < 2.5 && >= 2.0.0 - , monad-journal < 0.8 && >= 0.4 + , monad-journal < 0.9 && >= 0.4 , split < 0.3 && >= 0.2.2 , temporary < 1.3 && >= 1.2.0.3 - if impl(ghc < 7.8) Build-Depends: convertible < 1.2 && >= 1.1.0.0 if impl(ghc >= 8.0) @@ -340,6 +344,7 @@ Test-Suite spec cabal-helper < 0.9 && >= 0.8.0.0 , ghc < 8.4 && >= 7.8 , ghc-mod + , ghc-mod-core Test-Suite shelltest @@ -349,7 +354,7 @@ Test-Suite shelltest Type: exitcode-stdio-1.0 Build-Tools: shelltest Build-Depends: base < 4.11 && >= 4.6.0.1 - , process < 1.5 + , process < 1.7 -- , shelltestrunner >= 1.3.5 if !flag(shelltest) Buildable: False @@ -373,6 +378,7 @@ Benchmark criterion , temporary < 1.3 && >= 1.2.0.3 , ghc-mod + , ghc-mod-core Buildable: False Flag shelltest From 5ebd13bfcee3501dafad6eeee9983062b1de8e35 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Mon, 25 Sep 2017 15:22:27 +0200 Subject: [PATCH 06/50] Move the core functionality into new package ghc-mod-core --- core/{ => src}/Data/Binary/Generic.hs | 0 core/{ => src}/GhcMod/CabalHelper.hs | 0 core/{ => src}/GhcMod/Caching.hs | 0 core/{ => src}/GhcMod/Caching/Types.hs | 0 core/{ => src}/GhcMod/Convert.hs | 0 core/{ => src}/GhcMod/Cradle.hs | 0 core/{ => src}/GhcMod/CustomPackageDb.hs | 0 core/{ => src}/GhcMod/DebugLogger.hs | 0 core/{ => src}/GhcMod/Doc.hs | 0 core/{ => src}/GhcMod/DynFlags.hs | 0 core/{ => src}/GhcMod/DynFlagsTH.hs | 0 core/{ => src}/GhcMod/Error.hs | 0 core/{ => src}/GhcMod/FileMapping.hs | 0 core/{ => src}/GhcMod/Gap.hs | 0 core/{ => src}/GhcMod/GhcPkg.hs | 0 core/{ => src}/GhcMod/HomeModuleGraph.hs | 0 core/{ => src}/GhcMod/LightGhc.hs | 0 core/{ => src}/GhcMod/Logger.hs | 0 core/{ => src}/GhcMod/Logging.hs | 0 core/{ => src}/GhcMod/Monad.hs | 0 core/{ => src}/GhcMod/Monad/Compat.hs_h | 0 core/{ => src}/GhcMod/Monad/Env.hs | 0 core/{ => src}/GhcMod/Monad/Log.hs | 0 core/{ => src}/GhcMod/Monad/Newtypes.hs | 0 core/{ => src}/GhcMod/Monad/Orphans.hs | 0 core/{ => src}/GhcMod/Monad/Out.hs | 0 core/{ => src}/GhcMod/Monad/State.hs | 0 core/{ => src}/GhcMod/Monad/Types.hs | 0 core/{ => src}/GhcMod/Options/DocUtils.hs | 0 core/{ => src}/GhcMod/Options/Help.hs | 0 core/{ => src}/GhcMod/Options/Options.hs | 0 core/{ => src}/GhcMod/Output.hs | 0 core/{ => src}/GhcMod/PathsAndFiles.hs | 0 core/{ => src}/GhcMod/Pretty.hs | 0 core/{ => src}/GhcMod/Read.hs | 0 core/{ => src}/GhcMod/SrcUtils.hs | 0 core/{ => src}/GhcMod/Stack.hs | 0 core/{ => src}/GhcMod/Target.hs | 0 core/{ => src}/GhcMod/Types.hs | 0 core/{ => src}/GhcMod/Utils.hs | 0 core/{ => src}/GhcMod/World.hs | 0 41 files changed, 0 insertions(+), 0 deletions(-) rename core/{ => src}/Data/Binary/Generic.hs (100%) rename core/{ => src}/GhcMod/CabalHelper.hs (100%) rename core/{ => src}/GhcMod/Caching.hs (100%) rename core/{ => src}/GhcMod/Caching/Types.hs (100%) rename core/{ => src}/GhcMod/Convert.hs (100%) rename core/{ => src}/GhcMod/Cradle.hs (100%) rename core/{ => src}/GhcMod/CustomPackageDb.hs (100%) rename core/{ => src}/GhcMod/DebugLogger.hs (100%) rename core/{ => src}/GhcMod/Doc.hs (100%) rename core/{ => src}/GhcMod/DynFlags.hs (100%) rename core/{ => src}/GhcMod/DynFlagsTH.hs (100%) rename core/{ => src}/GhcMod/Error.hs (100%) rename core/{ => src}/GhcMod/FileMapping.hs (100%) rename core/{ => src}/GhcMod/Gap.hs (100%) rename core/{ => src}/GhcMod/GhcPkg.hs (100%) rename core/{ => src}/GhcMod/HomeModuleGraph.hs (100%) rename core/{ => src}/GhcMod/LightGhc.hs (100%) rename core/{ => src}/GhcMod/Logger.hs (100%) rename core/{ => src}/GhcMod/Logging.hs (100%) rename core/{ => src}/GhcMod/Monad.hs (100%) rename core/{ => src}/GhcMod/Monad/Compat.hs_h (100%) rename core/{ => src}/GhcMod/Monad/Env.hs (100%) rename core/{ => src}/GhcMod/Monad/Log.hs (100%) rename core/{ => src}/GhcMod/Monad/Newtypes.hs (100%) rename core/{ => src}/GhcMod/Monad/Orphans.hs (100%) rename core/{ => src}/GhcMod/Monad/Out.hs (100%) rename core/{ => src}/GhcMod/Monad/State.hs (100%) rename core/{ => src}/GhcMod/Monad/Types.hs (100%) rename core/{ => src}/GhcMod/Options/DocUtils.hs (100%) rename core/{ => src}/GhcMod/Options/Help.hs (100%) rename core/{ => src}/GhcMod/Options/Options.hs (100%) rename core/{ => src}/GhcMod/Output.hs (100%) rename core/{ => src}/GhcMod/PathsAndFiles.hs (100%) rename core/{ => src}/GhcMod/Pretty.hs (100%) rename core/{ => src}/GhcMod/Read.hs (100%) rename core/{ => src}/GhcMod/SrcUtils.hs (100%) rename core/{ => src}/GhcMod/Stack.hs (100%) rename core/{ => src}/GhcMod/Target.hs (100%) rename core/{ => src}/GhcMod/Types.hs (100%) rename core/{ => src}/GhcMod/Utils.hs (100%) rename core/{ => src}/GhcMod/World.hs (100%) diff --git a/core/Data/Binary/Generic.hs b/core/src/Data/Binary/Generic.hs similarity index 100% rename from core/Data/Binary/Generic.hs rename to core/src/Data/Binary/Generic.hs diff --git a/core/GhcMod/CabalHelper.hs b/core/src/GhcMod/CabalHelper.hs similarity index 100% rename from core/GhcMod/CabalHelper.hs rename to core/src/GhcMod/CabalHelper.hs diff --git a/core/GhcMod/Caching.hs b/core/src/GhcMod/Caching.hs similarity index 100% rename from core/GhcMod/Caching.hs rename to core/src/GhcMod/Caching.hs diff --git a/core/GhcMod/Caching/Types.hs b/core/src/GhcMod/Caching/Types.hs similarity index 100% rename from core/GhcMod/Caching/Types.hs rename to core/src/GhcMod/Caching/Types.hs diff --git a/core/GhcMod/Convert.hs b/core/src/GhcMod/Convert.hs similarity index 100% rename from core/GhcMod/Convert.hs rename to core/src/GhcMod/Convert.hs diff --git a/core/GhcMod/Cradle.hs b/core/src/GhcMod/Cradle.hs similarity index 100% rename from core/GhcMod/Cradle.hs rename to core/src/GhcMod/Cradle.hs diff --git a/core/GhcMod/CustomPackageDb.hs b/core/src/GhcMod/CustomPackageDb.hs similarity index 100% rename from core/GhcMod/CustomPackageDb.hs rename to core/src/GhcMod/CustomPackageDb.hs diff --git a/core/GhcMod/DebugLogger.hs b/core/src/GhcMod/DebugLogger.hs similarity index 100% rename from core/GhcMod/DebugLogger.hs rename to core/src/GhcMod/DebugLogger.hs diff --git a/core/GhcMod/Doc.hs b/core/src/GhcMod/Doc.hs similarity index 100% rename from core/GhcMod/Doc.hs rename to core/src/GhcMod/Doc.hs diff --git a/core/GhcMod/DynFlags.hs b/core/src/GhcMod/DynFlags.hs similarity index 100% rename from core/GhcMod/DynFlags.hs rename to core/src/GhcMod/DynFlags.hs diff --git a/core/GhcMod/DynFlagsTH.hs b/core/src/GhcMod/DynFlagsTH.hs similarity index 100% rename from core/GhcMod/DynFlagsTH.hs rename to core/src/GhcMod/DynFlagsTH.hs diff --git a/core/GhcMod/Error.hs b/core/src/GhcMod/Error.hs similarity index 100% rename from core/GhcMod/Error.hs rename to core/src/GhcMod/Error.hs diff --git a/core/GhcMod/FileMapping.hs b/core/src/GhcMod/FileMapping.hs similarity index 100% rename from core/GhcMod/FileMapping.hs rename to core/src/GhcMod/FileMapping.hs diff --git a/core/GhcMod/Gap.hs b/core/src/GhcMod/Gap.hs similarity index 100% rename from core/GhcMod/Gap.hs rename to core/src/GhcMod/Gap.hs diff --git a/core/GhcMod/GhcPkg.hs b/core/src/GhcMod/GhcPkg.hs similarity index 100% rename from core/GhcMod/GhcPkg.hs rename to core/src/GhcMod/GhcPkg.hs diff --git a/core/GhcMod/HomeModuleGraph.hs b/core/src/GhcMod/HomeModuleGraph.hs similarity index 100% rename from core/GhcMod/HomeModuleGraph.hs rename to core/src/GhcMod/HomeModuleGraph.hs diff --git a/core/GhcMod/LightGhc.hs b/core/src/GhcMod/LightGhc.hs similarity index 100% rename from core/GhcMod/LightGhc.hs rename to core/src/GhcMod/LightGhc.hs diff --git a/core/GhcMod/Logger.hs b/core/src/GhcMod/Logger.hs similarity index 100% rename from core/GhcMod/Logger.hs rename to core/src/GhcMod/Logger.hs diff --git a/core/GhcMod/Logging.hs b/core/src/GhcMod/Logging.hs similarity index 100% rename from core/GhcMod/Logging.hs rename to core/src/GhcMod/Logging.hs diff --git a/core/GhcMod/Monad.hs b/core/src/GhcMod/Monad.hs similarity index 100% rename from core/GhcMod/Monad.hs rename to core/src/GhcMod/Monad.hs diff --git a/core/GhcMod/Monad/Compat.hs_h b/core/src/GhcMod/Monad/Compat.hs_h similarity index 100% rename from core/GhcMod/Monad/Compat.hs_h rename to core/src/GhcMod/Monad/Compat.hs_h diff --git a/core/GhcMod/Monad/Env.hs b/core/src/GhcMod/Monad/Env.hs similarity index 100% rename from core/GhcMod/Monad/Env.hs rename to core/src/GhcMod/Monad/Env.hs diff --git a/core/GhcMod/Monad/Log.hs b/core/src/GhcMod/Monad/Log.hs similarity index 100% rename from core/GhcMod/Monad/Log.hs rename to core/src/GhcMod/Monad/Log.hs diff --git a/core/GhcMod/Monad/Newtypes.hs b/core/src/GhcMod/Monad/Newtypes.hs similarity index 100% rename from core/GhcMod/Monad/Newtypes.hs rename to core/src/GhcMod/Monad/Newtypes.hs diff --git a/core/GhcMod/Monad/Orphans.hs b/core/src/GhcMod/Monad/Orphans.hs similarity index 100% rename from core/GhcMod/Monad/Orphans.hs rename to core/src/GhcMod/Monad/Orphans.hs diff --git a/core/GhcMod/Monad/Out.hs b/core/src/GhcMod/Monad/Out.hs similarity index 100% rename from core/GhcMod/Monad/Out.hs rename to core/src/GhcMod/Monad/Out.hs diff --git a/core/GhcMod/Monad/State.hs b/core/src/GhcMod/Monad/State.hs similarity index 100% rename from core/GhcMod/Monad/State.hs rename to core/src/GhcMod/Monad/State.hs diff --git a/core/GhcMod/Monad/Types.hs b/core/src/GhcMod/Monad/Types.hs similarity index 100% rename from core/GhcMod/Monad/Types.hs rename to core/src/GhcMod/Monad/Types.hs diff --git a/core/GhcMod/Options/DocUtils.hs b/core/src/GhcMod/Options/DocUtils.hs similarity index 100% rename from core/GhcMod/Options/DocUtils.hs rename to core/src/GhcMod/Options/DocUtils.hs diff --git a/core/GhcMod/Options/Help.hs b/core/src/GhcMod/Options/Help.hs similarity index 100% rename from core/GhcMod/Options/Help.hs rename to core/src/GhcMod/Options/Help.hs diff --git a/core/GhcMod/Options/Options.hs b/core/src/GhcMod/Options/Options.hs similarity index 100% rename from core/GhcMod/Options/Options.hs rename to core/src/GhcMod/Options/Options.hs diff --git a/core/GhcMod/Output.hs b/core/src/GhcMod/Output.hs similarity index 100% rename from core/GhcMod/Output.hs rename to core/src/GhcMod/Output.hs diff --git a/core/GhcMod/PathsAndFiles.hs b/core/src/GhcMod/PathsAndFiles.hs similarity index 100% rename from core/GhcMod/PathsAndFiles.hs rename to core/src/GhcMod/PathsAndFiles.hs diff --git a/core/GhcMod/Pretty.hs b/core/src/GhcMod/Pretty.hs similarity index 100% rename from core/GhcMod/Pretty.hs rename to core/src/GhcMod/Pretty.hs diff --git a/core/GhcMod/Read.hs b/core/src/GhcMod/Read.hs similarity index 100% rename from core/GhcMod/Read.hs rename to core/src/GhcMod/Read.hs diff --git a/core/GhcMod/SrcUtils.hs b/core/src/GhcMod/SrcUtils.hs similarity index 100% rename from core/GhcMod/SrcUtils.hs rename to core/src/GhcMod/SrcUtils.hs diff --git a/core/GhcMod/Stack.hs b/core/src/GhcMod/Stack.hs similarity index 100% rename from core/GhcMod/Stack.hs rename to core/src/GhcMod/Stack.hs diff --git a/core/GhcMod/Target.hs b/core/src/GhcMod/Target.hs similarity index 100% rename from core/GhcMod/Target.hs rename to core/src/GhcMod/Target.hs diff --git a/core/GhcMod/Types.hs b/core/src/GhcMod/Types.hs similarity index 100% rename from core/GhcMod/Types.hs rename to core/src/GhcMod/Types.hs diff --git a/core/GhcMod/Utils.hs b/core/src/GhcMod/Utils.hs similarity index 100% rename from core/GhcMod/Utils.hs rename to core/src/GhcMod/Utils.hs diff --git a/core/GhcMod/World.hs b/core/src/GhcMod/World.hs similarity index 100% rename from core/GhcMod/World.hs rename to core/src/GhcMod/World.hs From a7406d42c34a008517e20d3f05af61b4e489d47a Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Mon, 25 Sep 2017 15:22:27 +0200 Subject: [PATCH 07/50] Squash branch hie-integration-rebased-split-up-3 - Add ModuleLoader to ghc-mod-core This it to enable integration of tooling using ghc-mod-core into haskell-ide-engine, making use of a shared session and artifact cache. - Remove FileUri and replace with FilePath - Replace useless Monad constraint with MonadIO - Removed extensible state - Bump haskell-src-exts upper bound - Update for current dev cabal-helper - Moved code from ghc-mod-core ModuleLoader.hs back into hie - Bump haskell-src-exts upper bound --- .gitignore | 5 + .gitlab-ci.yml | 10 +- GhcMod/Exe/Debug.hs | 2 +- core/{src => }/Data/Binary/Generic.hs | 0 core/{src => }/GhcMod/CabalHelper.hs | 0 core/{src => }/GhcMod/Caching.hs | 0 core/{src => }/GhcMod/Caching/Types.hs | 0 core/{src => }/GhcMod/Convert.hs | 0 core/{src => }/GhcMod/Cradle.hs | 0 core/{src => }/GhcMod/CustomPackageDb.hs | 0 core/{src => }/GhcMod/DebugLogger.hs | 0 core/{src => }/GhcMod/Doc.hs | 0 core/{src => }/GhcMod/DynFlags.hs | 0 core/{src => }/GhcMod/DynFlagsTH.hs | 4 + core/{src => }/GhcMod/Error.hs | 0 core/{src => }/GhcMod/FileMapping.hs | 3 +- core/{src => }/GhcMod/Gap.hs | 10 +- core/{src => }/GhcMod/GhcPkg.hs | 0 core/{src => }/GhcMod/HomeModuleGraph.hs | 0 core/{src => }/GhcMod/LightGhc.hs | 3 + core/{src => }/GhcMod/Logger.hs | 0 core/{src => }/GhcMod/Logging.hs | 0 core/GhcMod/ModuleLoader.hs | 133 ++++++++++++++++++++++ core/{src => }/GhcMod/Monad.hs | 0 core/{src => }/GhcMod/Monad/Compat.hs_h | 0 core/{src => }/GhcMod/Monad/Env.hs | 0 core/{src => }/GhcMod/Monad/Log.hs | 0 core/{src => }/GhcMod/Monad/Newtypes.hs | 0 core/{src => }/GhcMod/Monad/Orphans.hs | 0 core/{src => }/GhcMod/Monad/Out.hs | 0 core/{src => }/GhcMod/Monad/State.hs | 0 core/{src => }/GhcMod/Monad/Types.hs | 0 core/{src => }/GhcMod/Options/DocUtils.hs | 0 core/{src => }/GhcMod/Options/Help.hs | 0 core/{src => }/GhcMod/Options/Options.hs | 0 core/{src => }/GhcMod/Output.hs | 0 core/{src => }/GhcMod/PathsAndFiles.hs | 0 core/{src => }/GhcMod/Pretty.hs | 0 core/{src => }/GhcMod/Read.hs | 0 core/{src => }/GhcMod/SrcUtils.hs | 12 +- core/{src => }/GhcMod/Stack.hs | 0 core/{src => }/GhcMod/Target.hs | 124 ++++++++++++++++---- core/{src => }/GhcMod/Types.hs | 0 core/{src => }/GhcMod/Utils.hs | 2 +- core/{src => }/GhcMod/World.hs | 0 core/GhcModCore.hs | 4 + core/ghc-mod-core.cabal | 3 +- ghc-mod.cabal | 2 +- rundocker.sh | 6 + 49 files changed, 291 insertions(+), 32 deletions(-) rename core/{src => }/Data/Binary/Generic.hs (100%) rename core/{src => }/GhcMod/CabalHelper.hs (100%) rename core/{src => }/GhcMod/Caching.hs (100%) rename core/{src => }/GhcMod/Caching/Types.hs (100%) rename core/{src => }/GhcMod/Convert.hs (100%) rename core/{src => }/GhcMod/Cradle.hs (100%) rename core/{src => }/GhcMod/CustomPackageDb.hs (100%) rename core/{src => }/GhcMod/DebugLogger.hs (100%) rename core/{src => }/GhcMod/Doc.hs (100%) rename core/{src => }/GhcMod/DynFlags.hs (100%) rename core/{src => }/GhcMod/DynFlagsTH.hs (97%) rename core/{src => }/GhcMod/Error.hs (100%) rename core/{src => }/GhcMod/FileMapping.hs (97%) rename core/{src => }/GhcMod/Gap.hs (99%) rename core/{src => }/GhcMod/GhcPkg.hs (100%) rename core/{src => }/GhcMod/HomeModuleGraph.hs (100%) rename core/{src => }/GhcMod/LightGhc.hs (97%) rename core/{src => }/GhcMod/Logger.hs (100%) rename core/{src => }/GhcMod/Logging.hs (100%) create mode 100644 core/GhcMod/ModuleLoader.hs rename core/{src => }/GhcMod/Monad.hs (100%) rename core/{src => }/GhcMod/Monad/Compat.hs_h (100%) rename core/{src => }/GhcMod/Monad/Env.hs (100%) rename core/{src => }/GhcMod/Monad/Log.hs (100%) rename core/{src => }/GhcMod/Monad/Newtypes.hs (100%) rename core/{src => }/GhcMod/Monad/Orphans.hs (100%) rename core/{src => }/GhcMod/Monad/Out.hs (100%) rename core/{src => }/GhcMod/Monad/State.hs (100%) rename core/{src => }/GhcMod/Monad/Types.hs (100%) rename core/{src => }/GhcMod/Options/DocUtils.hs (100%) rename core/{src => }/GhcMod/Options/Help.hs (100%) rename core/{src => }/GhcMod/Options/Options.hs (100%) rename core/{src => }/GhcMod/Output.hs (100%) rename core/{src => }/GhcMod/PathsAndFiles.hs (100%) rename core/{src => }/GhcMod/Pretty.hs (100%) rename core/{src => }/GhcMod/Read.hs (100%) rename core/{src => }/GhcMod/SrcUtils.hs (93%) rename core/{src => }/GhcMod/Stack.hs (100%) rename core/{src => }/GhcMod/Target.hs (79%) rename core/{src => }/GhcMod/Types.hs (100%) rename core/{src => }/GhcMod/Utils.hs (98%) rename core/{src => }/GhcMod/World.hs (100%) create mode 100755 rundocker.sh diff --git a/.gitignore b/.gitignore index c3e127b1f..e7fac986e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ elisp/*.elc /.cabal-sandbox/ /.stack-work/ /test/data/**/stack.yaml +/test/data/**/.stack-work +/test/data/**/.cabal-sandbox add-source-timestamps package.cache cabal.sandbox.config @@ -20,3 +22,6 @@ cabal.sandbox.config cabal-dev /TAGS /tags +/.bash_history +/.travis.yml.orig +/cabal.project.az diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e9914bc83..3c56cf5f3 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,12 +4,18 @@ stages: .before_script_template: &common_before_script before_script: - ls -l .. - - apt-get update && apt-get install alex happy + - apt-get update && apt-get install alex happy libtinfo-dev - ghc-pkg list - - cabal update && cabal install --only-dependencies -j2 --enable-tests --enable-documentation + - (cd .. && git clone https://github.com/alanz/cabal-helper.git) + - cabal update + - cabal sandbox --sandbox=$HOME/.sandbox init + - cabal sandbox add-source ../cabal-helper + - cabal sandbox add-source ../ghc-mod/ghc-mod-core + - cabal install --only-dependencies -j2 --enable-tests --enable-documentation - mkdir -p ../ghc-mod.sdist-$CI_PIPELINE_ID - touch ChangeLog - cabal sdist --output-directory=../ghc-mod.sdist-$CI_PIPELINE_ID + - cp cabal.sandbox.config ../ghc-mod.sdist-$CI_PIPELINE_ID/ - cd ../ghc-mod.sdist-$CI_PIPELINE_ID after_script: diff --git a/GhcMod/Exe/Debug.hs b/GhcMod/Exe/Debug.hs index 2ba7ac556..3cdfd4443 100644 --- a/GhcMod/Exe/Debug.hs +++ b/GhcMod/Exe/Debug.hs @@ -123,7 +123,7 @@ componentInfo ts = do mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn candidates = findCandidates $ map snd mdlcs cn = pickComponent candidates - opts <- targetGhcOptions crdl sefnmn + opts <- fst <$> targetGhcOptions crdl sefnmn return $ unlines $ [ "Matching Components:\n" ++ renderGm (nest 4 $ diff --git a/core/src/Data/Binary/Generic.hs b/core/Data/Binary/Generic.hs similarity index 100% rename from core/src/Data/Binary/Generic.hs rename to core/Data/Binary/Generic.hs diff --git a/core/src/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs similarity index 100% rename from core/src/GhcMod/CabalHelper.hs rename to core/GhcMod/CabalHelper.hs diff --git a/core/src/GhcMod/Caching.hs b/core/GhcMod/Caching.hs similarity index 100% rename from core/src/GhcMod/Caching.hs rename to core/GhcMod/Caching.hs diff --git a/core/src/GhcMod/Caching/Types.hs b/core/GhcMod/Caching/Types.hs similarity index 100% rename from core/src/GhcMod/Caching/Types.hs rename to core/GhcMod/Caching/Types.hs diff --git a/core/src/GhcMod/Convert.hs b/core/GhcMod/Convert.hs similarity index 100% rename from core/src/GhcMod/Convert.hs rename to core/GhcMod/Convert.hs diff --git a/core/src/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs similarity index 100% rename from core/src/GhcMod/Cradle.hs rename to core/GhcMod/Cradle.hs diff --git a/core/src/GhcMod/CustomPackageDb.hs b/core/GhcMod/CustomPackageDb.hs similarity index 100% rename from core/src/GhcMod/CustomPackageDb.hs rename to core/GhcMod/CustomPackageDb.hs diff --git a/core/src/GhcMod/DebugLogger.hs b/core/GhcMod/DebugLogger.hs similarity index 100% rename from core/src/GhcMod/DebugLogger.hs rename to core/GhcMod/DebugLogger.hs diff --git a/core/src/GhcMod/Doc.hs b/core/GhcMod/Doc.hs similarity index 100% rename from core/src/GhcMod/Doc.hs rename to core/GhcMod/Doc.hs diff --git a/core/src/GhcMod/DynFlags.hs b/core/GhcMod/DynFlags.hs similarity index 100% rename from core/src/GhcMod/DynFlags.hs rename to core/GhcMod/DynFlags.hs diff --git a/core/src/GhcMod/DynFlagsTH.hs b/core/GhcMod/DynFlagsTH.hs similarity index 97% rename from core/src/GhcMod/DynFlagsTH.hs rename to core/GhcMod/DynFlagsTH.hs index 776c588f9..d83419a8b 100644 --- a/core/src/GhcMod/DynFlagsTH.hs +++ b/core/GhcMod/DynFlagsTH.hs @@ -83,6 +83,10 @@ deriveEqDynFlags qds = do , "FlushOut" , "FlushErr" , "Settings" -- I think these can't cange at runtime + , "LogFinaliser" -- added for ghc-8.2 + , "LogOutput" -- added for ghc-8.2 + , "OverridingBool" -- added for ghc-8.2 + , "Scheme" -- added for ghc-8.2 ] ignoredTypeOccNames = [ "OnOff" ] diff --git a/core/src/GhcMod/Error.hs b/core/GhcMod/Error.hs similarity index 100% rename from core/src/GhcMod/Error.hs rename to core/GhcMod/Error.hs diff --git a/core/src/GhcMod/FileMapping.hs b/core/GhcMod/FileMapping.hs similarity index 97% rename from core/src/GhcMod/FileMapping.hs rename to core/GhcMod/FileMapping.hs index e05a54066..403e3fcf4 100644 --- a/core/src/GhcMod/FileMapping.hs +++ b/core/GhcMod/FileMapping.hs @@ -48,7 +48,8 @@ loadMappedFileSource from src = do tmpdir <- cradleTempDir `fmap` cradle enc <- liftIO . mkTextEncoding . optEncoding =<< options to <- liftIO $ do - (fn, h) <- openTempFile tmpdir (takeFileName from) + (fn', h) <- openTempFile tmpdir (takeFileName from) + fn <- getCanonicalFileNameSafe fn' hSetEncoding h enc hPutStr h src hClose h diff --git a/core/src/GhcMod/Gap.hs b/core/GhcMod/Gap.hs similarity index 99% rename from core/src/GhcMod/Gap.hs rename to core/GhcMod/Gap.hs index dff6b87f3..03a90c426 100644 --- a/core/src/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -70,6 +70,7 @@ import NameSet import OccName import Outputable import PprTyThing +import IfaceSyn import StringBuffer import TcType import Var (varType) @@ -108,7 +109,10 @@ import TcRnTypes #endif #endif -#if MIN_VERSION_GLASGOW_HASKELL(8,0,1,20161117) +#if MIN_VERSION_GLASGOW_HASKELL(8,2,0,0) +import GHC hiding (ClsInst, withCleanupSession, setLogAction) +import qualified GHC (withCleanupSession) +#elif MIN_VERSION_GLASGOW_HASKELL(8,0,1,20161117) import GHC hiding (ClsInst, withCleanupSession) import qualified GHC (withCleanupSession) #elif __GLASGOW_HASKELL__ >= 706 @@ -459,9 +463,9 @@ pprInfo m pefas (thing, fixity, insts) = showWithLoc (pprDefinedAt' (getName axiom)) $ hang (ptext (sLit "type instance") <+> pprTypeApp (coAxiomTyCon axiom) lhs_tys) 2 (equals <+> ppr rhs) -#else +# else pprFamInst' ispec = showWithLoc (pprDefinedAt' (getName ispec)) (pprFamInstHdr ispec) -#endif +# endif #else pprTyThingInContextLoc' pefas' thing' = showWithLoc (pprDefinedAt' thing') (pprTyThingInContext pefas' thing') #endif diff --git a/core/src/GhcMod/GhcPkg.hs b/core/GhcMod/GhcPkg.hs similarity index 100% rename from core/src/GhcMod/GhcPkg.hs rename to core/GhcMod/GhcPkg.hs diff --git a/core/src/GhcMod/HomeModuleGraph.hs b/core/GhcMod/HomeModuleGraph.hs similarity index 100% rename from core/src/GhcMod/HomeModuleGraph.hs rename to core/GhcMod/HomeModuleGraph.hs diff --git a/core/src/GhcMod/LightGhc.hs b/core/GhcMod/LightGhc.hs similarity index 97% rename from core/src/GhcMod/LightGhc.hs rename to core/GhcMod/LightGhc.hs index 146f2c095..52def76d4 100644 --- a/core/src/GhcMod/LightGhc.hs +++ b/core/GhcMod/LightGhc.hs @@ -31,7 +31,10 @@ initStaticOpts = return () newLightEnv :: IOish m => (DynFlags -> LightGhc DynFlags) -> m HscEnv newLightEnv mdf = do df <- liftIO $ do +#if MIN_VERSION_GLASGOW_HASKELL(8,2,0,0) +#else initStaticOpts +#endif settings <- initSysTools (Just libdir) initDynFlags $ defaultDynFlags settings diff --git a/core/src/GhcMod/Logger.hs b/core/GhcMod/Logger.hs similarity index 100% rename from core/src/GhcMod/Logger.hs rename to core/GhcMod/Logger.hs diff --git a/core/src/GhcMod/Logging.hs b/core/GhcMod/Logging.hs similarity index 100% rename from core/src/GhcMod/Logging.hs rename to core/GhcMod/Logging.hs diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs new file mode 100644 index 000000000..b1367adac --- /dev/null +++ b/core/GhcMod/ModuleLoader.hs @@ -0,0 +1,133 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE OverloadedStrings #-} +-- | Uses GHC hooks to load a TypecheckedModule + +module GhcMod.ModuleLoader + ( getTypecheckedModuleGhc + , getTypecheckedModuleGhc' + ) where + +import Control.Monad.IO.Class + +import qualified Data.Map as Map +import Data.IORef + +import qualified GhcMod.Monad as GM +import qualified GhcMod.Target as GM +import qualified GhcMod.Types as GM + +import GHC (TypecheckedModule) +import qualified GHC +import qualified DynFlags as GHC +import qualified GhcMonad as GHC +import qualified Hooks as GHC +import qualified HscMain as GHC +import qualified HscTypes as GHC +import qualified TcRnMonad as GHC + +import System.Directory +import System.FilePath + +-- --------------------------------------------------------------------- + +getMappedFileName :: FilePath -> GM.FileMappingMap -> FilePath +getMappedFileName fname mfs = + case Map.lookup fname mfs of + Just fm -> GM.fmPath fm + Nothing -> fname + +canonicalizeModSummary :: (MonadIO m) => + GHC.ModSummary -> m (Maybe FilePath) +canonicalizeModSummary = + traverse (liftIO . canonicalizePath) . GHC.ml_hs_file . GHC.ms_location + +tweakModSummaryDynFlags :: GHC.ModSummary -> GHC.ModSummary +tweakModSummaryDynFlags ms = + let df = GHC.ms_hspp_opts ms + in ms { GHC.ms_hspp_opts = GHC.gopt_set df GHC.Opt_KeepRawTokenStream } + +-- | Gets a TypecheckedModule from a given file +-- The `wrapper` allows arbitary data to be captured during +-- the compilation process, like errors and warnings +-- Appends the parent directories of all the mapped files +-- to the includePaths for CPP purposes. +-- Use in combination with `runActionInContext` for best results +getTypecheckedModuleGhc' :: GM.IOish m + => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule) +getTypecheckedModuleGhc' wrapper targetFile = do + cfileName <- liftIO $ canonicalizePath targetFile + mfs <- GM.getMMappedFiles + mFileName <- liftIO . canonicalizePath $ getMappedFileName cfileName mfs + ref <- liftIO $ newIORef Nothing + let keepInfo = pure . (mFileName ==) + saveModule = writeIORef ref . Just + res <- getTypecheckedModuleGhc wrapper [cfileName] keepInfo saveModule + mtm <- liftIO $ readIORef ref + return (res, mtm) + +-- | like getTypecheckedModuleGhc' but allows you to keep an arbitary number of Modules +-- `keepInfo` decides which TypecheckedModule to keep +-- `saveModule` is the callback that is passed the TypecheckedModule +getTypecheckedModuleGhc :: GM.IOish m + => (GM.GmlT m () -> GM.GmlT m a) -> [FilePath] -> (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GM.GhcModT m a +getTypecheckedModuleGhc wrapper targetFiles keepInfo saveModule = do + mfs <- GM.getMMappedFiles + let ips = map takeDirectory $ Map.keys mfs + setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } + GM.runGmlTWith' (map Left targetFiles) + (return . setIncludePaths) + (Just $ updateHooks keepInfo saveModule) + wrapper + (return ()) + +updateHooks + :: (FilePath -> IO Bool) + -> (TypecheckedModule -> IO ()) + -> GHC.Hooks + -> GHC.Hooks +updateHooks fp ref hooks = hooks { +#if __GLASGOW_HASKELL__ <= 710 + GHC.hscFrontendHook = Just $ hscFrontend fp ref +#else + GHC.hscFrontendHook = Just $ fmap GHC.FrontendTypecheck . hscFrontend fp ref +#endif + } + + +-- | Warning: discards all changes to Session +runGhcInHsc :: GHC.Ghc a -> GHC.Hsc a +runGhcInHsc action = do + env <- GHC.getHscEnv + session <- liftIO $ newIORef env + liftIO $ GHC.reflectGhc action $ GHC.Session session + + +-- | Frontend hook that keeps the TypecheckedModule for its first argument +-- and stores it in the IORef passed to it +hscFrontend :: (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GHC.ModSummary -> GHC.Hsc GHC.TcGblEnv +hscFrontend keepInfoFunc saveModule mod_summary = do + mfn <- canonicalizeModSummary mod_summary + -- md = GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod mod_summary + keepInfo <- case mfn of + Just fileName -> liftIO $ keepInfoFunc fileName + Nothing -> pure False + -- liftIO $ debugm $ "hscFrontend: got mod,file" ++ show (md, mfn) + if keepInfo + then runGhcInHsc $ do + let modSumWithRaw = tweakModSummaryDynFlags mod_summary + + p' <- GHC.parseModule modSumWithRaw + let p = p' {GHC.pm_mod_summary = mod_summary} + tc <- GHC.typecheckModule p + let tc_gbl_env = fst $ GHC.tm_internals_ tc + + liftIO $ saveModule tc + return tc_gbl_env + else do + hpm <- GHC.hscParse' mod_summary + hsc_env <- GHC.getHscEnv + GHC.tcRnModule' hsc_env mod_summary False hpm + +-- --------------------------------------------------------------------- + diff --git a/core/src/GhcMod/Monad.hs b/core/GhcMod/Monad.hs similarity index 100% rename from core/src/GhcMod/Monad.hs rename to core/GhcMod/Monad.hs diff --git a/core/src/GhcMod/Monad/Compat.hs_h b/core/GhcMod/Monad/Compat.hs_h similarity index 100% rename from core/src/GhcMod/Monad/Compat.hs_h rename to core/GhcMod/Monad/Compat.hs_h diff --git a/core/src/GhcMod/Monad/Env.hs b/core/GhcMod/Monad/Env.hs similarity index 100% rename from core/src/GhcMod/Monad/Env.hs rename to core/GhcMod/Monad/Env.hs diff --git a/core/src/GhcMod/Monad/Log.hs b/core/GhcMod/Monad/Log.hs similarity index 100% rename from core/src/GhcMod/Monad/Log.hs rename to core/GhcMod/Monad/Log.hs diff --git a/core/src/GhcMod/Monad/Newtypes.hs b/core/GhcMod/Monad/Newtypes.hs similarity index 100% rename from core/src/GhcMod/Monad/Newtypes.hs rename to core/GhcMod/Monad/Newtypes.hs diff --git a/core/src/GhcMod/Monad/Orphans.hs b/core/GhcMod/Monad/Orphans.hs similarity index 100% rename from core/src/GhcMod/Monad/Orphans.hs rename to core/GhcMod/Monad/Orphans.hs diff --git a/core/src/GhcMod/Monad/Out.hs b/core/GhcMod/Monad/Out.hs similarity index 100% rename from core/src/GhcMod/Monad/Out.hs rename to core/GhcMod/Monad/Out.hs diff --git a/core/src/GhcMod/Monad/State.hs b/core/GhcMod/Monad/State.hs similarity index 100% rename from core/src/GhcMod/Monad/State.hs rename to core/GhcMod/Monad/State.hs diff --git a/core/src/GhcMod/Monad/Types.hs b/core/GhcMod/Monad/Types.hs similarity index 100% rename from core/src/GhcMod/Monad/Types.hs rename to core/GhcMod/Monad/Types.hs diff --git a/core/src/GhcMod/Options/DocUtils.hs b/core/GhcMod/Options/DocUtils.hs similarity index 100% rename from core/src/GhcMod/Options/DocUtils.hs rename to core/GhcMod/Options/DocUtils.hs diff --git a/core/src/GhcMod/Options/Help.hs b/core/GhcMod/Options/Help.hs similarity index 100% rename from core/src/GhcMod/Options/Help.hs rename to core/GhcMod/Options/Help.hs diff --git a/core/src/GhcMod/Options/Options.hs b/core/GhcMod/Options/Options.hs similarity index 100% rename from core/src/GhcMod/Options/Options.hs rename to core/GhcMod/Options/Options.hs diff --git a/core/src/GhcMod/Output.hs b/core/GhcMod/Output.hs similarity index 100% rename from core/src/GhcMod/Output.hs rename to core/GhcMod/Output.hs diff --git a/core/src/GhcMod/PathsAndFiles.hs b/core/GhcMod/PathsAndFiles.hs similarity index 100% rename from core/src/GhcMod/PathsAndFiles.hs rename to core/GhcMod/PathsAndFiles.hs diff --git a/core/src/GhcMod/Pretty.hs b/core/GhcMod/Pretty.hs similarity index 100% rename from core/src/GhcMod/Pretty.hs rename to core/GhcMod/Pretty.hs diff --git a/core/src/GhcMod/Read.hs b/core/GhcMod/Read.hs similarity index 100% rename from core/src/GhcMod/Read.hs rename to core/GhcMod/Read.hs diff --git a/core/src/GhcMod/SrcUtils.hs b/core/GhcMod/SrcUtils.hs similarity index 93% rename from core/src/GhcMod/SrcUtils.hs rename to core/GhcMod/SrcUtils.hs index 30999f3f1..89fb5453d 100644 --- a/core/src/GhcMod/SrcUtils.hs +++ b/core/GhcMod/SrcUtils.hs @@ -47,8 +47,14 @@ type CstGenQS = M.Map Var Type -- | Generic type to simplify SYB definition type CstGenQT a = forall m. GhcMonad m => a Id -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS) -collectSpansTypes :: (GhcMonad m) => Bool -> G.TypecheckedModule -> (Int, Int) -> m [(SrcSpan, Type)] -collectSpansTypes withConstraints tcs lc = +collectSpansTypes :: (GhcMonad m) => Bool -> G.TypecheckedModule -> (Int,Int) -> m [(SrcSpan, Type)] +collectSpansTypes withConstraints tcs lc = collectSpansTypes' withConstraints tcs (`G.spans` lc) + +collectAllSpansTypes :: (GhcMonad m) => Bool -> G.TypecheckedModule -> m [(SrcSpan, Type)] +collectAllSpansTypes withConstraints tcs = collectSpansTypes' withConstraints tcs (const True) + +collectSpansTypes' :: (GhcMonad m) => Bool -> G.TypecheckedModule -> (SrcSpan -> Bool) -> m [(SrcSpan, Type)] +collectSpansTypes' withConstraints tcs f = -- This walks AST top-down, left-to-right, while carrying CstGenQS down the tree -- (but not left-to-right) everythingStagedWithContext TypeChecker M.empty (liftM2 (++)) @@ -92,7 +98,7 @@ collectSpansTypes withConstraints tcs lc = collectBinders = listifyStaged TypeChecker (const True) -- Gets monomorphic type with location getType' x@(L spn _) - | G.isGoodSrcSpan spn && spn `G.spans` lc + | G.isGoodSrcSpan spn && f spn = getType tcs x | otherwise = return Nothing -- Gets constrained type diff --git a/core/src/GhcMod/Stack.hs b/core/GhcMod/Stack.hs similarity index 100% rename from core/src/GhcMod/Stack.hs rename to core/GhcMod/Stack.hs diff --git a/core/src/GhcMod/Target.hs b/core/GhcMod/Target.hs similarity index 79% rename from core/src/GhcMod/Target.hs rename to core/GhcMod/Target.hs index 907c4f9a3..02f447e96 100644 --- a/core/src/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -21,6 +21,9 @@ import Control.Arrow import Control.Applicative import Control.Category ((.)) import GHC +import qualified Hooks as GHC +import qualified HscTypes as GHC +import qualified GhcMonad as G #if __GLASGOW_HASKELL__ >= 800 import GHC.LanguageExtensions #endif @@ -146,16 +149,42 @@ runGmlT' :: IOish m -> GhcModT m a runGmlT' fns mdf action = runGmlTWith fns mdf id action --- | Run a GmlT action (i.e. a function in the GhcMonad) in the context --- of certain files or modules, with updated GHC flags and a final --- transformation +-- | Run a GmlT action (i.e. a function in the GhcMonad) in the context of +-- certain files or modules, with updated GHC flags, and updated ModuleGraph +runGmlTfm :: IOish m + => [Either FilePath ModuleName] + -> (forall gm. GhcMonad gm => DynFlags -> gm DynFlags) + -> Maybe (GHC.Hooks -> GHC.Hooks) + -> GmlT m a + -> GhcModT m a +runGmlTfm fns mdf mUpdateHooks action + = runGmlTWith' fns mdf mUpdateHooks id action + +-- | Run a GmlT action (i.e. a function in the GhcMonad) in the context of +-- certain files or modules, with updated GHC flags, updated ModuleGraph and a +-- final transformation runGmlTWith :: IOish m => [Either FilePath ModuleName] -> (forall gm. GhcMonad gm => DynFlags -> gm DynFlags) -> (GmlT m a -> GmlT m b) -> GmlT m a -> GhcModT m b -runGmlTWith efnmns' mdf wrapper action = do +runGmlTWith efnmns' mdf wrapper action = + runGmlTWith' efnmns' mdf Nothing wrapper action + +-- | Run a GmlT action (i.e. a function in the GhcMonad) in the context of +-- certain files or modules, with updated GHC flags, updated ModuleGraph and a +-- final transformation +runGmlTWith' :: IOish m + => [Either FilePath ModuleName] + -> (forall gm. GhcMonad gm => DynFlags -> gm DynFlags) + -> Maybe (GHC.Hooks -> GHC.Hooks) + -- ^ If a hook update is provided, force the reloading + -- of the specified targets + -> (GmlT m a -> GmlT m b) + -> GmlT m a + -> GhcModT m b +runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do crdl <- cradle Options { optGhcUserOptions } <- options @@ -163,9 +192,14 @@ runGmlTWith efnmns' mdf wrapper action = do ccfns = map (cradleCurrentDir crdl ) fns cfns <- mapM getCanonicalFileNameSafe ccfns let serfnmn = Set.fromList $ map Right mns ++ map Left cfns - opts <- targetGhcOptions crdl serfnmn + (opts, mappedStrs) <- targetGhcOptions crdl serfnmn let opts' = opts ++ ["-O0"] ++ optGhcUserOptions + gmVomit + "session-ghc-options" + (text "Using the following mapped files") + (intercalate " " $ map (("\""++) . (++"\"")) mappedStrs) + gmVomit "session-ghc-options" (text "Initializing GHC session with following options") @@ -179,31 +213,39 @@ runGmlTWith efnmns' mdf wrapper action = do initSession opts' $ setHscNothing >>> setLogger >>> mdf - mappedStrs <- getMMappedFilePaths - let targetStrs = mappedStrs ++ map moduleNameString mns ++ cfns + let targetStrs = map moduleNameString mns ++ cfns + + gmVomit + "session-ghc-options" + (text "Using the following targets") + (intercalate " " $ map (("\""++) . (++"\"")) targetStrs) unGmlT $ wrapper $ do - loadTargets opts targetStrs + loadTargets opts targetStrs mUpdateHooks action targetGhcOptions :: forall m. IOish m => Cradle -> Set (Either FilePath ModuleName) - -> GhcModT m [GHCOption] + -> GhcModT m ([GHCOption],[FilePath]) targetGhcOptions crdl sefnmn = do when (Set.null sefnmn) $ error "targetGhcOptions: no targets given" case cradleProject crdl of proj | isCabalHelperProject proj -> cabalOpts crdl - | otherwise -> sandboxOpts crdl + | otherwise -> do + opts <- sandboxOpts crdl + mappedStrs <- getMMappedFilePaths + return (opts, mappedStrs) where zipMap f l = l `zip` (f `map` l) - cabalOpts :: Cradle -> GhcModT m [GHCOption] + cabalOpts :: Cradle -> GhcModT m ([GHCOption],[FilePath]) cabalOpts Cradle{..} = do mcs <- cabalResolvedComponents - + mappedStrs <- getMMappedFilePaths + let mappedComps = zipMap (moduleComponents mcs . Left) mappedStrs let mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn candidates = findCandidates $ map snd mdlcs @@ -214,17 +256,22 @@ targetGhcOptions crdl sefnmn = do then do -- First component should be ChLibName, if no lib will take lexically first exe. let cns = filter (/= ChSetupHsName) $ Map.keys mcs + cn = head cns + mappedStrsInComp = map fst $ filter (Set.member cn . snd) mappedComps gmLog GmDebug "" $ strDoc $ "Could not find a component assignment, falling back to picking library component in cabal file." - return $ gmcGhcOpts (fromJustNote "targetGhcOptions, no-assignment" $ Map.lookup (head cns) mcs) - ++ ["-Wno-missing-home-modules"] + let opts = gmcGhcOpts (fromJustNote "targetGhcOptions, no-assignment" $ Map.lookup cn mcs) + ++ ["-Wno-missing-home-modules"] + return (opts, mappedStrsInComp) else do when noCandidates $ throwError $ GMECabalCompAssignment mdlcs let cn = pickComponent candidates - return $ gmcGhcOpts (fromJustNote "targetGhcOptions" $ Map.lookup cn mcs) - ++ ["-Wno-missing-home-modules"] + mappedStrsInComp = map fst $ filter (Set.member cn . snd) mappedComps + opts = gmcGhcOpts (fromJustNote "targetGhcOptions" $ Map.lookup cn mcs) + ++ ["-Wno-missing-home-modules"] + return (opts, mappedStrsInComp) resolvedComponentsCache :: IOish m => FilePath -> Cached (GhcModT m) GhcModState @@ -450,8 +497,8 @@ resolveGmComponents mcache cs = do same f a b = (f a) == (f b) -- | Set the files as targets and load them. -loadTargets :: IOish m => [GHCOption] -> [FilePath] -> GmlT m () -loadTargets opts targetStrs = do +loadTargets :: IOish m => [GHCOption] -> [FilePath] -> Maybe (GHC.Hooks -> GHC.Hooks) -> GmlT m () +loadTargets opts targetStrs mUpdateHooks = do targets' <- withLightHscEnv opts $ \env -> liftM (nubBy ((==) `on` targetId)) @@ -459,20 +506,33 @@ loadTargets opts targetStrs = do >>= mapM relativize let targets = map (\t -> t { targetAllowObjCode = False }) targets' + targetFileNames = concatMap filePathFromTarget targets gmLog GmDebug "loadTargets" $ text "Loading" <+>: fsep (map (text . showTargetId) targets) + + let filterModSums = isJust mUpdateHooks + gmLog GmDebug "loadTargets" $ + text "filterModSums" <+>: text (show filterModSums) + setTargets targets + when filterModSums $ updateModuleGraph setDynFlagsRecompile targetFileNames + mg <- depanal [] False let interp = needsHscInterpreted mg target <- hscTarget <$> getSessionDynFlags when (interp && target /= HscInterpreted) $ do - _ <- setSessionDynFlags . setHscInterpreted =<< getSessionDynFlags + let + setHooks :: DynFlags -> DynFlags + setHooks df = df { GHC.hooks = (fromMaybe id mUpdateHooks) (GHC.hooks df) } + _ <- setSessionDynFlags . setHscInterpreted . setHooks =<< getSessionDynFlags gmLog GmInfo "loadTargets" $ text "Target needs interpeter, switching to LinkInMemory/HscInterpreted. Perfectly normal if anything is using TemplateHaskell, QuasiQuotes or PatternSynonyms." + when filterModSums $ updateModuleGraph setDynFlagsRecompile targetFileNames + target' <- hscTarget <$> getSessionDynFlags case target' of @@ -485,6 +545,8 @@ loadTargets opts targetStrs = do void $ load LoadAllTargets _ -> error ("loadTargets: unsupported hscTarget") + when filterModSums $ updateModuleGraph unSetDynFlagsRecompile targetFileNames + gmLog GmDebug "loadTargets" $ text "Loading done" where @@ -498,6 +560,30 @@ loadTargets opts targetStrs = do showTargetId (Target (TargetModule s) _ _) = moduleNameString s showTargetId (Target (TargetFile s _) _ _) = s + filePathFromTarget (Target (TargetModule _) _ _) = [] + filePathFromTarget (Target (TargetFile s _) _ _) = [s] + + updateModuleGraph :: (GhcMonad m, GmState m, GmEnv m, + MonadIO m, GmLog m, GmOut m) + => (DynFlags -> DynFlags) -> [FilePath] -> m () + updateModuleGraph df fps = do + let + fpSet = Set.fromList fps + updateHooks df = df { GHC.hooks = (fromMaybe id mUpdateHooks) (GHC.hooks df)} + mustRecompile ms = case (ml_hs_file . ms_location) ms of + Nothing -> ms + Just f -> if Set.member f fpSet + then ms {ms_hspp_opts = (df . updateHooks) (ms_hspp_opts ms)} + else ms + update s = s {hsc_mod_graph = map mustRecompile (hsc_mod_graph s)} + G.modifySession update + + setDynFlagsRecompile :: DynFlags -> DynFlags + setDynFlagsRecompile df = gopt_set df Opt_ForceRecomp + + unSetDynFlagsRecompile :: DynFlags -> DynFlags + unSetDynFlagsRecompile df = gopt_unset df Opt_ForceRecomp + needsHscInterpreted :: ModuleGraph -> Bool needsHscInterpreted = any $ \ms -> let df = ms_hspp_opts ms in diff --git a/core/src/GhcMod/Types.hs b/core/GhcMod/Types.hs similarity index 100% rename from core/src/GhcMod/Types.hs rename to core/GhcMod/Types.hs diff --git a/core/src/GhcMod/Utils.hs b/core/GhcMod/Utils.hs similarity index 98% rename from core/src/GhcMod/Utils.hs rename to core/GhcMod/Utils.hs index 7c282357b..0d18ce81c 100644 --- a/core/src/GhcMod/Utils.hs +++ b/core/GhcMod/Utils.hs @@ -113,7 +113,7 @@ withMappedFile file action = getCanonicalFileNameSafe file >>= lookupMMappedFile runWithFile (Just to) = action $ fmPath to runWithFile _ = action file -getCanonicalFileNameSafe :: (IOish m, GmEnv m) => FilePath -> m FilePath +getCanonicalFileNameSafe :: (IOish m) => FilePath -> m FilePath getCanonicalFileNameSafe fn = do let fn' = normalise fn pl <- liftIO $ rights <$> (mapM ((try :: IO FilePath -> IO (Either SomeException FilePath)) . canonicalizePath . joinPath) $ reverse $ inits $ splitPath' fn') diff --git a/core/src/GhcMod/World.hs b/core/GhcMod/World.hs similarity index 100% rename from core/src/GhcMod/World.hs rename to core/GhcMod/World.hs diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs index a7ba32d13..ab4b54ab4 100644 --- a/core/GhcModCore.hs +++ b/core/GhcModCore.hs @@ -40,12 +40,16 @@ module GhcModCore ( , loadMappedFile , loadMappedFileSource , unloadMappedFile + -- * HIE integration utilities + , getTypecheckedModuleGhc + , getTypecheckedModuleGhc' ) where import GhcMod.Cradle import GhcMod.FileMapping import GhcMod.Logging import GhcMod.Monad +import GhcMod.ModuleLoader import GhcMod.Output import GhcMod.Target import GhcMod.Types diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 751e3cbf9..ce9a0e88f 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -69,6 +69,7 @@ Library GhcMod.LightGhc GhcMod.Logger GhcMod.Logging + GhcMod.ModuleLoader GhcMod.Monad GhcMod.Monad.Env GhcMod.Monad.Log @@ -116,7 +117,7 @@ Library , fingertree < 0.2 && >= 0.1.1.0 , ghc-paths < 0.2 && >= 0.1.0.9 , ghc-syb-utils < 0.3 && >= 0.2.3 - , haskell-src-exts < 1.20 && >= 1.18 + , haskell-src-exts < 1.21 && >= 1.18 , hlint < 3.0 && >= 2.0.8 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 87b0e4543..0e386f98c 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -191,7 +191,7 @@ Library , ghc-paths < 0.2 && >= 0.1.0.9 , ghc-syb-utils < 0.3 && >= 0.2.3 , ghc-mod-core == 5.9.0.0 - , haskell-src-exts < 1.20 && >= 1.18 + , haskell-src-exts < 1.21 && >= 1.18 , hlint < 3.0 && >= 2.0.8 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 diff --git a/rundocker.sh b/rundocker.sh new file mode 100755 index 000000000..6a938c125 --- /dev/null +++ b/rundocker.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +# Start up a docker vm using the gitlab CI container + +# docker run --rm -i -t registry.gitlab.com/dxld/ghc-mod:ghc8.2.1-cabal-install2.0.0.0 /bin/bash +docker run --rm -i -t -v `pwd`:/root registry.gitlab.com/dxld/ghc-mod:ghc8.2.1-cabal-install2.0.0.0 /bin/bash From 47e200a728a575f407ee6f9893d9a1e77b1b5325 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 27 Jan 2018 19:59:25 +0200 Subject: [PATCH 08/50] Remove stale dependencies --- core/ghc-mod-core.cabal | 112 ---------------------------------------- 1 file changed, 112 deletions(-) diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index ce9a0e88f..3bac0a6b4 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -104,21 +104,17 @@ Library , directory , filepath , mtl - , old-time , process , template-haskell , time , transformers , base < 4.11 && >= 4.6.0.1 - , djinn-ghc < 0.1 && >= 0.0.2.2 , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 - , fingertree < 0.2 && >= 0.1.1.0 , ghc-paths < 0.2 && >= 0.1.0.9 , ghc-syb-utils < 0.3 && >= 0.2.3 , haskell-src-exts < 1.21 && >= 1.18 - , hlint < 3.0 && >= 2.0.8 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 , optparse-applicative < 0.15 && >= 0.13.0.0 @@ -128,7 +124,6 @@ Library , split < 0.3 && >= 0.2.2 , syb < 0.8 && >= 0.5.1 , temporary < 1.3 && >= 1.2.0.3 - , text < 1.3 && >= 1.2.1.3 , transformers-base < 0.5 && >= 0.4.4 , cabal-helper < 0.9 && >= 0.8 @@ -140,113 +135,6 @@ Library Build-Depends: convertible < 1.2 && >= 1.1.0.0 - --- Test-Suite doctest --- Type: exitcode-stdio-1.0 --- Default-Language: Haskell2010 --- HS-Source-Dirs: test --- Ghc-Options: -Wall --- Default-Extensions: ConstraintKinds, FlexibleContexts --- Main-Is: doctests.hs --- Build-Depends: base < 4.10 && >= 4.6.0.1 --- , doctest < 0.12 && >= 0.9.3 - - --- Test-Suite spec --- Default-Language: Haskell2010 --- Default-Extensions: ScopedTypeVariables, RecordWildCards, NamedFieldPuns, --- ConstraintKinds, FlexibleContexts, --- DataKinds, KindSignatures, TypeOperators, ViewPatterns --- Main-Is: Main.hs --- Hs-Source-Dirs: test, src --- Ghc-Options: -Wall -fno-warn-deprecations -threaded --- Type: exitcode-stdio-1.0 --- Other-Modules: Paths_ghc_mod --- Dir --- TestUtils - --- -- $ ls test/*Spec.hs | sed 's_^.*/\(.*\)\.hs$_\1_' | sort --- BrowseSpec --- CabalHelperSpec --- CaseSplitSpec --- CheckSpec --- CradleSpec --- CustomPackageDbSpec --- FileMappingSpec --- FindSpec --- FlagSpec --- GhcPkgSpec --- HomeModuleGraphSpec --- InfoSpec --- LangSpec --- LintSpec --- ListSpec --- MonadSpec --- PathsAndFilesSpec --- ShellParseSpec --- TargetSpec - --- Build-Depends: --- -- See Note [GHC Boot libraries] --- containers --- , directory --- , filepath --- , mtl --- , process --- , transformers - --- , base < 4.10 && >= 4.6.0.1 --- , fclabels < 2.1 && >= 2.0 --- , hspec < 2.4 && >= 2.0.0 --- , monad-journal < 0.8 && >= 0.4 --- , split < 0.3 && >= 0.2.2 --- , temporary < 1.3 && >= 1.2.0.3 - - --- if impl(ghc < 7.8) --- Build-Depends: convertible < 1.2 && >= 1.1.0.0 --- if impl(ghc >= 8.0) --- Build-Depends: ghc-boot - --- Build-Depends: --- cabal-helper < 0.8 && >= 0.7.1.0 --- , ghc < 8.2 && >= 7.6 --- , ghc-mod - - --- Test-Suite shelltest --- Default-Language: Haskell2010 --- Main-Is: ShellTest.hs --- Hs-Source-Dirs: shelltest --- Type: exitcode-stdio-1.0 --- Build-Tools: shelltest --- Build-Depends: base < 4.10 && >= 4.6.0.1 --- , process < 1.5 --- -- , shelltestrunner >= 1.3.5 --- if !flag(shelltest) --- Buildable: False - - --- Benchmark criterion --- Type: exitcode-stdio-1.0 --- Default-Language: Haskell2010 --- Default-Extensions: ScopedTypeVariables, RecordWildCards, NamedFieldPuns, --- ConstraintKinds, FlexibleContexts, --- DataKinds, KindSignatures, TypeOperators, ViewPatterns --- HS-Source-Dirs: bench, test --- Main-Is: Bench.hs --- Build-Depends: --- -- See Note [GHC Boot libraries] --- directory --- , filepath - --- , base < 4.10 && >= 4.6.0.1 --- , criterion < 1.2 && >= 1.1.1.0 --- , temporary < 1.3 && >= 1.2.0.3 - --- , ghc-mod --- Buildable: False - Flag shelltest Description: Enable/disable shelltest test-suite Default: False From 9cc749834aa6bacf57117f182cd282f2c5eaa556 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Wed, 14 Mar 2018 22:47:48 +0200 Subject: [PATCH 09/50] Initial preparation for cabal new-build Needs matching update in cabal-helper --- core/GhcMod/CabalHelper.hs | 9 ++++++--- core/GhcMod/Cradle.hs | 33 ++++++++++++++++++++++++--------- core/GhcMod/GhcPkg.hs | 2 ++ core/GhcMod/Types.hs | 2 ++ 4 files changed, 34 insertions(+), 12 deletions(-) diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index 1e82c39e9..cf95cd894 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -185,7 +185,10 @@ withCabal action = do case proj of CabalProject -> do gmLog GmDebug "" $ strDoc "reconfiguring Cabal project" - cabalReconfigure (optPrograms opts) crdl flgs + cabalReconfigure "configure" (optPrograms opts) crdl flgs + CabalNewProject -> do + gmLog GmDebug "" $ strDoc "reconfiguring Cabal new-build project" + cabalReconfigure "new-configure" (optPrograms opts) crdl flgs StackProject {} -> do gmLog GmDebug "" $ strDoc "reconfiguring Stack project" -- TODO: we could support flags for stack too, but it seems @@ -202,7 +205,7 @@ withCabal action = do action where - cabalReconfigure progs crdl flgs = do + cabalReconfigure cmd progs crdl flgs = do readProc <- gmReadProcess withDirectory_ (cradleRootDir crdl) $ do cusPkgStack <- maybe [] ((PackageDb "clear"):) <$> getCustomPkgDbStack @@ -220,7 +223,7 @@ withCabal action = do toFlag (f, False) = '-':f flagOpt = ["--flags", unwords $ map toFlag flgs] - liftIO $ void $ readProc (T.cabalProgram progs) ("configure":progOpts) "" + liftIO $ void $ readProc (T.cabalProgram progs) (cmd:progOpts) "" stackReconfigure deps crdl progs = do withDirectory_ (cradleRootDir crdl) $ do supported <- haveStackSupport diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 9226fd580..6def07299 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -87,15 +87,30 @@ cabalCradle cabalProg wdir = do gmLog GmInfo "" $ text "'cabal' executable wasn't found, trying next project type" mzero - gmLog GmInfo "" $ text "Using Cabal project at" <+>: text cabalDir - return Cradle { - cradleProject = CabalProject - , cradleCurrentDir = wdir - , cradleRootDir = cabalDir - , cradleTempDir = error "tmpDir" - , cradleCabalFile = Just cabalFile - , cradleDistDir = "dist" - } + isDistNewstyle <- liftIO $ doesDirectoryExist $ cabalDir "dist-newstyle" + -- TODO: consider a flag to choose new-build if neither "dist" nor "dist-newstyle" exist + -- Or default to is for cabal >= 2.0 ?, unless flag saying old style + if isDistNewstyle + then do + gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir + return Cradle { + cradleProject = CabalNewProject + , cradleCurrentDir = wdir + , cradleRootDir = cabalDir + , cradleTempDir = error "tmpDir" + , cradleCabalFile = Just cabalFile + , cradleDistDir = "dist-newstyle" + } + else do + gmLog GmInfo "" $ text "Using Cabal project at" <+>: text cabalDir + return Cradle { + cradleProject = CabalProject + , cradleCurrentDir = wdir + , cradleRootDir = cabalDir + , cradleTempDir = error "tmpDir" + , cradleCabalFile = Just cabalFile + , cradleDistDir = "dist" + } stackCradle :: (IOish m, GmLog m, GmOut m) => FilePath -> FilePath -> MaybeT m Cradle diff --git a/core/GhcMod/GhcPkg.hs b/core/GhcMod/GhcPkg.hs index 746b2eac9..b18b6caae 100644 --- a/core/GhcMod/GhcPkg.hs +++ b/core/GhcMod/GhcPkg.hs @@ -85,6 +85,8 @@ getPackageDbStack = do return $ [GlobalDb, db] CabalProject -> getCabalPackageDbStack + CabalNewProject -> + getCabalPackageDbStack (StackProject StackEnv {..}) -> return $ [GlobalDb, PackageDb seSnapshotPkgDb, PackageDb seLocalPkgDb] return $ fromMaybe stack mCusPkgStack diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index ecaf5911b..673a086d4 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -133,6 +133,7 @@ defaultOptions = Options { ---------------------------------------------------------------- data Project = CabalProject + | CabalNewProject | SandboxProject | PlainProject | StackProject StackEnv @@ -141,6 +142,7 @@ data Project = CabalProject isCabalHelperProject :: Project -> Bool isCabalHelperProject StackProject {} = True isCabalHelperProject CabalProject {} = True +isCabalHelperProject CabalNewProject {} = True isCabalHelperProject _ = False data StackEnv = StackEnv { From e3427d154045956af734fea71796142348fc7d37 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 11 Feb 2018 21:16:19 +0200 Subject: [PATCH 10/50] Support GHC 8.4 - Add cabal-helper local copy - Remove redundant packages, bump haskell-src-exts upper bound - Relax various upper bounds --- cabal.project | 1 + core/GhcMod/DynFlagsTH.hs | 37 +++++++++- core/GhcMod/Error.hs | 1 + core/GhcMod/Gap.hs | 85 ++++++++++++++++++---- core/GhcMod/LightGhc.hs | 8 +++ core/GhcMod/Logger.hs | 2 +- core/GhcMod/Options/Help.hs | 8 ++- core/GhcMod/Pretty.hs | 1 + core/GhcMod/SrcUtils.hs | 79 +++++++++++++++++---- core/GhcMod/Target.hs | 138 +++++++++++++++++++++++++++++++----- core/GhcMod/Types.hs | 10 +++ core/GhcModCore.hs | 4 ++ core/LICENSE | 1 + core/ghc-mod-core.cabal | 16 ++--- ghc-mod.cabal | 40 +++++------ test/CabalHelperSpec.hs | 2 +- test/CheckSpec.hs | 6 +- test/TestUtils.hs | 6 ++ 18 files changed, 363 insertions(+), 82 deletions(-) create mode 100644 core/LICENSE diff --git a/cabal.project b/cabal.project index 0d3711349..4b8b8e5f2 100644 --- a/cabal.project +++ b/cabal.project @@ -1,2 +1,3 @@ packages: . ./core + ../cabal-helper diff --git a/core/GhcMod/DynFlagsTH.hs b/core/GhcMod/DynFlagsTH.hs index 776c588f9..46827958e 100644 --- a/core/GhcMod/DynFlagsTH.hs +++ b/core/GhcMod/DynFlagsTH.hs @@ -22,7 +22,13 @@ module GhcMod.DynFlagsTH where import Language.Haskell.TH import Language.Haskell.TH.Syntax import Control.Applicative +#if __GLASGOW_HASKELL__ >= 804 +import GHC.LanguageExtensions +import qualified EnumSet as E +import qualified Data.Set as IS +#else import qualified Data.IntSet as IS +#endif import Data.Maybe import Data.Generics.Aliases import Data.Generics.Schemes @@ -83,6 +89,10 @@ deriveEqDynFlags qds = do , "FlushOut" , "FlushErr" , "Settings" -- I think these can't cange at runtime + , "LogFinaliser" -- added for ghc-8.2 + , "LogOutput" -- added for ghc-8.2 + , "OverridingBool" -- added for ghc-8.2 + , "Scheme" -- added for ghc-8.2 ] ignoredTypeOccNames = [ "OnOff" ] @@ -164,13 +174,26 @@ deriveEqDynFlags qds = do "generalFlags" -> checkIntSet "generalFlags" "warningFlags" -> checkIntSet "warningFlags" +#if __GLASGOW_HASKELL__ >= 804 + "dumpFlags" -> checkIntSet "dumpFlags" + "fatalWarningFlags" -> checkIntSet "fatalWarningFlags" + "extensionFlags" -> checkIntSet "extensionFlags" +#endif _ -> [e| [($(return fa) == $(return fb), if $(return fa) == $(return fb) then "" else ("default changed:" ++ fon) )] |] checkIntSet fieldName = do - let eqfn = [| let fn aa bb = r + let eqfn = [| let fn aa' bb' = r where +#if __GLASGOW_HASKELL__ >= 804 + aa = toSet aa' + bb = toSet bb' +#else + aa = aa' + bb = bb' +#endif + uni = IS.union aa bb dif = IS.intersection aa bb delta = IS.difference uni dif @@ -180,3 +203,15 @@ deriveEqDynFlags qds = do in fn |] [e| $(eqfn) $(return fa) $(return fb) |] + + +#if __GLASGOW_HASKELL__ >= 804 +toSet es = IS.fromList $ E.toList es + +deriving instance Ord GeneralFlag +deriving instance Ord DynFlags.WarningFlag +deriving instance Ord DynFlags.DumpFlag +deriving instance Ord DynFlags.LlvmTarget +deriving instance Ord Extension +deriving instance Eq LlvmTarget +#endif diff --git a/core/GhcMod/Error.hs b/core/GhcMod/Error.hs index 968c357b0..e04e1713a 100644 --- a/core/GhcMod/Error.hs +++ b/core/GhcMod/Error.hs @@ -49,6 +49,7 @@ import Paths_ghc_mod_core (version) import GhcMod.Types import GhcMod.Pretty +import Prelude hiding ( (<>) ) type GmError m = MonadError GhcModError m diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index dff6b87f3..91bed2556 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -47,8 +47,19 @@ module GhcMod.Gap ( , GhcMod.Gap.isSynTyCon , parseModuleHeader , mkErrStyle' +#if __GLASGOW_HASKELL__ < 804 , everythingStagedWithContext +#endif , withCleanupSession +#if __GLASGOW_HASKELL__ >= 804 + , GHC.GhcPs + , GHC.GhcRn + , GHC.GhcTc +#else + , GhcPs + , GhcRn + , GhcTc +#endif ) where import Control.Applicative hiding (empty) @@ -70,6 +81,7 @@ import NameSet import OccName import Outputable import PprTyThing +import IfaceSyn import StringBuffer import TcType import Var (varType) @@ -108,7 +120,10 @@ import TcRnTypes #endif #endif -#if MIN_VERSION_GLASGOW_HASKELL(8,0,1,20161117) +#if MIN_VERSION_GLASGOW_HASKELL(8,2,0,0) +import GHC hiding (ClsInst, withCleanupSession, setLogAction) +import qualified GHC (withCleanupSession) +#elif MIN_VERSION_GLASGOW_HASKELL(8,0,1,20161117) import GHC hiding (ClsInst, withCleanupSession) import qualified GHC (withCleanupSession) #elif __GLASGOW_HASKELL__ >= 706 @@ -125,7 +140,9 @@ import UniqFM (eltsUFM) import Module #endif -#if __GLASGOW_HASKELL__ >= 704 +#if __GLASGOW_HASKELL__ >= 804 +import qualified EnumSet as E (EnumSet, empty) +#elif __GLASGOW_HASKELL__ >= 704 import qualified Data.IntSet as I (IntSet, empty) #endif @@ -140,10 +157,12 @@ import Parser import SrcLoc import Packages import Data.Generics (GenericQ, extQ, gmapQ) +#if __GLASGOW_HASKELL__ < 804 import GHC.SYB.Utils (Stage(..)) +#endif import GhcMod.Types (Expression(..)) -import Prelude +import Prelude hiding ( (<>) ) ---------------------------------------------------------------- ---------------------------------------------------------------- @@ -284,7 +303,11 @@ fileModSummary :: GhcMonad m => FilePath -> m ModSummary fileModSummary file' = do mss <- getModuleGraph file <- liftIO $ canonicalizePath file' +#if __GLASGOW_HASKELL__ >= 804 + [ms] <- liftIO $ flip filterM (mgModSummaries mss) $ \m -> +#else [ms] <- liftIO $ flip filterM mss $ \m -> +#endif (Just file==) <$> canonicalizePath `traverse` ml_hs_file (ms_location m) return ms @@ -296,8 +319,14 @@ withInteractiveContext action = gbracket setup teardown body body _ = do topImports >>= setCtx action + topImports :: GhcMonad m => m [InteractiveImport] topImports = do +#if __GLASGOW_HASKELL__ >= 804 + mg <- getModuleGraph + ms <- filterM moduleIsInterpreted =<< map ms_mod <$> (return $ mgModSummaries mg) +#else ms <- filterM moduleIsInterpreted =<< map ms_mod <$> getModuleGraph +#endif let iis = map (IIModule . modName) ms #if __GLASGOW_HASKELL__ >= 704 return iis @@ -393,7 +422,7 @@ class HasType a where getType :: GhcMonad m => TypecheckedModule -> a -> m (Maybe (SrcSpan, Type)) -instance HasType (LHsBind Id) where +instance HasType (LHsBind GhcTc) where #if __GLASGOW_HASKELL__ >= 708 getType _ (L spn FunBind{fun_matches = m}) = return $ Just (spn, typ) where in_tys = mg_arg_tys m @@ -417,7 +446,10 @@ filterOutChildren get_thing xs infoThing :: GhcMonad m => (FilePath -> FilePath) -> Expression -> m SDoc infoThing m (Expression str) = do names <- parseName str -#if __GLASGOW_HASKELL__ >= 708 +#if __GLASGOW_HASKELL__ >= 804 + mb_stuffs <- mapM (getInfo False) names + let filtered = filterOutChildren (\(t,_f,_i,_fam,_doc) -> t) (catMaybes mb_stuffs) +#elif __GLASGOW_HASKELL__ >= 708 mb_stuffs <- mapM (getInfo False) names let filtered = filterOutChildren (\(t,_f,_i,_fam) -> t) (catMaybes mb_stuffs) #else @@ -426,7 +458,14 @@ infoThing m (Expression str) = do #endif return $ vcat (intersperse (text "") $ map (pprInfo m False) filtered) -#if __GLASGOW_HASKELL__ >= 708 +#if __GLASGOW_HASKELL__ >= 804 +pprInfo :: (FilePath -> FilePath) -> Bool -> (TyThing, GHC.Fixity, [ClsInst], [FamInst],SDoc) -> SDoc +pprInfo m _ (thing, fixity, insts, famInsts,_doc) + = pprTyThingInContextLoc' thing + $$ show_fixity fixity + $$ vcat (map pprInstance' insts) + $$ vcat (map pprFamInst' famInsts) +#elif __GLASGOW_HASKELL__ >= 708 pprInfo :: (FilePath -> FilePath) -> Bool -> (TyThing, GHC.Fixity, [ClsInst], [FamInst]) -> SDoc pprInfo m _ (thing, fixity, insts, famInsts) = pprTyThingInContextLoc' thing @@ -459,9 +498,9 @@ pprInfo m pefas (thing, fixity, insts) = showWithLoc (pprDefinedAt' (getName axiom)) $ hang (ptext (sLit "type instance") <+> pprTypeApp (coAxiomTyCon axiom) lhs_tys) 2 (equals <+> ppr rhs) -#else +# else pprFamInst' ispec = showWithLoc (pprDefinedAt' (getName ispec)) (pprFamInstHdr ispec) -#endif +# endif #else pprTyThingInContextLoc' pefas' thing' = showWithLoc (pprDefinedAt' thing') (pprTyThingInContext pefas' thing') #endif @@ -514,7 +553,7 @@ nameForUser = pprOccName . getOccName occNameForUser :: OccName -> SDoc occNameForUser = pprOccName -deSugar :: TypecheckedModule -> LHsExpr Id -> HscEnv +deSugar :: TypecheckedModule -> LHsExpr GhcTc -> HscEnv -> IO (Maybe CoreExpr) #if __GLASGOW_HASKELL__ >= 708 deSugar _ e hs_env = snd <$> deSugarExpr hs_env e @@ -555,7 +594,11 @@ fromTyThing _ = GtN ---------------------------------------------------------------- ---------------------------------------------------------------- -#if __GLASGOW_HASKELL__ >= 704 +#if __GLASGOW_HASKELL__ >= 804 +type WarnFlags = E.EnumSet WarningFlag +emptyWarnFlags :: WarnFlags +emptyWarnFlags = E.empty +#elif __GLASGOW_HASKELL__ >= 704 type WarnFlags = I.IntSet emptyWarnFlags :: WarnFlags emptyWarnFlags = I.empty @@ -568,15 +611,22 @@ emptyWarnFlags = [] ---------------------------------------------------------------- ---------------------------------------------------------------- +-- See https://ghc.haskell.org/trac/ghc/wiki/Migration/8.4#GHCAPIchanges +#if __GLASGOW_HASKELL__ <= 802 +type GhcPs = RdrName +type GhcRn = Name +type GhcTc = Id +#endif + #if __GLASGOW_HASKELL__ >= 708 -type GLMatch = LMatch RdrName (LHsExpr RdrName) +type GLMatch = LMatch GhcPs (LHsExpr GhcPs) type GLMatchI = LMatch Id (LHsExpr Id) #else -type GLMatch = LMatch RdrName +type GLMatch = LMatch GhcPs type GLMatchI = LMatch Id #endif -getClass :: [LInstDecl Name] -> Maybe (Name, SrcSpan) +getClass :: [LInstDecl GhcRn] -> Maybe (Name, SrcSpan) #if __GLASGOW_HASKELL__ >= 802 -- Instance declarations of sort 'instance F (G a)' getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = HsIB _ (L _ (HsForAllTy _ (L _ (HsAppTy (L _ (HsTyVar _ (L _ className))) _)))) _}))] = Just (className, loc) @@ -664,7 +714,7 @@ parseModuleHeader :: String -- ^ Haskell module source text (full Unicode is supported) -> DynFlags -> FilePath -- ^ the filename (for source locations) - -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName)) + -> Either ErrorMessages (WarningMessages, Located (HsModule GhcPs)) parseModuleHeader str dflags filename = let loc = mkRealSrcLoc (mkFastString filename) 1 1 @@ -672,7 +722,11 @@ parseModuleHeader str dflags filename = in case L.unP Parser.parseHeader (mkPState dflags buf loc) of +#if __GLASGOW_HASKELL__ >= 804 + PFailed _ sp err -> +#else PFailed sp err -> +#endif #if __GLASGOW_HASKELL__ >= 706 Left (unitBag (mkPlainErrMsg dflags sp err)) #else @@ -700,8 +754,10 @@ instance NFData ByteString where rnf (Chunk _ b) = rnf b #endif +#if __GLASGOW_HASKELL__ < 804 -- | Like 'everything', but avoid known potholes, based on the 'Stage' that -- generated the Ast. +-- everythingWithContext :: s -> (r -> r -> r) -> GenericQ (s -> (r, s)) -> GenericQ r everythingStagedWithContext :: Stage -> s -> (r -> r -> r) -> r -> GenericQ (s -> (r, s)) -> GenericQ r everythingStagedWithContext stage s0 f z q x | (const False @@ -716,6 +772,7 @@ everythingStagedWithContext stage s0 f z q x #endif fixity = const (stage Bool (r, s') = q x s0 +#endif withCleanupSession :: GhcMonad m => m a -> m a #if __GLASGOW_HASKELL__ >= 800 diff --git a/core/GhcMod/LightGhc.hs b/core/GhcMod/LightGhc.hs index 146f2c095..4edae7293 100644 --- a/core/GhcMod/LightGhc.hs +++ b/core/GhcMod/LightGhc.hs @@ -31,9 +31,17 @@ initStaticOpts = return () newLightEnv :: IOish m => (DynFlags -> LightGhc DynFlags) -> m HscEnv newLightEnv mdf = do df <- liftIO $ do +#if MIN_VERSION_GLASGOW_HASKELL(8,2,0,0) +#else initStaticOpts +#endif settings <- initSysTools (Just libdir) +#if __GLASGOW_HASKELL__ >= 804 + let llvmTgtList = [] -- TODO: where should this come from? + initDynFlags $ defaultDynFlags settings llvmTgtList +#else initDynFlags $ defaultDynFlags settings +#endif hsc_env <- liftIO $ newHscEnv df df' <- runLightGhc hsc_env $ mdf df diff --git a/core/GhcMod/Logger.hs b/core/GhcMod/Logger.hs index 3ccf89bdb..1affd11ea 100644 --- a/core/GhcMod/Logger.hs +++ b/core/GhcMod/Logger.hs @@ -19,7 +19,7 @@ import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef) import System.FilePath (normalise) import ErrUtils -import GHC +import GHC hiding ( convert ) import HscTypes import Outputable import qualified GHC as G diff --git a/core/GhcMod/Options/Help.hs b/core/GhcMod/Options/Help.hs index b23487cc5..5156f588f 100644 --- a/core/GhcMod/Options/Help.hs +++ b/core/GhcMod/Options/Help.hs @@ -14,6 +14,7 @@ -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see . {-# LANGUAGE OverloadedStrings, FlexibleInstances, GeneralizedNewtypeDeriving #-} +{-# LANGUAGE CPP #-} module GhcMod.Options.Help where @@ -33,6 +34,11 @@ type MyDoc = MyDocM (Maybe Doc) () instance IsString (MyDocM (Maybe Doc) a) where fromString = append . para +#if __GLASGOW_HASKELL__ >= 804 +instance Semigroup (MyDocM (Maybe Doc) ()) where + (<>) = mappend +#endif + instance Monoid (MyDocM (Maybe Doc) ()) where mappend a b = append $ doc a <> doc b mempty = append PP.empty @@ -47,7 +53,7 @@ append s = modify m >> return undefined m Nothing = Just s m (Just old) = Just $ old PP..$. s -infixr 7 \\ +infixr 7 \\ -- comment to sort out CPP (\\) :: MyDoc -> MyDoc -> MyDoc (\\) a b = append $ doc a PP.<+> doc b diff --git a/core/GhcMod/Pretty.hs b/core/GhcMod/Pretty.hs index d2737888c..acc219e63 100644 --- a/core/GhcMod/Pretty.hs +++ b/core/GhcMod/Pretty.hs @@ -40,6 +40,7 @@ import Outputable (SDoc, withPprStyleDoc) import GhcMod.Types import GhcMod.Doc import GhcMod.Gap (renderGm) +import Prelude hiding ( (<>)) renderSDoc :: GhcMonad m => SDoc -> m Doc renderSDoc sdoc = do diff --git a/core/GhcMod/SrcUtils.hs b/core/GhcMod/SrcUtils.hs index 30999f3f1..f16d7e1d0 100644 --- a/core/GhcMod/SrcUtils.hs +++ b/core/GhcMod/SrcUtils.hs @@ -1,5 +1,7 @@ -- TODO: remove CPP once Gap(ed) {-# LANGUAGE CPP, TupleSections, FlexibleInstances, Rank2Types #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module GhcMod.SrcUtils where @@ -9,12 +11,13 @@ import CoreUtils (exprType) import Data.Generics import Data.Maybe import Data.Ord as O -import GHC (LHsExpr, LPat, Id, DynFlags, SrcSpan, Type, Located, ParsedSource, RenamedSource, TypecheckedSource, GenLocated(L)) -import Var (Var) +import GHC (LHsExpr, LPat, DynFlags, SrcSpan, Type, Located, ParsedSource, RenamedSource, TypecheckedSource, GenLocated(L)) import qualified GHC as G import qualified Var as G import qualified Type as G +#if __GLASGOW_HASKELL__ < 804 import GHC.SYB.Utils +#endif import GhcMonad import qualified Language.Haskell.Exts as HE import GhcMod.Doc @@ -31,42 +34,56 @@ import qualified Data.Map as M ---------------------------------------------------------------- -instance HasType (LHsExpr Id) where +instance HasType (LHsExpr GhcTc) where getType tcm e = do hs_env <- G.getSession mbe <- liftIO $ Gap.deSugar tcm e hs_env return $ (G.getLoc e, ) <$> CoreUtils.exprType <$> mbe -instance HasType (LPat Id) where +instance HasType (LPat GhcTc) where getType _ (G.L spn pat) = return $ Just (spn, hsPatType pat) ---------------------------------------------------------------- +#if __GLASGOW_HASKELL__ >= 804 +-- | Stores mapping from monomorphic to polymorphic types +type CstGenQS = M.Map (G.IdP GhcTc) Type +-- | Generic type to simplify SYB definition +type CstGenQT m a = a GhcTc -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS) +#else -- | Stores mapping from monomorphic to polymorphic types -type CstGenQS = M.Map Var Type +type CstGenQS = M.Map G.Var Type -- | Generic type to simplify SYB definition -type CstGenQT a = forall m. GhcMonad m => a Id -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS) +type CstGenQT a = forall m. GhcMonad m => a G.Id -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS) +#endif -collectSpansTypes :: (GhcMonad m) => Bool -> G.TypecheckedModule -> (Int, Int) -> m [(SrcSpan, Type)] +collectSpansTypes :: forall m.(GhcMonad m) => Bool -> G.TypecheckedModule -> (Int, Int) -> m [(SrcSpan, Type)] collectSpansTypes withConstraints tcs lc = -- This walks AST top-down, left-to-right, while carrying CstGenQS down the tree -- (but not left-to-right) +#if __GLASGOW_HASKELL__ >= 804 + everythingWithContext M.empty (liftM2 (++)) +#else everythingStagedWithContext TypeChecker M.empty (liftM2 (++)) (return []) +#endif ((return [],) - `mkQ` (hsBind :: CstGenQT G.LHsBind) -- matches on binds - `extQ` (genericCT :: CstGenQT G.LHsExpr) -- matches on expressions - `extQ` (genericCT :: CstGenQT G.LPat) -- matches on patterns + `mkQ` (hsBind :: G.LHsBind GhcTc -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS)) -- matches on binds + `extQ` (genericCT :: G.LHsExpr GhcTc -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS)) -- matches on expressions + `extQ` (genericCT :: G.LPat GhcTc -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS)) -- matches on patterns + ) (G.tm_typechecked_source tcs) where -- Helper function to insert mapping into CstGenQS insExp x = M.insert (G.abe_mono x) (G.varType $ G.abe_poly x) -- If there is AbsBinds here, insert mapping into CstGenQS if needed + hsBind (L _ G.AbsBinds{abs_exports = es'}) s | withConstraints = (return [], foldr insExp s es') | otherwise = (return [], s) -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 804 +#elif __GLASGOW_HASKELL__ >= 800 -- TODO: move to Gap -- Note: this deals with bindings with explicit type signature, e.g. -- double :: Num a => a -> a @@ -83,20 +100,33 @@ collectSpansTypes withConstraints tcs lc = -- Otherwise, it's the same as other cases hsBind x s = genericCT x s -- Generic SYB function to get type + genericCT :: forall b . (Data (b GhcTc), HasType (Located (b GhcTc))) + => Located (b GhcTc) -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS) genericCT x s | withConstraints = (maybe [] (uncurry $ constrainedType (collectBinders x) s) <$> getType' x, s) | otherwise = (maybeToList <$> getType' x, s) +#if __GLASGOW_HASKELL__ >= 804 -- Collects everything with Id from LHsBind, LHsExpr, or LPat - collectBinders :: Data a => a -> [Id] + collectBinders :: Data a => a -> [G.IdP GhcTc] + collectBinders = listify (const True) +#else + -- Collects everything with Id from LHsBind, LHsExpr, or LPat + collectBinders :: Data a => a -> [G.Id] collectBinders = listifyStaged TypeChecker (const True) +#endif -- Gets monomorphic type with location + getType' :: forall t . (HasType (Located t)) => Located t -> m (Maybe (SrcSpan, Type)) getType' x@(L spn _) - | G.isGoodSrcSpan spn && spn `G.spans` lc + | G.isGoodSrcSpan spn && (spn `G.spans` lc) = getType tcs x | otherwise = return Nothing -- Gets constrained type - constrainedType :: [Var] -- ^ Binders in expression, i.e. anything with Id +#if __GLASGOW_HASKELL__ >= 804 + constrainedType :: [G.IdP GhcTc] -- ^ Binders in expression, i.e. anything with Id +#else + constrainedType :: [G.Var] -- ^ Binders in expression, i.e. anything with Id +#endif -> CstGenQS -- ^ Map from Id to polymorphic type -> SrcSpan -- ^ extent of expression, copied to result -> Type -- ^ monomorphic type @@ -112,10 +142,17 @@ collectSpansTypes withConstraints tcs lc = build x | Just cti <- x `M.lookup` s = let (preds', ctt) = getPreds cti +#if __GLASGOW_HASKELL__ >= 804 + -- list of type variables in monomorphic type + vts = listify G.isTyVar $ G.varType x + -- list of type variables in polymorphic type + tvm = listify G.isTyVarTy ctt +#else -- list of type variables in monomorphic type vts = listifyStaged TypeChecker G.isTyVar $ G.varType x -- list of type variables in polymorphic type tvm = listifyStaged TypeChecker G.isTyVarTy ctt +#endif in Just (preds', zip vts tvm) | otherwise = Nothing -- list of constraints @@ -138,22 +175,36 @@ collectSpansTypes withConstraints tcs lc = | otherwise = ([], x) listifySpans :: Typeable a => TypecheckedSource -> (Int, Int) -> [Located a] +#if __GLASGOW_HASKELL__ >= 804 +listifySpans tcs lc = listify p tcs +#else listifySpans tcs lc = listifyStaged TypeChecker p tcs +#endif where p (L spn _) = G.isGoodSrcSpan spn && spn `G.spans` lc listifyParsedSpans :: Typeable a => ParsedSource -> (Int, Int) -> [Located a] +#if __GLASGOW_HASKELL__ >= 804 +listifyParsedSpans pcs lc = listify p pcs +#else listifyParsedSpans pcs lc = listifyStaged Parser p pcs +#endif where p (L spn _) = G.isGoodSrcSpan spn && spn `G.spans` lc listifyRenamedSpans :: Typeable a => RenamedSource -> (Int, Int) -> [Located a] +#if __GLASGOW_HASKELL__ >= 804 +listifyRenamedSpans pcs lc = listify p pcs +#else listifyRenamedSpans pcs lc = listifyStaged Renamer p pcs +#endif where p (L spn _) = G.isGoodSrcSpan spn && spn `G.spans` lc +#if __GLASGOW_HASKELL__ < 804 listifyStaged :: Typeable r => Stage -> (r -> Bool) -> GenericQ [r] listifyStaged s p = everythingStaged s (++) [] ([] `mkQ` (\x -> [x | p x])) +#endif cmp :: SrcSpan -> SrcSpan -> Ordering cmp a b diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index 2294cfa8d..de39bc6e6 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -21,6 +21,9 @@ import Control.Arrow import Control.Applicative import Control.Category ((.)) import GHC +import qualified Hooks as GHC +import qualified HscTypes as GHC +import qualified GhcMonad as G #if __GLASGOW_HASKELL__ >= 800 import GHC.LanguageExtensions #endif @@ -146,16 +149,42 @@ runGmlT' :: IOish m -> GhcModT m a runGmlT' fns mdf action = runGmlTWith fns mdf id action --- | Run a GmlT action (i.e. a function in the GhcMonad) in the context --- of certain files or modules, with updated GHC flags and a final --- transformation +-- | Run a GmlT action (i.e. a function in the GhcMonad) in the context of +-- certain files or modules, with updated GHC flags, and updated ModuleGraph +runGmlTfm :: IOish m + => [Either FilePath ModuleName] + -> (forall gm. GhcMonad gm => DynFlags -> gm DynFlags) + -> Maybe (GHC.Hooks -> GHC.Hooks) + -> GmlT m a + -> GhcModT m a +runGmlTfm fns mdf mUpdateHooks action + = runGmlTWith' fns mdf mUpdateHooks id action + +-- | Run a GmlT action (i.e. a function in the GhcMonad) in the context of +-- certain files or modules, with updated GHC flags, updated ModuleGraph and a +-- final transformation runGmlTWith :: IOish m => [Either FilePath ModuleName] -> (forall gm. GhcMonad gm => DynFlags -> gm DynFlags) -> (GmlT m a -> GmlT m b) -> GmlT m a -> GhcModT m b -runGmlTWith efnmns' mdf wrapper action = do +runGmlTWith efnmns' mdf wrapper action = + runGmlTWith' efnmns' mdf Nothing wrapper action + +-- | Run a GmlT action (i.e. a function in the GhcMonad) in the context of +-- certain files or modules, with updated GHC flags, updated ModuleGraph and a +-- final transformation +runGmlTWith' :: IOish m + => [Either FilePath ModuleName] + -> (forall gm. GhcMonad gm => DynFlags -> gm DynFlags) + -> Maybe (GHC.Hooks -> GHC.Hooks) + -- ^ If a hook update is provided, force the reloading + -- of the specified targets + -> (GmlT m a -> GmlT m b) + -> GmlT m a + -> GhcModT m b +runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do crdl <- cradle Options { optGhcUserOptions } <- options @@ -163,9 +192,14 @@ runGmlTWith efnmns' mdf wrapper action = do ccfns = map (cradleCurrentDir crdl ) fns cfns <- mapM getCanonicalFileNameSafe ccfns let serfnmn = Set.fromList $ map Right mns ++ map Left cfns - opts <- targetGhcOptions crdl serfnmn + (opts, mappedStrs) <- targetGhcOptions crdl serfnmn let opts' = opts ++ ["-O0", "-fno-warn-missing-home-modules"] ++ optGhcUserOptions + gmVomit + "session-ghc-options" + (text "Using the following mapped files") + (intercalate " " $ map (("\""++) . (++"\"")) mappedStrs) + gmVomit "session-ghc-options" (text "Initializing GHC session with following options") @@ -182,28 +216,37 @@ runGmlTWith efnmns' mdf wrapper action = do mappedStrs <- getMMappedFilePaths let targetStrs = mappedStrs ++ map moduleNameString mns ++ cfns + gmVomit + "session-ghc-options" + (text "Using the following targets") + (intercalate " " $ map (("\""++) . (++"\"")) targetStrs) + unGmlT $ wrapper $ do - loadTargets opts targetStrs + loadTargets opts targetStrs mUpdateHooks action targetGhcOptions :: forall m. IOish m => Cradle -> Set (Either FilePath ModuleName) - -> GhcModT m [GHCOption] + -> GhcModT m ([GHCOption],[FilePath]) targetGhcOptions crdl sefnmn = do when (Set.null sefnmn) $ error "targetGhcOptions: no targets given" case cradleProject crdl of proj | isCabalHelperProject proj -> cabalOpts crdl - | otherwise -> sandboxOpts crdl + | otherwise -> do + opts <- sandboxOpts crdl + mappedStrs <- getMMappedFilePaths + return (opts, mappedStrs) where zipMap f l = l `zip` (f `map` l) - cabalOpts :: Cradle -> GhcModT m [String] + cabalOpts :: Cradle -> GhcModT m ([GHCOption],[FilePath]) cabalOpts Cradle{..} = do mcs <- cabalResolvedComponents - + mappedStrs <- getMMappedFilePaths + let mappedComps = zipMap (moduleComponents mcs . Left) mappedStrs let mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn candidates = findCandidates $ map snd mdlcs @@ -214,15 +257,22 @@ targetGhcOptions crdl sefnmn = do then do -- First component should be ChLibName, if no lib will take lexically first exe. let cns = filter (/= ChSetupHsName) $ Map.keys mcs + cn = head cns + mappedStrsInComp = map fst $ filter (Set.member cn . snd) mappedComps gmLog GmDebug "" $ strDoc $ "Could not find a component assignment, falling back to picking library component in cabal file." - return $ gmcGhcOpts $ fromJustNote "targetGhcOptions, no-assignment" $ Map.lookup (head cns) mcs + let opts = gmcGhcOpts (fromJustNote "targetGhcOptions, no-assignment" $ Map.lookup cn mcs) + ++ ["-Wno-missing-home-modules"] + return (opts, mappedStrsInComp) else do when noCandidates $ throwError $ GMECabalCompAssignment mdlcs let cn = pickComponent candidates - return $ gmcGhcOpts $ fromJustNote "targetGhcOptions" $ Map.lookup cn mcs + mappedStrsInComp = map fst $ filter (Set.member cn . snd) mappedComps + opts = gmcGhcOpts (fromJustNote "targetGhcOptions" $ Map.lookup cn mcs) + ++ ["-Wno-missing-home-modules"] + return (opts, mappedStrsInComp) resolvedComponentsCache :: IOish m => FilePath -> Cached (GhcModT m) GhcModState @@ -311,7 +361,7 @@ packageGhcOptions = do | otherwise -> sandboxOpts crdl -- also works for plain projects! -sandboxOpts :: (IOish m, GmEnv m) => Cradle -> m [String] +sandboxOpts :: (IOish m, GmEnv m) => Cradle -> m [GHCOption] sandboxOpts crdl = do mCusPkgDb <- getCustomPkgDbStack pkgDbStack <- liftIO $ getSandboxPackageDbStack @@ -367,8 +417,8 @@ resolveEntrypoint Cradle {..} c@GmComponent {..} = do -- ghc do the warning about it. Right now we run that module through -- resolveModule like any other resolveChEntrypoints :: FilePath -> ChEntrypoint -> IO [CompilationUnit] -resolveChEntrypoints _ (ChLibEntrypoint em om _) = - return $ map (Right . chModToMod) (em ++ om) +resolveChEntrypoints _ (ChLibEntrypoint em om sm) = + return $ map (Right . chModToMod) (em ++ om ++ sm) resolveChEntrypoints _ (ChExeEntrypoint main om) = return $ [Left main] ++ map (Right . chModToMod) om @@ -448,8 +498,8 @@ resolveGmComponents mcache cs = do same f a b = (f a) == (f b) -- | Set the files as targets and load them. -loadTargets :: IOish m => [GHCOption] -> [FilePath] -> GmlT m () -loadTargets opts targetStrs = do +loadTargets :: IOish m => [GHCOption] -> [FilePath] -> Maybe (GHC.Hooks -> GHC.Hooks) -> GmlT m () +loadTargets opts targetStrs mUpdateHooks = do targets' <- withLightHscEnv opts $ \env -> liftM (nubBy ((==) `on` targetId)) @@ -457,32 +507,51 @@ loadTargets opts targetStrs = do >>= mapM relativize let targets = map (\t -> t { targetAllowObjCode = False }) targets' + targetFileNames = concatMap filePathFromTarget targets gmLog GmDebug "loadTargets" $ text "Loading" <+>: fsep (map (text . showTargetId) targets) + + let filterModSums = isJust mUpdateHooks + gmLog GmDebug "loadTargets" $ + text "filterModSums" <+>: text (show filterModSums) + setTargets targets + when filterModSums $ updateModuleGraph setDynFlagsRecompile targetFileNames + mg <- depanal [] False let interp = needsHscInterpreted mg target <- hscTarget <$> getSessionDynFlags when (interp && target /= HscInterpreted) $ do - _ <- setSessionDynFlags . setHscInterpreted =<< getSessionDynFlags + let + setHooks :: DynFlags -> DynFlags + setHooks df = df { GHC.hooks = (fromMaybe id mUpdateHooks) (GHC.hooks df) } + _ <- setSessionDynFlags . setHscInterpreted . setHooks =<< getSessionDynFlags gmLog GmInfo "loadTargets" $ text "Target needs interpeter, switching to LinkInMemory/HscInterpreted. Perfectly normal if anything is using TemplateHaskell, QuasiQuotes or PatternSynonyms." + when filterModSums $ updateModuleGraph setDynFlagsRecompile targetFileNames + target' <- hscTarget <$> getSessionDynFlags case target' of HscNothing -> do void $ load LoadAllTargets +#if __GLASGOW_HASKELL__ >= 804 + forM_ (mgModSummaries mg) $ +#else forM_ mg $ +#endif handleSourceError (gmLog GmDebug "loadTargets" . text . show) . void . (parseModule >=> typecheckModule >=> desugarModule) HscInterpreted -> do void $ load LoadAllTargets _ -> error ("loadTargets: unsupported hscTarget") + when filterModSums $ updateModuleGraph unSetDynFlagsRecompile targetFileNames + gmLog GmDebug "loadTargets" $ text "Loading done" where @@ -496,8 +565,41 @@ loadTargets opts targetStrs = do showTargetId (Target (TargetModule s) _ _) = moduleNameString s showTargetId (Target (TargetFile s _) _ _) = s + filePathFromTarget (Target (TargetModule _) _ _) = [] + filePathFromTarget (Target (TargetFile s _) _ _) = [s] + + updateModuleGraph :: (GhcMonad m, GmState m, GmEnv m, + MonadIO m, GmLog m, GmOut m) + => (DynFlags -> DynFlags) -> [FilePath] -> m () + updateModuleGraph df fps = do + let + fpSet = Set.fromList fps + updateHooks df = df { GHC.hooks = (fromMaybe id mUpdateHooks) (GHC.hooks df)} + mustRecompile ms = case (ml_hs_file . ms_location) ms of + Nothing -> ms + Just f -> if Set.member f fpSet + then ms {ms_hspp_opts = (df . updateHooks) (ms_hspp_opts ms)} + else ms +#if __GLASGOW_HASKELL__ >= 804 + update s = s {hsc_mod_graph = mkModuleGraph $ map mustRecompile (mgModSummaries $ hsc_mod_graph s)} +#else + update s = s {hsc_mod_graph = map mustRecompile (hsc_mod_graph s)} +#endif + G.modifySession update + + setDynFlagsRecompile :: DynFlags -> DynFlags + setDynFlagsRecompile df = gopt_set df Opt_ForceRecomp + + unSetDynFlagsRecompile :: DynFlags -> DynFlags + unSetDynFlagsRecompile df = gopt_unset df Opt_ForceRecomp + needsHscInterpreted :: ModuleGraph -> Bool +#if __GLASGOW_HASKELL__ >= 804 +needsHscInterpreted mg = foo (mgModSummaries mg) + where foo = any $ \ms -> +#else needsHscInterpreted = any $ \ms -> +#endif let df = ms_hspp_opts ms in #if __GLASGOW_HASKELL__ >= 800 TemplateHaskell `xopt` df diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index 06d3a625a..a2720a94b 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -184,6 +184,11 @@ data GhcModLog = GhcModLog { gmLogMessages :: [(GmLogLevel, String, Doc)] } deriving (Show) +#if __GLASGOW_HASKELL__ >= 804 +instance Semigroup GhcModLog where + (<>) = mappend +#endif + instance Monoid GhcModLog where mempty = GhcModLog (Just GmPanic) (Last Nothing) mempty GhcModLog ml vd ls `mappend` GhcModLog ml' vd' ls' = @@ -275,6 +280,11 @@ instance Binary GmModuleGraph where swapMap :: Ord v => Map k v -> Map v k swapMap = Map.fromList . map (\(x, y) -> (y, x)) . Map.toList +#if __GLASGOW_HASKELL__ >= 804 +instance Semigroup GmModuleGraph where + (<>) = mappend +#endif + instance Monoid GmModuleGraph where mempty = GmModuleGraph mempty mappend (GmModuleGraph a) (GmModuleGraph a') = diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs index a7ba32d13..ab4b54ab4 100644 --- a/core/GhcModCore.hs +++ b/core/GhcModCore.hs @@ -40,12 +40,16 @@ module GhcModCore ( , loadMappedFile , loadMappedFileSource , unloadMappedFile + -- * HIE integration utilities + , getTypecheckedModuleGhc + , getTypecheckedModuleGhc' ) where import GhcMod.Cradle import GhcMod.FileMapping import GhcMod.Logging import GhcMod.Monad +import GhcMod.ModuleLoader import GhcMod.Output import GhcMod.Target import GhcMod.Types diff --git a/core/LICENSE b/core/LICENSE new file mode 100644 index 000000000..9f26b637f --- /dev/null +++ b/core/LICENSE @@ -0,0 +1 @@ +Foo \ No newline at end of file diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index e077f3a61..ddc5afed7 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -54,6 +54,7 @@ Library GhcMod.LightGhc GhcMod.Logger GhcMod.Logging + GhcMod.ModuleLoader GhcMod.Monad GhcMod.Monad.Env GhcMod.Monad.Log @@ -88,40 +89,35 @@ Library , directory , filepath , mtl - , old-time , process , template-haskell , time , transformers - , base < 4.11 && >= 4.6.0.1 - , djinn-ghc < 0.1 && >= 0.0.2.2 + , base < 4.12 && >= 4.6.0.1 , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 - , fingertree < 0.2 && >= 0.1.1.0 , ghc-paths < 0.2 && >= 0.1.0.9 - , ghc-syb-utils < 0.3 && >= 0.2.3 - , haskell-src-exts < 1.20 && >= 1.18 - , hlint < 3.0 && >= 2.0.8 + , haskell-src-exts < 1.21 && >= 1.18 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 , optparse-applicative < 0.15 && >= 0.13.0.0 , pipes < 4.4 && >= 4.1 , safe < 0.4 && >= 0.3.9 - , semigroups < 0.19 && >= 0.10.0 , split < 0.3 && >= 0.2.2 , syb < 0.8 && >= 0.5.1 , temporary < 1.3 && >= 1.2.0.3 - , text < 1.3 && >= 1.2.1.3 , transformers-base < 0.5 && >= 0.4.4 , cabal-helper < 0.9 && >= 0.8.0.2 - , ghc < 8.4 && >= 7.6 + , ghc < 8.5 && >= 7.6 if impl(ghc >= 8.0) Build-Depends: ghc-boot if impl(ghc < 7.8) Build-Depends: convertible < 1.2 && >= 1.1.0.0 + if impl(ghc < 8.4) + Build-Depends: ghc-syb-utils < 0.3 && >= 0.2.3 Source-Repository head Type: git diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 71ebb09b4..52e8914f0 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -135,18 +135,17 @@ Library , time , transformers - , base < 4.11 && >= 4.6.0.1 + , base < 4.12 && >= 4.6.0.1 , djinn-ghc < 0.1 && >= 0.0.2.2 - , extra < 1.6 && >= 1.4 + , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 - , ghc-syb-utils < 0.3 && >= 0.2.3 , ghc-mod-core == 5.9.0.0 - , haskell-src-exts < 1.20 && >= 1.18 - , hlint < 2.1 && >= 2.0.8 + , haskell-src-exts < 1.21 && >= 1.18 + , hlint < 2.2 && >= 2.0.8 , monad-control < 1.1 && >= 1 - , monad-journal < 0.8 && >= 0.4 - , optparse-applicative < 0.14 && >= 0.13.0.0 + , monad-journal < 0.9 && >= 0.4 + , optparse-applicative < 0.15 && >= 0.13.0.0 , pipes < 4.4 && >= 4.1 , safe < 0.4 && >= 0.3.9 , semigroups < 0.19 && >= 0.10.0 @@ -157,11 +156,12 @@ Library , transformers-base < 0.5 && >= 0.4.4 , cabal-helper < 0.9 && >= 0.8.0.0 - , ghc < 8.4 && >= 7.8 - , ghc-mod-core + , ghc < 8.5 && >= 7.8 if impl(ghc >= 8.0) Build-Depends: ghc-boot + if impl(ghc < 8.4) + Build-Depends: ghc-syb-utils < 0.3 && >= 0.2.3 Executable ghc-mod Default-Language: Haskell2010 @@ -182,14 +182,14 @@ Executable ghc-mod , mtl , process - , base < 4.11 && >= 4.6.0.1 + , base < 4.12 && >= 4.6.0.1 , fclabels < 2.1 && >= 2.0 , monad-control < 1.1 && >= 1 - , optparse-applicative < 0.14 && >= 0.13.0.0 + , optparse-applicative < 0.15 && >= 0.13.0.0 , semigroups < 0.19 && >= 0.10.0 , split < 0.3 && >= 0.2.2 - , ghc < 8.4 && >= 7.8 + , ghc < 8.5 && >= 7.8 , ghc-mod , ghc-mod-core @@ -213,7 +213,7 @@ Executable ghc-modi , process , time - , base < 4.11 && >= 4.6.0.1 + , base < 4.12 && >= 4.6.0.1 , ghc-mod , ghc-mod-core @@ -226,7 +226,7 @@ Test-Suite doctest Ghc-Options: -Wall Default-Extensions: ConstraintKinds, FlexibleContexts Main-Is: doctests.hs - Build-Depends: base < 4.11 && >= 4.6.0.1 + Build-Depends: base < 4.12 && >= 4.6.0.1 , doctest < 0.14 && >= 0.11.3 Test-Suite spec @@ -273,10 +273,10 @@ Test-Suite spec , process , transformers - , base < 4.11 && >= 4.6.0.1 + , base < 4.12 && >= 4.6.0.1 , fclabels < 2.1 && >= 2.0 - , hspec < 2.5 && >= 2.0.0 - , monad-journal < 0.8 && >= 0.4 + , hspec < 2.6 && >= 2.0.0 + , monad-journal < 0.9 && >= 0.4 , split < 0.3 && >= 0.2.2 , temporary < 1.3 && >= 1.2.0.3 @@ -288,7 +288,7 @@ Test-Suite spec Build-Depends: cabal-helper < 0.9 && >= 0.8.0.0 - , ghc < 8.4 && >= 7.8 + , ghc < 8.5 && >= 7.8 , ghc-mod , ghc-mod-core @@ -300,7 +300,7 @@ Test-Suite shelltest Type: exitcode-stdio-1.0 if flag(shelltest) Build-Tools: shelltest - Build-Depends: base < 4.11 && >= 4.6.0.1 + Build-Depends: base < 4.12 && >= 4.6.0.1 , process < 1.5 -- , shelltestrunner >= 1.3.5 if !flag(shelltest) @@ -320,7 +320,7 @@ Benchmark criterion directory , filepath - , base < 4.11 && >= 4.6.0.1 + , base < 4.12 && >= 4.6.0.1 , criterion < 1.2 && >= 1.1.1.0 , temporary < 1.3 && >= 1.2.0.3 diff --git a/test/CabalHelperSpec.hs b/test/CabalHelperSpec.hs index f2119b024..43cd33506 100644 --- a/test/CabalHelperSpec.hs +++ b/test/CabalHelperSpec.hs @@ -86,7 +86,7 @@ spec = do opts <- map gmcGhcOpts <$> runD' tdir getComponents let ghcOpts = head opts pkgs = pkgOptions ghcOpts - pkgs `shouldBe` ["Cabal","base"] + pkgs `shouldBe` ["base","Cabal"] test diff --git a/test/CheckSpec.hs b/test/CheckSpec.hs index efe024cd2..c14d1603c 100644 --- a/test/CheckSpec.hs +++ b/test/CheckSpec.hs @@ -64,8 +64,10 @@ spec = do it "works with cabal builtin preprocessors" $ do withDirectory_ "test/data/cabal-preprocessors" $ do _ <- system "cabal clean" - _ <- system "cabal build" - res <- runD $ checkSyntax ["Main.hs"] + -- _ <- system "cabal build" + _ <- system "cabal build -v3" + -- res <- runD $ checkSyntax ["Main.hs"] + res <- runV $ checkSyntax ["Main.hs"] res `shouldBe` "Preprocessed.hsc:3:1:Warning: Top-level binding with no type signature: warning :: ()\n" it "Uses the right qualification style" $ do diff --git a/test/TestUtils.hs b/test/TestUtils.hs index 3d252f151..e487a22a5 100644 --- a/test/TestUtils.hs +++ b/test/TestUtils.hs @@ -3,6 +3,7 @@ module TestUtils ( run , runD , runD' + , runV , runE , runNullLog , runGmOutDef @@ -77,6 +78,11 @@ runD' :: FilePath -> GhcModT IO a -> IO a runD' dir = extract . runGhcModTSpec' dir (setLogLevel testLogLevel defaultOptions) +-- | Run GhcMod with default options +runV :: GhcModT IO a -> IO a +runV = + extract . runGhcModTSpec (setLogLevel GmVomit defaultOptions) + setLogLevel :: GmLogLevel -> Options -> Options setLogLevel = set (lOoptLogLevel . lOptOutput) From 9e07bc0429c59382a76cfeda21ac3d70e2a7d938 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 15 Apr 2018 16:47:13 +0200 Subject: [PATCH 11/50] Add ModuleLoader --- core/GhcMod/ModuleLoader.hs | 138 ++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 core/GhcMod/ModuleLoader.hs diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs new file mode 100644 index 000000000..8fbf0ba01 --- /dev/null +++ b/core/GhcMod/ModuleLoader.hs @@ -0,0 +1,138 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE OverloadedStrings #-} +-- | Uses GHC hooks to load a TypecheckedModule + +module GhcMod.ModuleLoader + ( getTypecheckedModuleGhc + , getTypecheckedModuleGhc' + ) where + +import Control.Monad.IO.Class + +import qualified Data.Map as Map +import Data.IORef + +import qualified GhcMod.Monad as GM +import qualified GhcMod.Target as GM +import qualified GhcMod.Types as GM + +import GHC (TypecheckedModule) +import qualified GHC +import qualified DynFlags as GHC +import qualified GhcMonad as GHC +import qualified Hooks as GHC +import qualified HscMain as GHC +import qualified HscTypes as GHC +import qualified TcRnMonad as GHC + +import System.Directory +import System.FilePath + +-- --------------------------------------------------------------------- + +getMappedFileName :: FilePath -> GM.FileMappingMap -> FilePath +getMappedFileName fname mfs = + case Map.lookup fname mfs of + Just fm -> GM.fmPath fm + Nothing -> fname + +canonicalizeModSummary :: (MonadIO m) => + GHC.ModSummary -> m (Maybe FilePath) +canonicalizeModSummary = + traverse (liftIO . canonicalizePath) . GHC.ml_hs_file . GHC.ms_location + +tweakModSummaryDynFlags :: GHC.ModSummary -> GHC.ModSummary +tweakModSummaryDynFlags ms = + let df = GHC.ms_hspp_opts ms + in ms { GHC.ms_hspp_opts = GHC.gopt_set df GHC.Opt_KeepRawTokenStream } + +-- | Gets a TypecheckedModule from a given file +-- The `wrapper` allows arbitary data to be captured during +-- the compilation process, like errors and warnings +-- Appends the parent directories of all the mapped files +-- to the includePaths for CPP purposes. +-- Use in combination with `runActionInContext` for best results +getTypecheckedModuleGhc' :: GM.IOish m + => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule) +getTypecheckedModuleGhc' wrapper targetFile = do + cfileName <- liftIO $ canonicalizePath targetFile + mfs <- GM.getMMappedFiles + mFileName <- liftIO . canonicalizePath $ getMappedFileName cfileName mfs + ref <- liftIO $ newIORef Nothing + let keepInfo = pure . (mFileName ==) + saveModule = writeIORef ref . Just + res <- getTypecheckedModuleGhc wrapper [cfileName] keepInfo saveModule + mtm <- liftIO $ readIORef ref + return (res, mtm) + +-- | like getTypecheckedModuleGhc' but allows you to keep an arbitary number of Modules +-- `keepInfo` decides which TypecheckedModule to keep +-- `saveModule` is the callback that is passed the TypecheckedModule +getTypecheckedModuleGhc :: GM.IOish m + => (GM.GmlT m () -> GM.GmlT m a) -> [FilePath] -> (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GM.GhcModT m a +getTypecheckedModuleGhc wrapper targetFiles keepInfo saveModule = do + mfs <- GM.getMMappedFiles + let ips = map takeDirectory $ Map.keys mfs + setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } + GM.runGmlTWith' (map Left targetFiles) + (return . setIncludePaths) + (Just $ updateHooks keepInfo saveModule) + wrapper + (return ()) + +updateHooks + :: (FilePath -> IO Bool) + -> (TypecheckedModule -> IO ()) + -> GHC.Hooks + -> GHC.Hooks +updateHooks fp ref hooks = hooks { +#if __GLASGOW_HASKELL__ <= 710 + GHC.hscFrontendHook = Just $ hscFrontend fp ref +#else + GHC.hscFrontendHook = Just $ fmap GHC.FrontendTypecheck . hscFrontend fp ref +#endif + } + + +-- | Warning: discards all changes to Session +runGhcInHsc :: GHC.Ghc a -> GHC.Hsc a +runGhcInHsc action = do + env <- GHC.getHscEnv + session <- liftIO $ newIORef env + liftIO $ GHC.reflectGhc action $ GHC.Session session + + +-- | Frontend hook that keeps the TypecheckedModule for its first argument +-- and stores it in the IORef passed to it +hscFrontend :: (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GHC.ModSummary -> GHC.Hsc GHC.TcGblEnv +hscFrontend keepInfoFunc saveModule mod_summary = do + mfn <- canonicalizeModSummary mod_summary + -- md = GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod mod_summary + keepInfo <- case mfn of + Just fileName -> liftIO $ keepInfoFunc fileName + Nothing -> pure False + -- liftIO $ debugm $ "hscFrontend: got mod,file" ++ show (md, mfn) + if keepInfo + then runGhcInHsc $ do + let modSumWithRaw = tweakModSummaryDynFlags mod_summary + + p' <- GHC.parseModule modSumWithRaw + let p = p' {GHC.pm_mod_summary = mod_summary} + tc <- GHC.typecheckModule p + let tc_gbl_env = fst $ GHC.tm_internals_ tc + + liftIO $ saveModule tc + return tc_gbl_env + else do + hpm <- GHC.hscParse' mod_summary + hsc_env <- GHC.getHscEnv +#if __GLASGOW_HASKELL__ >= 804 + -- tcRnModule' :: ModSummary -> Bool -> HsParsedModule -> Hsc TcGblEnv + GHC.tcRnModule' mod_summary False hpm +#else + GHC.tcRnModule' hsc_env mod_summary False hpm +#endif + +-- --------------------------------------------------------------------- + From fd02f84cbcaf96a40c51b62da4aa6729561f61b5 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Tue, 24 Apr 2018 21:41:46 +0200 Subject: [PATCH 12/50] Update for GHC 8.4.2, removing auto command - As djinn-ghc is not updated. - Update for hie integration --- GhcMod.hs | 2 +- GhcMod/Exe/CaseSplit.hs | 12 ++++++---- GhcMod/Exe/Debug.hs | 2 +- GhcMod/Exe/FillSig.hs | 38 ++++++++++++++++-------------- GhcMod/Exe/Test.hs | 4 ++++ core/GhcMod/SrcUtils.hs | 13 +++++++--- ghc-mod.cabal | 6 ++--- src/GhcMod/Exe/Options/Commands.hs | 15 +++++++----- src/GhcModMain.hs | 2 +- 9 files changed, 56 insertions(+), 38 deletions(-) diff --git a/GhcMod.hs b/GhcMod.hs index 893475901..1e0b6e3f7 100644 --- a/GhcMod.hs +++ b/GhcMod.hs @@ -48,7 +48,7 @@ module GhcMod ( , splits , sig , refine - , auto + -- , auto , modules , languages , flags diff --git a/GhcMod/Exe/CaseSplit.hs b/GhcMod/Exe/CaseSplit.hs index d866fb6f2..80afd35a0 100644 --- a/GhcMod/Exe/CaseSplit.hs +++ b/GhcMod/Exe/CaseSplit.hs @@ -12,7 +12,7 @@ import System.FilePath import Prelude import qualified DataCon as Ty -import GHC (GhcMonad, LPat, Id, ParsedModule(..), TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) +import GHC (GhcMonad, LPat, ParsedModule(..), TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) import qualified GHC as G import Outputable (PprStyle) import qualified TyCon as Ty @@ -88,7 +88,7 @@ getSrcSpanTypeForFnSplit :: GhcMonad m => G.ModSummary -> Int -> Int -> m (Maybe getSrcSpanTypeForFnSplit modSum lineNo colNo = do p@ParsedModule{pm_parsed_source = _pms} <- G.parseModule modSum tcm@TypecheckedModule{tm_typechecked_source = tcs} <- G.typecheckModule p - let varPat = find isPatternVar $ listifySpans tcs (lineNo, colNo) :: Maybe (LPat Id) + let varPat = find isPatternVar $ listifySpans tcs (lineNo, colNo) :: Maybe (LPat Gap.GhcTc) match = last $ listifySpans tcs (lineNo, colNo) :: Gap.GLMatchI case varPat of Nothing -> return Nothing @@ -96,7 +96,9 @@ getSrcSpanTypeForFnSplit modSum lineNo colNo = do varT <- Gap.getType tcm varPat' -- Finally we get the type of the var case varT of Just varT' -> -#if __GLASGOW_HASKELL__ >= 710 +#if __GLASGOW_HASKELL__ >= 804 + let (L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match +#elif __GLASGOW_HASKELL__ >= 710 let (L matchL (G.Match _ _ _ (G.GRHSs rhsLs _))) = match #else let (L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match @@ -104,11 +106,11 @@ getSrcSpanTypeForFnSplit modSum lineNo colNo = do in return $ Just (SplitInfo (getPatternVarName varPat') matchL varT' (map G.getLoc rhsLs) ) _ -> return Nothing -isPatternVar :: LPat Id -> Bool +isPatternVar :: LPat Gap.GhcTc -> Bool isPatternVar (L _ (G.VarPat _)) = True isPatternVar _ = False -getPatternVarName :: LPat Id -> G.Name +getPatternVarName :: LPat Gap.GhcTc -> G.Name #if __GLASGOW_HASKELL__ >= 800 getPatternVarName (L _ (G.VarPat (L _ vName))) = G.getName vName #else diff --git a/GhcMod/Exe/Debug.hs b/GhcMod/Exe/Debug.hs index 2ba7ac556..7005bbb48 100644 --- a/GhcMod/Exe/Debug.hs +++ b/GhcMod/Exe/Debug.hs @@ -123,7 +123,7 @@ componentInfo ts = do mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn candidates = findCandidates $ map snd mdlcs cn = pickComponent candidates - opts <- targetGhcOptions crdl sefnmn + (opts,_) <- targetGhcOptions crdl sefnmn return $ unlines $ [ "Matching Components:\n" ++ renderGm (nest 4 $ diff --git a/GhcMod/Exe/FillSig.hs b/GhcMod/Exe/FillSig.hs index c8bb9255a..e5efb84a5 100644 --- a/GhcMod/Exe/FillSig.hs +++ b/GhcMod/Exe/FillSig.hs @@ -4,15 +4,14 @@ module GhcMod.Exe.FillSig ( sig , refine - , auto + -- , auto ) where import Data.Char (isSymbol) import Data.Function (on) import Data.Functor -import Data.List (find, nub, sortBy) +import Data.List (find, sortBy) import qualified Data.Map as M -import Data.Maybe (catMaybes) import Prelude import Exception (ghandle, SomeException(..)) @@ -20,7 +19,6 @@ import GHC (GhcMonad, Id, ParsedModule(..), TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) import Pretty (($$), text, nest) import qualified GHC as G -import qualified Name as G import Outputable (PprStyle) import qualified Type as Ty import qualified HsBinds as Ty @@ -28,7 +26,7 @@ import qualified Class as Ty import qualified Var as Ty import qualified HsPat as Ty import qualified Language.Haskell.Exts as HE -import Djinn.GHC +-- import Djinn.GHC import qualified GhcMod.Gap as Gap import GhcMod.Convert @@ -51,7 +49,7 @@ import GHC (unLoc) -- Possible signatures we can find: function or instance data SigInfo - = Signature SrcSpan [G.RdrName] (G.HsType G.RdrName) + = Signature SrcSpan [G.RdrName] (G.HsType Gap.GhcPs) | InstanceDecl SrcSpan G.Class | TyFamDecl SrcSpan G.RdrName TyFamType {- True if closed -} [G.RdrName] @@ -115,7 +113,7 @@ getSignature :: GhcMonad m => G.ModSummary -> Int -> Int -> m (Maybe SigInfo) getSignature modSum lineNo colNo = do p@ParsedModule{pm_parsed_source = ps} <- G.parseModule modSum -- Inspect the parse tree to find the signature - case listifyParsedSpans ps (lineNo, colNo) :: [G.LHsDecl G.RdrName] of + case listifyParsedSpans ps (lineNo, colNo) :: [G.LHsDecl Gap.GhcPs] of #if __GLASGOW_HASKELL__ >= 802 [L loc (G.SigD (Ty.TypeSig names (G.HsWC _ (G.HsIB _ (L _ ty) _))))] -> #elif __GLASGOW_HASKELL__ >= 800 @@ -279,7 +277,7 @@ class FnArgsInfo ty name | ty -> name, name -> ty where getFnName :: DynFlags -> PprStyle -> name -> String getFnArgs :: ty -> [FnArg] -instance FnArgsInfo (G.HsType G.RdrName) (G.RdrName) where +instance FnArgsInfo (G.HsType Gap.GhcPs) (G.RdrName) where getFnName dflag style name = showOccName dflag style $ Gap.occName name #if __GLASGOW_HASKELL__ >= 800 getFnArgs (G.HsForAllTy _ (L _ iTy)) @@ -421,7 +419,7 @@ findVar dflag style tcm tcs lineNo colNo = _ -> return Nothing _ -> return Nothing where - lst :: [G.LHsExpr Id] + lst :: [G.LHsExpr Gap.GhcTc] lst = sortBy (cmp `on` G.getLoc) $ listifySpans tcs (lineNo, colNo) infinitePrefixSupply :: String -> [String] @@ -432,7 +430,7 @@ doParen :: Bool -> String -> String doParen False s = s doParen True s = if ' ' `elem` s then '(':s ++ ")" else s -isSearchedVar :: Id -> G.HsExpr Id -> Bool +isSearchedVar :: Id -> G.HsExpr Gap.GhcTc -> Bool #if __GLASGOW_HASKELL__ >= 800 isSearchedVar i (G.HsVar (L _ i2)) = i == i2 #else @@ -444,7 +442,8 @@ isSearchedVar _ _ = False ---------------------------------------------------------------- -- REFINE AUTOMATICALLY ---------------------------------------------------------------- - +{- +This function needs djinn, which does not seem to be supported any more auto :: IOish m => FilePath -- ^ A target file. -> Int -- ^ Line number. @@ -516,10 +515,10 @@ tyThingsToInfo (G.AnId i : xs) = tyThingsToInfo (_:xs) = tyThingsToInfo xs -- Find the Id of the function and the pattern where the hole is located -getPatsForVariable :: G.TypecheckedSource -> (Int,Int) -> (Id, [Ty.LPat Id]) +getPatsForVariable :: G.TypecheckedSource -> (Int,Int) -> (Id, [Ty.LPat Gap.GhcTc]) getPatsForVariable tcs (lineNo, colNo) = let (L _ bnd:_) = sortBy (cmp `on` G.getLoc) $ - listifySpans tcs (lineNo, colNo) :: [G.LHsBind Id] + listifySpans tcs (lineNo, colNo) :: [G.LHsBind Gap.GhcTc] in case bnd of G.PatBind { Ty.pat_lhs = L ploc pat } -> case pat of Ty.ConPatIn (L _ i) _ -> (i, [L ploc pat]) @@ -527,19 +526,22 @@ getPatsForVariable tcs (lineNo, colNo) = G.FunBind { Ty.fun_id = L _ funId } -> let m = sortBy (cmp `on` G.getLoc) $ listifySpans tcs (lineNo, colNo) #if __GLASGOW_HASKELL__ >= 708 - :: [G.LMatch Id (G.LHsExpr Id)] + :: [G.LMatch Gap.GhcTc (G.LHsExpr Gap.GhcTc)] #else - :: [G.LMatch Id] + :: [G.LMatch Gap.GhcTc] #endif -#if __GLASGOW_HASKELL__ >= 710 +#if __GLASGOW_HASKELL__ >= 804 + (L _ (G.Match _ pats _):_) = m +#elif __GLASGOW_HASKELL__ >= 710 (L _ (G.Match _ pats _ _):_) = m #else (L _ (G.Match pats _ _):_) = m #endif in (funId, pats) _ -> (error "This should never happen", []) +-} -getBindingsForPat :: Ty.Pat Id -> M.Map G.Name Type +getBindingsForPat :: Ty.Pat Gap.GhcTc -> M.Map G.Name Type #if __GLASGOW_HASKELL__ >= 800 getBindingsForPat (Ty.VarPat (L _ i)) = M.singleton (G.getName i) (Ty.varType i) #else @@ -568,7 +570,7 @@ getBindingsForPat (Ty.ConPatIn (L _ i) d) = getBindingsForPat (Ty.ConPatOut { Ty.pat_args = d }) = getBindingsForRecPat d getBindingsForPat _ = M.empty -getBindingsForRecPat :: Ty.HsConPatDetails Id -> M.Map G.Name Type +getBindingsForRecPat :: Ty.HsConPatDetails Gap.GhcTc -> M.Map G.Name Type #if __GLASGOW_HASKELL__ >= 800 getBindingsForRecPat (G.PrefixCon args) = #else diff --git a/GhcMod/Exe/Test.hs b/GhcMod/Exe/Test.hs index d3901270f..53d1801ae 100644 --- a/GhcMod/Exe/Test.hs +++ b/GhcMod/Exe/Test.hs @@ -22,7 +22,11 @@ test f = runGmlT' [Left f] (fmap setHscInterpreted . deferErrors) $ do mg <- getModuleGraph root <- cradleRootDir <$> cradle f' <- makeRelative root <$> liftIO (canonicalizePath f) +#if __GLASGOW_HASKELL__ >= 804 + let Just ms = find ((==Just f') . ml_hs_file . ms_location) (mgModSummaries mg) +#else let Just ms = find ((==Just f') . ml_hs_file . ms_location) mg +#endif mdl = ms_mod ms mn = moduleName mdl diff --git a/core/GhcMod/SrcUtils.hs b/core/GhcMod/SrcUtils.hs index f16d7e1d0..4a5f5be4b 100644 --- a/core/GhcMod/SrcUtils.hs +++ b/core/GhcMod/SrcUtils.hs @@ -57,8 +57,15 @@ type CstGenQS = M.Map G.Var Type type CstGenQT a = forall m. GhcMonad m => a G.Id -> CstGenQS -> (m [(SrcSpan, Type)], CstGenQS) #endif -collectSpansTypes :: forall m.(GhcMonad m) => Bool -> G.TypecheckedModule -> (Int, Int) -> m [(SrcSpan, Type)] -collectSpansTypes withConstraints tcs lc = +collectSpansTypes :: (GhcMonad m) => Bool -> G.TypecheckedModule -> (Int,Int) -> m [(SrcSpan, Type)] +collectSpansTypes withConstraints tcs lc = collectSpansTypes' withConstraints tcs (`G.spans` lc) + +collectAllSpansTypes :: (GhcMonad m) => Bool -> G.TypecheckedModule -> m [(SrcSpan, Type)] +collectAllSpansTypes withConstraints tcs = collectSpansTypes' withConstraints tcs (const True) + +collectSpansTypes' :: forall m. (GhcMonad m) => Bool -> G.TypecheckedModule -> (SrcSpan -> Bool) -> m [(SrcSpan, Type)] +-- collectSpansTypes' :: forall m.(GhcMonad m) => Bool -> G.TypecheckedModule -> (Int, Int) -> m [(SrcSpan, Type)] +collectSpansTypes' withConstraints tcs f = -- This walks AST top-down, left-to-right, while carrying CstGenQS down the tree -- (but not left-to-right) #if __GLASGOW_HASKELL__ >= 804 @@ -118,7 +125,7 @@ collectSpansTypes withConstraints tcs lc = -- Gets monomorphic type with location getType' :: forall t . (HasType (Located t)) => Located t -> m (Maybe (SrcSpan, Type)) getType' x@(L spn _) - | G.isGoodSrcSpan spn && (spn `G.spans` lc) + | G.isGoodSrcSpan spn && f spn = getType tcs x | otherwise = return Nothing -- Gets constrained type diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 52e8914f0..c52d098ec 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -92,7 +92,7 @@ Extra-Source-Files: ChangeLog Custom-Setup Setup-Depends: base - , Cabal < 2.1 && >= 1.24 + , Cabal < 2.3 && >= 1.24 , cabal-doctest < 1.1 && >= 1 Library @@ -136,7 +136,7 @@ Library , transformers , base < 4.12 && >= 4.6.0.1 - , djinn-ghc < 0.1 && >= 0.0.2.2 + -- , djinn-ghc < 0.1 && >= 0.0.2.2 , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 @@ -227,7 +227,7 @@ Test-Suite doctest Default-Extensions: ConstraintKinds, FlexibleContexts Main-Is: doctests.hs Build-Depends: base < 4.12 && >= 4.6.0.1 - , doctest < 0.14 && >= 0.11.3 + , doctest < 0.16 && >= 0.11.3 Test-Suite spec Default-Language: Haskell2010 diff --git a/src/GhcMod/Exe/Options/Commands.hs b/src/GhcMod/Exe/Options/Commands.hs index cd8ef550a..e4929246b 100644 --- a/src/GhcMod/Exe/Options/Commands.hs +++ b/src/GhcMod/Exe/Options/Commands.hs @@ -13,12 +13,15 @@ -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see . +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module GhcMod.Exe.Options.Commands where +#if __GLASGOW_HASKELL__ < 804 import Data.Semigroup +#endif import Options.Applicative import Options.Applicative.Types import Options.Applicative.Builder.Internal @@ -55,7 +58,7 @@ data GhcModCommands = | CmdType Bool FilePath Point | CmdSplit FilePath Point | CmdSig FilePath Point - | CmdAuto FilePath Point + -- | CmdAuto FilePath Point | CmdRefine FilePath Point Expr | CmdTest FilePath -- interactive-only commands @@ -167,9 +170,9 @@ commands = "ghc-mod would add the following on the next line:" code "func x y z f = _func_body" "(See: https://github.com/DanielG/ghc-mod/pull/274)" - <> command "auto" - $$ info autoArgSpec - $$ progDesc "Try to automatically fill the contents of a hole" + -- <> command "auto" + -- $$ info autoArgSpec + -- $$ progDesc "Try to automatically fill the contents of a hole" <> command "refine" $$ info refineArgSpec $$ progDesc "Refine the typed hole at (LINE,COL) given EXPR" @@ -229,7 +232,7 @@ locArgSpec x = x modulesArgSpec, docArgSpec, findArgSpec, lintArgSpec, browseArgSpec, checkArgSpec, expandArgSpec, - infoArgSpec, typeArgSpec, autoArgSpec, splitArgSpec, + infoArgSpec, typeArgSpec, splitArgSpec, sigArgSpec, refineArgSpec, debugComponentArgSpec, mapArgSpec, unmapArgSpec, legacyInteractiveArgSpec :: Parser GhcModCommands @@ -277,7 +280,7 @@ typeArgSpec = locArgSpec $ CmdType <$> $$ long "constraints" <=> short 'c' <=> help "Include constraints into type signature" -autoArgSpec = locArgSpec (pure CmdAuto) +-- autoArgSpec = locArgSpec (pure CmdAuto) splitArgSpec = locArgSpec (pure CmdSplit) sigArgSpec = locArgSpec (pure CmdSig) refineArgSpec = locArgSpec (pure CmdRefine) <*> strArg "SYMBOL" diff --git a/src/GhcModMain.hs b/src/GhcModMain.hs index d4c011661..e6b6bdbfd 100644 --- a/src/GhcModMain.hs +++ b/src/GhcModMain.hs @@ -151,7 +151,7 @@ ghcCommands (CmdInfo file symb) = info file $ Expression symb ghcCommands (CmdType wCon file (line, col)) = types wCon file line col ghcCommands (CmdSplit file (line, col)) = splits file line col ghcCommands (CmdSig file (line, col)) = sig file line col -ghcCommands (CmdAuto file (line, col)) = auto file line col +-- ghcCommands (CmdAuto file (line, col)) = auto file line col ghcCommands (CmdRefine file (line, col) expr) = refine file line col $ Expression expr -- interactive-only commands ghcCommands (CmdMapFile f) = From 90c7c0faac794a3b582aa794fa9f6eba5f190269 Mon Sep 17 00:00:00 2001 From: Thomas Smith Date: Sat, 21 Apr 2018 13:05:59 +0200 Subject: [PATCH 13/50] Implement splits' to return a structured restult for case splitting - Refactor splits and split' to reduce duplicate code - Make performSplit less partial - Fix error in determining SplitResult source locations. - Accommodate AST change in 8.4.1 - Fix typo in GHC version check --- GhcMod/Exe/CaseSplit.hs | 109 +++++++++++++++++++++++++++++----------- core/GhcMod/Gap.hs | 4 +- 2 files changed, 83 insertions(+), 30 deletions(-) diff --git a/GhcMod/Exe/CaseSplit.hs b/GhcMod/Exe/CaseSplit.hs index 80afd35a0..cf01159b2 100644 --- a/GhcMod/Exe/CaseSplit.hs +++ b/GhcMod/Exe/CaseSplit.hs @@ -2,6 +2,8 @@ module GhcMod.Exe.CaseSplit ( splits + , splits' + , SplitResult(..) ) where import Data.List (find, intercalate) @@ -12,7 +14,7 @@ import System.FilePath import Prelude import qualified DataCon as Ty -import GHC (GhcMonad, LPat, ParsedModule(..), TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) +import GHC (GhcMonad, LPat, TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) import qualified GHC as G import Outputable (PprStyle) import qualified TyCon as Ty @@ -42,8 +44,15 @@ data SplitToTextInfo = SplitToTextInfo { sVarName :: String , sVarSpan :: SrcSpan , sTycons :: [String] } +data SplitResult = SplitResult { sStartLine :: Int + , sStartCol :: Int + , sEndLine :: Int + , sEndCol :: Int + , sNewText :: T.Text } -- | Splitting a variable in a equation. +-- Unlike splits', this performs parsing an type checking on every invocation. +-- This is meant for consumption by tools that call ghc-mod as a binary. splits :: IOish m => FilePath -- ^ A target file. -> Int -- ^ Line number. @@ -53,41 +62,81 @@ splits file lineNo colNo = ghandle handler $ runGmlT' [Left file] deferErrors $ do oopts <- outputOpts crdl <- cradle - style <- getStyle - dflag <- G.getSessionDynFlags modSum <- fileModSummaryWithMapping (cradleCurrentDir crdl file) - whenFound' oopts (getSrcSpanTypeForSplit modSum lineNo colNo) $ \x -> do - let (varName, bndLoc, (varLoc,varT)) - | (SplitInfo vn bl vlvt _matches) <- x - = (vn, bl, vlvt) - | (TySplitInfo vn bl vlvt) <- x - = (vn, bl, vlvt) - varName' = showName dflag style varName -- Convert name to string - t <- withMappedFile file $ \file' -> - genCaseSplitTextFile file' (SplitToTextInfo varName' bndLoc varLoc $ - getTyCons dflag style varName varT) - return $!! (fourInts bndLoc, t) + p <- G.parseModule modSum + tcm <- G.typecheckModule p + whenFound' oopts (performSplit file tcm lineNo colNo) $ + \(SplitResult sLine sCol eLine eCol newText) -> + return $!! ((sLine, sCol, eLine, eCol), T.unpack newText) where handler (SomeException ex) = do gmLog GmException "splits" $ text "" $$ nest 4 (showToDoc ex) emptyResult =<< outputOpts +-- | Split an identifier in a function definition. +-- Meant for library-usage. +splits' :: IOish m => FilePath -> TypecheckedModule -> Int -> Int -> GhcModT m (Maybe SplitResult) +splits' file tcm lineNo colNo = + ghandle handler $ runGmlT' [Left file] deferErrors $ performSplit file tcm lineNo colNo + where + handler (SomeException ex) = do + gmLog GmException "splits'" $ + text "" $$ nest 4 (showToDoc ex) + return Nothing + +performSplit :: IOish m => FilePath -> TypecheckedModule -> Int -> Int -> GmlT m (Maybe SplitResult) +performSplit file tcm lineNo colNo = do + style <- getStyle + dflag <- G.getSessionDynFlags + maybeSplitInfo <- getSrcSpanTypeForSplit tcm lineNo colNo + sequenceA $ constructSplitResult file maybeSplitInfo dflag style + +constructSplitResult :: (IOish m) => FilePath -> Maybe SplitInfo -> DynFlags -> PprStyle -> Maybe (GmlT m SplitResult) +constructSplitResult file maybeSplitInfo dflag style = do + splitInfo <- maybeSplitInfo + let splitToTextInfo = constructSplitToTextInfo splitInfo dflag style + startLoc <- maybeSrcSpanStart $ sBindingSpan splitToTextInfo + endLoc <- maybeSrcSpanEnd $ sBindingSpan splitToTextInfo + let startLine = G.srcLocLine startLoc + startCol = G.srcLocCol startLoc + endLine = G.srcLocLine endLoc + endCol = G.srcLocCol endLoc + newText = genCaseSplitTextFile file splitToTextInfo + return $ SplitResult startLine startCol endLine endCol . T.pack <$> newText + +constructSplitToTextInfo :: SplitInfo -> DynFlags -> PprStyle -> SplitToTextInfo +constructSplitToTextInfo splitInfo dflag style = + SplitToTextInfo varName' bndLoc varLoc typeCons + where + typeCons = getTyCons dflag style varName varT + varName' = showName dflag style varName -- Convert name to string + (varName, bndLoc, varLoc, varT) = case splitInfo of + (SplitInfo vn bl (vl, vt) _matches) -> (vn, bl, vl, vt) + (TySplitInfo vn bl (vl, vt)) -> (vn, bl, vl, vt) + +maybeSrcSpanStart :: G.SrcSpan -> Maybe G.RealSrcLoc +maybeSrcSpanStart s = case G.srcSpanStart s of + (G.RealSrcLoc startLoc) -> Just startLoc + _ -> Nothing + +maybeSrcSpanEnd :: G.SrcSpan -> Maybe G.RealSrcLoc +maybeSrcSpanEnd s = case G.srcSpanEnd s of + (G.RealSrcLoc endLoc) -> Just endLoc + _ -> Nothing ---------------------------------------------------------------- -- a. Code for getting the information of the variable -getSrcSpanTypeForSplit :: GhcMonad m => G.ModSummary -> Int -> Int -> m (Maybe SplitInfo) -getSrcSpanTypeForSplit modSum lineNo colNo = do - fn <- getSrcSpanTypeForFnSplit modSum lineNo colNo +getSrcSpanTypeForSplit :: GhcMonad m => TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) +getSrcSpanTypeForSplit tcm lineNo colNo = do + fn <- getSrcSpanTypeForFnSplit tcm lineNo colNo if isJust fn then return fn - else getSrcSpanTypeForTypeSplit modSum lineNo colNo + else getSrcSpanTypeForTypeSplit tcm lineNo colNo -- Information for a function case split -getSrcSpanTypeForFnSplit :: GhcMonad m => G.ModSummary -> Int -> Int -> m (Maybe SplitInfo) -getSrcSpanTypeForFnSplit modSum lineNo colNo = do - p@ParsedModule{pm_parsed_source = _pms} <- G.parseModule modSum - tcm@TypecheckedModule{tm_typechecked_source = tcs} <- G.typecheckModule p +getSrcSpanTypeForFnSplit :: GhcMonad m => TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) +getSrcSpanTypeForFnSplit tcm@TypecheckedModule{tm_typechecked_source = tcs} lineNo colNo = do let varPat = find isPatternVar $ listifySpans tcs (lineNo, colNo) :: Maybe (LPat Gap.GhcTc) match = last $ listifySpans tcs (lineNo, colNo) :: Gap.GLMatchI case varPat of @@ -119,8 +168,8 @@ getPatternVarName (L _ (G.VarPat vName)) = G.getName vName getPatternVarName _ = error "This should never happened" -- TODO: Information for a type family case split -getSrcSpanTypeForTypeSplit :: GhcMonad m => G.ModSummary -> Int -> Int -> m (Maybe SplitInfo) -getSrcSpanTypeForTypeSplit _modSum _lineNo _colNo = return Nothing +getSrcSpanTypeForTypeSplit :: GhcMonad m => TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) +getSrcSpanTypeForTypeSplit _tcm _lineNo _colNo = return Nothing ---------------------------------------------------------------- -- b. Code for getting the possible constructors @@ -209,11 +258,13 @@ showFieldNames dflag style v (x:xs) = let fName = showName dflag style x ---------------------------------------------------------------- -- c. Code for performing the case splitting -genCaseSplitTextFile :: (MonadIO m, GhcMonad m) => - FilePath -> SplitToTextInfo -> m String -genCaseSplitTextFile file info = liftIO $ do - t <- T.readFile file - return $ getCaseSplitText (T.lines t) info + +genCaseSplitTextFile :: IOish m => + FilePath -> SplitToTextInfo -> GmlT m String +genCaseSplitTextFile file info = + withMappedFile file $ \file' -> liftIO $ do + t <- T.readFile file' + return $ getCaseSplitText (T.lines t) info getCaseSplitText :: [T.Text] -> SplitToTextInfo -> String getCaseSplitText t SplitToTextInfo{ sVarName = sVN, sBindingSpan = sBS diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index 91bed2556..b75ae3004 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -618,7 +618,9 @@ type GhcRn = Name type GhcTc = Id #endif -#if __GLASGOW_HASKELL__ >= 708 +#if __GLASGOW_HASKELL__ >= 804 +type GLMatchI = LMatch GhcTc (LHsExpr GhcTc) +#elif __GLASGOW_HASKELL__ >= 708 type GLMatch = LMatch GhcPs (LHsExpr GhcPs) type GLMatchI = LMatch Id (LHsExpr Id) #else From 9ea60d5753dfabde8feb136443981d1645d7177a Mon Sep 17 00:00:00 2001 From: Zubin Duggal Date: Wed, 9 May 2018 11:20:57 +0530 Subject: [PATCH 14/50] Use canonicalizePath in FileMapping - Canonicalize mapped path also - Fix compilation with GHC 8.4.3 --- core/GhcMod/FileMapping.hs | 7 ++++--- core/GhcMod/Gap.hs | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/core/GhcMod/FileMapping.hs b/core/GhcMod/FileMapping.hs index e05a54066..5b9d891b8 100644 --- a/core/GhcMod/FileMapping.hs +++ b/core/GhcMod/FileMapping.hs @@ -57,11 +57,12 @@ loadMappedFileSource from src = do loadMappedFile' :: IOish m => FilePath -> FilePath -> Bool -> GhcModT m () loadMappedFile' from to isTemp = do - cfn <- getCanonicalFileNameSafe from + cfn <- liftIO $ canonicalizePath from unloadMappedFile' cfn crdl <- cradle - let to' = makeRelative (cradleRootDir crdl) to - addMMappedFile cfn (FileMapping to' isTemp) + to' <- liftIO $ canonicalizePath to + let to'' = makeRelative (cradleRootDir crdl) to' + addMMappedFile cfn (FileMapping to'' isTemp) mapFile :: (IOish m, GmState m) => HscEnv -> Target -> m Target mapFile _ (Target tid@(TargetFile filePath _) taoc _) = do diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index b75ae3004..a77496ff4 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -619,12 +619,13 @@ type GhcTc = Id #endif #if __GLASGOW_HASKELL__ >= 804 +type GLMatch = LMatch GhcPs (LHsExpr GhcPs) type GLMatchI = LMatch GhcTc (LHsExpr GhcTc) #elif __GLASGOW_HASKELL__ >= 708 -type GLMatch = LMatch GhcPs (LHsExpr GhcPs) +type GLMatch = LMatch GhcPs (LHsExpr GhcPs) type GLMatchI = LMatch Id (LHsExpr Id) #else -type GLMatch = LMatch GhcPs +type GLMatch = LMatch GhcPs type GLMatchI = LMatch Id #endif From 214fe1b9f5e604047699465ef903cb44368e205f Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 17 Jun 2018 18:50:21 +0200 Subject: [PATCH 15/50] Match code style to the existing code i.e. all GHC stuff is qualified with G. --- GhcMod/Exe/CaseSplit.hs | 59 ++++++++++++++++++++--------------------- core/GhcMod/Gap.hs | 13 --------- 2 files changed, 29 insertions(+), 43 deletions(-) diff --git a/GhcMod/Exe/CaseSplit.hs b/GhcMod/Exe/CaseSplit.hs index cf01159b2..d1deea041 100644 --- a/GhcMod/Exe/CaseSplit.hs +++ b/GhcMod/Exe/CaseSplit.hs @@ -14,7 +14,6 @@ import System.FilePath import Prelude import qualified DataCon as Ty -import GHC (GhcMonad, LPat, TypecheckedModule(..), DynFlags, SrcSpan, Type, GenLocated(L)) import qualified GHC as G import Outputable (PprStyle) import qualified TyCon as Ty @@ -37,11 +36,11 @@ import Control.DeepSeq -- CASE SPLITTING ---------------------------------------------------------------- -data SplitInfo = SplitInfo G.Name SrcSpan (SrcSpan, Type) [SrcSpan] - | TySplitInfo G.Name SrcSpan (SrcSpan, Ty.Kind) +data SplitInfo = SplitInfo G.Name G.SrcSpan (G.SrcSpan, G.Type) [G.SrcSpan] + | TySplitInfo G.Name G.SrcSpan (G.SrcSpan, Ty.Kind) data SplitToTextInfo = SplitToTextInfo { sVarName :: String - , sBindingSpan :: SrcSpan - , sVarSpan :: SrcSpan + , sBindingSpan :: G.SrcSpan + , sVarSpan :: G.SrcSpan , sTycons :: [String] } data SplitResult = SplitResult { sStartLine :: Int @@ -76,7 +75,7 @@ splits file lineNo colNo = -- | Split an identifier in a function definition. -- Meant for library-usage. -splits' :: IOish m => FilePath -> TypecheckedModule -> Int -> Int -> GhcModT m (Maybe SplitResult) +splits' :: IOish m => FilePath -> G.TypecheckedModule -> Int -> Int -> GhcModT m (Maybe SplitResult) splits' file tcm lineNo colNo = ghandle handler $ runGmlT' [Left file] deferErrors $ performSplit file tcm lineNo colNo where @@ -85,14 +84,14 @@ splits' file tcm lineNo colNo = text "" $$ nest 4 (showToDoc ex) return Nothing -performSplit :: IOish m => FilePath -> TypecheckedModule -> Int -> Int -> GmlT m (Maybe SplitResult) +performSplit :: IOish m => FilePath -> G.TypecheckedModule -> Int -> Int -> GmlT m (Maybe SplitResult) performSplit file tcm lineNo colNo = do style <- getStyle dflag <- G.getSessionDynFlags maybeSplitInfo <- getSrcSpanTypeForSplit tcm lineNo colNo sequenceA $ constructSplitResult file maybeSplitInfo dflag style -constructSplitResult :: (IOish m) => FilePath -> Maybe SplitInfo -> DynFlags -> PprStyle -> Maybe (GmlT m SplitResult) +constructSplitResult :: (IOish m) => FilePath -> Maybe SplitInfo -> G.DynFlags -> PprStyle -> Maybe (GmlT m SplitResult) constructSplitResult file maybeSplitInfo dflag style = do splitInfo <- maybeSplitInfo let splitToTextInfo = constructSplitToTextInfo splitInfo dflag style @@ -105,7 +104,7 @@ constructSplitResult file maybeSplitInfo dflag style = do newText = genCaseSplitTextFile file splitToTextInfo return $ SplitResult startLine startCol endLine endCol . T.pack <$> newText -constructSplitToTextInfo :: SplitInfo -> DynFlags -> PprStyle -> SplitToTextInfo +constructSplitToTextInfo :: SplitInfo -> G.DynFlags -> PprStyle -> SplitToTextInfo constructSplitToTextInfo splitInfo dflag style = SplitToTextInfo varName' bndLoc varLoc typeCons where @@ -127,7 +126,7 @@ maybeSrcSpanEnd s = case G.srcSpanEnd s of ---------------------------------------------------------------- -- a. Code for getting the information of the variable -getSrcSpanTypeForSplit :: GhcMonad m => TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) +getSrcSpanTypeForSplit :: G.GhcMonad m => G.TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) getSrcSpanTypeForSplit tcm lineNo colNo = do fn <- getSrcSpanTypeForFnSplit tcm lineNo colNo if isJust fn @@ -135,10 +134,10 @@ getSrcSpanTypeForSplit tcm lineNo colNo = do else getSrcSpanTypeForTypeSplit tcm lineNo colNo -- Information for a function case split -getSrcSpanTypeForFnSplit :: GhcMonad m => TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) -getSrcSpanTypeForFnSplit tcm@TypecheckedModule{tm_typechecked_source = tcs} lineNo colNo = do - let varPat = find isPatternVar $ listifySpans tcs (lineNo, colNo) :: Maybe (LPat Gap.GhcTc) - match = last $ listifySpans tcs (lineNo, colNo) :: Gap.GLMatchI +getSrcSpanTypeForFnSplit :: G.GhcMonad m => G.TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) +getSrcSpanTypeForFnSplit tcm@G.TypecheckedModule{G.tm_typechecked_source = tcs} lineNo colNo = do + let varPat = find isPatternVar $ listifySpans tcs (lineNo, colNo) :: Maybe (G.LPat Gap.GhcTc) + match = last $ listifySpans tcs (lineNo, colNo) :: G.LMatch Gap.GhcTc (G.LHsExpr Gap.GhcTc) case varPat of Nothing -> return Nothing Just varPat' -> do @@ -146,42 +145,42 @@ getSrcSpanTypeForFnSplit tcm@TypecheckedModule{tm_typechecked_source = tcs} line case varT of Just varT' -> #if __GLASGOW_HASKELL__ >= 804 - let (L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match + let (G.L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match #elif __GLASGOW_HASKELL__ >= 710 - let (L matchL (G.Match _ _ _ (G.GRHSs rhsLs _))) = match + let (G.L matchL (G.Match _ _ _ (G.GRHSs rhsLs _))) = match #else - let (L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match + let (G.L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match #endif in return $ Just (SplitInfo (getPatternVarName varPat') matchL varT' (map G.getLoc rhsLs) ) _ -> return Nothing -isPatternVar :: LPat Gap.GhcTc -> Bool -isPatternVar (L _ (G.VarPat _)) = True +isPatternVar :: G.LPat Gap.GhcTc -> Bool +isPatternVar (G.L _ (G.VarPat _)) = True isPatternVar _ = False -getPatternVarName :: LPat Gap.GhcTc -> G.Name +getPatternVarName :: G.LPat Gap.GhcTc -> G.Name #if __GLASGOW_HASKELL__ >= 800 -getPatternVarName (L _ (G.VarPat (L _ vName))) = G.getName vName +getPatternVarName (G.L _ (G.VarPat (G.L _ vName))) = G.getName vName #else -getPatternVarName (L _ (G.VarPat vName)) = G.getName vName +getPatternVarName (G.L _ (G.VarPat vName)) = G.getName vName #endif getPatternVarName _ = error "This should never happened" -- TODO: Information for a type family case split -getSrcSpanTypeForTypeSplit :: GhcMonad m => TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) +getSrcSpanTypeForTypeSplit :: G.GhcMonad m => G.TypecheckedModule -> Int -> Int -> m (Maybe SplitInfo) getSrcSpanTypeForTypeSplit _tcm _lineNo _colNo = return Nothing ---------------------------------------------------------------- -- b. Code for getting the possible constructors -getTyCons :: DynFlags -> PprStyle -> G.Name -> G.Type -> [String] +getTyCons :: G.DynFlags -> PprStyle -> G.Name -> G.Type -> [String] getTyCons dflag style name ty | Just (tyCon, _) <- Ty.splitTyConApp_maybe ty = let name' = showName dflag style name -- Convert name to string in getTyCon dflag style name' tyCon getTyCons dflag style name _ = [showName dflag style name] -- Write cases for one type -getTyCon :: DynFlags -> PprStyle -> String -> Ty.TyCon -> [String] +getTyCon :: G.DynFlags -> PprStyle -> String -> Ty.TyCon -> [String] -- 1. Non-matcheable type constructors getTyCon _ _ name tyCon | isNotMatcheableTyCon tyCon = [name] -- 2. Special cases @@ -203,7 +202,7 @@ isNotMatcheableTyCon ty = Ty.isPrimTyCon ty -- Primitive types, such as Int# || Ty.isFunTyCon ty -- Function types -- Write case for one constructor -getDataCon :: DynFlags -> PprStyle -> String -> Ty.DataCon -> String +getDataCon :: G.DynFlags -> PprStyle -> String -> Ty.DataCon -> String -- 1. Infix constructors getDataCon dflag style vName dcon | Ty.dataConIsInfix dcon = let dName = showName dflag style $ Ty.dataConName dcon @@ -247,7 +246,7 @@ newVarsSpecialSingleton :: String -> Int -> Int -> String newVarsSpecialSingleton v _ 1 = v newVarsSpecialSingleton v start n = newVars v start n -showFieldNames :: DynFlags -> PprStyle -> String -> [G.Name] -> String +showFieldNames :: G.DynFlags -> PprStyle -> String -> [G.Name] -> String showFieldNames _ _ _ [] = "" -- This should never happen showFieldNames dflag style v (x:xs) = let fName = showName dflag style x fAcc = fName ++ " = " ++ v ++ "_" ++ fName @@ -277,7 +276,7 @@ getCaseSplitText t SplitToTextInfo{ sVarName = sVN, sBindingSpan = sBS replaced' = head replaced : map (indentBindingTo sBS) (tail replaced) in T.unpack $ T.intercalate (T.pack "\n") (concat replaced') -getBindingText :: [T.Text] -> SrcSpan -> [T.Text] +getBindingText :: [T.Text] -> G.SrcSpan -> [T.Text] getBindingText t srcSpan = let Just (sl,sc,el,ec) = Gap.getSrcSpan srcSpan lines_ = drop (sl - 1) $ take el t @@ -288,7 +287,7 @@ getBindingText t srcSpan = let (first,rest,last_) = (head lines_, tail $ init lines_, last lines_) in T.drop (sc - 1) first : rest ++ [T.take ec last_] -srcSpanDifference :: SrcSpan -> SrcSpan -> (Int,Int,Int,Int) +srcSpanDifference :: G.SrcSpan -> G.SrcSpan -> (Int,Int,Int,Int) srcSpanDifference b v = let Just (bsl,bsc,_ ,_) = Gap.getSrcSpan b Just (vsl,vsc,vel,vec) = Gap.getSrcSpan v @@ -307,7 +306,7 @@ replaceVarWithTyCon t (vsl,vsc,_,vec) varname tycon = else T.replicate spacesToAdd (T.pack " ") `T.append` line) [0 ..] t -indentBindingTo :: SrcSpan -> [T.Text] -> [T.Text] +indentBindingTo :: G.SrcSpan -> [T.Text] -> [T.Text] indentBindingTo bndLoc binds = let Just (_,sl,_,_) = Gap.getSrcSpan bndLoc indent = (T.replicate (sl - 1) (T.pack " ") `T.append`) diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index a77496ff4..33252b040 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -37,8 +37,6 @@ module GhcMod.Gap ( , fileModSummary , WarnFlags , emptyWarnFlags - , GLMatch - , GLMatchI , getClass , occName , listVisibleModuleNames @@ -618,17 +616,6 @@ type GhcRn = Name type GhcTc = Id #endif -#if __GLASGOW_HASKELL__ >= 804 -type GLMatch = LMatch GhcPs (LHsExpr GhcPs) -type GLMatchI = LMatch GhcTc (LHsExpr GhcTc) -#elif __GLASGOW_HASKELL__ >= 708 -type GLMatch = LMatch GhcPs (LHsExpr GhcPs) -type GLMatchI = LMatch Id (LHsExpr Id) -#else -type GLMatch = LMatch GhcPs -type GLMatchI = LMatch Id -#endif - getClass :: [LInstDecl GhcRn] -> Maybe (Name, SrcSpan) #if __GLASGOW_HASKELL__ >= 802 -- Instance declarations of sort 'instance F (G a)' From 66fc0980d2c731caf36215969a31bff8ef40f3e2 Mon Sep 17 00:00:00 2001 From: Zubin Duggal Date: Sat, 8 Jul 2017 12:57:11 +0530 Subject: [PATCH 16/50] Only load mapped files from the current component --- GhcMod/Exe/Debug.hs | 2 +- core/GhcMod/Target.hs | 2 +- core/GhcMod/Utils.hs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GhcMod/Exe/Debug.hs b/GhcMod/Exe/Debug.hs index 7005bbb48..3cdfd4443 100644 --- a/GhcMod/Exe/Debug.hs +++ b/GhcMod/Exe/Debug.hs @@ -123,7 +123,7 @@ componentInfo ts = do mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn candidates = findCandidates $ map snd mdlcs cn = pickComponent candidates - (opts,_) <- targetGhcOptions crdl sefnmn + opts <- fst <$> targetGhcOptions crdl sefnmn return $ unlines $ [ "Matching Components:\n" ++ renderGm (nest 4 $ diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index de39bc6e6..63d295d01 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -193,6 +193,7 @@ runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do cfns <- mapM getCanonicalFileNameSafe ccfns let serfnmn = Set.fromList $ map Right mns ++ map Left cfns (opts, mappedStrs) <- targetGhcOptions crdl serfnmn + let opts' = opts ++ ["-O0", "-fno-warn-missing-home-modules"] ++ optGhcUserOptions gmVomit @@ -213,7 +214,6 @@ runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do initSession opts' $ setHscNothing >>> setLogger >>> mdf - mappedStrs <- getMMappedFilePaths let targetStrs = mappedStrs ++ map moduleNameString mns ++ cfns gmVomit diff --git a/core/GhcMod/Utils.hs b/core/GhcMod/Utils.hs index 7c282357b..0d18ce81c 100644 --- a/core/GhcMod/Utils.hs +++ b/core/GhcMod/Utils.hs @@ -113,7 +113,7 @@ withMappedFile file action = getCanonicalFileNameSafe file >>= lookupMMappedFile runWithFile (Just to) = action $ fmPath to runWithFile _ = action file -getCanonicalFileNameSafe :: (IOish m, GmEnv m) => FilePath -> m FilePath +getCanonicalFileNameSafe :: (IOish m) => FilePath -> m FilePath getCanonicalFileNameSafe fn = do let fn' = normalise fn pl <- liftIO $ rights <$> (mapM ((try :: IO FilePath -> IO (Either SomeException FilePath)) . canonicalizePath . joinPath) $ reverse $ inits $ splitPath' fn') From 55f6eea0c78698d59f6b5565db2ed7702e07b990 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Mon, 2 Jul 2018 18:53:31 +0200 Subject: [PATCH 17/50] Update for GHC 8.6 --- core/GhcMod/DebugLogger.hs | 4 ++++ core/GhcMod/DynFlagsTH.hs | 4 ++++ core/GhcMod/Gap.hs | 18 ++++++++++++++++-- core/GhcMod/LightGhc.hs | 5 ++++- core/GhcMod/ModuleLoader.hs | 11 +++++++++++ 5 files changed, 39 insertions(+), 3 deletions(-) diff --git a/core/GhcMod/DebugLogger.hs b/core/GhcMod/DebugLogger.hs index 6e9dfa821..4f118221c 100644 --- a/core/GhcMod/DebugLogger.hs +++ b/core/GhcMod/DebugLogger.hs @@ -133,6 +133,10 @@ gmPrintDoc_ mode pprCols putS doc #if __GLASGOW_HASKELL__ >= 708 put (ZStr s) next = putS (zString s) >> next #endif +#if __GLASGOW_HASKELL__ >= 806 + put (LStr s) next = putS (unpackLitString s) >> next +#else put (LStr s _l) next = putS (unpackLitString s) >> next +#endif done = return () -- hPutChar hdl '\n' diff --git a/core/GhcMod/DynFlagsTH.hs b/core/GhcMod/DynFlagsTH.hs index 46827958e..ffd81439b 100644 --- a/core/GhcMod/DynFlagsTH.hs +++ b/core/GhcMod/DynFlagsTH.hs @@ -93,6 +93,7 @@ deriveEqDynFlags qds = do , "LogOutput" -- added for ghc-8.2 , "OverridingBool" -- added for ghc-8.2 , "Scheme" -- added for ghc-8.2 + , "LoadedPlugin" -- added for ghc-8.6 ] ignoredTypeOccNames = [ "OnOff" ] @@ -205,6 +206,9 @@ deriveEqDynFlags qds = do [e| $(eqfn) $(return fa) $(return fb) |] +#if __GLASGOW_HASKELL__ >= 806 +deriving instance Eq IncludeSpecs +#endif #if __GLASGOW_HASKELL__ >= 804 toSet es = IS.fromList $ E.toList es diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index 33252b040..a1482c726 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -232,7 +232,11 @@ renderGm = Pretty.fullRender Pretty.PageMode 80 1.2 string_txt "" string_txt (Pretty.Chr c) s = c:s string_txt (Pretty.Str s1) s2 = s1 ++ s2 string_txt (Pretty.PStr s1) s2 = unpackFS s1 ++ s2 +#if __GLASGOW_HASKELL__ >= 806 + string_txt (Pretty.LStr s1) s2 = unpackLitString s1 ++ s2 +#else string_txt (Pretty.LStr s1 _) s2 = unpackLitString s1 ++ s2 +#endif #if __GLASGOW_HASKELL__ >= 708 string_txt (Pretty.ZStr s1) s2 = zString s1 ++ s2 #endif @@ -421,7 +425,12 @@ class HasType a where instance HasType (LHsBind GhcTc) where -#if __GLASGOW_HASKELL__ >= 708 +#if __GLASGOW_HASKELL__ >= 806 + getType _ (L spn FunBind{fun_matches = m}) = return $ Just (spn, typ) + where in_tys = mg_arg_tys $ mg_ext m + out_typ = mg_res_ty $ mg_ext m + typ = mkFunTys in_tys out_typ +#elif __GLASGOW_HASKELL__ >= 708 getType _ (L spn FunBind{fun_matches = m}) = return $ Just (spn, typ) where in_tys = mg_arg_tys m out_typ = mg_res_ty m @@ -617,7 +626,12 @@ type GhcTc = Id #endif getClass :: [LInstDecl GhcRn] -> Maybe (Name, SrcSpan) -#if __GLASGOW_HASKELL__ >= 802 +#if __GLASGOW_HASKELL__ >= 806 +-- Instance declarations of sort 'instance F (G a)' +getClass [L loc (ClsInstD _ (ClsInstDecl {cid_poly_ty = HsIB _ (L _ (HsForAllTy _ _ (L _ (HsAppTy _ (L _ (HsTyVar _ _ (L _ className))) _))))}))] = Just (className, loc) +-- Instance declarations of sort 'instance F G' (no variables) +getClass [L loc (ClsInstD _ (ClsInstDecl {cid_poly_ty = HsIB _ (L _ (HsAppTy _ (L _ (HsTyVar _ _ (L _ className))) _))}))] = Just (className, loc) +#elif __GLASGOW_HASKELL__ >= 802 -- Instance declarations of sort 'instance F (G a)' getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = HsIB _ (L _ (HsForAllTy _ (L _ (HsAppTy (L _ (HsTyVar _ (L _ className))) _)))) _}))] = Just (className, loc) -- Instance declarations of sort 'instance F G' (no variables) diff --git a/core/GhcMod/LightGhc.hs b/core/GhcMod/LightGhc.hs index 4edae7293..7e441c731 100644 --- a/core/GhcMod/LightGhc.hs +++ b/core/GhcMod/LightGhc.hs @@ -36,7 +36,10 @@ newLightEnv mdf = do initStaticOpts #endif settings <- initSysTools (Just libdir) -#if __GLASGOW_HASKELL__ >= 804 +#if __GLASGOW_HASKELL__ >= 806 + let llvmTgtList = ([],[]) -- TODO: where should this come from? + initDynFlags $ defaultDynFlags settings llvmTgtList +#elif __GLASGOW_HASKELL__ >= 804 let llvmTgtList = [] -- TODO: where should this come from? initDynFlags $ defaultDynFlags settings llvmTgtList #else diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs index 8fbf0ba01..d9f99ace6 100644 --- a/core/GhcMod/ModuleLoader.hs +++ b/core/GhcMod/ModuleLoader.hs @@ -73,8 +73,19 @@ getTypecheckedModuleGhc :: GM.IOish m => (GM.GmlT m () -> GM.GmlT m a) -> [FilePath] -> (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GM.GhcModT m a getTypecheckedModuleGhc wrapper targetFiles keepInfo saveModule = do mfs <- GM.getMMappedFiles + +#if __GLASGOW_HASKELL__ >= 806 + let ips = map takeDirectory $ Map.keys mfs + getPaths ips' df = GHC.IncludeSpecs qpaths (ips' ++ gpaths) + where + -- Note, introduced for include path issues on windows, see + -- https://ghc.haskell.org/trac/ghc/ticket/14312 + GHC.IncludeSpecs qpaths gpaths = GHC.includePaths df + setIncludePaths df = df { GHC.includePaths = getPaths ips df } +#else let ips = map takeDirectory $ Map.keys mfs setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } +#endif GM.runGmlTWith' (map Left targetFiles) (return . setIncludePaths) (Just $ updateHooks keepInfo saveModule) From 52752f940baa92fbaf4c54a20d55261badc2948c Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 14 Jul 2018 12:27:25 +0200 Subject: [PATCH 18/50] Update ghc-mod part for GHC 8.6 --- GhcMod/Exe/CaseSplit.hs | 16 ++++----- GhcMod/Exe/FillSig.hs | 74 +++++++++++++++++++++++++++++++++++------ 2 files changed, 69 insertions(+), 21 deletions(-) diff --git a/GhcMod/Exe/CaseSplit.hs b/GhcMod/Exe/CaseSplit.hs index d1deea041..4753f1db7 100644 --- a/GhcMod/Exe/CaseSplit.hs +++ b/GhcMod/Exe/CaseSplit.hs @@ -144,22 +144,18 @@ getSrcSpanTypeForFnSplit tcm@G.TypecheckedModule{G.tm_typechecked_source = tcs} varT <- Gap.getType tcm varPat' -- Finally we get the type of the var case varT of Just varT' -> -#if __GLASGOW_HASKELL__ >= 804 - let (G.L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match -#elif __GLASGOW_HASKELL__ >= 710 - let (G.L matchL (G.Match _ _ _ (G.GRHSs rhsLs _))) = match -#else - let (G.L matchL (G.Match _ _ (G.GRHSs rhsLs _))) = match -#endif + let (G.L matchL (G.Match { G.m_grhss = G.GRHSs { G.grhssGRHSs = rhsLs }})) = match in return $ Just (SplitInfo (getPatternVarName varPat') matchL varT' (map G.getLoc rhsLs) ) _ -> return Nothing isPatternVar :: G.LPat Gap.GhcTc -> Bool -isPatternVar (G.L _ (G.VarPat _)) = True -isPatternVar _ = False +isPatternVar (G.L _ (G.VarPat {})) = True +isPatternVar _ = False getPatternVarName :: G.LPat Gap.GhcTc -> G.Name -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 +getPatternVarName (G.L _ (G.VarPat _ (G.L _ vName))) = G.getName vName +#elif __GLASGOW_HASKELL__ >= 800 getPatternVarName (G.L _ (G.VarPat (G.L _ vName))) = G.getName vName #else getPatternVarName (G.L _ (G.VarPat vName)) = G.getName vName diff --git a/GhcMod/Exe/FillSig.hs b/GhcMod/Exe/FillSig.hs index e5efb84a5..8791331ab 100644 --- a/GhcMod/Exe/FillSig.hs +++ b/GhcMod/Exe/FillSig.hs @@ -114,7 +114,9 @@ getSignature modSum lineNo colNo = do p@ParsedModule{pm_parsed_source = ps} <- G.parseModule modSum -- Inspect the parse tree to find the signature case listifyParsedSpans ps (lineNo, colNo) :: [G.LHsDecl Gap.GhcPs] of -#if __GLASGOW_HASKELL__ >= 802 +#if __GLASGOW_HASKELL__ >= 806 + [L loc (G.SigD _ (Ty.TypeSig _ names (G.HsWC _ (G.HsIB _ (L _ ty)))))] -> +#elif __GLASGOW_HASKELL__ >= 802 [L loc (G.SigD (Ty.TypeSig names (G.HsWC _ (G.HsIB _ (L _ ty) _))))] -> #elif __GLASGOW_HASKELL__ >= 800 [L loc (G.SigD (Ty.TypeSig names (G.HsIB _ (G.HsWC _ _ (L _ ty)))))] -> @@ -125,7 +127,7 @@ getSignature modSum lineNo colNo = do #endif -- We found a type signature return $ Just $ Signature loc (map G.unLoc names) ty - [L _ (G.InstD _)] -> do + [L _ (G.InstD {})] -> do -- We found an instance declaration TypecheckedModule{tm_renamed_source = Just tcs ,tm_checked_module_info = minfo} <- G.typecheckModule p @@ -133,7 +135,9 @@ getSignature modSum lineNo colNo = do case Gap.getClass lst of Just (clsName,loc) -> obtainClassInfo minfo clsName loc _ -> return Nothing -#if __GLASGOW_HASKELL__ >= 802 +#if __GLASGOW_HASKELL__ >= 806 + [L loc (G.TyClD _ (G.FamDecl _ (G.FamilyDecl _ info (L _ name) (G.HsQTvs _ vars) _ _ _)))] -> do +#elif __GLASGOW_HASKELL__ >= 802 [L loc (G.TyClD (G.FamDecl (G.FamilyDecl info (L _ name) (G.HsQTvs _ vars _) _ _ _)))] -> do #elif __GLASGOW_HASKELL__ >= 800 [L loc (G.TyClD (G.FamDecl (G.FamilyDecl info (L _ name) (G.HsQTvs _ vars _) _ _)))] -> do @@ -155,7 +159,11 @@ getSignature modSum lineNo colNo = do G.DataFamily -> Data #endif -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 + getTyFamVarName x = case x of + L _ (G.UserTyVar _ (G.L _ n)) -> n + L _ (G.KindedTyVar _ (G.L _ n) _) -> n +#elif __GLASGOW_HASKELL__ >= 800 getTyFamVarName x = case x of L _ (G.UserTyVar (G.L _ n)) -> n L _ (G.KindedTyVar (G.L _ n) _) -> n @@ -279,7 +287,9 @@ class FnArgsInfo ty name | ty -> name, name -> ty where instance FnArgsInfo (G.HsType Gap.GhcPs) (G.RdrName) where getFnName dflag style name = showOccName dflag style $ Gap.occName name -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 + getFnArgs (G.HsForAllTy _ _ (L _ iTy)) +#elif __GLASGOW_HASKELL__ >= 800 getFnArgs (G.HsForAllTy _ (L _ iTy)) #elif __GLASGOW_HASKELL__ >= 710 getFnArgs (G.HsForAllTy _ _ _ _ (L _ iTy)) @@ -288,11 +298,18 @@ instance FnArgsInfo (G.HsType Gap.GhcPs) (G.RdrName) where #endif = getFnArgs iTy +#if __GLASGOW_HASKELL__ >= 806 + getFnArgs (G.HsParTy _ (L _ iTy)) = getFnArgs iTy + getFnArgs (G.HsFunTy _ (L _ lTy) (L _ rTy)) = +#else getFnArgs (G.HsParTy (L _ iTy)) = getFnArgs iTy getFnArgs (G.HsFunTy (L _ lTy) (L _ rTy)) = +#endif (if fnarg lTy then FnArgFunction else FnArgNormal):getFnArgs rTy where fnarg ty = case ty of -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 + (G.HsForAllTy _ _ (L _ iTy)) -> +#elif __GLASGOW_HASKELL__ >= 800 (G.HsForAllTy _ (L _ iTy)) -> #elif __GLASGOW_HASKELL__ >= 710 (G.HsForAllTy _ _ _ _ (L _ iTy)) -> @@ -301,8 +318,12 @@ instance FnArgsInfo (G.HsType Gap.GhcPs) (G.RdrName) where #endif fnarg iTy +#if __GLASGOW_HASKELL__ >= 806 + (G.HsParTy _ (L _ iTy)) -> fnarg iTy +#else (G.HsParTy (L _ iTy)) -> fnarg iTy - (G.HsFunTy _ _) -> True +#endif + (G.HsFunTy {} ) -> True _ -> False getFnArgs _ = [] @@ -399,7 +420,9 @@ findVar -> m (Maybe (SrcSpan, String, Type, Bool)) findVar dflag style tcm tcs lineNo colNo = case lst of -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 + e@(L _ (G.HsVar _ (L _ i))):others -> do +#elif __GLASGOW_HASKELL__ >= 800 e@(L _ (G.HsVar (L _ i))):others -> do #else e@(L _ (G.HsVar i)):others -> do @@ -413,7 +436,11 @@ findVar dflag style tcm tcs lineNo colNo = name = getFnName dflag style i -- If inside an App, we need parenthesis b = case others of +#if __GLASGOW_HASKELL__ >= 806 + L _ (G.HsApp _ (L _ a1) (L _ a2)):_ -> +#else L _ (G.HsApp (L _ a1) (L _ a2)):_ -> +#endif isSearchedVar i a1 || isSearchedVar i a2 _ -> False _ -> return Nothing @@ -431,7 +458,9 @@ doParen False s = s doParen True s = if ' ' `elem` s then '(':s ++ ")" else s isSearchedVar :: Id -> G.HsExpr Gap.GhcTc -> Bool -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 +isSearchedVar i (G.HsVar _ (L _ i2)) = i == i2 +#elif __GLASGOW_HASKELL__ >= 800 isSearchedVar i (G.HsVar (L _ i2)) = i == i2 #else isSearchedVar i (G.HsVar i2) = i == i2 @@ -542,29 +571,52 @@ getPatsForVariable tcs (lineNo, colNo) = -} getBindingsForPat :: Ty.Pat Gap.GhcTc -> M.Map G.Name Type -#if __GLASGOW_HASKELL__ >= 800 +#if __GLASGOW_HASKELL__ >= 806 +getBindingsForPat (Ty.VarPat _ (L _ i)) = M.singleton (G.getName i) (Ty.varType i) +#elif __GLASGOW_HASKELL__ >= 800 getBindingsForPat (Ty.VarPat (L _ i)) = M.singleton (G.getName i) (Ty.varType i) #else getBindingsForPat (Ty.VarPat i) = M.singleton (G.getName i) (Ty.varType i) #endif +#if __GLASGOW_HASKELL__ >= 806 +getBindingsForPat (Ty.LazyPat _ (L _ l)) = getBindingsForPat l +getBindingsForPat (Ty.BangPat _ (L _ b)) = getBindingsForPat b +getBindingsForPat (Ty.AsPat _ (L _ a) (L _ i)) = +#else getBindingsForPat (Ty.LazyPat (L _ l)) = getBindingsForPat l getBindingsForPat (Ty.BangPat (L _ b)) = getBindingsForPat b getBindingsForPat (Ty.AsPat (L _ a) (L _ i)) = +#endif M.insert (G.getName a) (Ty.varType a) (getBindingsForPat i) -#if __GLASGOW_HASKELL__ >= 708 +#if __GLASGOW_HASKELL__ >= 806 +getBindingsForPat (Ty.ListPat _ l) = + M.unions $ map (\(L _ i) -> getBindingsForPat i) l +#elif __GLASGOW_HASKELL__ >= 708 getBindingsForPat (Ty.ListPat l _ _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l #else getBindingsForPat (Ty.ListPat l _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l #endif +#if __GLASGOW_HASKELL__ >= 806 +getBindingsForPat (Ty.TuplePat _ l _) = + M.unions $ map (\(L _ i) -> getBindingsForPat i) l +#else getBindingsForPat (Ty.TuplePat l _ _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l +#endif +#if __GLASGOW_HASKELL__ < 806 getBindingsForPat (Ty.PArrPat l _) = M.unions $ map (\(L _ i) -> getBindingsForPat i) l +#endif +#if __GLASGOW_HASKELL__ >= 806 +getBindingsForPat (Ty.ViewPat _ _ (L _ i)) = getBindingsForPat i +getBindingsForPat (Ty.SigPat _ (L _ i)) = getBindingsForPat i +#else getBindingsForPat (Ty.ViewPat _ (L _ i) _) = getBindingsForPat i getBindingsForPat (Ty.SigPatIn (L _ i) _) = getBindingsForPat i getBindingsForPat (Ty.SigPatOut (L _ i) _) = getBindingsForPat i +#endif getBindingsForPat (Ty.ConPatIn (L _ i) d) = M.insert (G.getName i) (Ty.varType i) (getBindingsForRecPat d) getBindingsForPat (Ty.ConPatOut { Ty.pat_args = d }) = getBindingsForRecPat d From 973e46c08b2512507529ff63369b8b589d9b6afe Mon Sep 17 00:00:00 2001 From: Luke Lau Date: Tue, 28 Aug 2018 14:42:45 +0100 Subject: [PATCH 19/50] Return parsed module in getTypecheckedModuleGhc --- core/GhcMod/ModuleLoader.hs | 38 +++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs index 8fbf0ba01..f01952650 100644 --- a/core/GhcMod/ModuleLoader.hs +++ b/core/GhcMod/ModuleLoader.hs @@ -17,7 +17,7 @@ import qualified GhcMod.Monad as GM import qualified GhcMod.Target as GM import qualified GhcMod.Types as GM -import GHC (TypecheckedModule) +import GHC (TypecheckedModule, ParsedModule) import qualified GHC import qualified DynFlags as GHC import qualified GhcMonad as GHC @@ -54,43 +54,47 @@ tweakModSummaryDynFlags ms = -- to the includePaths for CPP purposes. -- Use in combination with `runActionInContext` for best results getTypecheckedModuleGhc' :: GM.IOish m - => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule) + => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule, Maybe ParsedModule) getTypecheckedModuleGhc' wrapper targetFile = do cfileName <- liftIO $ canonicalizePath targetFile mfs <- GM.getMMappedFiles mFileName <- liftIO . canonicalizePath $ getMappedFileName cfileName mfs - ref <- liftIO $ newIORef Nothing + refTypechecked <- liftIO $ newIORef Nothing + refParsed <- liftIO $ newIORef Nothing let keepInfo = pure . (mFileName ==) - saveModule = writeIORef ref . Just - res <- getTypecheckedModuleGhc wrapper [cfileName] keepInfo saveModule - mtm <- liftIO $ readIORef ref - return (res, mtm) + saveTypechecked = writeIORef refTypechecked . Just + saveParsed = writeIORef refParsed . Just + res <- getTypecheckedModuleGhc wrapper [cfileName] keepInfo saveTypechecked saveParsed + mtm <- liftIO $ readIORef refTypechecked + mpm <- liftIO $ readIORef refParsed + return (res, mtm, mpm) -- | like getTypecheckedModuleGhc' but allows you to keep an arbitary number of Modules -- `keepInfo` decides which TypecheckedModule to keep -- `saveModule` is the callback that is passed the TypecheckedModule getTypecheckedModuleGhc :: GM.IOish m - => (GM.GmlT m () -> GM.GmlT m a) -> [FilePath] -> (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GM.GhcModT m a -getTypecheckedModuleGhc wrapper targetFiles keepInfo saveModule = do + => (GM.GmlT m () -> GM.GmlT m a) -> [FilePath] -> (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> (ParsedModule -> IO ()) -> GM.GhcModT m a +getTypecheckedModuleGhc wrapper targetFiles keepInfo saveTypechecked saveParsed = do mfs <- GM.getMMappedFiles let ips = map takeDirectory $ Map.keys mfs setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } GM.runGmlTWith' (map Left targetFiles) (return . setIncludePaths) - (Just $ updateHooks keepInfo saveModule) + (Just $ updateHooks keepInfo saveTypechecked saveParsed) wrapper (return ()) updateHooks :: (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) + -> (ParsedModule -> IO ()) -> GHC.Hooks -> GHC.Hooks -updateHooks fp ref hooks = hooks { +updateHooks fp ref refParsed hooks = hooks { #if __GLASGOW_HASKELL__ <= 710 GHC.hscFrontendHook = Just $ hscFrontend fp ref #else - GHC.hscFrontendHook = Just $ fmap GHC.FrontendTypecheck . hscFrontend fp ref + GHC.hscFrontendHook = Just $ fmap GHC.FrontendTypecheck . hscFrontend fp ref refParsed #endif } @@ -105,24 +109,26 @@ runGhcInHsc action = do -- | Frontend hook that keeps the TypecheckedModule for its first argument -- and stores it in the IORef passed to it -hscFrontend :: (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> GHC.ModSummary -> GHC.Hsc GHC.TcGblEnv -hscFrontend keepInfoFunc saveModule mod_summary = do +hscFrontend :: (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> (ParsedModule -> IO ()) -> GHC.ModSummary -> GHC.Hsc GHC.TcGblEnv +hscFrontend keepInfoFunc saveTypechecked saveParsed mod_summary = do mfn <- canonicalizeModSummary mod_summary -- md = GHC.moduleNameString $ GHC.moduleName $ GHC.ms_mod mod_summary keepInfo <- case mfn of Just fileName -> liftIO $ keepInfoFunc fileName Nothing -> pure False - -- liftIO $ debugm $ "hscFrontend: got mod,file" ++ show (md, mfn) + if keepInfo then runGhcInHsc $ do let modSumWithRaw = tweakModSummaryDynFlags mod_summary p' <- GHC.parseModule modSumWithRaw let p = p' {GHC.pm_mod_summary = mod_summary} + liftIO $ saveParsed p + tc <- GHC.typecheckModule p let tc_gbl_env = fst $ GHC.tm_internals_ tc - liftIO $ saveModule tc + liftIO $ saveTypechecked tc return tc_gbl_env else do hpm <- GHC.hscParse' mod_summary From 30f31ad61003cfc36f4de0f67aee5031cc54ba77 Mon Sep 17 00:00:00 2001 From: Luke Lau Date: Sun, 9 Sep 2018 17:29:01 +0100 Subject: [PATCH 20/50] Rename getTypecheckedModule to getModules --- core/GhcMod/ModuleLoader.hs | 23 ++++++++++++----------- core/GhcModCore.hs | 4 ++-- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs index f01952650..fd36791f2 100644 --- a/core/GhcMod/ModuleLoader.hs +++ b/core/GhcMod/ModuleLoader.hs @@ -4,8 +4,8 @@ -- | Uses GHC hooks to load a TypecheckedModule module GhcMod.ModuleLoader - ( getTypecheckedModuleGhc - , getTypecheckedModuleGhc' + ( getModulesGhc + , getModulesGhc' ) where import Control.Monad.IO.Class @@ -47,15 +47,15 @@ tweakModSummaryDynFlags ms = let df = GHC.ms_hspp_opts ms in ms { GHC.ms_hspp_opts = GHC.gopt_set df GHC.Opt_KeepRawTokenStream } --- | Gets a TypecheckedModule from a given file +-- | Gets a TypecheckedModule and/or ParsedModule from a given file -- The `wrapper` allows arbitary data to be captured during -- the compilation process, like errors and warnings -- Appends the parent directories of all the mapped files -- to the includePaths for CPP purposes. -- Use in combination with `runActionInContext` for best results -getTypecheckedModuleGhc' :: GM.IOish m +getModulesGhc' :: GM.IOish m => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule, Maybe ParsedModule) -getTypecheckedModuleGhc' wrapper targetFile = do +getModulesGhc' wrapper targetFile = do cfileName <- liftIO $ canonicalizePath targetFile mfs <- GM.getMMappedFiles mFileName <- liftIO . canonicalizePath $ getMappedFileName cfileName mfs @@ -64,17 +64,18 @@ getTypecheckedModuleGhc' wrapper targetFile = do let keepInfo = pure . (mFileName ==) saveTypechecked = writeIORef refTypechecked . Just saveParsed = writeIORef refParsed . Just - res <- getTypecheckedModuleGhc wrapper [cfileName] keepInfo saveTypechecked saveParsed + res <- getModulesGhc wrapper [cfileName] keepInfo saveTypechecked saveParsed mtm <- liftIO $ readIORef refTypechecked mpm <- liftIO $ readIORef refParsed return (res, mtm, mpm) --- | like getTypecheckedModuleGhc' but allows you to keep an arbitary number of Modules --- `keepInfo` decides which TypecheckedModule to keep --- `saveModule` is the callback that is passed the TypecheckedModule -getTypecheckedModuleGhc :: GM.IOish m +-- | like getModulesGhc' but allows you to keep an arbitary number of Modules +-- `keepInfo` decides which module to keep +-- `saveTypechecked` is the callback that is passed the TypecheckedModule +-- `saveParsed` is the callback that is passed the ParsedModule +getModulesGhc :: GM.IOish m => (GM.GmlT m () -> GM.GmlT m a) -> [FilePath] -> (FilePath -> IO Bool) -> (TypecheckedModule -> IO ()) -> (ParsedModule -> IO ()) -> GM.GhcModT m a -getTypecheckedModuleGhc wrapper targetFiles keepInfo saveTypechecked saveParsed = do +getModulesGhc wrapper targetFiles keepInfo saveTypechecked saveParsed = do mfs <- GM.getMMappedFiles let ips = map takeDirectory $ Map.keys mfs setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs index ab4b54ab4..8ffce212a 100644 --- a/core/GhcModCore.hs +++ b/core/GhcModCore.hs @@ -41,8 +41,8 @@ module GhcModCore ( , loadMappedFileSource , unloadMappedFile -- * HIE integration utilities - , getTypecheckedModuleGhc - , getTypecheckedModuleGhc' + , getModulesGhc + , getModulesGhc' ) where import GhcMod.Cradle From 3be79fe40819851ea3b96aa1ea8bdbe7a02a3439 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 22 Sep 2018 17:49:05 +0200 Subject: [PATCH 21/50] Satisfies deps and configures with GHC 8.6.1 --- cabal.project | 21 ++++++++++++++++++++- core/ghc-mod-core.cabal | 6 +++--- ghc-mod.cabal | 28 ++++++++++++++-------------- 3 files changed, 37 insertions(+), 18 deletions(-) diff --git a/cabal.project b/cabal.project index 4b8b8e5f2..83c709426 100644 --- a/cabal.project +++ b/cabal.project @@ -1,3 +1,22 @@ packages: . ./core - ../cabal-helper + -- ../cabal-helper + -- ../polyparse + + +source-repository-package + type: git + location: https://github.com/bergmark/polyparse + tag: 8a69ee7e57db798c106d8b56dce05b1dfc4fed37 + + +source-repository-package + type: git + location: https://github.com/alanz/cabal-helper + tag: 4ba48c3b8bd0df732b5e65bc13655595a53392bb + +allow-newer:HTTP-4000.3.12:base +allow-newer:polyparse-1.12:base +allow-newer:unliftio-core-0.1.2.0:base +allow-newer:fclabels-2.0.3.3:base +allow-newer:fclabels-2.0.3.3:template-haskell diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index ddc5afed7..a281df939 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -94,7 +94,7 @@ Library , time , transformers - , base < 4.12 && >= 4.6.0.1 + , base < 4.14 && >= 4.6.0.1 , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 @@ -109,8 +109,8 @@ Library , temporary < 1.3 && >= 1.2.0.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 0.9 && >= 0.8.0.2 - , ghc < 8.5 && >= 7.6 + , cabal-helper < 1.1 && >= 1.0 + , ghc < 8.7 && >= 7.6 if impl(ghc >= 8.0) Build-Depends: ghc-boot diff --git a/ghc-mod.cabal b/ghc-mod.cabal index c52d098ec..17b213f83 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -92,7 +92,7 @@ Extra-Source-Files: ChangeLog Custom-Setup Setup-Depends: base - , Cabal < 2.3 && >= 1.24 + , Cabal < 2.5 && >= 1.24 , cabal-doctest < 1.1 && >= 1 Library @@ -135,7 +135,7 @@ Library , time , transformers - , base < 4.12 && >= 4.6.0.1 + , base < 4.14 && >= 4.6.0.1 -- , djinn-ghc < 0.1 && >= 0.0.2.2 , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 @@ -152,11 +152,11 @@ Library , split < 0.3 && >= 0.2.2 , syb < 0.8 && >= 0.5.1 , temporary < 1.3 && >= 1.2.0.3 - , text < 1.3 && >= 1.2.1.3 + , text < 1.4 && >= 1.2.1.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 0.9 && >= 0.8.0.0 - , ghc < 8.5 && >= 7.8 + , cabal-helper < 1.1 && >= 1.0 + , ghc < 8.7 && >= 7.8 if impl(ghc >= 8.0) Build-Depends: ghc-boot @@ -182,14 +182,14 @@ Executable ghc-mod , mtl , process - , base < 4.12 && >= 4.6.0.1 + , base < 4.14 && >= 4.6.0.1 , fclabels < 2.1 && >= 2.0 , monad-control < 1.1 && >= 1 , optparse-applicative < 0.15 && >= 0.13.0.0 , semigroups < 0.19 && >= 0.10.0 , split < 0.3 && >= 0.2.2 - , ghc < 8.5 && >= 7.8 + , ghc < 8.7 && >= 7.8 , ghc-mod , ghc-mod-core @@ -213,7 +213,7 @@ Executable ghc-modi , process , time - , base < 4.12 && >= 4.6.0.1 + , base < 4.14 && >= 4.6.0.1 , ghc-mod , ghc-mod-core @@ -226,7 +226,7 @@ Test-Suite doctest Ghc-Options: -Wall Default-Extensions: ConstraintKinds, FlexibleContexts Main-Is: doctests.hs - Build-Depends: base < 4.12 && >= 4.6.0.1 + Build-Depends: base < 4.14 && >= 4.6.0.1 , doctest < 0.16 && >= 0.11.3 Test-Suite spec @@ -273,7 +273,7 @@ Test-Suite spec , process , transformers - , base < 4.12 && >= 4.6.0.1 + , base < 4.14 && >= 4.6.0.1 , fclabels < 2.1 && >= 2.0 , hspec < 2.6 && >= 2.0.0 , monad-journal < 0.9 && >= 0.4 @@ -287,8 +287,8 @@ Test-Suite spec Build-Depends: ghc-boot Build-Depends: - cabal-helper < 0.9 && >= 0.8.0.0 - , ghc < 8.5 && >= 7.8 + cabal-helper < 1.1 && >= 0.8.0.0 + , ghc < 8.7 && >= 7.8 , ghc-mod , ghc-mod-core @@ -300,7 +300,7 @@ Test-Suite shelltest Type: exitcode-stdio-1.0 if flag(shelltest) Build-Tools: shelltest - Build-Depends: base < 4.12 && >= 4.6.0.1 + Build-Depends: base < 4.14 && >= 4.6.0.1 , process < 1.5 -- , shelltestrunner >= 1.3.5 if !flag(shelltest) @@ -320,7 +320,7 @@ Benchmark criterion directory , filepath - , base < 4.12 && >= 4.6.0.1 + , base < 4.14 && >= 4.6.0.1 , criterion < 1.2 && >= 1.1.1.0 , temporary < 1.3 && >= 1.2.0.3 From 65bc41d88a4088a8ec9636ac6c68da00ae42c5ca Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 22 Sep 2018 20:28:30 +0200 Subject: [PATCH 22/50] Update for Monad Fail Proposal And cabal-helper-1.0.0 --- GhcMod/Exe/Debug.hs | 22 ++++++++++++++-------- GhcMod/Exe/FillSig.hs | 6 ++++-- GhcMod/Exe/Test.hs | 5 ++++- core/GhcMod/Gap.hs | 8 +++++--- core/GhcMod/GhcPkg.hs | 12 ++++++++---- core/GhcMod/Logging.hs | 11 ++++++++--- core/GhcMod/PathsAndFiles.hs | 6 ++++++ core/GhcMod/Stack.hs | 15 +++++++++------ core/GhcMod/Target.hs | 5 ++++- 9 files changed, 62 insertions(+), 28 deletions(-) diff --git a/GhcMod/Exe/Debug.hs b/GhcMod/Exe/Debug.hs index 3cdfd4443..81db2cc8b 100644 --- a/GhcMod/Exe/Debug.hs +++ b/GhcMod/Exe/Debug.hs @@ -34,12 +34,15 @@ debugInfo = do Options {..} <- options Cradle {..} <- cradle - [ghcPath, ghcPkgPath] <- liftIO $ + mpaths <- liftIO $ case cradleProject of StackProject se -> catMaybes <$> sequence [getStackGhcPath se, getStackGhcPkgPath se] _ -> return ["ghc", "ghc-pkg"] + (ghcPath, ghcPkgPath) <- case mpaths of + [ghc,ghcp] -> return (ghc,ghcp) + _ -> error "pattern match fail" cabal <- case cradleProject of @@ -67,13 +70,16 @@ debugInfo = do stackPaths :: IOish m => GhcModT m [String] stackPaths = do - Cradle { cradleProject = StackProject senv } <- cradle - ghc <- getStackGhcPath senv - ghcPkg <- getStackGhcPkgPath senv - return $ - [ "Stack ghc executable: " ++ show ghc - , "Stack ghc-pkg executable:" ++ show ghcPkg - ] + Cradle { cradleProject = menv } <- cradle + case menv of + StackProject senv -> do + ghc <- getStackGhcPath senv + ghcPkg <- getStackGhcPkgPath senv + return $ + [ "Stack ghc executable: " ++ show ghc + , "Stack ghc-pkg executable:" ++ show ghcPkg + ] + _ -> error "stackPaths:expected a stack project" cabalDebug :: IOish m => FilePath -> GhcModT m [String] cabalDebug ghcPkgPath = do diff --git a/GhcMod/Exe/FillSig.hs b/GhcMod/Exe/FillSig.hs index 8791331ab..9c7f8cdc0 100644 --- a/GhcMod/Exe/FillSig.hs +++ b/GhcMod/Exe/FillSig.hs @@ -129,9 +129,11 @@ getSignature modSum lineNo colNo = do return $ Just $ Signature loc (map G.unLoc names) ty [L _ (G.InstD {})] -> do -- We found an instance declaration - TypecheckedModule{tm_renamed_source = Just tcs + TypecheckedModule{tm_renamed_source = mtcs ,tm_checked_module_info = minfo} <- G.typecheckModule p - let lst = listifyRenamedSpans tcs (lineNo, colNo) + let lst = case mtcs of + Just tcs -> listifyRenamedSpans tcs (lineNo, colNo) + _ -> error "pattern match fail" case Gap.getClass lst of Just (clsName,loc) -> obtainClassInfo minfo clsName loc _ -> return Nothing diff --git a/GhcMod/Exe/Test.hs b/GhcMod/Exe/Test.hs index 53d1801ae..e3fd7df5d 100644 --- a/GhcMod/Exe/Test.hs +++ b/GhcMod/Exe/Test.hs @@ -30,7 +30,10 @@ test f = runGmlT' [Left f] (fmap setHscInterpreted . deferErrors) $ do mdl = ms_mod ms mn = moduleName mdl - Just mi <- getModuleInfo mdl + mmi <- getModuleInfo mdl + mi <- case mmi of + Just mi -> return mi + _ -> error "pattern match fail" let exs = map (occNameString . getOccName) $ modInfoExports mi cqs = filter ("prop_" `isPrefixOf`) exs diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index a1482c726..5b65898b8 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -306,12 +306,14 @@ fileModSummary file' = do mss <- getModuleGraph file <- liftIO $ canonicalizePath file' #if __GLASGOW_HASKELL__ >= 804 - [ms] <- liftIO $ flip filterM (mgModSummaries mss) $ \m -> + mss <- liftIO $ flip filterM (mgModSummaries mss) $ \m -> #else - [ms] <- liftIO $ flip filterM mss $ \m -> + mss <- liftIO $ flip filterM mss $ \m -> #endif (Just file==) <$> canonicalizePath `traverse` ml_hs_file (ms_location m) - return ms + case mss of + [ms] -> return ms + _ -> error "pattern match Fail" withInteractiveContext :: GhcMonad m => m a -> m a withInteractiveContext action = gbracket setup teardown body diff --git a/core/GhcMod/GhcPkg.hs b/core/GhcMod/GhcPkg.hs index 746b2eac9..b2412ebef 100644 --- a/core/GhcMod/GhcPkg.hs +++ b/core/GhcMod/GhcPkg.hs @@ -68,8 +68,10 @@ getGhcPkgProgram = do progs <- optPrograms <$> options case cradleProject crdl of (StackProject senv) -> do - Just ghcPkg <- getStackGhcPkgPath senv - return ghcPkg + mghcPkg <- getStackGhcPkgPath senv + case mghcPkg of + Just ghcPkg -> return ghcPkg + _ -> error "pattern match fail" _ -> return $ ghcPkgProgram progs @@ -81,8 +83,10 @@ getPackageDbStack = do PlainProject -> return [GlobalDb, UserDb] SandboxProject -> do - Just db <- liftIO $ getSandboxDb crdl - return $ [GlobalDb, db] + mdb <- liftIO $ getSandboxDb crdl + case mdb of + Just db -> return $ [GlobalDb, db] + _ -> error "pattern match fail" CabalProject -> getCabalPackageDbStack (StackProject StackEnv {..}) -> diff --git a/core/GhcMod/Logging.hs b/core/GhcMod/Logging.hs index 930a56b68..7d5ffc878 100644 --- a/core/GhcMod/Logging.hs +++ b/core/GhcMod/Logging.hs @@ -48,8 +48,10 @@ gmSetLogLevel level = gmGetLogLevel :: forall m. GmLog m => m GmLogLevel gmGetLogLevel = do - GhcModLog { gmLogLevel = Just level } <- gmlHistory - return level + GhcModLog { gmLogLevel = mlevel } <- gmlHistory + case mlevel of + Just level -> return level + _ -> error "mempty value for GhcModLog must use a Just value" gmSetDumpLevel :: GmLog m => Bool -> m () gmSetDumpLevel level = @@ -73,7 +75,10 @@ decreaseLogLevel l = pred l -- False gmLog :: (MonadIO m, GmLog m, GmOut m) => GmLogLevel -> String -> Doc -> m () gmLog level loc' doc = do - GhcModLog { gmLogLevel = Just level' } <- gmlHistory + GhcModLog { gmLogLevel = mlevel' } <- gmlHistory + level' <- case mlevel' of + Nothing -> error "mempty value for GhcModLog must use a Just value" + Just l -> return l let loc | loc' == "" = empty | otherwise = text loc' <+>: empty diff --git a/core/GhcMod/PathsAndFiles.hs b/core/GhcMod/PathsAndFiles.hs index c55987c24..560dcaaad 100644 --- a/core/GhcMod/PathsAndFiles.hs +++ b/core/GhcMod/PathsAndFiles.hs @@ -14,6 +14,7 @@ -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see . +{-# LANGUAGE CPP #-} module GhcMod.PathsAndFiles ( module GhcMod.PathsAndFiles , module GhcMod.Caching @@ -81,7 +82,12 @@ findCustomPackageDbFile dir = getSandboxDb :: Cradle -> IO (Maybe GhcPkgDb) getSandboxDb crdl = do mConf <- traverse readFile =<< mightExist (sandboxConfigFile crdl) + +#if MIN_VERSION_cabal_helper(1,0,0) + bp <- return buildPlatform +#else bp <- buildPlatform readProcess +#endif return $ PackageDb . fixPkgDbVer bp <$> (extractSandboxDbDir =<< mConf) where diff --git a/core/GhcMod/Stack.hs b/core/GhcMod/Stack.hs index 0c0ada00e..4a1605fb1 100644 --- a/core/GhcMod/Stack.hs +++ b/core/GhcMod/Stack.hs @@ -40,12 +40,15 @@ import Prelude patchStackPrograms :: (IOish m, GmOut m) => Cradle -> Programs -> m Programs patchStackPrograms Cradle { cradleProject = (StackProject senv) } progs = do - Just ghc <- getStackGhcPath senv - Just ghcPkg <- getStackGhcPkgPath senv - return $ progs { - ghcProgram = ghc - , ghcPkgProgram = ghcPkg - } + mghc <- getStackGhcPath senv + mghcPkg <- getStackGhcPkgPath senv + case (mghc,mghcPkg) of + (Just ghc,Just ghcPkg) -> + return $ progs { + ghcProgram = ghc + , ghcPkgProgram = ghcPkg + } + _ -> error "pattern match fail" patchStackPrograms _crdl progs = return progs getStackEnv :: (IOish m, GmOut m, GmLog m) diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index 63d295d01..463e5deda 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -206,7 +206,10 @@ runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do (text "Initializing GHC session with following options") (intercalate " " $ map (("\""++) . (++"\"")) opts') - GhcModLog { gmLogLevel = Just level } <- gmlHistory + GhcModLog { gmLogLevel = mlevel } <- gmlHistory + level <- case mlevel of + Just level -> return level + _ -> error "pattern match fail" putErr <- gmErrStrIO let setLogger | level >= GmDebug = setDebugLogger putErr | otherwise = setEmptyLogger From 4461cafd271edbac16995bdd297eb3099a700dcc Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 26 Oct 2018 09:38:08 +1100 Subject: [PATCH 23/50] use new dist-dir command --- core/GhcMod/CabalHelper.hs | 3 +++ core/GhcMod/Cradle.hs | 19 ++++++++++++++++++- core/ghc-mod-core.cabal | 2 ++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index cf95cd894..e51501a8f 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -22,6 +22,9 @@ module GhcMod.CabalHelper , prepareCabalHelper , withAutogen , withCabal + + , runCHQuery + , packageId ) where import Control.Applicative diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 6def07299..c7dd90726 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -27,6 +27,10 @@ import System.FilePath import System.Environment import Prelude import Control.Monad.Trans.Journal (runJournalT) +import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, distDir) +-- import Distribution.System (buildPlatform) +import Data.List (intercalate) +import Data.Version (Version(..)) ---------------------------------------------------------------- @@ -74,6 +78,16 @@ fillTempDir crdl = do tmpDir <- liftIO $ newTempDir (cradleRootDir crdl) return crdl { cradleTempDir = tmpDir } +-- run :: Monad m => QueryEnv -> Maybe SomeLocalBuildInfo -> Query m a -> m a +-- run e s action = flip runReaderT e (flip evalStateT s (unQuery action)) + +-- -- | @runQuery env query@. Run a 'Query' under a given 'QueryEnv'. +-- runQuery :: Monad m +-- => QueryEnv +-- -> Query m a +-- -> m a +-- runQuery qe action = run qe Nothing action + cabalCradle :: (IOish m, GmLog m, GmOut m) => FilePath -> FilePath -> MaybeT m Cradle cabalCradle cabalProg wdir = do @@ -92,6 +106,9 @@ cabalCradle cabalProg wdir = do -- Or default to is for cabal >= 2.0 ?, unless flag saying old style if isDistNewstyle then do + let bp = "x86_64-osx" + dd <- liftIO $ runQuery (mkQueryEnv "." "dist-newstyle") distDir + gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir return Cradle { cradleProject = CabalNewProject @@ -99,7 +116,7 @@ cabalCradle cabalProg wdir = do , cradleRootDir = cabalDir , cradleTempDir = error "tmpDir" , cradleCabalFile = Just cabalFile - , cradleDistDir = "dist-newstyle" + , cradleDistDir = dd } else do gmLog GmInfo "" $ text "Using Cabal project at" <+>: text cabalDir diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index ddc5afed7..9a61131fa 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -94,6 +94,8 @@ Library , time , transformers + -- , Cabal + , base < 4.12 && >= 4.6.0.1 , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 From 5dc532bfe4fadfd10419a40065a4a4d0a071a47e Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 26 Oct 2018 11:47:00 +1100 Subject: [PATCH 24/50] remove hardcoded . --- core/GhcMod/Cradle.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index c7dd90726..2cd910ba1 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -107,7 +107,7 @@ cabalCradle cabalProg wdir = do if isDistNewstyle then do let bp = "x86_64-osx" - dd <- liftIO $ runQuery (mkQueryEnv "." "dist-newstyle") distDir + dd <- liftIO $ runQuery (mkQueryEnv wdir "dist-newstyle") distDir gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir return Cradle { From 9844e57e3f657781020d668589e0b558ef90c0c8 Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 26 Oct 2018 12:09:49 +1100 Subject: [PATCH 25/50] use proper dir --- core/GhcMod/Cradle.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 2cd910ba1..9af3b2c2b 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -107,7 +107,7 @@ cabalCradle cabalProg wdir = do if isDistNewstyle then do let bp = "x86_64-osx" - dd <- liftIO $ runQuery (mkQueryEnv wdir "dist-newstyle") distDir + dd <- liftIO $ runQuery (mkQueryEnv cabalDir "dist-newstyle") distDir gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir return Cradle { From 40da7b7a35fb01a29731b9f6b432c3c3a3d6dc1e Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 26 Oct 2018 14:15:05 +1100 Subject: [PATCH 26/50] cabal-helper-1.0.0.0 --- ghc-mod.cabal | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 49ea466d1..a35e97805 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -155,7 +155,7 @@ Library , text < 1.3 && >= 1.2.1.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 0.9 && >= 0.8.0.0 + , cabal-helper < 1.9 && >= 1.0.0.0 , ghc < 8.5 && >= 7.8 , ghc-mod-core From 97a3a4e463809c3512b8680bf938af693cc38d3b Mon Sep 17 00:00:00 2001 From: David Turnbull Date: Fri, 26 Oct 2018 14:18:26 +1100 Subject: [PATCH 27/50] also tell ghc-mod-core to use cabal-helper-1.0.0.0 --- core/ghc-mod-core.cabal | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 9a61131fa..2d771048f 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -111,7 +111,7 @@ Library , temporary < 1.3 && >= 1.2.0.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 0.9 && >= 0.8.0.2 + , cabal-helper < 1.9 && >= 1.0.0.0 , ghc < 8.5 && >= 7.6 if impl(ghc >= 8.0) From 8da12556dd131cc5b8415283ab9f05082d834797 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Tue, 6 Nov 2018 22:05:21 +0200 Subject: [PATCH 28/50] Fix compilation --- core/GhcMod/PathsAndFiles.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/GhcMod/PathsAndFiles.hs b/core/GhcMod/PathsAndFiles.hs index 560dcaaad..38be2b8d1 100644 --- a/core/GhcMod/PathsAndFiles.hs +++ b/core/GhcMod/PathsAndFiles.hs @@ -83,11 +83,11 @@ getSandboxDb :: Cradle -> IO (Maybe GhcPkgDb) getSandboxDb crdl = do mConf <- traverse readFile =<< mightExist (sandboxConfigFile crdl) -#if MIN_VERSION_cabal_helper(1,0,0) - bp <- return buildPlatform -#else +-- #if MIN_VERSION_cabal_helper(1,0,0) +-- bp <- return buildPlatform +-- #else bp <- buildPlatform readProcess -#endif +-- #endif return $ PackageDb . fixPkgDbVer bp <$> (extractSandboxDbDir =<< mConf) where From f4a7c89f8ae449e8d6ee766274b47c067b356523 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Thu, 8 Nov 2018 10:13:33 +0200 Subject: [PATCH 29/50] Delete some dead code --- core/GhcMod/Cradle.hs | 1 - 1 file changed, 1 deletion(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 9af3b2c2b..df3e6624d 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -106,7 +106,6 @@ cabalCradle cabalProg wdir = do -- Or default to is for cabal >= 2.0 ?, unless flag saying old style if isDistNewstyle then do - let bp = "x86_64-osx" dd <- liftIO $ runQuery (mkQueryEnv cabalDir "dist-newstyle") distDir gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir From f321acd18dbabf6e91e45e39713b33deec290806 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Thu, 8 Nov 2018 12:33:31 +0200 Subject: [PATCH 30/50] Can build tests too --- cabal.project | 13 +------------ ghc-mod.cabal | 2 +- test/CustomPackageDbSpec.hs | 5 ++++- test/GhcPkgSpec.hs | 5 ++++- test/MonadSpec.hs | 9 ++++++++- test/TestUtils.hs | 8 +------- 6 files changed, 19 insertions(+), 23 deletions(-) diff --git a/cabal.project b/cabal.project index 83c709426..a7a2fc926 100644 --- a/cabal.project +++ b/cabal.project @@ -4,19 +4,8 @@ packages: . -- ../polyparse -source-repository-package - type: git - location: https://github.com/bergmark/polyparse - tag: 8a69ee7e57db798c106d8b56dce05b1dfc4fed37 - - source-repository-package type: git location: https://github.com/alanz/cabal-helper - tag: 4ba48c3b8bd0df732b5e65bc13655595a53392bb + tag: 3d13936af2f8fa565e0a64431c6ed309b91b2695 -allow-newer:HTTP-4000.3.12:base -allow-newer:polyparse-1.12:base -allow-newer:unliftio-core-0.1.2.0:base -allow-newer:fclabels-2.0.3.3:base -allow-newer:fclabels-2.0.3.3:template-haskell diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 5274db145..c10022987 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -227,7 +227,7 @@ Test-Suite doctest Default-Extensions: ConstraintKinds, FlexibleContexts Main-Is: doctests.hs Build-Depends: base < 4.14 && >= 4.6.0.1 - , doctest < 0.16 && >= 0.11.3 + , doctest < 0.17 && >= 0.11.3 Test-Suite spec Default-Language: Haskell2010 diff --git a/test/CustomPackageDbSpec.hs b/test/CustomPackageDbSpec.hs index f25d59a5c..a1a3207e8 100644 --- a/test/CustomPackageDbSpec.hs +++ b/test/CustomPackageDbSpec.hs @@ -28,7 +28,10 @@ spec = do withDirectory_ "test/data/custom-cradle" $ do _ <- system "cabal configure" (s, s') <- runD $ do - Just stack <- getCustomPkgDbStack + mstack <- getCustomPkgDbStack + stack <- case mstack of + Just stack -> return stack + _ -> error "match failed" withCabal $ do stack' <- getCabalPackageDbStack return (stack, stack') diff --git a/test/GhcPkgSpec.hs b/test/GhcPkgSpec.hs index 19a160491..8ecdb4dbf 100644 --- a/test/GhcPkgSpec.hs +++ b/test/GhcPkgSpec.hs @@ -16,7 +16,10 @@ spec = do withDirectory_ "test/data/custom-cradle" $ do _ <- system "cabal configure" (s, s') <- runD $ do - Just stack <- getCustomPkgDbStack + mstack <- getCustomPkgDbStack + stack <- case mstack of + Just stack -> return stack + _ -> error "match failed" withCabal $ do stack' <- getPackageDbStack return (stack, stack') diff --git a/test/MonadSpec.hs b/test/MonadSpec.hs index 1110e7666..be02b2a1d 100644 --- a/test/MonadSpec.hs +++ b/test/MonadSpec.hs @@ -1,3 +1,4 @@ +{-# LANGUAGe CPP #-} module MonadSpec where import Test.Hspec @@ -13,8 +14,14 @@ spec = do (a, _h) <- runGmOutDef $ runGhcModT defaultOptions $ do +#if __GLASGOW_HASKELL__ >= 806 + mj <- return Nothing + case mj of + Just _ -> return "hello" + Nothing -> fail "oh noes" +#else Just _ <- return Nothing - return "hello" +#endif `catchError` (const $ fail "oh noes") a `shouldBe` (Left $ GMEString "oh noes") diff --git a/test/TestUtils.hs b/test/TestUtils.hs index 41f24d1f2..9be17968c 100644 --- a/test/TestUtils.hs +++ b/test/TestUtils.hs @@ -2,7 +2,6 @@ module TestUtils ( run , runD - , runV , runD' , runV , runE @@ -75,16 +74,11 @@ runD :: GhcModT IO a -> IO a runD = extract . runGhcModTSpec (setLogLevel testLogLevel defaultOptions) --- | Run GhcMod with default options, and vomit log level -runV :: GhcModT IO a -> IO a -runV = - extract . runGhcModTSpec (setLogLevel GmVomit defaultOptions) - runD' :: FilePath -> GhcModT IO a -> IO a runD' dir = extract . runGhcModTSpec' dir (setLogLevel testLogLevel defaultOptions) --- | Run GhcMod with default options +-- | Run GhcMod with default options, and vomit log level runV :: GhcModT IO a -> IO a runV = extract . runGhcModTSpec (setLogLevel GmVomit defaultOptions) From b51eff38ce2a8a5993ba6adf686515359db915f6 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Thu, 8 Nov 2018 22:54:17 +0200 Subject: [PATCH 31/50] Use cabal-helper 0.9.0.0 --- core/ghc-mod-core.cabal | 2 +- ghc-mod.cabal | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 507b60248..63cf82c78 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -109,7 +109,7 @@ Library , temporary < 1.3 && >= 1.2.0.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 1.9 && >= 1.0 + , cabal-helper < 0.10 && >= 0.9.0.0 , ghc < 8.7 && >= 7.6 if impl(ghc >= 8.0) diff --git a/ghc-mod.cabal b/ghc-mod.cabal index c10022987..4757a5531 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -155,7 +155,7 @@ Library , text < 1.4 && >= 1.2.1.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 1.9 && >= 1.0.0.0 + , cabal-helper < 0.10 && >= 0.9.0.0 , ghc < 8.7 && >= 7.8 if impl(ghc >= 8.0) @@ -286,7 +286,7 @@ Test-Suite spec Build-Depends: ghc-boot Build-Depends: - cabal-helper < 1.1 && >= 0.8.0.0 + cabal-helper < 0.10 && >= 0.9.0.0 , ghc < 8.7 && >= 7.8 , ghc-mod , ghc-mod-core From a2b695d4350b3dc9fef0474ff9b1048c839ed333 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Fri, 9 Nov 2018 10:49:21 +0200 Subject: [PATCH 32/50] Remove unused compatibility flag, add Compat.hs_h to dist --- core/GhcMod/Monad/Compat.hs_h | 3 --- core/ghc-mod-core.cabal | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/core/GhcMod/Monad/Compat.hs_h b/core/GhcMod/Monad/Compat.hs_h index 7437bfc90..cd90e5f1a 100644 --- a/core/GhcMod/Monad/Compat.hs_h +++ b/core/GhcMod/Monad/Compat.hs_h @@ -22,7 +22,4 @@ -- 'CoreMonad.MonadIO' and 'Control.Monad.IO.Class.MonadIO' are different -- classes before ghc 7.8 #define DIFFERENT_MONADIO 1 - --- RWST doen't have a MonadIO instance before ghc 7.8 -#define MONADIO_INSTANCES 1 #endif diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 63cf82c78..ad2c1847e 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -26,6 +26,7 @@ Description: Category: GHC, Development Cabal-Version: >= 1.24 Build-Type: Simple +Extra-Source-Files: GhcMod/Monad/Compat.hs_h Library Default-Language: Haskell2010 From 03739d5b6530a7d76668a97544b3ce1f2d6cd899 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 10 Nov 2018 15:54:03 +0200 Subject: [PATCH 33/50] Ignore .ghc.environment.* files Since ghc-mod goes to a lot of trouble to work out the environment all by itself. --- core/GhcMod/DynFlags.hs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/core/GhcMod/DynFlags.hs b/core/GhcMod/DynFlags.hs index 2021dcf0e..5b259e057 100644 --- a/core/GhcMod/DynFlags.hs +++ b/core/GhcMod/DynFlags.hs @@ -57,7 +57,13 @@ setHscInterpreted df = df { -- | Parse command line ghc options and add them to the 'DynFlags' passed addCmdOpts :: GhcMonad m => [GHCOption] -> DynFlags -> m DynFlags addCmdOpts cmdOpts df = - fst3 <$> G.parseDynamicFlags df (map G.noLoc cmdOpts) + -- + -- Passes "-hide-all-packages" to the GHC API to prevent parsing of + -- package environment files. However this only works if there is no + -- invocation of `setSessionDynFlags` before calling `initDynFlagsPure`. + -- See ghc tickets #15513, #15541. + -- Thanks @lspitzner + fst3 <$> G.parseDynamicFlags df (map G.noLoc ("-hide-all-packages":cmdOpts)) where fst3 (a,_,_) = a From b83dbb9a59ce00c4cc26151bb2111629a0907adc Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 10 Nov 2018 19:05:56 +0200 Subject: [PATCH 34/50] Use flag for disabling loading of .ghc.environment files They are still needed for plain projects, without stack or cabal files --- core/GhcMod/Cradle.hs | 9 +++++++++ core/GhcMod/DynFlags.hs | 30 +++++++++++++++++------------- core/GhcMod/LightGhc.hs | 6 +++--- core/GhcMod/Target.hs | 28 +++++++++++++++++++++------- 4 files changed, 50 insertions(+), 23 deletions(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index df3e6624d..edd5a3f28 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -5,6 +5,7 @@ module GhcMod.Cradle , findCradleNoLog , findSpecCradle , cleanupCradle + , shouldHideAllPackages -- * for @spec@ , plainCradle @@ -214,3 +215,11 @@ plainCradle wdir = do , cradleCabalFile = Nothing , cradleDistDir = "dist" } + +-- | Cabal produces .ghc.environment files which are loaded by GHC if +-- they exist. For all bar a plain style project this is incorrect +-- behaviour for ghc-mod, as ghc-mod works out which packages should +-- be loaded. +-- Identify whether this should be inhibited or not +shouldHideAllPackages :: Cradle -> Bool +shouldHideAllPackages crdl = not (cradleProject crdl == PlainProject) diff --git a/core/GhcMod/DynFlags.hs b/core/GhcMod/DynFlags.hs index 5b259e057..3384eb32e 100644 --- a/core/GhcMod/DynFlags.hs +++ b/core/GhcMod/DynFlags.hs @@ -55,15 +55,19 @@ setHscInterpreted df = df { } -- | Parse command line ghc options and add them to the 'DynFlags' passed -addCmdOpts :: GhcMonad m => [GHCOption] -> DynFlags -> m DynFlags -addCmdOpts cmdOpts df = - -- - -- Passes "-hide-all-packages" to the GHC API to prevent parsing of - -- package environment files. However this only works if there is no - -- invocation of `setSessionDynFlags` before calling `initDynFlagsPure`. - -- See ghc tickets #15513, #15541. - -- Thanks @lspitzner - fst3 <$> G.parseDynamicFlags df (map G.noLoc ("-hide-all-packages":cmdOpts)) +addCmdOpts :: GhcMonad m => Bool -> [GHCOption] -> DynFlags -> m DynFlags +addCmdOpts hideAllPackages cmdOpts df = + if not hideAllPackages + then fst3 <$> G.parseDynamicFlags df (map G.noLoc cmdOpts) + else + -- + -- Passes "-hide-all-packages" to the GHC API to prevent parsing of + -- package environment files. However this only works if there is no + -- invocation of `setSessionDynFlags` before calling `initDynFlagsPure`. + -- See ghc tickets #15513, #15541. + -- Thanks @lspitzner + fst3 <$> G.parseDynamicFlags df (map G.noLoc ("-hide-all-packages":cmdOpts)) + -- fst3 <$> G.parseDynamicFlags df (map G.noLoc cmdOpts) where fst3 (a,_,_) = a @@ -81,12 +85,12 @@ withDynFlags setFlags body = G.gbracket setup teardown (\_ -> body) return dflags teardown = void . G.setSessionDynFlags -withCmdFlags :: GhcMonad m => [GHCOption] -> m a -> m a -withCmdFlags flags body = G.gbracket setup teardown (\_ -> body) +withCmdFlags :: GhcMonad m => Bool -> [GHCOption] -> m a -> m a +withCmdFlags hideAllPackages flags body = G.gbracket setup teardown (\_ -> body) where setup = do dflags <- G.getSessionDynFlags - void $ G.setSessionDynFlags =<< addCmdOpts flags dflags + void $ G.setSessionDynFlags =<< addCmdOpts hideAllPackages flags dflags return dflags teardown = void . G.setSessionDynFlags @@ -104,7 +108,7 @@ allWarningFlags :: Gap.WarnFlags allWarningFlags = unsafePerformIO $ G.runGhc (Just libdir) $ do df <- G.getSessionDynFlags - df' <- addCmdOpts ["-Wall"] df + df' <- addCmdOpts False ["-Wall"] df return $ G.warningFlags df' ---------------------------------------------------------------- diff --git a/core/GhcMod/LightGhc.hs b/core/GhcMod/LightGhc.hs index 7e441c731..39d8daa53 100644 --- a/core/GhcMod/LightGhc.hs +++ b/core/GhcMod/LightGhc.hs @@ -61,13 +61,13 @@ withLightHscEnv' :: IOish m => (DynFlags -> LightGhc DynFlags) -> (HscEnv -> m a) -> m a withLightHscEnv' mdf action = gbracket (newLightEnv mdf) teardownLightEnv action -withLightHscEnv :: IOish m => [GHCOption] -> (HscEnv -> m a) -> m a -withLightHscEnv opts = withLightHscEnv' (f <=< liftIO . newHscEnv) +withLightHscEnv :: IOish m => Bool -> [GHCOption] -> (HscEnv -> m a) -> m a +withLightHscEnv hideAllPackages opts = withLightHscEnv' (f <=< liftIO . newHscEnv) where f env = runLightGhc env $ do -- HomeModuleGraph and probably all other clients get into all sorts of -- trouble if the package state isn't initialized here - _ <- setSessionDynFlags =<< addCmdOpts opts =<< getSessionDynFlags + _ <- setSessionDynFlags =<< addCmdOpts hideAllPackages opts =<< getSessionDynFlags getSessionDynFlags runLightGhc :: MonadIO m => HscEnv -> LightGhc a -> m a diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index 049d6835b..b5ef445da 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -33,6 +33,7 @@ import DynFlags import HscTypes import Pretty +import GhcMod.Cradle import GhcMod.DynFlags import GhcMod.Monad.Types import GhcMod.CabalHelper @@ -70,8 +71,10 @@ import System.FilePath runGmPkgGhc :: (IOish m, Gm m) => LightGhc a -> m a runGmPkgGhc action = do + crdl <- cradle + let hideAllPackages = shouldHideAllPackages crdl pkgOpts <- packageGhcOptions - withLightHscEnv pkgOpts $ \env -> liftIO $ runLightGhc env action + withLightHscEnv hideAllPackages pkgOpts $ \env -> liftIO $ runLightGhc env action initSession :: IOish m => [GHCOption] @@ -104,8 +107,10 @@ initSession opts mdf = do else gmLog GmDebug "initSession" $ text "Session already initialized" where - initDF Cradle { cradleTempDir } df = - setTmpDir cradleTempDir <$> (mdf =<< addCmdOpts opts df) + initDF c@Cradle { cradleTempDir, cradleProject } df = + if shouldHideAllPackages c + then setTmpDir cradleTempDir <$> (mdf =<< addCmdOpts False opts df) + else setTmpDir cradleTempDir <$> (mdf =<< addCmdOpts True opts df) teardownSession hsc_env_ref = do hsc_env <- liftIO $ readIORef hsc_env_ref @@ -196,6 +201,11 @@ runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do let opts' = opts ++ ["-O0", "-fno-warn-missing-home-modules"] ++ optGhcUserOptions + gmVomit + "session-ghc-options" + (text "hide all packages(ignore .ghc.environment):") + (show $ shouldHideAllPackages crdl) + gmVomit "session-ghc-options" (text "Using the following mapped files") @@ -388,8 +398,10 @@ resolveGmComponent :: (IOish m, Gm m) -> m (GmComponent 'GMCResolved (Set ModulePath)) resolveGmComponent mums c@GmComponent {..} = do distDir <- cradleDistDir <$> cradle + crdl <- cradle + let hideAllPackages = shouldHideAllPackages crdl gmLog GmDebug "resolveGmComponent" $ text $ show $ ghcOpts distDir - withLightHscEnv (ghcOpts distDir) $ \env -> do + withLightHscEnv hideAllPackages (ghcOpts distDir) $ \env -> do let srcDirs = if null gmcSourceDirs then [""] else gmcSourceDirs let mg = gmcHomeModuleGraph let simp = gmcEntrypoints @@ -413,9 +425,9 @@ resolveEntrypoint :: (IOish m, Gm m) => Cradle -> GmComponent 'GMCRaw ChEntrypoint -> m (GmComponent 'GMCRaw (Set ModulePath)) -resolveEntrypoint Cradle {..} c@GmComponent {..} = do +resolveEntrypoint crdl@Cradle {..} c@GmComponent {..} = do gmLog GmDebug "resolveEntrypoint" $ text $ show $ gmcGhcSrcOpts - withLightHscEnv gmcGhcSrcOpts $ \env -> do + withLightHscEnv (shouldHideAllPackages crdl) gmcGhcSrcOpts $ \env -> do let srcDirs = if null gmcSourceDirs then [""] else gmcSourceDirs eps <- liftIO $ resolveChEntrypoints cradleRootDir gmcEntrypoints rms <- resolveModule env srcDirs `mapM` eps @@ -508,8 +520,10 @@ resolveGmComponents mcache cs = do -- | Set the files as targets and load them. loadTargets :: IOish m => [GHCOption] -> [FilePath] -> Maybe (GHC.Hooks -> GHC.Hooks) -> GmlT m () loadTargets opts targetStrs mUpdateHooks = do + crdl <- cradle + let hideAllPackages = shouldHideAllPackages crdl targets' <- - withLightHscEnv opts $ \env -> + withLightHscEnv hideAllPackages opts $ \env -> liftM (nubBy ((==) `on` targetId)) (mapM ((`guessTarget` Nothing) >=> mapFile env) targetStrs) >>= mapM relativize From 82b5fcae88ee231d0194c4ae090f4d2f1c18d4c0 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 10 Nov 2018 19:38:59 +0200 Subject: [PATCH 35/50] Introduce LoadGhcEnvironment type To avoid boolean blindness --- core/GhcMod/Cradle.hs | 9 ++++++--- core/GhcMod/DynFlags.hs | 14 +++++++------- core/GhcMod/LightGhc.hs | 6 +++--- core/GhcMod/Target.hs | 20 +++++++++----------- core/GhcMod/Types.hs | 4 ++++ 5 files changed, 29 insertions(+), 24 deletions(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index edd5a3f28..5cb2418a1 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -5,7 +5,7 @@ module GhcMod.Cradle , findCradleNoLog , findSpecCradle , cleanupCradle - , shouldHideAllPackages + , shouldLoadGhcEnvironment -- * for @spec@ , plainCradle @@ -221,5 +221,8 @@ plainCradle wdir = do -- behaviour for ghc-mod, as ghc-mod works out which packages should -- be loaded. -- Identify whether this should be inhibited or not -shouldHideAllPackages :: Cradle -> Bool -shouldHideAllPackages crdl = not (cradleProject crdl == PlainProject) +shouldLoadGhcEnvironment :: Cradle -> LoadGhcEnvironment +shouldLoadGhcEnvironment crdl = + if cradleProject crdl == PlainProject + then LoadGhcEnvironment + else DontLoadGhcEnvironment diff --git a/core/GhcMod/DynFlags.hs b/core/GhcMod/DynFlags.hs index 3384eb32e..ba4fadb51 100644 --- a/core/GhcMod/DynFlags.hs +++ b/core/GhcMod/DynFlags.hs @@ -55,9 +55,9 @@ setHscInterpreted df = df { } -- | Parse command line ghc options and add them to the 'DynFlags' passed -addCmdOpts :: GhcMonad m => Bool -> [GHCOption] -> DynFlags -> m DynFlags -addCmdOpts hideAllPackages cmdOpts df = - if not hideAllPackages +addCmdOpts :: GhcMonad m => LoadGhcEnvironment -> [GHCOption] -> DynFlags -> m DynFlags +addCmdOpts loadGhcEnv cmdOpts df = + if loadGhcEnv == LoadGhcEnvironment then fst3 <$> G.parseDynamicFlags df (map G.noLoc cmdOpts) else -- @@ -85,12 +85,12 @@ withDynFlags setFlags body = G.gbracket setup teardown (\_ -> body) return dflags teardown = void . G.setSessionDynFlags -withCmdFlags :: GhcMonad m => Bool -> [GHCOption] -> m a -> m a -withCmdFlags hideAllPackages flags body = G.gbracket setup teardown (\_ -> body) +withCmdFlags :: GhcMonad m => LoadGhcEnvironment -> [GHCOption] -> m a -> m a +withCmdFlags loadGhcEnv flags body = G.gbracket setup teardown (\_ -> body) where setup = do dflags <- G.getSessionDynFlags - void $ G.setSessionDynFlags =<< addCmdOpts hideAllPackages flags dflags + void $ G.setSessionDynFlags =<< addCmdOpts loadGhcEnv flags dflags return dflags teardown = void . G.setSessionDynFlags @@ -108,7 +108,7 @@ allWarningFlags :: Gap.WarnFlags allWarningFlags = unsafePerformIO $ G.runGhc (Just libdir) $ do df <- G.getSessionDynFlags - df' <- addCmdOpts False ["-Wall"] df + df' <- addCmdOpts LoadGhcEnvironment ["-Wall"] df return $ G.warningFlags df' ---------------------------------------------------------------- diff --git a/core/GhcMod/LightGhc.hs b/core/GhcMod/LightGhc.hs index 39d8daa53..b9f758250 100644 --- a/core/GhcMod/LightGhc.hs +++ b/core/GhcMod/LightGhc.hs @@ -61,13 +61,13 @@ withLightHscEnv' :: IOish m => (DynFlags -> LightGhc DynFlags) -> (HscEnv -> m a) -> m a withLightHscEnv' mdf action = gbracket (newLightEnv mdf) teardownLightEnv action -withLightHscEnv :: IOish m => Bool -> [GHCOption] -> (HscEnv -> m a) -> m a -withLightHscEnv hideAllPackages opts = withLightHscEnv' (f <=< liftIO . newHscEnv) +withLightHscEnv :: IOish m => LoadGhcEnvironment -> [GHCOption] -> (HscEnv -> m a) -> m a +withLightHscEnv loadGhcEnv opts = withLightHscEnv' (f <=< liftIO . newHscEnv) where f env = runLightGhc env $ do -- HomeModuleGraph and probably all other clients get into all sorts of -- trouble if the package state isn't initialized here - _ <- setSessionDynFlags =<< addCmdOpts hideAllPackages opts =<< getSessionDynFlags + _ <- setSessionDynFlags =<< addCmdOpts loadGhcEnv opts =<< getSessionDynFlags getSessionDynFlags runLightGhc :: MonadIO m => HscEnv -> LightGhc a -> m a diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index b5ef445da..d752e6500 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -72,9 +72,9 @@ import System.FilePath runGmPkgGhc :: (IOish m, Gm m) => LightGhc a -> m a runGmPkgGhc action = do crdl <- cradle - let hideAllPackages = shouldHideAllPackages crdl + let loadGhcEnv = shouldLoadGhcEnvironment crdl pkgOpts <- packageGhcOptions - withLightHscEnv hideAllPackages pkgOpts $ \env -> liftIO $ runLightGhc env action + withLightHscEnv loadGhcEnv pkgOpts $ \env -> liftIO $ runLightGhc env action initSession :: IOish m => [GHCOption] @@ -108,9 +108,7 @@ initSession opts mdf = do gmLog GmDebug "initSession" $ text "Session already initialized" where initDF c@Cradle { cradleTempDir, cradleProject } df = - if shouldHideAllPackages c - then setTmpDir cradleTempDir <$> (mdf =<< addCmdOpts False opts df) - else setTmpDir cradleTempDir <$> (mdf =<< addCmdOpts True opts df) + setTmpDir cradleTempDir <$> (mdf =<< addCmdOpts (shouldLoadGhcEnvironment c) opts df) teardownSession hsc_env_ref = do hsc_env <- liftIO $ readIORef hsc_env_ref @@ -204,7 +202,7 @@ runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do gmVomit "session-ghc-options" (text "hide all packages(ignore .ghc.environment):") - (show $ shouldHideAllPackages crdl) + (show $ shouldLoadGhcEnvironment crdl) gmVomit "session-ghc-options" @@ -399,9 +397,9 @@ resolveGmComponent :: (IOish m, Gm m) resolveGmComponent mums c@GmComponent {..} = do distDir <- cradleDistDir <$> cradle crdl <- cradle - let hideAllPackages = shouldHideAllPackages crdl + let loadGhcEnv = shouldLoadGhcEnvironment crdl gmLog GmDebug "resolveGmComponent" $ text $ show $ ghcOpts distDir - withLightHscEnv hideAllPackages (ghcOpts distDir) $ \env -> do + withLightHscEnv loadGhcEnv (ghcOpts distDir) $ \env -> do let srcDirs = if null gmcSourceDirs then [""] else gmcSourceDirs let mg = gmcHomeModuleGraph let simp = gmcEntrypoints @@ -427,7 +425,7 @@ resolveEntrypoint :: (IOish m, Gm m) -> m (GmComponent 'GMCRaw (Set ModulePath)) resolveEntrypoint crdl@Cradle {..} c@GmComponent {..} = do gmLog GmDebug "resolveEntrypoint" $ text $ show $ gmcGhcSrcOpts - withLightHscEnv (shouldHideAllPackages crdl) gmcGhcSrcOpts $ \env -> do + withLightHscEnv (shouldLoadGhcEnvironment crdl) gmcGhcSrcOpts $ \env -> do let srcDirs = if null gmcSourceDirs then [""] else gmcSourceDirs eps <- liftIO $ resolveChEntrypoints cradleRootDir gmcEntrypoints rms <- resolveModule env srcDirs `mapM` eps @@ -521,9 +519,9 @@ resolveGmComponents mcache cs = do loadTargets :: IOish m => [GHCOption] -> [FilePath] -> Maybe (GHC.Hooks -> GHC.Hooks) -> GmlT m () loadTargets opts targetStrs mUpdateHooks = do crdl <- cradle - let hideAllPackages = shouldHideAllPackages crdl + let loadGhcEnv = shouldLoadGhcEnvironment crdl targets' <- - withLightHscEnv hideAllPackages opts $ \env -> + withLightHscEnv loadGhcEnv opts $ \env -> liftM (nubBy ((==) `on` targetId)) (mapM ((`guessTarget` Nothing) >=> mapFile env) targetStrs) >>= mapM relativize diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index 9609ed6c1..845c8da0d 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -167,6 +167,10 @@ data Cradle = Cradle { , cradleDistDir :: FilePath } deriving (Eq, Show, Ord) +data LoadGhcEnvironment = LoadGhcEnvironment + | DontLoadGhcEnvironment + deriving (Show,Eq) + data GmStream = GmOutStream | GmErrStream deriving (Show) From 33f01a0169020626b2982fc628f0a24f14f4688b Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 10 Nov 2018 19:52:36 +0200 Subject: [PATCH 36/50] Trying to bring in cabal-helper-wrapper exe for GHC 8.6.1 But I gather it needs an upate to Cabal, coming soon. --- core/ghc-mod-core.cabal | 1 + ghc-mod.cabal | 3 +++ 2 files changed, 4 insertions(+) diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index ad2c1847e..5b016a3d3 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -81,6 +81,7 @@ Library Data.Binary.Generic System.Directory.ModTime Other-Modules: Paths_ghc_mod_core + build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] binary diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 4757a5531..a4f08317c 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -120,6 +120,7 @@ Library GhcMod.Exe.PkgDoc GhcMod.Exe.Test Other-Modules: Paths_ghc_mod + build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] binary @@ -175,6 +176,7 @@ Executable ghc-mod Default-Extensions: ConstraintKinds, FlexibleContexts HS-Source-Dirs: src X-Internal: True + build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] directory @@ -203,6 +205,7 @@ Executable ghc-modi Cpp-Options: -DWINDOWS Default-Extensions: ConstraintKinds, FlexibleContexts HS-Source-Dirs: ., src + build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] binary From 8383b8cb8541cca79e1053b33d0396a73607e554 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 11 Nov 2018 19:49:19 +0200 Subject: [PATCH 37/50] Fill in missing constructor for Pretty Text for GHC 8.6 --- core/GhcMod/Gap.hs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/GhcMod/Gap.hs b/core/GhcMod/Gap.hs index 5b65898b8..f04e6b420 100644 --- a/core/GhcMod/Gap.hs +++ b/core/GhcMod/Gap.hs @@ -234,6 +234,9 @@ renderGm = Pretty.fullRender Pretty.PageMode 80 1.2 string_txt "" string_txt (Pretty.PStr s1) s2 = unpackFS s1 ++ s2 #if __GLASGOW_HASKELL__ >= 806 string_txt (Pretty.LStr s1) s2 = unpackLitString s1 ++ s2 + -- a '\0'-terminated array of bytes + string_txt (Pretty.RStr n c) s2 = replicate n c ++ s2 + -- a repeated character (e.g., ' ') #else string_txt (Pretty.LStr s1 _) s2 = unpackLitString s1 ++ s2 #endif @@ -241,7 +244,6 @@ renderGm = Pretty.fullRender Pretty.PageMode 80 1.2 string_txt "" string_txt (Pretty.ZStr s1) s2 = zString s1 ++ s2 #endif - ---------------------------------------------------------------- ---------------------------------------------------------------- From bd0867fcc5b162d99819d8629653601d6dc4b975 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 11 Nov 2018 21:08:39 +0200 Subject: [PATCH 38/50] Add RStr case in DebugLogger for GHC 8.6 --- core/GhcMod/DebugLogger.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/GhcMod/DebugLogger.hs b/core/GhcMod/DebugLogger.hs index 4f118221c..b40a3f724 100644 --- a/core/GhcMod/DebugLogger.hs +++ b/core/GhcMod/DebugLogger.hs @@ -134,7 +134,8 @@ gmPrintDoc_ mode pprCols putS doc put (ZStr s) next = putS (zString s) >> next #endif #if __GLASGOW_HASKELL__ >= 806 - put (LStr s) next = putS (unpackLitString s) >> next + put (LStr s) next = putS (unpackLitString s) >> next + put (RStr n c) next = putS (replicate n c) >> next #else put (LStr s _l) next = putS (unpackLitString s) >> next #endif From e5b7daf1a2c949b2d2900ae11b13a267ed25eedb Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Mon, 26 Nov 2018 21:58:27 +0200 Subject: [PATCH 39/50] Remove spurious up cabal-helper-wrapper dep --- core/ghc-mod-core.cabal | 1 - ghc-mod.cabal | 3 --- 2 files changed, 4 deletions(-) diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 5b016a3d3..ad2c1847e 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -81,7 +81,6 @@ Library Data.Binary.Generic System.Directory.ModTime Other-Modules: Paths_ghc_mod_core - build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] binary diff --git a/ghc-mod.cabal b/ghc-mod.cabal index a4f08317c..4757a5531 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -120,7 +120,6 @@ Library GhcMod.Exe.PkgDoc GhcMod.Exe.Test Other-Modules: Paths_ghc_mod - build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] binary @@ -176,7 +175,6 @@ Executable ghc-mod Default-Extensions: ConstraintKinds, FlexibleContexts HS-Source-Dirs: src X-Internal: True - build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] directory @@ -205,7 +203,6 @@ Executable ghc-modi Cpp-Options: -DWINDOWS Default-Extensions: ConstraintKinds, FlexibleContexts HS-Source-Dirs: ., src - build-tool-depends: cabal-helper:cabal-helper-wrapper Build-Depends: -- See Note [GHC Boot libraries] binary From 8df7fa3299b94c8cf6aa9d3075bab49f335ac909 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 23 Dec 2018 20:05:41 +0200 Subject: [PATCH 40/50] WIP on integrating new-gen cabal-helper --- cabal.project | 11 +- core/GhcMod/CabalHelper.hs | 247 +++++++++++++++++++++++++++-------- core/GhcMod/Cradle.hs | 63 ++++++++- core/GhcMod/ModuleLoader.hs | 4 + core/GhcMod/PathsAndFiles.hs | 8 +- core/GhcMod/Pretty.hs | 6 +- core/GhcMod/Target.hs | 8 ++ core/GhcMod/Types.hs | 40 +++--- core/ghc-mod-core.cabal | 2 +- ghc-mod.cabal | 4 +- 10 files changed, 302 insertions(+), 91 deletions(-) diff --git a/cabal.project b/cabal.project index a7a2fc926..834156e56 100644 --- a/cabal.project +++ b/cabal.project @@ -1,11 +1,10 @@ packages: . ./core - -- ../cabal-helper - -- ../polyparse + ../cabal-helper -source-repository-package - type: git - location: https://github.com/alanz/cabal-helper - tag: 3d13936af2f8fa565e0a64431c6ed309b91b2695 +-- source-repository-package +-- type: git +-- location: https://github.com/alanz/cabal-helper +-- tag: 3d13936af2f8fa565e0a64431c6ed309b91b2695 diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index e51501a8f..202bc4d03 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -15,6 +15,9 @@ -- along with this program. If not, see . {-# LANGUAGE CPP #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeFamilies #-} module GhcMod.CabalHelper ( getComponents , getGhcMergedPkgOptions @@ -24,12 +27,14 @@ module GhcMod.CabalHelper , withCabal , runCHQuery - , packageId + -- , packageId ) where import Control.Applicative import Control.Monad import Control.Category ((.)) +import Data.List.NonEmpty ( NonEmpty(..)) +import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Data.Version @@ -57,24 +62,26 @@ import Paths_ghc_mod_core as GhcMod -- access home modules getGhcMergedPkgOptions :: (Applicative m, IOish m, Gm m) => m [GHCOption] -getGhcMergedPkgOptions = chCached $ \distdir -> Cached { - cacheLens = Just (lGmcMergedPkgOptions . lGmCaches), - cacheFile = mergedPkgOptsCacheFile distdir, - cachedAction = \_tcf (_progs, _projdir, _ver) _ma -> do - opts <- runCHQuery ghcMergedPkgOptions - return ([setupConfigPath distdir], opts) - } +getGhcMergedPkgOptions = undefined +-- getGhcMergedPkgOptions = chCached $ \distdir -> Cached { +-- cacheLens = Just (lGmcMergedPkgOptions . lGmCaches), +-- cacheFile = mergedPkgOptsCacheFile distdir, +-- cachedAction = \_tcf (_progs, _projdir, _ver) _ma -> do +-- opts <- runCHQuery ghcMergedPkgOptions +-- return ([setupConfigPath distdir], opts) +-- } getCabalPackageDbStack :: (IOish m, Gm m) => m [GhcPkgDb] -getCabalPackageDbStack = chCached $ \distdir -> Cached { - cacheLens = Just (lGmcPackageDbStack . lGmCaches), - cacheFile = pkgDbStackCacheFile distdir, - cachedAction = \_tcf (_progs, _projdir, _ver) _ma -> do - crdl <- cradle - dbs <- map chPkgToGhcPkg <$> - runCHQuery packageDbStack - return ([setupConfigFile crdl, sandboxConfigFile crdl], dbs) - } +getCabalPackageDbStack = undefined +-- getCabalPackageDbStack = chCached $ \distdir -> Cached { +-- cacheLens = Just (lGmcPackageDbStack . lGmCaches), +-- cacheFile = pkgDbStackCacheFile distdir, +-- cachedAction = \_tcf (_progs, _projdir, _ver) _ma -> do +-- crdl <- cradle +-- dbs <- map chPkgToGhcPkg <$> +-- runCHQuery packageDbStack +-- return ([setupConfigFile crdl, sandboxConfigFile crdl], dbs) +-- } chPkgToGhcPkg :: ChPkgDb -> GhcPkgDb chPkgToGhcPkg ChPkgGlobal = GlobalDb @@ -88,54 +95,173 @@ chPkgToGhcPkg (ChPkgSpecific f) = PackageDb f -- 'resolveGmComponents'. getComponents :: (Applicative m, IOish m, Gm m) => m [GmComponent 'GMCRaw ChEntrypoint] -getComponents = chCached $ \distdir -> Cached { - cacheLens = Just (lGmcComponents . lGmCaches), - cacheFile = cabalHelperCacheFile distdir, - cachedAction = \ _tcf (_progs, _projdir, _ver) _ma -> do - cs <- runCHQuery $ components $ - GmComponent mempty - CH.<$> ghcOptions - CH.<.> ghcPkgOptions - CH.<.> ghcSrcOptions - CH.<.> ghcLangOptions - CH.<.> entrypoints - CH.<.> entrypoints - CH.<.> sourceDirs - return ([setupConfigPath distdir], cs) - } - -getQueryEnv :: (IOish m, GmOut m, GmEnv m) => m QueryEnv +getComponents = do + liftIO $ putStrLn $ "CabalHelper.getComponents entered" -- AZ + unit :| _ <- runCHQuery projectUnits + ui <- runCHQuery $ unitInfo unit + liftIO $ putStrLn $ "CabalHelper.getComponents got ui" -- AZ + cs <- runCHQuery $ do + let + doComp :: (ChComponentName, ChComponentInfo) -> GmComponent 'GMCRaw ChEntrypoint + doComp (cn,ci) = + GmComponent + { gmcHomeModuleGraph = mempty + , gmcGhcOpts = ciGhcOptions ci + , gmcGhcPkgOpts = ciGhcPkgOptions ci + , gmcGhcSrcOpts = ciGhcSrcOptions ci + , gmcGhcLangOpts = ciGhcLangOptions ci + , gmcRawEntrypoints = ciEntrypoints ci + , gmcEntrypoints = ciEntrypoints ci + , gmcSourceDirs = ciSourceDirs ci + , gmcName = ciComponentName ci + , gmcNeedsBuildOutput = ciNeedsBuildOutput ci + } + + return ( map doComp $ Map.toList $ uiComponents ui) + liftIO $ putStrLn $ "CabalHelper.getComponents got cs" -- AZ + return cs + +-- getComponents = chCached $ \distdir -> Cached { +-- cacheLens = Just (lGmcComponents . lGmCaches), +-- cacheFile = cabalHelperCacheFile distdir, +-- cachedAction = \ _tcf (_progs, _projdir, _ver) _ma -> do +-- cs <- runCHQuery $ components $ +-- GmComponent mempty +-- CH.<$> ghcOptions +-- CH.<.> ghcPkgOptions +-- CH.<.> ghcSrcOptions +-- CH.<.> ghcLangOptions +-- CH.<.> entrypoints +-- CH.<.> entrypoints +-- CH.<.> sourceDirs +-- return ([setupConfigPath distdir], cs) +-- } + +-- getQueryEnv :: forall m pt. (IOish m, GmOut m, GmEnv m) => m (Maybe ( QueryEnv pt)) +getQueryEnv :: (IOish m, GmOut m, GmEnv m) => m (QueryEnv pt) +getQueryEnv = undefined + {- getQueryEnv = do crdl <- cradle progs <- patchStackPrograms crdl =<< (optPrograms <$> options) readProc <- gmReadProcess - let projdir = cradleRootDir crdl - distdir = projdir cradleDistDir crdl - return (mkQueryEnv projdir distdir) { - qeReadProcess = readProc - , qePrograms = helperProgs progs - } - -runCHQuery :: (IOish m, GmOut m, GmEnv m) => Query m b -> m b + case cradleCabalFile crdl of + Nothing -> return Nothing + Just cabalFile -> do + let + distdirCradle = cradleDistDir crdl + (projdir,distdir) = case cradleProject crdl of + CabalProject -> (ProjLocCabalFile cabalFile,DistDirV1 distdirCradle) + CabalNewProject -> (ProjLocCabalFile cabalFile,DistDirV2 distdirCradle) + SandboxProject -> (ProjLocCabalFile cabalFile,DistDirV1 distdirCradle) + PlainProject -> (ProjLocCabalFile cabalFile,DistDirV1 distdirCradle) + StackProject env -> (ProjLocCabalFile cabalFile,DistDirStack distdirCradle) + qe <- liftIO $ mkQueryEnv projdir distdir + return (Just qe) + -- let + -- (projdir,distdir) = case cradleProject crdl of + -- CabalProject -> (ProjLocCabalFile cabalFile,DisDirV1 distdir) + -- CabalNewProject -> (ProjLocCabalFile cabalFile,DisDirV1 distdir) + -- SandboxProject -> (ProjLocCabalFile cabalFile,DisDirV1 distdir) + -- PlainProject -> (ProjLocCabalFile cabalFile,DisDirV1 distdir) + -- StackProject env -> (ProjLocCabalFile cabalFile,DisDirV1 distdir) + -- return (mkQueryEnv projdir distdir) { + -- qeReadProcess = readProc + -- , qePrograms = helperProgs progs + -- } + {- + let projdir = takeDirectory cabal_file + qe <- mkQueryEnv + (psProjDir cabal_file) + (psDistDir projdir) + +-} +-- getQueryEnv = do +-- crdl <- cradle +-- progs <- patchStackPrograms crdl =<< (optPrograms <$> options) +-- readProc <- gmReadProcess +-- let projdir = cradleRootDir crdl +-- distdir = projdir cradleDistDir crdl +-- return (mkQueryEnv projdir distdir) { +-- qeReadProcess = readProc +-- , qePrograms = helperProgs progs +-- } +-} + +runCHQuery :: (IOish m, GmOut m, GmEnv m) => Query pt b -> m b runCHQuery a = do qe <- getQueryEnv - runQuery qe a + liftIO $ runQuery a qe +-- runQuery :: Query pt a -> QueryEnv pt -> IO a +withQueryEnv :: (IOish m, GmOut m, GmEnv m) => (forall pt.QueryEnv pt -> IO a) -> m (Maybe a) +withQueryEnv f = do + crdl <- cradle + progs <- patchStackPrograms crdl =<< (optPrograms <$> options) + readProc <- gmReadProcess + case cradleCabalFile crdl of + Nothing -> return Nothing + Just cabalFile -> + case cradleProject crdl of + CabalProject -> Just <$> runProjSetup oldBuild cabalFile f + CabalNewProject -> Just <$> runProjSetup newBuild cabalFile f + SandboxProject -> Just <$> runProjSetup oldBuild cabalFile f + StackProject _env -> Just <$> runProjSetup stackBuild cabalFile f + PlainProject -> return Nothing + +runProjSetup :: (IOish m, GmOut m, GmEnv m) => ProjSetup pt -> FilePath -> (QueryEnv pt -> IO a) -> m a +runProjSetup ps cabalFile f = do + let projdir = takeDirectory cabalFile + qe <- liftIO $ mkQueryEnv + (psProjDir ps $ cabalFile) + (psDistDir ps $ projdir) + liftIO $ f qe + +data ProjSetup pt = + ProjSetup + { psDistDir :: FilePath -> DistDir pt + , psProjDir :: FilePath -> ProjLoc pt + } + +oldBuild :: ProjSetup 'V1 +oldBuild = ProjSetup + { psDistDir = \dir -> DistDirV1 (dir "dist") + , psProjDir = \cabal_file -> ProjLocCabalFile cabal_file + } + +newBuild :: ProjSetup 'V2 +newBuild = ProjSetup + { psDistDir = \dir -> DistDirV2 (dir "dist-newstyle") + , psProjDir = \cabal_file -> ProjLocV2Dir (takeDirectory cabal_file) + } + +stackBuild :: ProjSetup 'Stack +stackBuild = ProjSetup + { psDistDir = \_dir -> DistDirStack Nothing + , psProjDir = \cabal_file -> ProjLocStackDir (takeDirectory cabal_file) + } + +-- --------------------------------------------------------------------- prepareCabalHelper :: (IOish m, GmEnv m, GmOut m, GmLog m) => m () prepareCabalHelper = do + liftIO $ putStrLn $ "CabalHelper.prepareCabalHelper entered" -- AZ crdl <- cradle - when (isCabalHelperProject $ cradleProject crdl) $ - withCabal $ prepare =<< getQueryEnv + when (isCabalHelperProject $ cradleProject crdl) $ do + -- withCabal $ prepare =<< getQueryEnv + qe <- getQueryEnv + withCabal $ liftIO (prepare qe) withAutogen :: (IOish m, GmEnv m, GmOut m, GmLog m) => m a -> m a withAutogen action = do - gmLog GmDebug "" $ strDoc $ "making sure autogen files exist" + gmLog GmDebug "" $ strDoc "making sure autogen files exist" crdl <- cradle let projdir = cradleRootDir crdl distdir = projdir cradleDistDir crdl - (pkgName', _) <- runCHQuery packageId + -- (pkgName', _) <- runCHQuery packageId + (pkgName', _) <- runCHQuery undefined + unit :| _ <- runCHQuery projectUnits mCabalFile <- liftIO $ timeFile `traverse` cradleCabalFile crdl mCabalMacroHeader <- liftIO $ timeMaybe (distdir macrosHeaderPath) @@ -143,14 +269,14 @@ withAutogen action = do when (mCabalMacroHeader < mCabalFile || mCabalPathsModule < mCabalFile) $ do gmLog GmDebug "" $ strDoc $ "autogen files out of sync" - writeAutogen + writeAutogen unit action where - writeAutogen = do - gmLog GmDebug "" $ strDoc $ "writing Cabal autogen files" - writeAutogenFiles =<< getQueryEnv + writeAutogen unit = do + gmLog GmDebug "" $ strDoc "writing Cabal autogen files" + runCHQuery $ writeAutogenFiles unit withCabal :: (IOish m, GmEnv m, GmOut m, GmLog m) => m a -> m a @@ -166,8 +292,12 @@ withCabal action = do (flgs, pkgDbStackOutOfSync) <- do if haveSetupConfig then runCHQuery $ do - flgs <- nonDefaultConfigFlags - pkgDb <- map chPkgToGhcPkg <$> packageDbStack + unit :| _ <- projectUnits + ui <- unitInfo unit + -- flgs <- nonDefaultConfigFlags + let flgs = uiNonDefaultConfigFlags ui + -- pkgDb <- map chPkgToGhcPkg <$> packageDbStack + let pkgDb = map chPkgToGhcPkg (uiPackageDbStack ui) return (flgs, fromMaybe False $ (pkgDb /=) <$> cusPkgDb) else return ([], False) @@ -275,11 +405,12 @@ isSetupConfigOutOfDate worldCabalFile worldCabalConfig = do worldCabalConfig < worldCabalFile helperProgs :: Programs -> CH.Programs -helperProgs progs = CH.Programs { - cabalProgram = T.cabalProgram progs, - ghcProgram = T.ghcProgram progs, - ghcPkgProgram = T.ghcPkgProgram progs - } +helperProgs = undefined +-- helperProgs progs = CH.Programs { +-- cabalProgram = T.cabalProgram progs, +-- ghcProgram = T.ghcProgram progs, +-- ghcPkgProgram = T.ghcPkgProgram progs +-- } chCached :: (Applicative m, IOish m, Gm m, Binary a) => (FilePath -> Cached m GhcModState ChCacheData a) -> m a diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 5cb2418a1..4f69dcfbe 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -1,4 +1,12 @@ {-# LANGUAGE CPP #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE RecordWildCards #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE ImplicitParams #-} + + module GhcMod.Cradle ( findCradle , findCradle' @@ -28,7 +36,8 @@ import System.FilePath import System.Environment import Prelude import Control.Monad.Trans.Journal (runJournalT) -import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, distDir) +-- import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, distDir) +import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, DistDir(..), ProjType(..), ProjLoc(..), callProcessStderr ) -- import Distribution.System (buildPlatform) import Data.List (intercalate) import Data.Version (Version(..)) @@ -42,7 +51,7 @@ import Data.Version (Version(..)) findCradle :: (GmLog m, IOish m, GmOut m) => Programs -> m Cradle findCradle progs = findCradle' progs =<< liftIO getCurrentDirectory -findCradleNoLog :: forall m. (IOish m, GmOut m) => Programs -> m Cradle +findCradleNoLog :: forall m pt. (IOish m, GmOut m) => Programs -> m Cradle findCradleNoLog progs = fst <$> (runJournalT (findCradle progs) :: m (Cradle, GhcModLog)) @@ -107,7 +116,11 @@ cabalCradle cabalProg wdir = do -- Or default to is for cabal >= 2.0 ?, unless flag saying old style if isDistNewstyle then do - dd <- liftIO $ runQuery (mkQueryEnv cabalDir "dist-newstyle") distDir + -- dd <- liftIO $ runQuery (mkQueryEnv cabalDir "dist-newstyle") distDir + + -- runQuery :: Query pt a -> QueryEnv pt -> IO a + -- dd <- liftIO $ runQuery (mkQueryEnv cabalDir "dist-newstyle") distDir + let dd = "dist-newstyle" gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir return Cradle { @@ -226,3 +239,47 @@ shouldLoadGhcEnvironment crdl = if cradleProject crdl == PlainProject then LoadGhcEnvironment else DontLoadGhcEnvironment + +-- --------------------------------------------------------------------- +-- The following is moved here from cabal-helper test/GhcSession.hs + +data ProjSetup pt = + ProjSetup + { psDistDir :: FilePath -> DistDir pt + , psProjDir :: FilePath -> ProjLoc pt + , psConfigure :: FilePath -> IO () + , psBuild :: FilePath -> IO () + , psSdist :: FilePath -> FilePath -> IO () + } + +oldBuild :: ProjSetup 'V1 +oldBuild = ProjSetup + { psDistDir = \dir -> DistDirV1 (dir "dist") + , psProjDir = \cabal_file -> ProjLocCabalFile cabal_file + , psConfigure = \dir -> + runWithCwd dir "cabal" [ "configure" ] + , psBuild = \dir -> + runWithCwd dir "cabal" [ "build" ] + , psSdist = \srcdir destdir -> + runWithCwd srcdir "cabal" [ "sdist", "-v0", "--output-dir", destdir ] + } + +newBuild :: ProjSetup 'V2 +newBuild = ProjSetup + { psDistDir = \dir -> DistDirV2 (dir "dist-newstyle") + , psProjDir = \cabal_file -> ProjLocV2Dir (takeDirectory cabal_file) + , psConfigure = \dir -> + runWithCwd dir "cabal" [ "new-configure" ] + , psBuild = \dir -> + runWithCwd dir "cabal" [ "new-build" ] + , psSdist = \srcdir destdir -> + runWithCwd srcdir "cabal" [ "sdist", "-v0", "--output-dir", destdir ] + } + +runWithCwd :: FilePath -> String -> [String] -> IO () +runWithCwd cwd x xs = do + let ?verbose = True + callProcessStderr (Just cwd) x xs + + +-- --------------------------------------------------------------------- diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs index b34a5e52d..bde6f6645 100644 --- a/core/GhcMod/ModuleLoader.hs +++ b/core/GhcMod/ModuleLoader.hs @@ -56,9 +56,12 @@ tweakModSummaryDynFlags ms = getModulesGhc' :: GM.IOish m => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule, Maybe ParsedModule) getModulesGhc' wrapper targetFile = do + liftIO $ putStrLn $ "getModulesGhc':targetFile=" ++ targetFile -- AZ cfileName <- liftIO $ canonicalizePath targetFile mfs <- GM.getMMappedFiles + liftIO $ putStrLn $ "getModulesGhc':got mapped files" -- AZ mFileName <- liftIO . canonicalizePath $ getMappedFileName cfileName mfs + liftIO $ putStrLn $ "getModulesGhc':got mFileName" -- AZ refTypechecked <- liftIO $ newIORef Nothing refParsed <- liftIO $ newIORef Nothing let keepInfo = pure . (mFileName ==) @@ -90,6 +93,7 @@ getModulesGhc wrapper targetFiles keepInfo saveTypechecked saveParsed = do let ips = map takeDirectory $ Map.keys mfs setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } #endif + liftIO $ putStrLn $ "getModulesGhc:calling runGmlTWith'" -- AZ GM.runGmlTWith' (map Left targetFiles) (return . setIncludePaths) (Just $ updateHooks keepInfo saveTypechecked saveParsed) diff --git a/core/GhcMod/PathsAndFiles.hs b/core/GhcMod/PathsAndFiles.hs index 38be2b8d1..560dcaaad 100644 --- a/core/GhcMod/PathsAndFiles.hs +++ b/core/GhcMod/PathsAndFiles.hs @@ -83,11 +83,11 @@ getSandboxDb :: Cradle -> IO (Maybe GhcPkgDb) getSandboxDb crdl = do mConf <- traverse readFile =<< mightExist (sandboxConfigFile crdl) --- #if MIN_VERSION_cabal_helper(1,0,0) --- bp <- return buildPlatform --- #else +#if MIN_VERSION_cabal_helper(1,0,0) + bp <- return buildPlatform +#else bp <- buildPlatform readProcess --- #endif +#endif return $ PackageDb . fixPkgDbVer bp <$> (extractSandboxDbDir =<< mConf) where diff --git a/core/GhcMod/Pretty.hs b/core/GhcMod/Pretty.hs index acc219e63..2317a4769 100644 --- a/core/GhcMod/Pretty.hs +++ b/core/GhcMod/Pretty.hs @@ -50,7 +50,11 @@ renderSDoc sdoc = do gmComponentNameDoc :: ChComponentName -> Doc gmComponentNameDoc ChSetupHsName = text $ "Setup.hs" -#if MIN_VERSION_cabal_helper(0,8,0) +#if MIN_VERSION_cabal_helper(1,0,0) +gmComponentNameDoc (ChLibName ChMainLibName) = text $ "library" +gmComponentNameDoc (ChLibName (ChSubLibName n)) = text $ "library:" ++ n +gmComponentNameDoc (ChFLibName _) = text $ "flibrary" +#elif MIN_VERSION_cabal_helper(0,8,0) gmComponentNameDoc ChLibName = text $ "library" gmComponentNameDoc (ChSubLibName _)= text $ "library" gmComponentNameDoc (ChFLibName _) = text $ "flibrary" diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index d752e6500..cfa2c3a5b 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -188,14 +188,18 @@ runGmlTWith' :: IOish m -> GmlT m a -> GhcModT m b runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do + liftIO $ putStrLn $ "runGmlTWith' entered" -- AZ crdl <- cradle + liftIO $ putStrLn $ "runGmlTWith' got cradle" -- AZ Options { optGhcUserOptions } <- options let (fns, mns) = partitionEithers efnmns' ccfns = map (cradleCurrentDir crdl ) fns cfns <- mapM getCanonicalFileNameSafe ccfns let serfnmn = Set.fromList $ map Right mns ++ map Left cfns + liftIO $ putStrLn $ "runGmlTWith' calling targetGhcOptions" -- AZ (opts, mappedStrs) <- targetGhcOptions crdl serfnmn + liftIO $ putStrLn $ "runGmlTWith' got targetGhcOptions" -- AZ let opts' = opts ++ ["-O0", "-fno-warn-missing-home-modules"] ++ optGhcUserOptions @@ -248,6 +252,8 @@ targetGhcOptions :: forall m. IOish m targetGhcOptions crdl sefnmn = do when (Set.null sefnmn) $ error "targetGhcOptions: no targets given" + liftIO $ putStrLn $ "targetGhcOptions:cradleProject=" ++ show (cradleProject crdl) -- AZ + liftIO $ putStrLn $ "targetGhcOptions: isCabalHelperProject=" ++ show (isCabalHelperProject $ cradleProject crdl) -- AZ case cradleProject crdl of proj | isCabalHelperProject proj -> cabalOpts crdl @@ -260,7 +266,9 @@ targetGhcOptions crdl sefnmn = do cabalOpts :: Cradle -> GhcModT m ([GHCOption],[FilePath]) cabalOpts Cradle{..} = do + liftIO $ putStrLn $ "targetGhcOptions.cabalOpts:calling cabalResolvedComponents" --AZ mcs <- cabalResolvedComponents + liftIO $ putStrLn $ "targetGhcOptions.cabalOpts:after cabalResolvedComponents" --AZ mappedStrs <- getMMappedFilePaths let mappedComps = zipMap (moduleComponents mcs . Left) mappedStrs let mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index 845c8da0d..843eecde9 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -30,6 +30,7 @@ import Data.IORef import Data.Label.Derive import Distribution.Helper hiding (Programs(..)) import qualified Distribution.Helper as CabalHelper +-- CabalHelper.Shared.InterfaceTypes import Exception (ExceptionMonad) #if __GLASGOW_HASKELL__ < 708 import qualified MonadUtils as GHC (MonadIO(..)) @@ -154,18 +155,18 @@ data StackEnv = StackEnv { -- | The environment where this library is used. data Cradle = Cradle { - cradleProject :: Project + cradleProject :: !Project -- | The directory where this library is executed. - , cradleCurrentDir :: FilePath + , cradleCurrentDir :: !FilePath -- | The project root directory. - , cradleRootDir :: FilePath + , cradleRootDir :: !FilePath -- | Per-Project temporary directory - , cradleTempDir :: FilePath + , cradleTempDir :: !FilePath -- | The file name of the found cabal file. - , cradleCabalFile :: Maybe FilePath + , cradleCabalFile :: !(Maybe FilePath) -- | The build info directory. - , cradleDistDir :: FilePath - } deriving (Eq, Show, Ord) + , cradleDistDir :: !FilePath + } deriving (Eq, Ord, Show) data LoadGhcEnvironment = LoadGhcEnvironment | DontLoadGhcEnvironment @@ -299,15 +300,16 @@ instance Monoid GmModuleGraph where data GmComponentType = GMCRaw | GMCResolved data GmComponent (t :: GmComponentType) eps = GmComponent { - gmcHomeModuleGraph :: GmModuleGraph - , gmcGhcOpts :: [GHCOption] - , gmcGhcPkgOpts :: [GHCOption] - , gmcGhcSrcOpts :: [GHCOption] - , gmcGhcLangOpts :: [GHCOption] - , gmcRawEntrypoints :: ChEntrypoint - , gmcEntrypoints :: eps - , gmcSourceDirs :: [FilePath] - , gmcName :: ChComponentName + gmcHomeModuleGraph :: GmModuleGraph + , gmcGhcOpts :: [GHCOption] + , gmcGhcPkgOpts :: [GHCOption] + , gmcGhcSrcOpts :: [GHCOption] + , gmcGhcLangOpts :: [GHCOption] + , gmcRawEntrypoints :: ChEntrypoint + , gmcEntrypoints :: eps + , gmcSourceDirs :: [FilePath] + , gmcName :: ChComponentName + , gmcNeedsBuildOutput :: NeedsBuildOutput } deriving (Eq, Ord, Show, Read, Generic, Functor) instance Binary eps => Binary (GmComponent t eps) where @@ -388,6 +390,12 @@ instance Binary ChComponentName where instance Binary ChEntrypoint where put = ggput . from get = to `fmap` ggget +instance Binary ChLibraryName where + put = ggput . from + get = to `fmap` ggget +instance Binary NeedsBuildOutput where + put = ggput . from + get = to `fmap` ggget -- | Options for "lintWith" function data LintOpts = LintOpts { diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index ad2c1847e..440b2cd98 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -110,7 +110,7 @@ Library , temporary < 1.3 && >= 1.2.0.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 0.10 && >= 0.9.0.0 + , cabal-helper < 1.10 && >= 1.0.0.0 , ghc < 8.7 && >= 7.6 if impl(ghc >= 8.0) diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 4757a5531..77bfc9932 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -155,7 +155,7 @@ Library , text < 1.4 && >= 1.2.1.3 , transformers-base < 0.5 && >= 0.4.4 - , cabal-helper < 0.10 && >= 0.9.0.0 + , cabal-helper < 1.10 && >= 1.0.0.0 , ghc < 8.7 && >= 7.8 if impl(ghc >= 8.0) @@ -286,7 +286,7 @@ Test-Suite spec Build-Depends: ghc-boot Build-Depends: - cabal-helper < 0.10 && >= 0.9.0.0 + cabal-helper < 1.10 && >= 1.0.0.0 , ghc < 8.7 && >= 7.8 , ghc-mod , ghc-mod-core From 502a2e90d1424f8d90dbe9a4006d879ddbb8d44b Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Mon, 24 Dec 2018 20:17:26 +0200 Subject: [PATCH 41/50] WIP --- core/GhcMod/CabalHelper.hs | 53 +++++++++++++++++--------------------- core/GhcMod/Cradle.hs | 32 +++++++---------------- core/GhcMod/Types.hs | 18 ++++++++----- 3 files changed, 46 insertions(+), 57 deletions(-) diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index 202bc4d03..cfb19932b 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -42,6 +42,7 @@ import Data.Binary (Binary) import Data.Traversable import Distribution.Helper hiding (Programs(..)) import qualified Distribution.Helper as CH +import GhcMod.Cradle import qualified GhcMod.Types as T import GhcMod.Types import GhcMod.Monad.Types @@ -188,13 +189,29 @@ getQueryEnv = do -- } -} -runCHQuery :: (IOish m, GmOut m, GmEnv m) => Query pt b -> m b +runCHQuery :: forall m pt b.(IOish m, GmOut m, GmEnv m) => Query (pt :: ProjType) b -> m b runCHQuery a = do - qe <- getQueryEnv - liftIO $ runQuery a qe --- runQuery :: Query pt a -> QueryEnv pt -> IO a + crdl <- cradle + progs <- patchStackPrograms crdl =<< (optPrograms <$> options) + readProc <- gmReadProcess + case cradleCabalFile crdl of + Nothing -> error "runCHQuery 1" + Just cabalFile -> + case cradleProject crdl of + CabalProject -> runProjSetup oldBuild cabalFile (\qe -> runQuery a qe) + CabalNewProject -> runProjSetup newBuild cabalFile (\qe -> runQuery a qe) + SandboxProject -> runProjSetup oldBuild cabalFile (\qe -> runQuery a qe) + StackProject _env -> runProjSetup stackBuild cabalFile (\qe -> runQuery a qe) + PlainProject -> error "runCHQuery 2" +{- +runCHQuery a = do +-- qe <- getQueryEnv +-- liftIO $ runQuery a qe +-- -- runQuery :: Query pt a -> QueryEnv pt -> IO a +-} -withQueryEnv :: (IOish m, GmOut m, GmEnv m) => (forall pt.QueryEnv pt -> IO a) -> m (Maybe a) +-- withQueryEnv :: (IOish m, GmOut m, GmEnv m) => (forall pt . QueryEnv (pt :: ProjType) -> IO a) -> m (Maybe a) +withQueryEnv :: (IOish m, GmOut m, GmEnv m) => (forall pt . QueryEnv (pt :: ProjType) -> IO a) -> m (Maybe a) withQueryEnv f = do crdl <- cradle progs <- patchStackPrograms crdl =<< (optPrograms <$> options) @@ -209,7 +226,8 @@ withQueryEnv f = do StackProject _env -> Just <$> runProjSetup stackBuild cabalFile f PlainProject -> return Nothing -runProjSetup :: (IOish m, GmOut m, GmEnv m) => ProjSetup pt -> FilePath -> (QueryEnv pt -> IO a) -> m a +runProjSetup :: (IOish m, GmOut m, GmEnv m) + => ProjSetup (pt :: ProjType) -> FilePath -> (QueryEnv (pt :: ProjType) -> IO a) -> m a runProjSetup ps cabalFile f = do let projdir = takeDirectory cabalFile qe <- liftIO $ mkQueryEnv @@ -217,29 +235,6 @@ runProjSetup ps cabalFile f = do (psDistDir ps $ projdir) liftIO $ f qe -data ProjSetup pt = - ProjSetup - { psDistDir :: FilePath -> DistDir pt - , psProjDir :: FilePath -> ProjLoc pt - } - -oldBuild :: ProjSetup 'V1 -oldBuild = ProjSetup - { psDistDir = \dir -> DistDirV1 (dir "dist") - , psProjDir = \cabal_file -> ProjLocCabalFile cabal_file - } - -newBuild :: ProjSetup 'V2 -newBuild = ProjSetup - { psDistDir = \dir -> DistDirV2 (dir "dist-newstyle") - , psProjDir = \cabal_file -> ProjLocV2Dir (takeDirectory cabal_file) - } - -stackBuild :: ProjSetup 'Stack -stackBuild = ProjSetup - { psDistDir = \_dir -> DistDirStack Nothing - , psProjDir = \cabal_file -> ProjLocStackDir (takeDirectory cabal_file) - } -- --------------------------------------------------------------------- diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 4f69dcfbe..0a0a0c79a 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -15,6 +15,9 @@ module GhcMod.Cradle , cleanupCradle , shouldLoadGhcEnvironment + , oldBuild + , newBuild + , stackBuild -- * for @spec@ , plainCradle ) where @@ -243,37 +246,22 @@ shouldLoadGhcEnvironment crdl = -- --------------------------------------------------------------------- -- The following is moved here from cabal-helper test/GhcSession.hs -data ProjSetup pt = - ProjSetup - { psDistDir :: FilePath -> DistDir pt - , psProjDir :: FilePath -> ProjLoc pt - , psConfigure :: FilePath -> IO () - , psBuild :: FilePath -> IO () - , psSdist :: FilePath -> FilePath -> IO () - } - oldBuild :: ProjSetup 'V1 oldBuild = ProjSetup - { psDistDir = \dir -> DistDirV1 (dir "dist") + { psDistDir = \dir -> DistDirV1 (dir "dist") , psProjDir = \cabal_file -> ProjLocCabalFile cabal_file - , psConfigure = \dir -> - runWithCwd dir "cabal" [ "configure" ] - , psBuild = \dir -> - runWithCwd dir "cabal" [ "build" ] - , psSdist = \srcdir destdir -> - runWithCwd srcdir "cabal" [ "sdist", "-v0", "--output-dir", destdir ] } newBuild :: ProjSetup 'V2 newBuild = ProjSetup { psDistDir = \dir -> DistDirV2 (dir "dist-newstyle") , psProjDir = \cabal_file -> ProjLocV2Dir (takeDirectory cabal_file) - , psConfigure = \dir -> - runWithCwd dir "cabal" [ "new-configure" ] - , psBuild = \dir -> - runWithCwd dir "cabal" [ "new-build" ] - , psSdist = \srcdir destdir -> - runWithCwd srcdir "cabal" [ "sdist", "-v0", "--output-dir", destdir ] + } + +stackBuild :: ProjSetup 'Stack +stackBuild = ProjSetup + { psDistDir = \_dir -> DistDirStack Nothing + , psProjDir = \cabal_file -> ProjLocStackDir (takeDirectory cabal_file) } runWithCwd :: FilePath -> String -> [String] -> IO () diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index 843eecde9..ca70a1cd1 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -155,19 +155,25 @@ data StackEnv = StackEnv { -- | The environment where this library is used. data Cradle = Cradle { - cradleProject :: !Project + cradleProject :: Project -- | The directory where this library is executed. - , cradleCurrentDir :: !FilePath + , cradleCurrentDir :: FilePath -- | The project root directory. - , cradleRootDir :: !FilePath + , cradleRootDir :: FilePath -- | Per-Project temporary directory - , cradleTempDir :: !FilePath + , cradleTempDir :: FilePath -- | The file name of the found cabal file. - , cradleCabalFile :: !(Maybe FilePath) + , cradleCabalFile :: Maybe FilePath -- | The build info directory. - , cradleDistDir :: !FilePath + , cradleDistDir :: FilePath } deriving (Eq, Ord, Show) +data ProjSetup (pt :: ProjType) = + ProjSetup + { psDistDir :: FilePath -> DistDir pt + , psProjDir :: FilePath -> ProjLoc pt + } + data LoadGhcEnvironment = LoadGhcEnvironment | DontLoadGhcEnvironment deriving (Show,Eq) From 338469fc16b2dd9bff96d83ed67d60807039ebf7 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Wed, 26 Dec 2018 19:56:47 +0200 Subject: [PATCH 42/50] HaRe UtilsSpec tests pass with old build --- core/GhcMod/CabalHelper.hs | 112 +++++++++++++++++------------------- core/GhcMod/ModuleLoader.hs | 4 -- core/GhcMod/Target.hs | 18 +++--- 3 files changed, 61 insertions(+), 73 deletions(-) diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index cfb19932b..0f753077a 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -25,6 +25,7 @@ module GhcMod.CabalHelper , prepareCabalHelper , withAutogen , withCabal + , withProjSetup , runCHQuery -- , packageId @@ -95,13 +96,11 @@ chPkgToGhcPkg (ChPkgSpecific f) = PackageDb f -- The Component\'s 'gmcHomeModuleGraph' will be empty and has to be resolved by -- 'resolveGmComponents'. getComponents :: (Applicative m, IOish m, Gm m) - => m [GmComponent 'GMCRaw ChEntrypoint] -getComponents = do - liftIO $ putStrLn $ "CabalHelper.getComponents entered" -- AZ - unit :| _ <- runCHQuery projectUnits - ui <- runCHQuery $ unitInfo unit - liftIO $ putStrLn $ "CabalHelper.getComponents got ui" -- AZ - cs <- runCHQuery $ do + => ProjSetup pt -> m [GmComponent 'GMCRaw ChEntrypoint] +getComponents ps = do + unit :| _ <- runCHQuery ps projectUnits + ui <- runCHQuery ps $ unitInfo unit + cs <- runCHQuery ps $ do let doComp :: (ChComponentName, ChComponentInfo) -> GmComponent 'GMCRaw ChEntrypoint doComp (cn,ci) = @@ -119,7 +118,6 @@ getComponents = do } return ( map doComp $ Map.toList $ uiComponents ui) - liftIO $ putStrLn $ "CabalHelper.getComponents got cs" -- AZ return cs -- getComponents = chCached $ \distdir -> Cached { @@ -189,74 +187,71 @@ getQueryEnv = do -- } -} -runCHQuery :: forall m pt b.(IOish m, GmOut m, GmEnv m) => Query (pt :: ProjType) b -> m b -runCHQuery a = do +runCHQuery :: (IOish m, GmOut m, GmEnv m) + => ProjSetup (pt :: ProjType) -> Query (pt :: ProjType) b -> m b +runCHQuery ps a = do crdl <- cradle progs <- patchStackPrograms crdl =<< (optPrograms <$> options) readProc <- gmReadProcess case cradleCabalFile crdl of Nothing -> error "runCHQuery 1" - Just cabalFile -> - case cradleProject crdl of - CabalProject -> runProjSetup oldBuild cabalFile (\qe -> runQuery a qe) - CabalNewProject -> runProjSetup newBuild cabalFile (\qe -> runQuery a qe) - SandboxProject -> runProjSetup oldBuild cabalFile (\qe -> runQuery a qe) - StackProject _env -> runProjSetup stackBuild cabalFile (\qe -> runQuery a qe) - PlainProject -> error "runCHQuery 2" -{- -runCHQuery a = do --- qe <- getQueryEnv --- liftIO $ runQuery a qe --- -- runQuery :: Query pt a -> QueryEnv pt -> IO a --} + Just cabalFile -> runProjSetup ps cabalFile (\qe -> runQuery a qe) + +-- --------------------------------------------------------------------- + +runProjSetup :: (IOish m, GmOut m, GmEnv m) + => ProjSetup (pt :: ProjType) -> FilePath -> (QueryEnv (pt :: ProjType) -> IO a) -> m a +runProjSetup ps cabalFile f = do + let projdir = takeDirectory cabalFile + crdl <- cradle + progs <- patchStackPrograms crdl =<< (optPrograms <$> options) + readProc <- gmReadProcess + qeBare <- liftIO $ mkQueryEnv + (psProjDir ps $ cabalFile) + (psDistDir ps $ projdir) + let qe = qeBare + -- { qeReadProcess = \_ -> readProc + -- , qePrograms = helperProgs progs + -- } + r <- liftIO $ f qe + return r + +-- --------------------------------------------------------------------- --- withQueryEnv :: (IOish m, GmOut m, GmEnv m) => (forall pt . QueryEnv (pt :: ProjType) -> IO a) -> m (Maybe a) -withQueryEnv :: (IOish m, GmOut m, GmEnv m) => (forall pt . QueryEnv (pt :: ProjType) -> IO a) -> m (Maybe a) -withQueryEnv f = do +withProjSetup :: (IOish m, GmOut m, GmEnv m) => (forall pt . ProjSetup pt -> m a) -> m (Maybe a) +withProjSetup f = do crdl <- cradle progs <- patchStackPrograms crdl =<< (optPrograms <$> options) readProc <- gmReadProcess case cradleCabalFile crdl of Nothing -> return Nothing - Just cabalFile -> + Just cabalFile -> do case cradleProject crdl of - CabalProject -> Just <$> runProjSetup oldBuild cabalFile f - CabalNewProject -> Just <$> runProjSetup newBuild cabalFile f - SandboxProject -> Just <$> runProjSetup oldBuild cabalFile f - StackProject _env -> Just <$> runProjSetup stackBuild cabalFile f + CabalProject -> Just <$> f oldBuild + CabalNewProject -> Just <$> f newBuild + SandboxProject -> Just <$> f oldBuild + StackProject _env -> Just <$> f stackBuild PlainProject -> return Nothing -runProjSetup :: (IOish m, GmOut m, GmEnv m) - => ProjSetup (pt :: ProjType) -> FilePath -> (QueryEnv (pt :: ProjType) -> IO a) -> m a -runProjSetup ps cabalFile f = do - let projdir = takeDirectory cabalFile - qe <- liftIO $ mkQueryEnv - (psProjDir ps $ cabalFile) - (psDistDir ps $ projdir) - liftIO $ f qe - - -- --------------------------------------------------------------------- -prepareCabalHelper :: (IOish m, GmEnv m, GmOut m, GmLog m) => m () -prepareCabalHelper = do - liftIO $ putStrLn $ "CabalHelper.prepareCabalHelper entered" -- AZ +prepareCabalHelper :: (IOish m, GmEnv m, GmOut m, GmLog m) => ProjSetup pt -> m () +prepareCabalHelper ps = do crdl <- cradle when (isCabalHelperProject $ cradleProject crdl) $ do - -- withCabal $ prepare =<< getQueryEnv qe <- getQueryEnv - withCabal $ liftIO (prepare qe) + withCabal ps $ liftIO (prepare qe) -withAutogen :: (IOish m, GmEnv m, GmOut m, GmLog m) => m a -> m a -withAutogen action = do +withAutogen :: (IOish m, GmEnv m, GmOut m, GmLog m) => ProjSetup pt -> m a -> m a +withAutogen ps action = do gmLog GmDebug "" $ strDoc "making sure autogen files exist" crdl <- cradle let projdir = cradleRootDir crdl distdir = projdir cradleDistDir crdl - -- (pkgName', _) <- runCHQuery packageId - (pkgName', _) <- runCHQuery undefined - unit :| _ <- runCHQuery projectUnits + unit :| _ <- runCHQuery ps projectUnits + unitInfo <- runCHQuery ps $ unitInfo unit + let (pkgName',_) = uiPackageId unitInfo mCabalFile <- liftIO $ timeFile `traverse` cradleCabalFile crdl mCabalMacroHeader <- liftIO $ timeMaybe (distdir macrosHeaderPath) @@ -271,11 +266,12 @@ withAutogen action = do where writeAutogen unit = do gmLog GmDebug "" $ strDoc "writing Cabal autogen files" - runCHQuery $ writeAutogenFiles unit + runCHQuery ps $ writeAutogenFiles unit +-- --------------------------------------------------------------------- -withCabal :: (IOish m, GmEnv m, GmOut m, GmLog m) => m a -> m a -withCabal action = do +withCabal :: (IOish m, GmEnv m, GmOut m, GmLog m) => ProjSetup pt -> m a -> m a +withCabal ps action = do crdl <- cradle mCabalFile <- liftIO $ timeFile `traverse` cradleCabalFile crdl mCabalConfig <- liftIO $ timeMaybe (setupConfigFile crdl) @@ -286,7 +282,7 @@ withCabal action = do cusPkgDb <- getCustomPkgDbStack (flgs, pkgDbStackOutOfSync) <- do if haveSetupConfig - then runCHQuery $ do + then runCHQuery ps $ do unit :| _ <- projectUnits ui <- unitInfo unit -- flgs <- nonDefaultConfigFlags @@ -408,12 +404,12 @@ helperProgs = undefined -- } chCached :: (Applicative m, IOish m, Gm m, Binary a) - => (FilePath -> Cached m GhcModState ChCacheData a) -> m a -chCached c = do + => ProjSetup pt -> (FilePath -> Cached m GhcModState ChCacheData a) -> m a +chCached ps c = do projdir <- cradleRootDir <$> cradle distdir <- (projdir ) . cradleDistDir <$> cradle d <- cacheInputData projdir - withCabal $ cached projdir (c distdir) d + withCabal ps $ cached projdir (c distdir) d where -- we don't need to include the distdir in the cache input because when it -- changes the cache files will be gone anyways ;) diff --git a/core/GhcMod/ModuleLoader.hs b/core/GhcMod/ModuleLoader.hs index bde6f6645..b34a5e52d 100644 --- a/core/GhcMod/ModuleLoader.hs +++ b/core/GhcMod/ModuleLoader.hs @@ -56,12 +56,9 @@ tweakModSummaryDynFlags ms = getModulesGhc' :: GM.IOish m => (GM.GmlT m () -> GM.GmlT m a) -> FilePath -> GM.GhcModT m (a, Maybe TypecheckedModule, Maybe ParsedModule) getModulesGhc' wrapper targetFile = do - liftIO $ putStrLn $ "getModulesGhc':targetFile=" ++ targetFile -- AZ cfileName <- liftIO $ canonicalizePath targetFile mfs <- GM.getMMappedFiles - liftIO $ putStrLn $ "getModulesGhc':got mapped files" -- AZ mFileName <- liftIO . canonicalizePath $ getMappedFileName cfileName mfs - liftIO $ putStrLn $ "getModulesGhc':got mFileName" -- AZ refTypechecked <- liftIO $ newIORef Nothing refParsed <- liftIO $ newIORef Nothing let keepInfo = pure . (mFileName ==) @@ -93,7 +90,6 @@ getModulesGhc wrapper targetFiles keepInfo saveTypechecked saveParsed = do let ips = map takeDirectory $ Map.keys mfs setIncludePaths df = df { GHC.includePaths = ips ++ GHC.includePaths df } #endif - liftIO $ putStrLn $ "getModulesGhc:calling runGmlTWith'" -- AZ GM.runGmlTWith' (map Left targetFiles) (return . setIncludePaths) (Just $ updateHooks keepInfo saveTypechecked saveParsed) diff --git a/core/GhcMod/Target.hs b/core/GhcMod/Target.hs index cfa2c3a5b..859774a1c 100644 --- a/core/GhcMod/Target.hs +++ b/core/GhcMod/Target.hs @@ -188,18 +188,14 @@ runGmlTWith' :: IOish m -> GmlT m a -> GhcModT m b runGmlTWith' efnmns' mdf mUpdateHooks wrapper action = do - liftIO $ putStrLn $ "runGmlTWith' entered" -- AZ crdl <- cradle - liftIO $ putStrLn $ "runGmlTWith' got cradle" -- AZ Options { optGhcUserOptions } <- options let (fns, mns) = partitionEithers efnmns' ccfns = map (cradleCurrentDir crdl ) fns cfns <- mapM getCanonicalFileNameSafe ccfns let serfnmn = Set.fromList $ map Right mns ++ map Left cfns - liftIO $ putStrLn $ "runGmlTWith' calling targetGhcOptions" -- AZ (opts, mappedStrs) <- targetGhcOptions crdl serfnmn - liftIO $ putStrLn $ "runGmlTWith' got targetGhcOptions" -- AZ let opts' = opts ++ ["-O0", "-fno-warn-missing-home-modules"] ++ optGhcUserOptions @@ -252,8 +248,6 @@ targetGhcOptions :: forall m. IOish m targetGhcOptions crdl sefnmn = do when (Set.null sefnmn) $ error "targetGhcOptions: no targets given" - liftIO $ putStrLn $ "targetGhcOptions:cradleProject=" ++ show (cradleProject crdl) -- AZ - liftIO $ putStrLn $ "targetGhcOptions: isCabalHelperProject=" ++ show (isCabalHelperProject $ cradleProject crdl) -- AZ case cradleProject crdl of proj | isCabalHelperProject proj -> cabalOpts crdl @@ -266,9 +260,7 @@ targetGhcOptions crdl sefnmn = do cabalOpts :: Cradle -> GhcModT m ([GHCOption],[FilePath]) cabalOpts Cradle{..} = do - liftIO $ putStrLn $ "targetGhcOptions.cabalOpts:calling cabalResolvedComponents" --AZ mcs <- cabalResolvedComponents - liftIO $ putStrLn $ "targetGhcOptions.cabalOpts:after cabalResolvedComponents" --AZ mappedStrs <- getMMappedFilePaths let mappedComps = zipMap (moduleComponents mcs . Left) mappedStrs let mdlcs = moduleComponents mcs `zipMap` Set.toList sefnmn @@ -645,6 +637,10 @@ cabalResolvedComponents :: (IOish m) => GhcModT m (Map ChComponentName (GmComponent 'GMCResolved (Set ModulePath))) cabalResolvedComponents = do crdl@(Cradle{..}) <- cradle - comps <- mapM (resolveEntrypoint crdl) =<< getComponents - withAutogen $ - cached cradleRootDir (resolvedComponentsCache cradleDistDir) comps + r <- withProjSetup $ \ps -> do + comps <- mapM (resolveEntrypoint crdl) =<< (getComponents ps) + withAutogen ps $ + cached cradleRootDir (resolvedComponentsCache cradleDistDir) comps + case r of + Just foo -> return foo + Nothing -> error "cabalResolvedComponents" From be26c61aebdb872428ea42d53fc320ab15fbceac Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Wed, 26 Dec 2018 23:48:08 +0200 Subject: [PATCH 43/50] getComponents returns all components info --- core/GhcMod/CabalHelper.hs | 43 +++++++++++++++++++------------------- core/GhcMod/Cradle.hs | 4 ++-- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index 0f753077a..2565b9914 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -34,7 +34,7 @@ module GhcMod.CabalHelper import Control.Applicative import Control.Monad import Control.Category ((.)) -import Data.List.NonEmpty ( NonEmpty(..)) +import Data.List.NonEmpty ( NonEmpty(..), toList) import qualified Data.Map as Map import Data.Maybe import Data.Monoid @@ -98,26 +98,26 @@ chPkgToGhcPkg (ChPkgSpecific f) = PackageDb f getComponents :: (Applicative m, IOish m, Gm m) => ProjSetup pt -> m [GmComponent 'GMCRaw ChEntrypoint] getComponents ps = do - unit :| _ <- runCHQuery ps projectUnits - ui <- runCHQuery ps $ unitInfo unit - cs <- runCHQuery ps $ do - let - doComp :: (ChComponentName, ChComponentInfo) -> GmComponent 'GMCRaw ChEntrypoint - doComp (cn,ci) = - GmComponent - { gmcHomeModuleGraph = mempty - , gmcGhcOpts = ciGhcOptions ci - , gmcGhcPkgOpts = ciGhcPkgOptions ci - , gmcGhcSrcOpts = ciGhcSrcOptions ci - , gmcGhcLangOpts = ciGhcLangOptions ci - , gmcRawEntrypoints = ciEntrypoints ci - , gmcEntrypoints = ciEntrypoints ci - , gmcSourceDirs = ciSourceDirs ci - , gmcName = ciComponentName ci - , gmcNeedsBuildOutput = ciNeedsBuildOutput ci - } - - return ( map doComp $ Map.toList $ uiComponents ui) + let + doComp :: (ChComponentName, ChComponentInfo) -> GmComponent 'GMCRaw ChEntrypoint + doComp (cn,ci) = + GmComponent + { gmcHomeModuleGraph = mempty + , gmcGhcOpts = ciGhcOptions ci + , gmcGhcPkgOpts = ciGhcPkgOptions ci + , gmcGhcSrcOpts = ciGhcSrcOptions ci + , gmcGhcLangOpts = ciGhcLangOptions ci + , gmcRawEntrypoints = ciEntrypoints ci + , gmcEntrypoints = ciEntrypoints ci + , gmcSourceDirs = ciSourceDirs ci + , gmcName = ciComponentName ci + , gmcNeedsBuildOutput = ciNeedsBuildOutput ci + } + foo :: UnitInfo -> [GmComponent 'GMCRaw ChEntrypoint] + foo ui = map doComp $ Map.toList $ uiComponents ui + + ff <- runCHQuery ps $ allUnits foo + let cs = concat $ toList ff return cs -- getComponents = chCached $ \distdir -> Cached { @@ -226,6 +226,7 @@ withProjSetup f = do case cradleCabalFile crdl of Nothing -> return Nothing Just cabalFile -> do + -- liftIO $ putStrLn $ "withProjSetup:project=" ++ show (cradleProject crdl) case cradleProject crdl of CabalProject -> Just <$> f oldBuild CabalNewProject -> Just <$> f newBuild diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 0a0a0c79a..e753e924b 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -60,8 +60,8 @@ findCradleNoLog progs = findCradle' :: (GmLog m, IOish m, GmOut m) => Programs -> FilePath -> m Cradle findCradle' Programs { stackProgram, cabalProgram } dir = run $ - msum [ stackCradle stackProgram dir - , cabalCradle cabalProgram dir + msum [ cabalCradle cabalProgram dir + , stackCradle stackProgram dir , sandboxCradle dir , plainCradle dir ] From b87290460c2f3d37e0da7bc11603b63233f8a2be Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Thu, 27 Dec 2018 14:54:11 +0200 Subject: [PATCH 44/50] WIP. pausing now, need to wait for stack release --- core/GhcMod/CabalHelper.hs | 57 ++++++++++++++++++++++++++------------ core/GhcMod/Cradle.hs | 28 ++++++++++++++++++- core/GhcMod/Types.hs | 6 +++- 3 files changed, 71 insertions(+), 20 deletions(-) diff --git a/core/GhcMod/CabalHelper.hs b/core/GhcMod/CabalHelper.hs index 2565b9914..c15663a6b 100644 --- a/core/GhcMod/CabalHelper.hs +++ b/core/GhcMod/CabalHelper.hs @@ -34,10 +34,12 @@ module GhcMod.CabalHelper import Control.Applicative import Control.Monad import Control.Category ((.)) +import Data.Dynamic (toDyn, fromDynamic, Dynamic) import Data.List.NonEmpty ( NonEmpty(..), toList) import qualified Data.Map as Map import Data.Maybe import Data.Monoid +import Data.Typeable (Typeable) import Data.Version import Data.Binary (Binary) import Data.Traversable @@ -95,7 +97,7 @@ chPkgToGhcPkg (ChPkgSpecific f) = PackageDb f -- -- The Component\'s 'gmcHomeModuleGraph' will be empty and has to be resolved by -- 'resolveGmComponents'. -getComponents :: (Applicative m, IOish m, Gm m) +getComponents :: (Applicative m, IOish m, Gm m, Typeable pt) => ProjSetup pt -> m [GmComponent 'GMCRaw ChEntrypoint] getComponents ps = do let @@ -187,7 +189,7 @@ getQueryEnv = do -- } -} -runCHQuery :: (IOish m, GmOut m, GmEnv m) +runCHQuery :: (IOish m, GmOut m, GmEnv m, Typeable pt) => ProjSetup (pt :: ProjType) -> Query (pt :: ProjType) b -> m b runCHQuery ps a = do crdl <- cradle @@ -199,26 +201,45 @@ runCHQuery ps a = do -- --------------------------------------------------------------------- -runProjSetup :: (IOish m, GmOut m, GmEnv m) +runProjSetup :: (IOish m, GmOut m, GmEnv m, Typeable pt) => ProjSetup (pt :: ProjType) -> FilePath -> (QueryEnv (pt :: ProjType) -> IO a) -> m a runProjSetup ps cabalFile f = do let projdir = takeDirectory cabalFile crdl <- cradle - progs <- patchStackPrograms crdl =<< (optPrograms <$> options) - readProc <- gmReadProcess - qeBare <- liftIO $ mkQueryEnv - (psProjDir ps $ cabalFile) - (psDistDir ps $ projdir) - let qe = qeBare - -- { qeReadProcess = \_ -> readProc - -- , qePrograms = helperProgs progs - -- } - r <- liftIO $ f qe + -- progs <- patchStackPrograms crdl =<< (optPrograms <$> options) + -- readProc <- gmReadProcess + -- qeBare <- liftIO $ mkQueryEnv + -- (psProjDir ps $ cabalFile) + -- (psDistDir ps $ projdir) + -- let qe = qeBare + -- -- { qeReadProcess = \_ -> readProc + -- -- , qePrograms = helperProgs progs + -- -- } + -- r <- liftIO $ f qe + -- return r + r <- case cradleCabalFile crdl of + Nothing -> error "runProjSetup:Nothing" + Just cabalFile -> do + runF ps (cradleQueryEnv crdl) f + -- case cradleProject crdl of + -- CabalProject -> runF ps (cradleQueryEnv crdl) f + -- CabalNewProject -> liftIO $ f (fromJust $ cradleQueryEnvV2 crdl) + -- SandboxProject -> liftIO $ f (fromJust $ cradleQueryEnvV1 crdl) + -- StackProject _env -> liftIO $ f (fromJust $ cradleQueryEnvSt crdl) + -- PlainProject -> error $ "runProjSetup:PlainProject" return r +runF :: (MonadIO m, Typeable pt) => ProjSetup (pt :: ProjType) -> (Maybe Dynamic) -> (QueryEnv (pt :: ProjType) -> IO a) -> m a +runF _ Nothing _ = error "CabalHelper.runF" +runF _ (Just dqe) f = liftIO $ f qe + where + qe = case fromDynamic dqe of + Nothing -> error "CabalHelper.runF 2" + Just qe -> qe + -- --------------------------------------------------------------------- -withProjSetup :: (IOish m, GmOut m, GmEnv m) => (forall pt . ProjSetup pt -> m a) -> m (Maybe a) +withProjSetup :: (IOish m, GmOut m, GmEnv m) => (forall pt . Typeable pt => ProjSetup pt -> m a) -> m (Maybe a) withProjSetup f = do crdl <- cradle progs <- patchStackPrograms crdl =<< (optPrograms <$> options) @@ -236,14 +257,14 @@ withProjSetup f = do -- --------------------------------------------------------------------- -prepareCabalHelper :: (IOish m, GmEnv m, GmOut m, GmLog m) => ProjSetup pt -> m () +prepareCabalHelper :: (IOish m, GmEnv m, GmOut m, GmLog m, Typeable pt) => ProjSetup (pt :: ProjType) -> m () prepareCabalHelper ps = do crdl <- cradle when (isCabalHelperProject $ cradleProject crdl) $ do qe <- getQueryEnv withCabal ps $ liftIO (prepare qe) -withAutogen :: (IOish m, GmEnv m, GmOut m, GmLog m) => ProjSetup pt -> m a -> m a +withAutogen :: (IOish m, GmEnv m, GmOut m, GmLog m, Typeable pt) => ProjSetup pt -> m a -> m a withAutogen ps action = do gmLog GmDebug "" $ strDoc "making sure autogen files exist" crdl <- cradle @@ -271,7 +292,7 @@ withAutogen ps action = do -- --------------------------------------------------------------------- -withCabal :: (IOish m, GmEnv m, GmOut m, GmLog m) => ProjSetup pt -> m a -> m a +withCabal :: (IOish m, GmEnv m, GmOut m, GmLog m, Typeable pt) => ProjSetup (pt :: ProjType) -> m a -> m a withCabal ps action = do crdl <- cradle mCabalFile <- liftIO $ timeFile `traverse` cradleCabalFile crdl @@ -404,7 +425,7 @@ helperProgs = undefined -- ghcPkgProgram = T.ghcPkgProgram progs -- } -chCached :: (Applicative m, IOish m, Gm m, Binary a) +chCached :: (Applicative m, IOish m, Gm m, Binary a, Typeable pt) => ProjSetup pt -> (FilePath -> Cached m GhcModState ChCacheData a) -> m a chCached ps c = do projdir <- cradleRootDir <$> cradle diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index e753e924b..f11abb094 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -33,6 +33,7 @@ import GhcMod.Error import Safe import Control.Applicative import Control.Monad.Trans.Maybe +import Data.Dynamic (toDyn, fromDynamic, Dynamic) import Data.Maybe import System.Directory import System.FilePath @@ -40,7 +41,7 @@ import System.Environment import Prelude import Control.Monad.Trans.Journal (runJournalT) -- import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, distDir) -import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, DistDir(..), ProjType(..), ProjLoc(..), callProcessStderr ) +import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, DistDir(..), ProjType(..), ProjLoc(..), callProcessStderr, QueryEnv ) -- import Distribution.System (buildPlatform) import Data.List (intercalate) import Data.Version (Version(..)) @@ -124,6 +125,7 @@ cabalCradle cabalProg wdir = do -- runQuery :: Query pt a -> QueryEnv pt -> IO a -- dd <- liftIO $ runQuery (mkQueryEnv cabalDir "dist-newstyle") distDir let dd = "dist-newstyle" + qe <- MaybeT $ Just <$> makeQueryEnv newBuild cabalFile gmLog GmInfo "" $ text "Using Cabal new-build project at" <+>: text cabalDir return Cradle { @@ -133,8 +135,10 @@ cabalCradle cabalProg wdir = do , cradleTempDir = error "tmpDir" , cradleCabalFile = Just cabalFile , cradleDistDir = dd + , cradleQueryEnv = Just $ toDyn qe } else do + qe <- MaybeT $ Just <$> makeQueryEnv oldBuild cabalFile gmLog GmInfo "" $ text "Using Cabal project at" <+>: text cabalDir return Cradle { cradleProject = CabalProject @@ -143,6 +147,7 @@ cabalCradle cabalProg wdir = do , cradleTempDir = error "tmpDir" , cradleCabalFile = Just cabalFile , cradleDistDir = "dist" + , cradleQueryEnv = Just $ toDyn qe } stackCradle :: @@ -184,6 +189,7 @@ stackCradle stackProg wdir = do senv <- MaybeT $ getStackEnv cabalDir stackProg gmLog GmInfo "" $ text "Using Stack project at" <+>: text cabalDir + qe <- MaybeT $ Just <$> makeQueryEnv stackBuild cabalFile return Cradle { cradleProject = StackProject senv , cradleCurrentDir = wdir @@ -191,6 +197,7 @@ stackCradle stackProg wdir = do , cradleTempDir = error "tmpDir" , cradleCabalFile = Just cabalFile , cradleDistDir = seDistDir senv + , cradleQueryEnv = Just $ toDyn qe } stackCradleSpec :: @@ -218,6 +225,7 @@ sandboxCradle wdir = do , cradleTempDir = error "tmpDir" , cradleCabalFile = Nothing , cradleDistDir = "dist" + , cradleQueryEnv = Nothing } plainCradle :: (IOish m, GmLog m, GmOut m) => FilePath -> MaybeT m Cradle @@ -230,6 +238,7 @@ plainCradle wdir = do , cradleTempDir = error "tmpDir" , cradleCabalFile = Nothing , cradleDistDir = "dist" + , cradleQueryEnv = Nothing } -- | Cabal produces .ghc.environment files which are loaded by GHC if @@ -269,5 +278,22 @@ runWithCwd cwd x xs = do let ?verbose = True callProcessStderr (Just cwd) x xs +-- --------------------------------------------------------------------- + +makeQueryEnv :: (IOish m, GmOut m) + => forall pt. ProjSetup (pt :: ProjType) -> FilePath -> m (QueryEnv (pt :: ProjType)) +makeQueryEnv ps cabalFile = do + let projdir = takeDirectory cabalFile + -- crdl <- cradle + -- progs <- patchStackPrograms crdl =<< (optPrograms <$> options) + -- readProc <- gmReadProcess + qeBare <- liftIO $ mkQueryEnv + (psProjDir ps $ cabalFile) + (psDistDir ps $ projdir) + let qe = qeBare + -- { qeReadProcess = \_ -> readProc + -- , qePrograms = helperProgs progs + -- } + return qe -- --------------------------------------------------------------------- diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index ca70a1cd1..5a9f520fa 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -19,6 +19,7 @@ import Control.Monad import Control.DeepSeq import Data.Binary import Data.Binary.Generic +import Data.Dynamic (toDyn, fromDynamic, Dynamic) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) @@ -166,7 +167,9 @@ data Cradle = Cradle { , cradleCabalFile :: Maybe FilePath -- | The build info directory. , cradleDistDir :: FilePath - } deriving (Eq, Ord, Show) + , cradleQueryEnv :: !(Maybe Dynamic) -- QueryEnv pt + } + -- } deriving (Eq, Ord, Show) data ProjSetup (pt :: ProjType) = ProjSetup @@ -224,6 +227,7 @@ data GhcModState = GhcModState { gmGhcSession :: !(Maybe GmGhcSession) , gmCaches :: !GhcModCaches , gmMMappedFiles :: !FileMappingMap + -- , gmQueryEnvs :: ! } defaultGhcModState :: GhcModState From c450f34318eabdde109961a9aa98c749a059b764 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 30 Dec 2018 19:10:18 +0200 Subject: [PATCH 45/50] Revert to checking stack cradle first. Since it bales on presence of dist* --- core/GhcMod/Cradle.hs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index f11abb094..7d26e4b46 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -61,8 +61,8 @@ findCradleNoLog progs = findCradle' :: (GmLog m, IOish m, GmOut m) => Programs -> FilePath -> m Cradle findCradle' Programs { stackProgram, cabalProgram } dir = run $ - msum [ cabalCradle cabalProgram dir - , stackCradle stackProgram dir + msum [ stackCradle stackProgram dir + , cabalCradle cabalProgram dir , sandboxCradle dir , plainCradle dir ] @@ -189,6 +189,7 @@ stackCradle stackProg wdir = do senv <- MaybeT $ getStackEnv cabalDir stackProg gmLog GmInfo "" $ text "Using Stack project at" <+>: text cabalDir + gmLog GmInfo "" $ text "Using Stack dist dir at" <+>: text (seDistDir senv) -- AZ qe <- MaybeT $ Just <$> makeQueryEnv stackBuild cabalFile return Cradle { cradleProject = StackProject senv From 98c412241460deaeec881e3ec6f8741ac222dd63 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Thu, 3 Jan 2019 23:35:48 +0200 Subject: [PATCH 46/50] Get ghc-mod compiling too, commenting out stuff Which is not used by hie ... --- src/GhcModMain.hs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/GhcModMain.hs b/src/GhcModMain.hs index e6b6bdbfd..4517de98e 100644 --- a/src/GhcModMain.hs +++ b/src/GhcModMain.hs @@ -48,11 +48,12 @@ progMain (globalOptions, commands) = runGmOutT globalOptions $ -- ghc-modi legacyInteractive :: IOish m => GhcModT m () -legacyInteractive = do - prepareCabalHelper - asyncSymbolDb <- newAsyncSymbolDb - world <- getCurrentWorld - legacyInteractiveLoop asyncSymbolDb world +legacyInteractive = undefined +-- legacyInteractive = do +-- prepareCabalHelper +-- asyncSymbolDb <- newAsyncSymbolDb +-- world <- getCurrentWorld +-- legacyInteractiveLoop asyncSymbolDb world legacyInteractiveLoop :: IOish m => AsyncSymbolDb -> World -> GhcModT m () legacyInteractiveLoop asyncSymbolDb world = do From 9f4e9b65d02fb68452fc1d7582a9a1b444963b56 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sat, 16 Feb 2019 16:00:53 +0200 Subject: [PATCH 47/50] Works with alanz cabalhelper at wip/new-build For some definition of works. --- core/GhcMod/Cradle.hs | 9 ++------- core/GhcMod/Pretty.hs | 1 + core/GhcMod/Types.hs | 16 +++++++++++----- core/ghc-mod-core.cabal | 2 +- ghc-mod.cabal | 2 +- 5 files changed, 16 insertions(+), 14 deletions(-) diff --git a/core/GhcMod/Cradle.hs b/core/GhcMod/Cradle.hs index 7d26e4b46..b8815ab58 100644 --- a/core/GhcMod/Cradle.hs +++ b/core/GhcMod/Cradle.hs @@ -41,7 +41,7 @@ import System.Environment import Prelude import Control.Monad.Trans.Journal (runJournalT) -- import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, distDir) -import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, DistDir(..), ProjType(..), ProjLoc(..), callProcessStderr, QueryEnv ) +import Distribution.Helper (runQuery, mkQueryEnv, compilerVersion, DistDir(..), ProjType(..), ProjLoc(..), QueryEnv ) -- import Distribution.System (buildPlatform) import Data.List (intercalate) import Data.Version (Version(..)) @@ -271,14 +271,9 @@ newBuild = ProjSetup stackBuild :: ProjSetup 'Stack stackBuild = ProjSetup { psDistDir = \_dir -> DistDirStack Nothing - , psProjDir = \cabal_file -> ProjLocStackDir (takeDirectory cabal_file) + , psProjDir = \cabal_file -> ProjLocStackYaml ((takeDirectory cabal_file) "stack.yaml") } -runWithCwd :: FilePath -> String -> [String] -> IO () -runWithCwd cwd x xs = do - let ?verbose = True - callProcessStderr (Just cwd) x xs - -- --------------------------------------------------------------------- makeQueryEnv :: (IOish m, GmOut m) diff --git a/core/GhcMod/Pretty.hs b/core/GhcMod/Pretty.hs index 2317a4769..c83d4356a 100644 --- a/core/GhcMod/Pretty.hs +++ b/core/GhcMod/Pretty.hs @@ -38,6 +38,7 @@ import GHC import Outputable (SDoc, withPprStyleDoc) import GhcMod.Types +import Distribution.Helper import GhcMod.Doc import GhcMod.Gap (renderGm) import Prelude hiding ( (<>)) diff --git a/core/GhcMod/Types.hs b/core/GhcMod/Types.hs index 5a9f520fa..98450dea4 100644 --- a/core/GhcMod/Types.hs +++ b/core/GhcMod/Types.hs @@ -19,7 +19,7 @@ import Control.Monad import Control.DeepSeq import Data.Binary import Data.Binary.Generic -import Data.Dynamic (toDyn, fromDynamic, Dynamic) +import Data.Dynamic (Dynamic) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) @@ -322,9 +322,9 @@ data GmComponent (t :: GmComponentType) eps = GmComponent { , gmcNeedsBuildOutput :: NeedsBuildOutput } deriving (Eq, Ord, Show, Read, Generic, Functor) -instance Binary eps => Binary (GmComponent t eps) where - put = ggput . from - get = to `fmap` ggget +-- instance Binary eps => Binary (GmComponent t eps) where +-- put = ggput . from +-- get = to `fmap` ggget data ModulePath = ModulePath { mpModule :: ModuleName, mpPath :: FilePath } deriving (Eq, Ord, Show, Read, Generic, Typeable) @@ -400,12 +400,18 @@ instance Binary ChComponentName where instance Binary ChEntrypoint where put = ggput . from get = to `fmap` ggget -instance Binary ChLibraryName where +instance Binary CabalHelper.ChLibraryName where put = ggput . from get = to `fmap` ggget instance Binary NeedsBuildOutput where put = ggput . from get = to `fmap` ggget +instance Binary (GmComponent 'GMCResolved (Set ModulePath)) where + put = ggput . from + get = to `fmap` ggget +instance Binary (GmComponent 'GMCRaw (Set ModulePath)) where + put = ggput . from + get = to `fmap` ggget -- | Options for "lintWith" function data LintOpts = LintOpts { diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 440b2cd98..8e6ed299d 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -99,7 +99,7 @@ Library , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 - , haskell-src-exts < 1.21 && >= 1.18 + , haskell-src-exts < 1.22 && >= 1.18 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 , optparse-applicative < 0.15 && >= 0.13.0.0 diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 77bfc9932..771753b98 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -141,7 +141,7 @@ Library , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 , ghc-mod-core == 5.9.0.0 - , haskell-src-exts < 1.21 && >= 1.18 + , haskell-src-exts < 1.22 && >= 1.18 , hlint < 2.2 && >= 2.0.8 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 From 7fb6291cf8afeaed771041935277cb9cbffcedd2 Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 17 Feb 2019 16:39:10 +0200 Subject: [PATCH 48/50] Move the entire currently used (by hie) API into GhcModCore --- core/GhcModCore.hs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs index 8ffce212a..ee54adfc5 100644 --- a/core/GhcModCore.hs +++ b/core/GhcModCore.hs @@ -12,7 +12,7 @@ module GhcModCore ( , FileMapping(..) , defaultOptions -- * Logging - , GmLogLevel + , GmLogLevel(..) , increaseLogLevel , decreaseLogLevel , gmSetLogLevel @@ -27,6 +27,7 @@ module GhcModCore ( -- * Monad Types , GhcModT , IOish + , MonadIO(..) -- * Monad utilities , runGhcModT , withOptions @@ -43,6 +44,38 @@ module GhcModCore ( -- * HIE integration utilities , getModulesGhc , getModulesGhc' + -- * Manage GHC AST index vars for older GHCs + , GhcPs,GhcRn,GhcTc + -- Temporary home, see what there is, before strippint out + , findCradle' + , GmEnv + , gmeLocal + , gmCradle + , mkRevRedirMapFunc + , cradle + , GmOut(..) + , options + , GmLog(..) + , makeAbsolute' + , withMappedFile + , listVisibleModuleNames + , runLightGhc + , GHandler(..) + , gcatches + , GmlT(..) + , defaultLintOpts + , pretty + , gmsGet + , gmGhcSession + , gmgsSession + , getMMappedFiles + , withDynFlags + , ghcExceptionDoc + , mkErrStyle' + , renderGm + , LightGhc(..) + , OutputOpts(..) + , collectAllSpansTypes ) where import GhcMod.Cradle @@ -53,3 +86,10 @@ import GhcMod.ModuleLoader import GhcMod.Output import GhcMod.Target import GhcMod.Types + +import GhcMod.Gap (GhcPs,GhcRn,GhcTc,listVisibleModuleNames,mkErrStyle') +import GhcMod.Utils (mkRevRedirMapFunc,makeAbsolute',withMappedFile) +import GhcMod.LightGhc (runLightGhc) +import GhcMod.Error (GHandler(..),gcatches,ghcExceptionDoc) +import GhcMod.SrcUtils (pretty,collectAllSpansTypes) +import GhcMod.DynFlags (withDynFlags) From c488f3a97e8a6e3917a1a3c849ef51e889fccade Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 17 Feb 2019 17:01:25 +0200 Subject: [PATCH 49/50] Include the API used by HaRe --- core/GhcModCore.hs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs index ee54adfc5..30f2e5e0b 100644 --- a/core/GhcModCore.hs +++ b/core/GhcModCore.hs @@ -76,6 +76,13 @@ module GhcModCore ( , LightGhc(..) , OutputOpts(..) , collectAllSpansTypes + , gmlGetSession + , gmlSetSession + , cabalResolvedComponents + , ModulePath(..) + , GmComponent(..) + , GmComponentType(..) + , GmModuleGraph(..) ) where import GhcMod.Cradle From 1046813f81dd0eb084dcc3767ae72c8fdb1e336d Mon Sep 17 00:00:00 2001 From: Alan Zimmerman Date: Sun, 24 Feb 2019 14:50:54 +0200 Subject: [PATCH 50/50] Starting to move things around --- GhcMod.hs | 6 ++++++ {core/GhcMod => GhcMod}/SrcUtils.hs | 0 core/GhcMod/Logger.hs | 2 +- core/GhcModCore.hs | 8 +++++--- core/ghc-mod-core.cabal | 3 +-- ghc-mod.cabal | 1 + 6 files changed, 14 insertions(+), 6 deletions(-) rename {core/GhcMod => GhcMod}/SrcUtils.hs (100%) diff --git a/GhcMod.hs b/GhcMod.hs index 1e0b6e3f7..7793d772d 100644 --- a/GhcMod.hs +++ b/GhcMod.hs @@ -67,6 +67,9 @@ module GhcMod ( , loadMappedFile , loadMappedFileSource , unloadMappedFile + -- * API moving around stuff, temporary for now + , pretty + , collectAllSpansTypes ) where import GhcMod.Exe.Boot @@ -90,3 +93,6 @@ import GhcMod.Monad import GhcMod.Output import GhcMod.Target import GhcMod.Types + + +import GhcMod.SrcUtils (pretty,collectAllSpansTypes) diff --git a/core/GhcMod/SrcUtils.hs b/GhcMod/SrcUtils.hs similarity index 100% rename from core/GhcMod/SrcUtils.hs rename to GhcMod/SrcUtils.hs diff --git a/core/GhcMod/Logger.hs b/core/GhcMod/Logger.hs index 1affd11ea..6fd99f4f9 100644 --- a/core/GhcMod/Logger.hs +++ b/core/GhcMod/Logger.hs @@ -27,7 +27,7 @@ import Bag import SrcLoc import FastString -import GhcMod.Convert +import GhcMod.Convert (convert) import GhcMod.Doc (showPage) import GhcMod.DynFlags (withDynFlags) import GhcMod.Monad.Types diff --git a/core/GhcModCore.hs b/core/GhcModCore.hs index 30f2e5e0b..d010879c5 100644 --- a/core/GhcModCore.hs +++ b/core/GhcModCore.hs @@ -64,7 +64,6 @@ module GhcModCore ( , gcatches , GmlT(..) , defaultLintOpts - , pretty , gmsGet , gmGhcSession , gmgsSession @@ -75,7 +74,6 @@ module GhcModCore ( , renderGm , LightGhc(..) , OutputOpts(..) - , collectAllSpansTypes , gmlGetSession , gmlSetSession , cabalResolvedComponents @@ -83,6 +81,9 @@ module GhcModCore ( , GmComponent(..) , GmComponentType(..) , GmModuleGraph(..) + + -- * Used in ghc-mod + , convert ) where import GhcMod.Cradle @@ -98,5 +99,6 @@ import GhcMod.Gap (GhcPs,GhcRn,GhcTc,listVisibleModuleNames,mkErrStyle') import GhcMod.Utils (mkRevRedirMapFunc,makeAbsolute',withMappedFile) import GhcMod.LightGhc (runLightGhc) import GhcMod.Error (GHandler(..),gcatches,ghcExceptionDoc) -import GhcMod.SrcUtils (pretty,collectAllSpansTypes) +-- import GhcMod.SrcUtils (pretty,collectAllSpansTypes) import GhcMod.DynFlags (withDynFlags) +import GhcMod.Convert ( convert ) diff --git a/core/ghc-mod-core.cabal b/core/ghc-mod-core.cabal index 8e6ed299d..16ca8a471 100644 --- a/core/ghc-mod-core.cabal +++ b/core/ghc-mod-core.cabal @@ -71,7 +71,6 @@ Library GhcMod.PathsAndFiles GhcMod.Pretty GhcMod.Read - GhcMod.SrcUtils GhcMod.Stack GhcMod.Target GhcMod.Types @@ -99,7 +98,7 @@ Library , extra < 1.7 && >= 1.4 , fclabels < 2.1 && >= 2.0 , ghc-paths < 0.2 && >= 0.1.0.9 - , haskell-src-exts < 1.22 && >= 1.18 + -- , haskell-src-exts < 1.22 && >= 1.18 , monad-control < 1.1 && >= 1 , monad-journal < 0.9 && >= 0.4 , optparse-applicative < 0.15 && >= 0.13.0.0 diff --git a/ghc-mod.cabal b/ghc-mod.cabal index 771753b98..c01b6302d 100644 --- a/ghc-mod.cabal +++ b/ghc-mod.cabal @@ -119,6 +119,7 @@ Library GhcMod.Exe.Modules GhcMod.Exe.PkgDoc GhcMod.Exe.Test + GhcMod.SrcUtils Other-Modules: Paths_ghc_mod Build-Depends: -- See Note [GHC Boot libraries]