diff --git a/.github/workflows/hackage.yml b/.github/workflows/hackage.yml index 9e399a45da..a5c143dd78 100644 --- a/.github/workflows/hackage.yml +++ b/.github/workflows/hackage.yml @@ -25,7 +25,8 @@ jobs: "hls-module-name-plugin", "hls-pragmas-plugin", "hls-refine-imports-plugin", "hls-retrie-plugin", "hls-splice-plugin", "hls-tactics-plugin", - "hls-call-hierarchy-plugin", + "hls-call-hierarchy-plugin", "hls-alternate-number-format-plugin", + "hls-qualify-imported-names-plugin", "haskell-language-server"] # Uncomment 9.0.1 when ghcide is buildable ghc: [ "9.0.1", diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c5cbc73da2..086fc7d0e4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -237,9 +237,13 @@ jobs: name: Test hls-hlint-plugin test suite run: cabal test hls-hlint-plugin --test-options="$TEST_OPTS" || cabal test hls-hlint-plugin --test-options="$TEST_OPTS" || LSP_TEST_LOG_COLOR=0 LSP_TEST_LOG_MESSAGES=true LSP_TEST_LOG_STDERR=true cabal test hls-hlint-plugin --test-options="$TEST_OPTS" + - if: matrix.test + name: Test hls-alternate-number-format-plugin test suite + run: cabal test hls-alternate-number-format-plugin --test-options="$TEST_OPTS" || cabal test hls-alternate-number-format-plugin --test-options="$TEST_OPTS" || LSP_TEST_LOG_COLOR=0 LSP_TEST_LOG_MESSAGES=true LSP_TEST_LOG_STDERR=true cabal test hls-alternate-number-format-plugin --test-options="$TEST_OPTS" + - if: matrix.test name: Test hls-qualify-imported-names-plugin test suite - run: cabal test hls-qualify-imported-names-plugin --test-options="-j1 --rerun-update" || cabal test hls-qualify-imported-names-plugin --test-options="-j1 --rerun" || LSP_TEST_LOG_COLOR=0 LSP_TEST_LOG_MESSAGES=true LSP_TEST_LOG_STDERR=true cabal test hls-qualify-imported-names-plugin --test-options="-j1 --rerun" + run: cabal test hls-qualify-imported-names-plugin --test-options="$TEST_OPTS" || cabal test hls-qualify-imported-names-plugin --test-options="$TEST_OPTS" || LSP_TEST_LOG_COLOR=0 LSP_TEST_LOG_MESSAGES=true LSP_TEST_LOG_STDERR=true cabal test hls-qualify-imported-names-plugin --test-options="$TEST_OPTS" test_post_job: if: always() diff --git a/cabal-ghc901.project b/cabal-ghc901.project index 4fc039e768..18e63db8f3 100644 --- a/cabal-ghc901.project +++ b/cabal-ghc901.project @@ -25,6 +25,7 @@ packages: ./plugins/hls-module-name-plugin ./plugins/hls-ormolu-plugin ./plugins/hls-call-hierarchy-plugin + ./plugins/hls-alternate-number-format-plugin with-compiler: ghc-9.0.1 diff --git a/cabal-ghc921.project b/cabal-ghc921.project index 9b1795d445..5706da094e 100644 --- a/cabal-ghc921.project +++ b/cabal-ghc921.project @@ -24,6 +24,7 @@ packages: ./plugins/hls-module-name-plugin ./plugins/hls-ormolu-plugin ./plugins/hls-call-hierarchy-plugin + ./plugins/hls-alternate-number-format-plugin with-compiler: ghc-9.2.1 diff --git a/cabal.project b/cabal.project index c44a919bbf..90c322cc4f 100644 --- a/cabal.project +++ b/cabal.project @@ -24,9 +24,9 @@ packages: ./plugins/hls-module-name-plugin ./plugins/hls-ormolu-plugin ./plugins/hls-call-hierarchy-plugin + ./plugins/hls-alternate-number-format-plugin ./plugins/hls-qualify-imported-names-plugin - -- Standard location for temporary packages needed for particular environments -- For example it is used in the project gitlab mirror to help in the MAcOS M1 build script -- See https://github.com/haskell/haskell-language-server/blob/master/.gitlab-ci.yml diff --git a/docs/features.md b/docs/features.md index 1db259894b..37c203360b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -17,6 +17,7 @@ You can watch demos for some of these features [below](#demos). - [Module name suggestions](#module-names) for insertion or correction - [Call hierarchy support](#call-hierarchy) - [Qualify names from an import declaration](#qualify-imported-names) in your code +- [Suggest alternate numeric formats](#alternate-number-formatting) ## Demos @@ -51,3 +52,7 @@ You can watch demos for some of these features [below](#demos). ### Qualify imported names ![Qualify Imported Names Demo](../plugins/hls-qualify-imported-names-plugin/qualify-imported-names-demo.gif) + +### Alternate Number Formatting + +![Alternate Number Format Demo](../plugins/hls-alternate-number-format-plugin/HLSAll.gif) diff --git a/exe/Plugins.hs b/exe/Plugins.hs index c8f6a812db..4974677877 100644 --- a/exe/Plugins.hs +++ b/exe/Plugins.hs @@ -68,6 +68,10 @@ import Ide.Plugin.Pragmas as Pragmas import Ide.Plugin.Splice as Splice #endif +#if alternateNumberFormat +import Ide.Plugin.AlternateNumberFormat as AlternateNumberFormat +#endif + -- formatters #if floskell @@ -160,6 +164,9 @@ idePlugins includeExamples = pluginDescToIdePlugins allPlugins #endif #if splice Splice.descriptor "splice" : +#endif +#if alternateNumberFormat + AlternateNumberFormat.descriptor "alternateNumberFormat" : #endif -- The ghcide descriptors should come last so that the notification handlers -- (which restart the Shake build) run after everything else diff --git a/haskell-language-server.cabal b/haskell-language-server.cabal index 2fda1fb4fe..10690b00d0 100644 --- a/haskell-language-server.cabal +++ b/haskell-language-server.cabal @@ -156,6 +156,11 @@ flag splice default: True manual: True +flag alternateNumberFormat + description: Enable Alternate Number Format plugin + default: True + manual: True + flag qualifyImportedNames description: Enable qualifyImportedNames plugin default: True @@ -258,6 +263,11 @@ common splice build-depends: hls-splice-plugin ^>=1.0.0.1 cpp-options: -Dsplice +common alternateNumberFormat + if flag(alternateNumberFormat) + build-depends: hls-alternate-number-format-plugin ^>=1.0.0.0 + cpp-options: -DalternateNumberFormat + common qualifyImportedNames if flag(qualifyImportedNames) build-depends: hls-qualify-imported-names-plugin ^>=1.0.0.0 @@ -307,6 +317,7 @@ executable haskell-language-server , moduleName , pragmas , splice + , alternateNumberFormat , qualifyImportedNames , floskell , fourmolu diff --git a/plugins/hls-alternate-number-format-plugin/HLSAll.gif b/plugins/hls-alternate-number-format-plugin/HLSAll.gif new file mode 100644 index 0000000000..8788697714 Binary files /dev/null and b/plugins/hls-alternate-number-format-plugin/HLSAll.gif differ diff --git a/plugins/hls-alternate-number-format-plugin/LICENSE b/plugins/hls-alternate-number-format-plugin/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plugins/hls-alternate-number-format-plugin/README.md b/plugins/hls-alternate-number-format-plugin/README.md new file mode 100644 index 0000000000..5eb90c8a69 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/README.md @@ -0,0 +1,40 @@ +# Alternate Number Format Plugin + +The alternate number format plugin provides alternative formatting for Numeric Literals in source code. +These can be any numeric literal such as `123`, `0x45` or any of the other numeric formats. +The plugin is context aware and will provide suggestions based on currently active GHC extensions. + +## Setup + +The plugin requires no extra setup to work. Simply place your cursor on top of a literal and invoke the `codeAction` command for your editor. + +## Demo + +![Alternate format suggestions](HLSAll.gif) + +### Currently Supported GHC Extensions: +- `BinaryLiterals` +- `HexFloatLiterals` +- `NumDecimalLiterals` + +## Design + +The plugin is relatively simple, it traverses a files source contents using the GHC API. As it encounters Literals (of the type `HsExpr` with the constructor of either `HsLit` or `HsOverLit`), it will construct an internal `Literal` datatype that has additional information for use to generate suggestions. +Currently, the traversal is done in the file, `Literal.hs`, using the package [SYB](https://hackage.haskell.org/package/syb) for most of the heavy lifting. + +The plugin extends on top of SYB as the traversal done by basic combinators is not perfect. For whatever reason, when starting at the root `ParsedModule` the SYB traversal ignores Pattern Binds (`LPat GhcPs`). As a result, a combinator was created to match on TWO separate underlying types to dispatch on. + +To generate suggestions, the plugin leverages the `Numeric` package which provides a multitude of conversion functions to and from strings/numerics. The only slight change is the addition of extra work when using `NumDecimals` extension. The plugin will attempt to generate 3 choices for the user (this choice is not given for `Fractional` numerics). + +### Known Quirks +- Currently (and probably inefficiently), a Set is used as general accumulator for all Literals being captured. This is because again, through the intricacies of using SYB, we somehow will traverse Source Text multiple times and collect duplicate literals. + +- In the Test Suite, we are required to be explicit in where our `codeActions` will occur. Otherwise, a simple call to `getAllCodeActions` will not work, for whatever reason, there is not enough time to generate the code actions. + +- `PrimLiterals` are currently ignored. GHC API does not attach Source Text to Primitive Literal Nodes. As such these are ignored in the plugin. + +- Similarly, anything that produces a bad Source Span (i.e. can't be easily replaced by an edit) is ignored as well. + +## Changelog +### 1.0.0.0 +- First Release diff --git a/plugins/hls-alternate-number-format-plugin/hls-alternate-number-format-plugin.cabal b/plugins/hls-alternate-number-format-plugin/hls-alternate-number-format-plugin.cabal new file mode 100644 index 0000000000..634cb3acae --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/hls-alternate-number-format-plugin.cabal @@ -0,0 +1,72 @@ +cabal-version: 2.4 +name: hls-alternate-number-format-plugin +version: 1.0.0.0 +synopsis: Provide Alternate Number Formats plugin for Haskell Language Server +description: + Please see the README on GitHub at + +license: Apache-2.0 +license-file: LICENSE +author: Nick Suchecki +maintainer: nicksuchecki@gmail.com +category: Development +build-type: Simple +extra-source-files: + LICENSE + README.md + test/testdata/*.hs + test/testdata/*.yaml + +library + exposed-modules: Ide.Plugin.AlternateNumberFormat, Ide.Plugin.Conversion + other-modules: Ide.Plugin.Literals + hs-source-dirs: src + build-depends: + aeson + , base >=4.12 && < 5 + , containers + , ghcide >=1.5.0 && <1.6 + , ghc-boot-th + , hls-graph + , hls-plugin-api >=1.1 && < 1.3 + , hls-retrie-plugin + , hie-compat + , lens + , lsp + , mtl + , regex-tdfa + , syb + , text + , unordered-containers + + default-language: Haskell2010 + default-extensions: + CPP + LambdaCase + NamedFieldPuns + OverloadedStrings + RecordWildCards + +test-suite tests + type: exitcode-stdio-1.0 + default-language: Haskell2010 + hs-source-dirs: test + other-modules: Properties.Conversion + main-is: Main.hs + ghc-options: -threaded -rtsopts -with-rtsopts=-N -fno-ignore-asserts + build-depends: + , base >=4.12 && < 5 + , filepath + , hls-alternate-number-format-plugin + , hls-test-utils >=1.0 && <1.2 + , lsp + , QuickCheck + , regex-tdfa + , tasty-quickcheck + , text + + default-extensions: + LambdaCase + NamedFieldPuns + OverloadedStrings + RecordWildCards diff --git a/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/AlternateNumberFormat.hs b/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/AlternateNumberFormat.hs new file mode 100644 index 0000000000..ee2c203b70 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/AlternateNumberFormat.hs @@ -0,0 +1,125 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE TypeOperators #-} +module Ide.Plugin.AlternateNumberFormat (descriptor) where + +import Control.Lens ((^.)) +import Control.Monad.Except (ExceptT, MonadIO, liftIO) +import qualified Data.HashMap.Strict as HashMap +import Data.Text (Text) +import qualified Data.Text as T +import Development.IDE (GetParsedModule (GetParsedModule), + IdeState, RuleResult, Rules, + define, ideLogger, + realSrcSpanToRange, runAction, + use) +import Development.IDE.GHC.Compat hiding (getSrcSpan) +import Development.IDE.GHC.Compat.Util (toList) +import Development.IDE.Graph.Classes (Hashable, NFData) +import Development.IDE.Types.Logger as Logger +import GHC.Generics (Generic) +import Ide.Plugin.Conversion (FormatType, alternateFormat, + toFormatTypes) +import Ide.Plugin.Literals (Literal (..), collectLiterals, + getSrcSpan, getSrcText) +import Ide.Plugin.Retrie (handleMaybe, handleMaybeM, + response) +import Ide.Types +import Language.LSP.Types +import Language.LSP.Types.Lens (uri) + +descriptor :: PluginId -> PluginDescriptor IdeState +descriptor plId = (defaultPluginDescriptor plId) + { pluginHandlers = mkPluginHandler STextDocumentCodeAction codeActionHandler + , pluginRules = collectLiteralsRule + } + +data CollectLiterals = CollectLiterals + deriving (Show, Eq, Generic) + +instance Hashable CollectLiterals +instance NFData CollectLiterals + +type instance RuleResult CollectLiterals = CollectLiteralsResult + +data CollectLiteralsResult = CLR + { literals :: [Literal] + , formatTypes :: [FormatType] + } deriving (Generic) + +instance Show CollectLiteralsResult where + show _ = "" + +instance NFData CollectLiteralsResult + +collectLiteralsRule :: Rules () +collectLiteralsRule = define $ \CollectLiterals nfp -> do + pm <- use GetParsedModule nfp + -- get the current extensions active and transform them into FormatTypes + let fmts = getFormatTypes <$> pm + -- collect all the literals for a file + lits = collectLiterals . pm_parsed_source <$> pm + pure ([], CLR <$> lits <*> fmts) + where + getFormatTypes = toFormatTypes . toList . extensionFlags . ms_hspp_opts . pm_mod_summary + +codeActionHandler :: PluginMethodHandler IdeState 'TextDocumentCodeAction +codeActionHandler state _ (CodeActionParams _ _ docId currRange _) = response $ do + nfp <- getNormalizedFilePath docId + CLR{..} <- requestLiterals state nfp + -- remove any invalid literals (see validTarget comment) + let litsInRange = filter inCurrentRange literals + -- generate alternateFormats and zip with the literal that generated the alternates + literalPairs = map (\lit -> (lit, alternateFormat formatTypes lit)) litsInRange + -- make a code action for every literal and its' alternates (then flatten the result) + actions = concatMap (\(lit, alts) -> map (mkCodeAction nfp lit) alts) literalPairs + + logIO state $ "Literals: " <> show literals + + pure $ List actions + where + inCurrentRange :: Literal -> Bool + inCurrentRange lit = let srcSpan = getSrcSpan lit + in currRange `contains` srcSpan + + mkCodeAction :: NormalizedFilePath -> Literal -> Text -> Command |? CodeAction + mkCodeAction nfp lit alt = InR CodeAction { + _title = "Convert " <> getSrcText lit <> " into " <> alt + , _kind = Just $ CodeActionUnknown "quickfix.literals.style" + , _diagnostics = Nothing + , _isPreferred = Nothing + , _disabled = Nothing + , _edit = Just $ mkWorkspaceEdit nfp lit alt + , _command = Nothing + , _xdata = Nothing + } + + mkWorkspaceEdit :: NormalizedFilePath -> Literal -> Text -> WorkspaceEdit + mkWorkspaceEdit nfp lit alt = WorkspaceEdit changes Nothing Nothing + where + txtEdit = TextEdit (realSrcSpanToRange $ getSrcSpan lit) alt + changes = Just $ HashMap.fromList [( filePathToUri $ fromNormalizedFilePath nfp, List [txtEdit])] + +-- from HaddockComments.hs +contains :: Range -> RealSrcSpan -> Bool +contains Range {_start, _end} x = isInsideRealSrcSpan _start x || isInsideRealSrcSpan _end x + +isInsideRealSrcSpan :: Position -> RealSrcSpan -> Bool +p `isInsideRealSrcSpan` r = let (Range sp ep) = realSrcSpanToRange r in sp <= p && p <= ep + +getNormalizedFilePath :: Monad m => TextDocumentIdentifier -> ExceptT String m NormalizedFilePath +getNormalizedFilePath docId = handleMaybe "Error: converting to NormalizedFilePath" + $ uriToNormalizedFilePath + $ toNormalizedUri (docId ^. uri) + +requestLiterals :: MonadIO m => IdeState -> NormalizedFilePath -> ExceptT String m CollectLiteralsResult +requestLiterals state = handleMaybeM "Error: Could not Collect Literals" + . liftIO + . runAction "AlternateNumberFormat.CollectLiterals" state + . use CollectLiterals + + +logIO :: (MonadIO m, Show a) => IdeState -> a -> m () +logIO state = liftIO . Logger.logDebug (ideLogger state) . T.pack . show + diff --git a/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/Conversion.hs b/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/Conversion.hs new file mode 100644 index 0000000000..82425668f4 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/Conversion.hs @@ -0,0 +1,201 @@ +{-# LANGUAGE DeriveGeneric #-} +module Ide.Plugin.Conversion ( + alternateFormat + , hexRegex + , hexFloatRegex + , binaryRegex + , octalRegex + , decimalRegex + , numDecimalRegex + , matchLineRegex + , toFormatTypes + , FormatType + , generateNumDecimal + , toNumDecimal + , toBinary + , toOctal + , toHex + , toHexFloat + , toFloatDecimal + , toFloatExpDecimal +) where + +import Data.Char (toUpper) +import Data.List (delete, dropWhileEnd) +import Data.Maybe (mapMaybe) +import Data.Ratio (denominator, numerator) +import Data.Text (Text) +import qualified Data.Text as T +import Development.IDE.Graph.Classes (NFData) +import GHC.Generics (Generic) +import GHC.LanguageExtensions.Type (Extension (..)) +import GHC.Show (intToDigit) +import Ide.Plugin.Literals (Literal (..), getSrcText) +import Numeric +import Text.Regex.TDFA ((=~)) + +data FormatType = IntFormat IntFormatType + | FracFormat FracFormatType + | AnyFormat AnyFormatType + | NoFormat + deriving (Show, Eq, Generic) + +instance NFData FormatType + +data IntFormatType = HexFormat + | OctalFormat + | BinaryFormat + | NumDecimalFormat + deriving (Show, Eq, Generic) + +instance NFData IntFormatType + +data FracFormatType = HexFloatFormat + | ExponentFormat + deriving (Show, Eq, Generic) + +instance NFData FracFormatType + +data AnyFormatType = DecimalFormat + deriving (Show, Eq, Generic) + +instance NFData AnyFormatType + +-- | Generate alternate formats for a single Literal based on FormatType's given. +alternateFormat :: [FormatType] -> Literal -> [Text] +alternateFormat fmts lit = case lit of + IntLiteral _ _ val -> concatMap (alternateIntFormat val) (removeCurrentFormat lit fmts) + FracLiteral _ _ val -> if denominator val == 1 -- floats that can be integers we can represent as ints + then concatMap (alternateIntFormat (numerator val)) (removeCurrentFormat lit fmts) + else concatMap (alternateFracFormat val) (removeCurrentFormat lit fmts) + +alternateIntFormat :: Integer -> FormatType -> [Text] +alternateIntFormat val fmt = case fmt of + IntFormat ift -> case ift of + HexFormat -> [T.pack $ toHex val] + OctalFormat -> [T.pack $ toOctal val] + BinaryFormat -> [T.pack $ toBinary val] + NumDecimalFormat -> generateNumDecimal val -- this is the only reason we return List of Text :/ + AnyFormat DecimalFormat -> [T.pack $ toDecimal val] + _ -> [] + +alternateFracFormat :: Rational -> FormatType -> [Text] +alternateFracFormat val fmt = case fmt of + AnyFormat DecimalFormat -> [T.pack $ toFloatDecimal (fromRational val)] + FracFormat ExponentFormat -> [T.pack $ toFloatExpDecimal (fromRational val)] + FracFormat HexFloatFormat -> [T.pack $ toHexFloat (fromRational val)] + _ -> [] + +removeCurrentFormat :: Literal -> [FormatType] -> [FormatType] +removeCurrentFormat lit fmts = let srcText = getSrcText lit + in foldl (flip delete) fmts (sourceToFormatType srcText) + +-- | Regex to match a Haskell Hex Literal +hexRegex :: Text +hexRegex = "0[xX][a-fA-F0-9]+" + +-- | Regex to match a Haskell Hex Float Literal +hexFloatRegex :: Text +hexFloatRegex = "0[xX][a-fA-F0-9]+(\\.)?[a-fA-F0-9]*(p[+-]?[0-9]+)?" + +-- | Regex to match a Haskell Binary Literal +binaryRegex :: Text +binaryRegex = "0[bB][0|1]+" + +-- | Regex to match a Haskell Octal Literal +octalRegex :: Text +octalRegex = "0[oO][0-8]+" + +-- | Regex to match a Haskell Decimal Literal (no decimal points) +decimalRegex :: Text +decimalRegex = "[0-9]+(\\.[0-9]+)?" + +-- | Regex to match a Haskell Literal with an explicit exponent +numDecimalRegex :: Text +numDecimalRegex = "[0-9]+\\.[0-9]+[eE][+-]?[0-9]+" + +-- we want to be explicit in our matches +-- so we need to match the beginning/end of the source text +-- | Wraps a Regex with a beginning ("^") and end ("$") token +matchLineRegex :: Text -> Text +matchLineRegex regex = "^" <> regex <> "$" + +sourceToFormatType :: Text -> [FormatType] +sourceToFormatType srcText + | srcText =~ matchLineRegex hexRegex = [IntFormat HexFormat] + | srcText =~ matchLineRegex hexFloatRegex = [FracFormat HexFloatFormat] + | srcText =~ matchLineRegex octalRegex = [IntFormat OctalFormat] + | srcText =~ matchLineRegex binaryRegex = [IntFormat BinaryFormat] + -- can either be a NumDecimal or just a regular Fractional with an exponent + -- otherwise we wouldn't need to return a list + | srcText =~ matchLineRegex numDecimalRegex = [IntFormat NumDecimalFormat, FracFormat ExponentFormat] + -- just assume we are in base 10 with no decimals + | otherwise = [AnyFormat DecimalFormat] + +-- | Translate a list of Extensions into Format Types (plus a base set of Formats) +toFormatTypes :: [Extension] -> [FormatType] +toFormatTypes = (<>) baseFormatTypes . mapMaybe (`lookup` numericPairs) + where + baseFormatTypes = [IntFormat HexFormat, IntFormat OctalFormat, FracFormat ExponentFormat, AnyFormat DecimalFormat] + +-- current list of Numeric related extensions +-- LexicalNegation --- 9.0.1 > --- superset of NegativeLiterals +numericPairs :: [(Extension, FormatType)] +numericPairs = [(NumericUnderscores, NoFormat), (NegativeLiterals, NoFormat)] <> intPairs <> fracPairs + +intPairs :: [(Extension, FormatType)] +intPairs = [(BinaryLiterals, IntFormat BinaryFormat), (NumDecimals, IntFormat NumDecimalFormat)] + +fracPairs :: [(Extension, FormatType)] +fracPairs = [(HexFloatLiterals, FracFormat HexFloatFormat)] + +-- Generate up to 3 possible choices where: +-- dropWhile (\d -> val `div` d) > 1000) implies we want at MOST 3 digits to left of decimal +-- takeWhile (val >) implies we want to stop once we start to get numbers like: 0.1e[N] +-- take 3 implies we want at most three choices which will center around the format: +-- - 500.123e4 +-- - 50.0123e5 +-- - 5e.00123e6 +-- NOTE: showEFloat would also work, but results in only one option +generateNumDecimal :: Integer -> [Text] +generateNumDecimal val = map (toNumDecimal val) $ take 3 $ takeWhile (val >= ) $ dropWhile (\d -> (val `div` d) > 1000) divisors + where + divisors = 10 : map (*10) divisors + +toNumDecimal :: Integer -> Integer -> Text +toNumDecimal val divisor = let (q, r) = val `quotRem` divisor + numExponent = length $ filter (== '0') $ show divisor + -- remove unnecessary trailing zeroes from output + r' = dropWhileEnd (== '0') $ show r + -- but make sure there are still digits left!!! + r'' = if null r' then "0" else r' + in T.pack $ show q <> "." <> r'' <> "e" <> show numExponent + +toBase :: (Num a, Ord a) => (a -> ShowS) -> String -> a -> String +toBase conv header n + | n < 0 = '-' : header <> map toUpper (conv (abs n) "") + | otherwise = header <> map toUpper (conv n "") + +toOctal :: (Integral a, Show a) => a -> String +toOctal = toBase showOct "0o" + +toDecimal :: Integral a => a -> String +toDecimal = toBase showInt "" + +toBinary :: (Integral a, Show a) => a -> String +toBinary = toBase showBin "0b" + where + -- this is not defined in versions of Base < 4.16-ish + showBin = showIntAtBase 2 intToDigit + +toHex :: (Integral a, Show a) => a -> String +toHex = toBase showHex "0x" + +toFloatDecimal :: RealFloat a => a -> String +toFloatDecimal val = showFFloat Nothing val "" + +toFloatExpDecimal :: RealFloat a => a -> String +toFloatExpDecimal val = showEFloat Nothing val "" + +toHexFloat :: RealFloat a => a -> String +toHexFloat val = showHFloat val "" diff --git a/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/Literals.hs b/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/Literals.hs new file mode 100644 index 0000000000..cf462c08c3 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/src/Ide/Plugin/Literals.hs @@ -0,0 +1,152 @@ +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE DerivingVia #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE RankNTypes #-} +module Ide.Plugin.Literals ( + collectLiterals + , Literal(..) + , getSrcText + , getSrcSpan +) where + +import Data.Set (Set) +import qualified Data.Set as S +import Data.Text (Text) +import qualified Data.Text as T +import Development.IDE.GHC.Compat hiding (getSrcSpan) +import Development.IDE.GHC.Util (unsafePrintSDoc) +import Development.IDE.Graph.Classes (NFData (rnf)) +import qualified GHC.Generics as GHC +import Generics.SYB (Data, Typeable, cast, + everything) + +-- data type to capture what type of literal we are dealing with +-- provides location and possibly source text (for OverLits) as well as it's value +-- we currently don't have any use for PrimLiterals. They never have source text so we always drop them +-- | Captures a Numeric Literals Location, Source Text, and Value. +data Literal = IntLiteral RealSrcSpan Text Integer + | FracLiteral RealSrcSpan Text Rational + deriving (GHC.Generic, Show, Ord, Eq) + +instance NFData RealSrcSpan where + rnf x = x `seq` () + +instance NFData Literal + +-- | Return a Literal's Source representation +getSrcText :: Literal -> Text +getSrcText = \case + IntLiteral _ txt _ -> txt + FracLiteral _ txt _ -> txt + +-- | Return a Literal's Real Source location +getSrcSpan :: Literal -> RealSrcSpan +getSrcSpan = \case + IntLiteral ss _ _ -> ss + FracLiteral ss _ _ -> ss + +-- | Find all literals in a Parsed Source File +collectLiterals :: (Data ast, Typeable ast) => ast -> [Literal] +collectLiterals = S.toList . collectLiterals' + +collectLiterals' :: (Data ast, Typeable ast) => ast -> Set Literal +collectLiterals' = everything (<>) (mkQ2 (S.empty :: Set Literal) traverseLExpr traverseLPat) + +-- Located Patterns for whatever reason don't get picked up when using `(mkQ (S.empty :: Set Literal) traverseLExpr) +-- as such we need to explicit traverse those in order to pull out any literals +mkQ2 :: (Typeable a, Typeable b, Typeable c) => r -> (b -> r) -> (c -> r) -> a -> r +mkQ2 def left right datum = case cast datum of + Just datum' -> left datum' + Nothing -> maybe def right (cast datum) + +traverseLPat :: GenLocated SrcSpan (Pat GhcPs) -> Set Literal +traverseLPat (L sSpan pat) = traversePat sSpan pat + +traversePat :: SrcSpan -> Pat GhcPs -> Set Literal +traversePat sSpan = \case + LitPat _ lit -> getLiteralAsList sSpan lit + NPat _ (L olSpan overLit) sexpr1 sexpr2 -> getOverLiteralAsList olSpan overLit + <> collectLiterals' sexpr1 + <> collectLiterals' sexpr2 + NPlusKPat _ _ (L olSpan loverLit) overLit sexpr1 sexpr2 -> getOverLiteralAsList olSpan loverLit + <> getOverLiteralAsList sSpan overLit + <> collectLiterals' sexpr1 + <> collectLiterals' sexpr2 + ast -> collectLiterals' ast + +traverseLExpr :: GenLocated SrcSpan (HsExpr GhcPs) -> Set Literal +traverseLExpr (L sSpan hsExpr) = traverseExpr sSpan hsExpr + +traverseExpr :: SrcSpan -> HsExpr GhcPs -> Set Literal +traverseExpr sSpan = \case + HsOverLit _ overLit -> getOverLiteralAsList sSpan overLit + HsLit _ lit -> getLiteralAsList sSpan lit + expr -> collectLiterals' expr + +getLiteralAsList :: SrcSpan -> HsLit GhcPs -> Set Literal +getLiteralAsList sSpan lit = case sSpan of + RealSrcSpan rss _ -> getLiteralAsList' lit rss + _ -> S.empty + +getLiteralAsList' :: HsLit GhcPs -> RealSrcSpan -> Set Literal +getLiteralAsList' lit = maybe S.empty S.singleton . flip getLiteral lit + +-- Translate from Hs Type to our Literal type +getLiteral :: RealSrcSpan -> HsLit GhcPs -> Maybe Literal +getLiteral sSpan = \case + HsInt _ val -> fromIntegralLit sSpan val + HsRat _ val _ -> fromFractionalLit sSpan val + _ -> Nothing + +getOverLiteralAsList :: SrcSpan -> HsOverLit GhcPs -> Set Literal +getOverLiteralAsList sSpan lit = case sSpan of + RealSrcSpan rss _ -> getOverLiteralAsList' lit rss + _ -> S.empty + +getOverLiteralAsList' :: HsOverLit GhcPs -> RealSrcSpan -> Set Literal +getOverLiteralAsList' lit sSpan = maybe S.empty S.singleton (getOverLiteral sSpan lit) + +getOverLiteral :: RealSrcSpan -> HsOverLit GhcPs -> Maybe Literal +getOverLiteral sSpan OverLit{..} = case ol_val of + HsIntegral il -> fromIntegralLit sSpan il + HsFractional fl -> fromFractionalLit sSpan fl + _ -> Nothing +getOverLiteral _ _ = Nothing + +fromIntegralLit :: RealSrcSpan -> IntegralLit -> Maybe Literal +fromIntegralLit s (IL txt _ val) = fmap (\txt' -> IntLiteral s txt' val) (fromSourceText txt) + +fromFractionalLit :: RealSrcSpan -> FractionalLit -> Maybe Literal +fromFractionalLit s (FL txt _ val) = fmap (\txt' -> FracLiteral s txt' val) (fromSourceText txt) + +fromSourceText :: SourceText -> Maybe Text +fromSourceText = \case + SourceText s -> Just $ T.pack s + NoSourceText -> Nothing + +-- mostly for debugging purposes +literalToString :: HsLit p -> String +literalToString = \case + HsChar _ c -> "Char: " <> show c + HsCharPrim _ c -> "CharPrim: " <> show c + HsString _ fs -> "String: " <> show fs + HsStringPrim _ bs -> "StringPrim: " <> show bs + HsInt _ il -> "Int: " <> show il + HsIntPrim _ n -> "IntPrim: " <> show n + HsWordPrim _ n -> "WordPrim: " <> show n + HsInt64Prim _ n -> "Int64Prim: " <> show n + HsWord64Prim _ n -> "Word64Prim: " <> show n + HsInteger _ n ty -> "Integer: " <> show n <> " Type: " <> tyToLiteral ty + HsRat _ fl ty -> "Rat: " <> show fl <> " Type: " <> tyToLiteral ty + HsFloatPrim _ fl -> "FloatPrim: " <> show fl + HsDoublePrim _ fl -> "DoublePrim: " <> show fl + _ -> "XHsLit" + where + tyToLiteral :: Type -> String + tyToLiteral = unsafePrintSDoc . ppr + +overLitToString :: OverLitVal -> String +overLitToString = \case + HsIntegral int -> case int of { IL _ _ val -> "IntegralOverLit: " <> show val } + HsFractional frac -> case frac of { FL _ _ val -> "RationalOverLit: " <> show val } + HsIsString _ str -> "HIsString: " <> show str diff --git a/plugins/hls-alternate-number-format-plugin/test/Main.hs b/plugins/hls-alternate-number-format-plugin/test/Main.hs new file mode 100644 index 0000000000..ad19324bcb --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/Main.hs @@ -0,0 +1,178 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE ViewPatterns #-} +module Main ( main ) where + +import Data.Either (rights) +import Data.List (find) +import Data.Text (Text) +import qualified Data.Text as T +import Debug.Trace +import qualified Ide.Plugin.AlternateNumberFormat as AlternateNumberFormat +import qualified Ide.Plugin.Conversion as Conversion +import Language.LSP.Types (toEither) +import Language.LSP.Types.Lens (kind) +import Properties.Conversion (conversions) +import System.FilePath ((<.>), ()) +import Test.Hls +import Text.Regex.TDFA ((=~)) + +main :: IO () +main = defaultTestRunner test + +alternateNumberFormatPlugin :: PluginDescriptor IdeState +alternateNumberFormatPlugin = AlternateNumberFormat.descriptor "alternateNumberFormat" + + +-- NOTE: For whatever reason, this plugin does not play nice with creating Code Actions on time. +-- As a result tests will mostly pass if `import Prelude` is added at the top. We (mostly fendor) surmise this has something +-- to do with how +test :: TestTree +test = testGroup "alternateNumberFormat" [ + codeActionHex "TIntDtoH" 3 13 + , codeActionOctal "TIntDtoO" 3 13 + , codeActionBinary "TIntDtoB" 4 13 + , codeActionNumDecimal "TIntDtoND" 5 13 + , codeActionFracExp "TFracDtoE" 3 13 + , codeActionFloatHex "TFracDtoHF" 4 13 + , codeActionDecimal "TIntHtoD" 3 13 + , codeActionDecimal "TFracHFtoD" 4 13 + , codeActionProperties "TFindLiteralIntPattern" [(3, 25), (4,25)] $ \actions -> do + liftIO $ length actions @?= 4 + , codeActionProperties "TFindLiteralIntCase" [(3, 29)] $ \actions -> do + liftIO $ length actions @?= 2 + , codeActionProperties "TFindLiteralIntCase2" [(4, 21)] $ \actions -> do + liftIO $ length actions @?= 2 + , codeActionProperties "TFindLiteralDoReturn" [(5, 10)] $ \actions -> do + liftIO $ length actions @?= 2 + , codeActionProperties "TFindLiteralDoLet" [(5, 13), (6, 13)] $ \actions -> do + liftIO $ length actions @?= 4 + , codeActionProperties "TFindLiteralList" [(3, 28)] $ \actions -> do + liftIO $ length actions @?= 2 + , codeActionProperties "TExpectNoBinaryFormat" [(3, 12)] $ \actions -> do + liftIO $ length actions @?= 2 + liftIO $ actions `doesNotContain` binaryRegex @? "Contains binary codeAction" + , codeActionProperties "TExpectBinaryFormat" [(4, 10)] $ \actions -> do + liftIO $ length actions @?= 3 + liftIO $ actions `contains` binaryRegex @? "Does not contain binary codeAction" + , codeActionProperties "TExpectNoHexFloatFormat" [(3, 14)] $ \actions -> do + liftIO $ length actions @?= 1 + liftIO $ actions `doesNotContain` hexFloatRegex @? "Contains hex float codeAction" + , codeActionProperties "TExpectHexFloatFormat" [(4, 12)] $ \actions -> do + liftIO $ length actions @?= 2 + liftIO $ actions `contains` hexFloatRegex @? "Does not contain hex float codeAction" + , codeActionProperties "TExpectNoNumDecimalFormat" [(3, 16)] $ \actions -> do + liftIO $ length actions @?= 2 + liftIO $ actions `doesNotContain` numDecimalRegex @? "Contains numDecimal codeAction" + , codeActionProperties "TExpectNumDecimalFormat" [(4, 14)] $ \actions -> do + liftIO $ length actions @?= 5 + liftIO $ actions `contains` numDecimalRegex @? "Contains numDecimal codeAction" + , conversions + ] + +codeActionProperties :: TestName -> [(Int, Int)] -> ([CodeAction] -> Session ()) -> TestTree +codeActionProperties fp locs assertions = testCase fp $ do + runSessionWithServer alternateNumberFormatPlugin testDataDir $ do + openDoc (fp <.> ".hs") "haskell" >>= codeActionsFromLocs >>= findAlternateNumberActions >>= assertions + where + -- similar to codeActionTest + codeActionsFromLocs doc = concat <$> mapM (getCodeActions doc . uncurry pointRange) locs + +findAlternateNumberActions :: [Command |? CodeAction] -> Session [CodeAction] +findAlternateNumberActions = pure . filter isAlternateNumberCodeAction . rights . map toEither + where + isAlternateNumberCodeAction CodeAction{_kind} = case _kind of + Nothing -> False + Just kind -> case kind of + CodeActionUnknown txt -> txt == "quickfix.literals.style" + _ -> False + +-- most helpers derived from explicit-imports-plugin Main Test file + +testDataDir :: FilePath +testDataDir = "test" "testdata" + +goldenAlternateFormat :: FilePath -> (TextDocumentIdentifier -> Session ()) -> TestTree +goldenAlternateFormat fp = goldenWithHaskellDoc alternateNumberFormatPlugin (fp <> " (golden)") testDataDir fp "expected" "hs" + +codeActionTest :: (Maybe Text -> Bool) -> FilePath -> Int -> Int -> TestTree +codeActionTest filter' fp line col = goldenAlternateFormat fp $ \doc -> do + actions <- getCodeActions doc (pointRange line col) + -- can't generate code actions? + case find (filter' . codeActionTitle) actions of + Just (InR x) -> executeCodeAction x + _ -> liftIO $ assertFailure "Unable to find CodeAction" + +codeActionDecimal :: FilePath -> Int -> Int -> TestTree +codeActionDecimal = codeActionTest isDecimalCodeAction + +codeActionHex :: FilePath -> Int -> Int -> TestTree +codeActionHex = codeActionTest isHexCodeAction + +codeActionOctal :: FilePath -> Int -> Int -> TestTree +codeActionOctal = codeActionTest isOctalCodeAction + +codeActionBinary :: FilePath -> Int -> Int -> TestTree +codeActionBinary = codeActionTest isBinaryCodeAction + +codeActionNumDecimal :: FilePath -> Int -> Int -> TestTree +codeActionNumDecimal = codeActionTest isNumDecimalCodeAction + +codeActionFracExp :: FilePath -> Int -> Int -> TestTree +codeActionFracExp = codeActionTest isNumDecimalCodeAction + +codeActionFloatHex :: FilePath -> Int -> Int -> TestTree +codeActionFloatHex = codeActionTest isHexFloatCodeAction + +codeActionTitle :: (Command |? CodeAction) -> Maybe Text +codeActionTitle (InR CodeAction {_title}) = Just _title +codeActionTitle _ = Nothing + +codeActionTitle' :: CodeAction -> Text +codeActionTitle' CodeAction{_title} = _title + +pointRange :: Int -> Int -> Range +pointRange + (subtract 1 -> line) + (subtract 1 -> col) = + Range (Position line col) (Position line $ col + 1) + +contains :: [CodeAction] -> Text -> Bool +acts `contains` regex = any (\action -> codeActionTitle' action =~ regex) acts + +doesNotContain :: [CodeAction] -> Text -> Bool +acts `doesNotContain` regex = not $ acts `contains` regex + +convertPrefix, intoInfix, hexRegex, hexFloatRegex, binaryRegex, octalRegex, numDecimalRegex, decimalRegex :: Text +convertPrefix = "Convert (" <> T.intercalate "|" [Conversion.hexRegex, Conversion.hexFloatRegex, Conversion.binaryRegex, Conversion.octalRegex, Conversion.numDecimalRegex, Conversion.decimalRegex] <> ")" +intoInfix = " into " +hexRegex = intoInfix <> Conversion.hexRegex +hexFloatRegex = intoInfix <> Conversion.hexFloatRegex +binaryRegex = intoInfix <> Conversion.binaryRegex +octalRegex = intoInfix <> Conversion.octalRegex +numDecimalRegex = intoInfix <> Conversion.numDecimalRegex +decimalRegex = intoInfix <> Conversion.decimalRegex + +isCodeAction :: Text -> Maybe Text -> Bool +isCodeAction userRegex (Just txt) = txt =~ Conversion.matchLineRegex (convertPrefix <> userRegex) +isCodeAction _ _ = False + +isHexCodeAction :: Maybe Text -> Bool +isHexCodeAction = isCodeAction hexRegex + +isHexFloatCodeAction :: Maybe Text -> Bool +isHexFloatCodeAction = isCodeAction hexFloatRegex + +isBinaryCodeAction :: Maybe Text -> Bool +isBinaryCodeAction = isCodeAction binaryRegex + +isOctalCodeAction :: Maybe Text -> Bool +isOctalCodeAction = isCodeAction octalRegex + +-- This can match EITHER an integer as NumDecimal extension or a Fractional +-- as in 1.23e-3 (so anything with an exponent really) +isNumDecimalCodeAction :: Maybe Text -> Bool +isNumDecimalCodeAction = isCodeAction numDecimalRegex + +isDecimalCodeAction :: Maybe Text -> Bool +isDecimalCodeAction = isCodeAction decimalRegex diff --git a/plugins/hls-alternate-number-format-plugin/test/Properties/Conversion.hs b/plugins/hls-alternate-number-format-plugin/test/Properties/Conversion.hs new file mode 100644 index 0000000000..bba32e8850 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/Properties/Conversion.hs @@ -0,0 +1,38 @@ +{-# LANGUAGE TypeApplications #-} +module Properties.Conversion where + +import Ide.Plugin.Conversion +import Test.Hls (TestTree, testGroup) +import Test.Tasty.QuickCheck (testProperty) +import Text.Regex.TDFA ((=~)) + +conversions :: TestTree +conversions = testGroup "Conversions" $ map (uncurry testProperty) [("Match NumDecimal", prop_regexMatchesNumDecimal) + , ("Match Hex", prop_regexMatchesHex) + , ("Match Octal", prop_regexMatchesOctal) + , ("Match Binary", prop_regexMatchesBinary) + ] <> map (uncurry testProperty) [("Match HexFloat", prop_regexMatchesHexFloat @Double) + , ("Match FloatDecimal", prop_regexMatchesFloatDecimal) + , ("Match FloatExpDecimal", prop_regexMatchesFloatExpDecimal) + ] + +prop_regexMatchesNumDecimal :: Integer -> Bool +prop_regexMatchesNumDecimal = all (=~ numDecimalRegex) . generateNumDecimal + +prop_regexMatchesHex :: (Integral a, Show a) => a -> Bool +prop_regexMatchesHex = (=~ hexRegex ) . toHex + +prop_regexMatchesOctal :: (Integral a, Show a) => a -> Bool +prop_regexMatchesOctal = (=~ octalRegex) . toOctal + +prop_regexMatchesBinary :: (Integral a, Show a) => a -> Bool +prop_regexMatchesBinary = (=~ binaryRegex) . toBinary + +prop_regexMatchesHexFloat :: (RealFloat a) => a -> Bool +prop_regexMatchesHexFloat = (=~ hexFloatRegex) . toHexFloat + +prop_regexMatchesFloatDecimal :: (RealFloat a) => a -> Bool +prop_regexMatchesFloatDecimal = (=~ decimalRegex ) . toFloatDecimal + +prop_regexMatchesFloatExpDecimal :: (RealFloat a) => a -> Bool +prop_regexMatchesFloatExpDecimal = (=~ numDecimalRegex ) . toFloatExpDecimal diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectBinaryFormat.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectBinaryFormat.hs new file mode 100644 index 0000000000..8e8578088f --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectBinaryFormat.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE BinaryLiterals #-} +module TExpectBinaryFormat where + +binary = 459 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectHexFloatFormat.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectHexFloatFormat.hs new file mode 100644 index 0000000000..ea008c51e9 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectHexFloatFormat.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE HexFloatLiterals #-} +module TExpectHexFloatFormat where + +hexFloat = 459.123 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoBinaryFormat.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoBinaryFormat.hs new file mode 100644 index 0000000000..a590fd35a8 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoBinaryFormat.hs @@ -0,0 +1,3 @@ +module TExpectNoBinaryFormat where + +noBinary = 459 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoHexFloatFormat.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoHexFloatFormat.hs new file mode 100644 index 0000000000..2e3487b513 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoHexFloatFormat.hs @@ -0,0 +1,3 @@ +module TExpectNoHexFloatFormat where + +noHexFloat = 459.123 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoNumDecimalFormat.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoNumDecimalFormat.hs new file mode 100644 index 0000000000..b4d0d3580f --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNoNumDecimalFormat.hs @@ -0,0 +1,3 @@ +module TExpectNoNumDecimalFormat where + +noNumDecimal = 499999 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNumDecimalFormat.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNumDecimalFormat.hs new file mode 100644 index 0000000000..e5cbb72ec9 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TExpectNumDecimalFormat.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE NumDecimals #-} +module TExpectNumDecimalFormat where + +numDecimal = 499999 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralDoLet.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralDoLet.hs new file mode 100644 index 0000000000..bb2b4a2960 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralDoLet.hs @@ -0,0 +1,7 @@ +module TFindLiteralDoLet where + +doLet :: IO () +doLet = do + let x = 199 + y = 144 + pure () diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralDoReturn.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralDoReturn.hs new file mode 100644 index 0000000000..81e2d4f74f --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralDoReturn.hs @@ -0,0 +1,5 @@ +module TFindLiteralDoReturn where + +doReturn :: IO Integer +doReturn = do + pure 54 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntCase.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntCase.hs new file mode 100644 index 0000000000..bc5e834597 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntCase.hs @@ -0,0 +1,4 @@ +module TFindLiteralIntCase where + +caseExpression x = case x + 34 of + _ -> "testing if we find a literal in the case statement" diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntCase2.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntCase2.hs new file mode 100644 index 0000000000..29af4c1cd9 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntCase2.hs @@ -0,0 +1,5 @@ +module TFindLiteralIntCase where + +caseExpression x = case x of + 57 -> "testing to find literals in matching cases" + _ -> "" diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntPattern.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntPattern.hs new file mode 100644 index 0000000000..cc01a972ee --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralIntPattern.hs @@ -0,0 +1,5 @@ +module TFindLiteralIntPattern where + +patternMatchingFunction 1 = "one" +patternMatchingFunction 2 = "two" +patternMatchingFunction _ = "the rest of the numbers" diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralList.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralList.hs new file mode 100644 index 0000000000..e28b5bd0ce --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFindLiteralList.hs @@ -0,0 +1,3 @@ +module TFindLiteralList where + +listTest = [reverse $ show 57] diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoE.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoE.expected.hs new file mode 100644 index 0000000000..b0b934cc0e --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoE.expected.hs @@ -0,0 +1,3 @@ +module TFracDtoE where + +convertMe = 1.2345e2 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoE.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoE.hs new file mode 100644 index 0000000000..ed82675f31 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoE.hs @@ -0,0 +1,3 @@ +module TFracDtoE where + +convertMe = 123.45 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoHF.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoHF.expected.hs new file mode 100644 index 0000000000..3a5ce2845d --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoHF.expected.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE HexFloatLiterals #-} +module TFracDtoHF where + +convertMe = 0x1.edccccccccccdp6 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoHF.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoHF.hs new file mode 100644 index 0000000000..07def4e222 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracDtoHF.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE HexFloatLiterals #-} +module TFracDtoHF where + +convertMe = 123.45 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFracHFtoD.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracHFtoD.expected.hs new file mode 100644 index 0000000000..07def4e222 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracHFtoD.expected.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE HexFloatLiterals #-} +module TFracDtoHF where + +convertMe = 123.45 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TFracHFtoD.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracHFtoD.hs new file mode 100644 index 0000000000..3a5ce2845d --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TFracHFtoD.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE HexFloatLiterals #-} +module TFracDtoHF where + +convertMe = 0x1.edccccccccccdp6 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoB.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoB.expected.hs new file mode 100644 index 0000000000..6f44263012 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoB.expected.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE BinaryLiterals #-} +module TIntDtoB where + +convertMe = 0b1100 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoB.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoB.hs new file mode 100644 index 0000000000..501465c049 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoB.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE BinaryLiterals #-} +module TIntDtoB where + +convertMe = 12 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoH.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoH.expected.hs new file mode 100644 index 0000000000..b974c16d98 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoH.expected.hs @@ -0,0 +1,3 @@ +module TIntDtoH where + +convertMe = 0xC diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoH.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoH.hs new file mode 100644 index 0000000000..07fef56ab7 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoH.hs @@ -0,0 +1,3 @@ +module TIntDtoH where + +convertMe = 12 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoND.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoND.expected.hs new file mode 100644 index 0000000000..b9624b6418 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoND.expected.hs @@ -0,0 +1,5 @@ +{-# LANGUAGE NumDecimals #-} +module TIntDtoND where + +convertMe :: Integer +convertMe = 125.345e3 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoND.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoND.hs new file mode 100644 index 0000000000..f0980354f7 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoND.hs @@ -0,0 +1,5 @@ +{-# LANGUAGE NumDecimals #-} +module TIntDtoND where + +convertMe :: Integer +convertMe = 125345 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoO.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoO.expected.hs new file mode 100644 index 0000000000..7089e85ef7 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoO.expected.hs @@ -0,0 +1,3 @@ +module TIntDtoO where + +convertMe = 0o14 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoO.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoO.hs new file mode 100644 index 0000000000..d3db0c599b --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntDtoO.hs @@ -0,0 +1,3 @@ +module TIntDtoO where + +convertMe = 12 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntHtoD.expected.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntHtoD.expected.hs new file mode 100644 index 0000000000..07fef56ab7 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntHtoD.expected.hs @@ -0,0 +1,3 @@ +module TIntDtoH where + +convertMe = 12 diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/TIntHtoD.hs b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntHtoD.hs new file mode 100644 index 0000000000..b974c16d98 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/TIntHtoD.hs @@ -0,0 +1,3 @@ +module TIntDtoH where + +convertMe = 0xC diff --git a/plugins/hls-alternate-number-format-plugin/test/testdata/hie.yaml b/plugins/hls-alternate-number-format-plugin/test/testdata/hie.yaml new file mode 100644 index 0000000000..a8ba03e1b0 --- /dev/null +++ b/plugins/hls-alternate-number-format-plugin/test/testdata/hie.yaml @@ -0,0 +1,24 @@ +cradle: + direct: + arguments: + - -i + - -i. + - TIntDtoH + - TIntDtoB + - TIntDtoO + - TIntDtoND + - TFracDtoE + - TFracDtoHF + - TIntHtoD + - TFracHFtoD + - TFindLiteralIntPattern + - TFindLiteralIntCase + - TFindLiteralIntCase2 + - TFindLiteralDoReturn + - TFindLiteralDoLet + - TFindLiteralList + - TExpectNoBinaryFormat + - TExpectBinaryFormat + - TExpectNoHexFloatFormat + - TExpectHexFloatFormat + - -Wall diff --git a/stack-8.10.5.yaml b/stack-8.10.5.yaml index cf9d3a1f56..dfb469fc0c 100644 --- a/stack-8.10.5.yaml +++ b/stack-8.10.5.yaml @@ -29,6 +29,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack-8.10.6.yaml b/stack-8.10.6.yaml index c97d983ab7..0119547d22 100644 --- a/stack-8.10.6.yaml +++ b/stack-8.10.6.yaml @@ -26,6 +26,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack-8.10.7.yaml b/stack-8.10.7.yaml index f4b2a0e486..91ea6ee7eb 100644 --- a/stack-8.10.7.yaml +++ b/stack-8.10.7.yaml @@ -26,6 +26,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack-8.6.5.yaml b/stack-8.6.5.yaml index f89af06523..0c7bdc0564 100644 --- a/stack-8.6.5.yaml +++ b/stack-8.6.5.yaml @@ -27,6 +27,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack-8.8.3.yaml b/stack-8.8.3.yaml index 29c60e5ba5..e5b47b2cbc 100644 --- a/stack-8.8.3.yaml +++ b/stack-8.8.3.yaml @@ -27,6 +27,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack-8.8.4.yaml b/stack-8.8.4.yaml index aec1fe0a4b..ae69125b10 100644 --- a/stack-8.8.4.yaml +++ b/stack-8.8.4.yaml @@ -27,6 +27,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack-9.0.1.yaml b/stack-9.0.1.yaml index 21ca0b2827..9320543613 100644 --- a/stack-9.0.1.yaml +++ b/stack-9.0.1.yaml @@ -27,6 +27,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock diff --git a/stack.yaml b/stack.yaml index d7fea814e0..2fb75adca6 100644 --- a/stack.yaml +++ b/stack.yaml @@ -26,6 +26,7 @@ packages: - ./plugins/hls-pragmas-plugin - ./plugins/hls-module-name-plugin - ./plugins/hls-ormolu-plugin + - ./plugins/hls-alternate-number-format-plugin ghc-options: "$everything": -haddock