forked from purescript/purescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActions.hs
More file actions
285 lines (253 loc) · 11.7 KB
/
Actions.hs
File metadata and controls
285 lines (253 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
module Language.PureScript.Ide.Imports.Actions
( addImplicitImport
, addQualifiedImport
, addImportForIdentifier
, answerRequest
-- for tests
, addImplicitImport'
, addQualifiedImport'
, addExplicitImport'
)
where
import Protolude hiding (moduleName)
import Control.Lens ((^.), has)
import Data.List (nubBy)
import Data.Map qualified as Map
import Data.Text qualified as T
import Language.PureScript qualified as P
import Language.PureScript.Constants.Prim qualified as C
import Language.PureScript.Ide.Completion (getExactMatches)
import Language.PureScript.Ide.Error (IdeError(..))
import Language.PureScript.Ide.Filter (Filter)
import Language.PureScript.Ide.Imports (Import(..), parseImportsFromFile', prettyPrintImportSection)
import Language.PureScript.Ide.State (getAllModules, runQuery, escapeSQL)
import Language.PureScript.Ide.Prim (idePrimDeclarations)
import Language.PureScript.Ide.Types (Ide, IdeDeclaration(..), IdeType(..), Match(..), Success(..), _IdeDeclModule, ideDtorName, ideDtorTypeName, ideTCName, ideTypeName, ideTypeOpName, ideValueOpName, toText)
import Language.PureScript.Ide.Util (discardAnn, identifierFromIdeDeclaration)
import System.IO.UTF8 (writeUTF8FileT)
import Language.PureScript.Ide.Filter qualified as F
import Language.PureScript.Names (runModuleName)
import Language.PureScript.Ide.Filter.Declaration (declarationTypeToText)
import Codec.Serialise (deserialise)
import Data.List qualified as List
import Data.ByteString.Lazy qualified as Lazy
import Language.PureScript (ModuleName(..))
-- | Adds an implicit import like @import Prelude@ to a Sourcefile.
addImplicitImport
:: (MonadIO m, MonadError IdeError m)
=> FilePath -- ^ The source file read from
-> P.ModuleName -- ^ The module to import
-> m [Text]
addImplicitImport fp mn = do
(_, pre, imports, post) <- parseImportsFromFile' fp
let newImportSection = addImplicitImport' imports mn
pure $ joinSections (pre, newImportSection, post)
addImplicitImport' :: [Import] -> P.ModuleName -> [Text]
addImplicitImport' imports mn =
prettyPrintImportSection (Import mn P.Implicit Nothing : imports)
-- | Adds a qualified import like @import Data.Map as Map@ to a source file.
addQualifiedImport
:: (MonadIO m, MonadError IdeError m)
=> FilePath
-- ^ The sourcefile read from
-> P.ModuleName
-- ^ The module to import
-> P.ModuleName
-- ^ The qualifier under which to import
-> m [Text]
addQualifiedImport fp mn qualifier = do
(_, pre, imports, post) <- parseImportsFromFile' fp
let newImportSection = addQualifiedImport' imports mn qualifier
pure $ joinSections (pre, newImportSection, post)
addQualifiedImport' :: [Import] -> P.ModuleName -> P.ModuleName -> [Text]
addQualifiedImport' imports mn qualifier =
prettyPrintImportSection (Import mn P.Implicit (Just qualifier) : imports)
-- | Adds an explicit import like @import Prelude (unit)@ to a Sourcefile. If an
-- explicit import already exists for the given module, it adds the identifier
-- to that imports list.
--
-- So @addExplicitImport "/File.purs" "bind" "Prelude"@ with an already existing
-- @import Prelude (bind)@ in the file File.purs returns @["import Prelude
-- (bind, unit)"]@
addExplicitImport :: (MonadIO m, MonadError IdeError m) =>
FilePath -> IdeDeclaration -> P.ModuleName -> Maybe P.ModuleName -> m [Text]
addExplicitImport fp decl moduleName qualifier = do
(mn, pre, imports, post) <- parseImportsFromFile' fp
let newImportSection =
-- TODO: Open an issue when this PR is merged, we should optimise this
-- so that this case does not write to disc
if mn == moduleName
then imports
else addExplicitImport' decl moduleName qualifier imports
pure $ joinSections (pre, prettyPrintImportSection newImportSection, post)
addExplicitImport' :: IdeDeclaration -> P.ModuleName -> Maybe P.ModuleName -> [Import] -> [Import]
addExplicitImport' decl moduleName qualifier imports =
let
isImplicitlyImported =
any (\case
Import mn P.Implicit qualifier' -> mn == moduleName && qualifier == qualifier'
_ -> False) imports
isNotExplicitlyImportedFromPrim =
moduleName == C.M_Prim &&
not (any (\case
Import C.M_Prim (P.Explicit _) Nothing -> True
_ -> False) imports)
-- We can't import Modules from other modules
isModule = has _IdeDeclModule decl
matches (Import mn (P.Explicit _) qualifier') = mn == moduleName && qualifier == qualifier'
matches _ = False
freshImport = Import moduleName (P.Explicit [refFromDeclaration decl]) qualifier
in
if isImplicitlyImported || isNotExplicitlyImportedFromPrim || isModule
then imports
else updateAtFirstOrPrepend matches (insertDeclIntoImport decl) freshImport imports
where
refFromDeclaration (IdeDeclTypeClass tc) =
P.TypeClassRef ideSpan (tc ^. ideTCName)
refFromDeclaration (IdeDeclDataConstructor dtor) =
P.TypeRef ideSpan (dtor ^. ideDtorTypeName) Nothing
refFromDeclaration (IdeDeclType t) =
P.TypeRef ideSpan (t ^. ideTypeName) (Just [])
refFromDeclaration (IdeDeclValueOperator op) =
P.ValueOpRef ideSpan (op ^. ideValueOpName)
refFromDeclaration (IdeDeclTypeOperator op) =
P.TypeOpRef ideSpan (op ^. ideTypeOpName)
refFromDeclaration d =
P.ValueRef ideSpan (P.Ident (identifierFromIdeDeclaration d))
-- Adds a declaration to an import:
-- TypeDeclaration "Maybe" + Data.Maybe (maybe) -> Data.Maybe(Maybe, maybe)
insertDeclIntoImport :: IdeDeclaration -> Import -> Import
insertDeclIntoImport decl' (Import mn (P.Explicit refs) qual) =
Import mn (P.Explicit (sort (insertDeclIntoRefs decl' refs))) qual
insertDeclIntoImport _ is = is
insertDeclIntoRefs :: IdeDeclaration -> [P.DeclarationRef] -> [P.DeclarationRef]
insertDeclIntoRefs d@(IdeDeclDataConstructor dtor) refs =
updateAtFirstOrPrepend
(matchType (dtor ^. ideDtorTypeName))
(insertDtor (dtor ^. ideDtorName))
(refFromDeclaration d)
refs
insertDeclIntoRefs (IdeDeclType t) refs
| any matches refs = refs
where
matches (P.TypeRef _ typeName _) = _ideTypeName t == typeName
matches _ = False
insertDeclIntoRefs dr refs = nubBy ((==) `on` P.prettyPrintRef) (refFromDeclaration dr : refs)
insertDtor _ (P.TypeRef ss tn' _) = P.TypeRef ss tn' Nothing
insertDtor _ refs = refs
matchType :: P.ProperName 'P.TypeName -> P.DeclarationRef -> Bool
matchType tn (P.TypeRef _ n _) = tn == n
matchType _ _ = False
-- | Looks up the given identifier in the currently loaded modules.
--
-- * Throws an error if the identifier cannot be found.
--
-- * If exactly one match is found, adds an explicit import to the importsection
--
-- * If more than one possible imports are found, reports the possibilities as a
-- list of completions.
addImportForIdentifier
:: (Ide m, MonadError IdeError m)
=> FilePath -- ^ The Sourcefile to read from
-> Text -- ^ The identifier to import
-> Maybe P.ModuleName -- ^ The optional qualifier under which to import
-> [Filter] -- ^ Filters to apply before searching for the identifier
-> m (Either [Match IdeDeclaration] [Text])
addImportForIdentifier fp ident qual filters' = do
let filters = F.exactFilter ident : filters'
rows :: [(Text, Lazy.ByteString)] <- runQuery $
"select module_name, declaration " <>
"from ide_declarations where " <>
T.intercalate " and " (
mapMaybe (\case
F.Filter (Left modules) ->
Just $ "module_name in (" <> T.intercalate "," (toList modules <&> runModuleName <&> \m -> "'" <> m <> "'") <> ")"
F.Filter (Right (F.Prefix f)) -> Just $ "name glob '" <> escapeSQL f <> "*'"
F.Filter (Right (F.Exact f)) -> Just $ "name glob '" <> escapeSQL f <> "'"
F.Filter (Right (F.Namespace namespaces)) ->
Just $ "namespace in (" <> T.intercalate "," (toList namespaces <&> \n -> "'" <> toText n <> "'") <> ")"
F.Filter (Right (F.DeclType dt)) ->
Just $ "namespace in (" <> T.intercalate "," (toList dt <&> \t -> "'" <> declarationTypeToText t <> "'") <> ")"
F.Filter _ -> Nothing)
filters)
modules <- getAllModules Nothing
-- Fallback to volatile state if SQLite returns no results (e.g., for Prim modules)
let declarations :: [Match IdeDeclaration] =
if null rows
then
let addPrim = Map.union idePrimDeclarations
in fmap discardAnn
<$> getExactMatches ident filters (addPrim modules)
else
rows <&> \(m, bs) -> Match (ModuleName m, discardAnn $ deserialise bs)
let
matches = declarations
& filter (\(Match (_, d)) -> not (has _IdeDeclModule d))
case matches of
[] ->
throwError (NotFound "Couldn't find the given identifier. \
\Have you loaded the corresponding module?")
-- Only one match was found for the given identifier, so we can insert it
-- right away
[Match (m, decl)] ->
Right <$> addExplicitImport fp decl m qual
-- This case comes up for newtypes and dataconstructors. Because values and
-- types don't share a namespace we can get multiple matches from the same
-- module. This also happens for parameterized types, as these generate both
-- a type as well as a type synonym.
ms@[Match (m1, d1), Match (m2, d2)] ->
if m1 /= m2
-- If the modules don't line up we just ask the user to specify the
-- module
then pure (Left ms)
else case decideRedundantCase d1 d2 <|> decideRedundantCase d2 d1 of
-- If dataconstructor and type line up we just import the
-- dataconstructor as that will give us an unnecessary import warning at
-- worst
Just decl ->
Right <$> addExplicitImport fp decl m1 qual
-- Here we need the user to specify whether they wanted a
-- dataconstructor or a type
Nothing ->
throwError (GeneralError "Undecidable between type and dataconstructor")
-- Multiple matches were found so we need to ask the user to clarify which
-- module they meant
xs ->
pure (Left xs)
where
decideRedundantCase d@(IdeDeclDataConstructor dtor) (IdeDeclType t) =
if dtor ^. ideDtorTypeName == t ^. ideTypeName then Just d else Nothing
decideRedundantCase IdeDeclType{} ts@IdeDeclTypeSynonym{} =
Just ts
decideRedundantCase _ _ = Nothing
-- | Writes a list of lines to @Just filepath@ and responds with a @TextResult@,
-- or returns the lines as a @MultilineTextResult@ if @Nothing@ was given as the
-- first argument.
answerRequest :: (MonadIO m) => Maybe FilePath -> [Text] -> m Success
answerRequest outfp rs =
case outfp of
Nothing -> pure (MultilineTextResult rs)
Just outfp' -> do
liftIO (writeUTF8FileT outfp' (T.unlines rs))
pure (TextResult ("Written to " <> T.pack outfp'))
-- | If none of the elements of the list satisfy the given predicate 'predicate', then prepend the default value 'def'
-- to the given list. Otherwise, update the first element of the list that satisfies 'predicate' with the updating
-- function 'update'.
updateAtFirstOrPrepend :: (a -> Bool) -> (a -> a) -> a -> [a] -> [a]
updateAtFirstOrPrepend predicate update def xs =
case break predicate xs of
(before, []) -> def : before
(before, x : after) -> before ++ [update x] ++ after
ideSpan :: P.SourceSpan
ideSpan = P.internalModuleSourceSpan "<psc-ide>"
joinSections :: ([Text], [Text], [Text]) -> [Text]
joinSections (pre, decls, post) = pre `joinLine` (decls `joinLine` post)
where
isBlank = T.all (== ' ')
joinLine as bs
| Just ln1 <- lastMay as
, Just ln2 <- head bs
, not (isBlank ln1) && not (isBlank ln2) =
as ++ [""] ++ bs
| otherwise =
as ++ bs