forked from haskell/haskell-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.hs
3755 lines (3640 loc) · 140 KB
/
Main.hs
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -Wno-redundant-constraints #-} -- don't warn about usage HasCallStack
module Main
( main
) where
import Control.Applicative.Combinators
import Control.Lens ((^.))
import Control.Monad
import Data.Default
import Data.Foldable
import Data.List.Extra
import Data.Maybe
import qualified Data.Text as T
import Data.Tuple.Extra
import Development.IDE.GHC.Util
import Development.IDE.Plugin.Completions.Types (extendImportCommandId)
import Development.IDE.Test
import Development.IDE.Types.Location
import Development.Shake (getDirectoryFilesIO)
import Ide.Types
import qualified Language.LSP.Protocol.Lens as L
import Language.LSP.Protocol.Message
import Language.LSP.Protocol.Types hiding
(SemanticTokensEdit (_start),
mkRange)
import Language.LSP.Test
import System.Directory
import System.FilePath
import qualified System.IO.Extra
import System.IO.Extra hiding (withTempDir)
import System.Time.Extra
import Test.Tasty
import Test.Tasty.ExpectedFailure
import Test.Tasty.HUnit
import Text.Regex.TDFA ((=~))
import Development.IDE.Plugin.CodeAction (matchRegExMultipleImports)
import Test.Hls
import qualified Development.IDE.Plugin.CodeAction as Refactor
import qualified Development.IDE.Plugin.HLS.GhcIde as GhcIde
import qualified Test.AddArgument
main :: IO ()
main = defaultTestRunner tests
refactorPlugin :: IO (IdePlugins IdeState)
refactorPlugin = do
exactprintLog <- pluginTestRecorder
ghcideLog <- pluginTestRecorder
pure $ IdePlugins $
[ Refactor.iePluginDescriptor exactprintLog "ghcide-code-actions-imports-exports"
, Refactor.typeSigsPluginDescriptor exactprintLog "ghcide-code-actions-type-signatures"
, Refactor.bindingsPluginDescriptor exactprintLog "ghcide-code-actions-bindings"
, Refactor.fillHolePluginDescriptor exactprintLog "ghcide-code-actions-fill-holes"
, Refactor.extendImportPluginDescriptor exactprintLog "ghcide-completions-1"
] ++ GhcIde.descriptors ghcideLog
tests :: TestTree
tests =
testGroup "refactor"
[ initializeTests
, codeActionTests
, codeActionHelperFunctionTests
, completionTests
]
initializeTests :: TestTree
initializeTests = withResource acquire release tests
where
tests :: IO (TResponseMessage Method_Initialize) -> TestTree
tests getInitializeResponse = testGroup "initialize response capabilities"
[ chk " code action" _codeActionProvider (Just (InR (CodeActionOptions {_workDoneProgress = Just False, _codeActionKinds = Nothing, _resolveProvider = Just False})))
, che " execute command" _executeCommandProvider [extendImportCommandId]
]
where
chk :: (Eq a, Show a) => TestName -> (ServerCapabilities -> a) -> a -> TestTree
chk title getActual expected =
testCase title $ getInitializeResponse >>= \ir -> expected @=? (getActual . innerCaps) ir
che :: TestName -> (ServerCapabilities -> Maybe ExecuteCommandOptions) -> [T.Text] -> TestTree
che title getActual expected = testCase title $ do
ir <- getInitializeResponse
ExecuteCommandOptions {_commands = commands} <- case getActual $ innerCaps ir of
Just eco -> pure eco
Nothing -> assertFailure "Was expecting Just ExecuteCommandOptions, got Nothing"
-- Check if expected exists in commands. Note that commands can arrive in different order.
mapM_ (\e -> any (\o -> T.isSuffixOf e o) commands @? show (expected, show commands)) expected
acquire :: IO (TResponseMessage Method_Initialize)
acquire = run initializeResponse
release :: TResponseMessage Method_Initialize -> IO ()
release = mempty
innerCaps :: TResponseMessage Method_Initialize -> ServerCapabilities
innerCaps (TResponseMessage _ _ (Right (InitializeResult c _))) = c
innerCaps (TResponseMessage _ _ (Left _)) = error "Initialization error"
completionTests :: TestTree
completionTests =
testGroup "auto import snippets"
[ completionCommandTest
"show imports not in list - simple"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad (msum)", "f = joi"]
(Position 3 6)
"join"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad (msum, join)", "f = joi"]
, completionCommandTest
"show imports not in list - multi-line"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad (\n msum)", "f = joi"]
(Position 4 6)
"join"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad (\n msum, join)", "f = joi"]
, completionCommandTest
"show imports not in list - names with _"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M (msum)", "f = M.mapM_"]
(Position 3 11)
"mapM_"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M (msum, mapM_)", "f = M.mapM_"]
, completionCommandTest
"show imports not in list - initial empty list"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M ()", "f = M.joi"]
(Position 3 10)
"join"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M (join)", "f = M.joi"]
, testGroup "qualified imports"
[ completionCommandTest
"single"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad ()", "f = Control.Monad.joi"]
(Position 3 22)
"join"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad (join)", "f = Control.Monad.joi"]
, completionCommandTest
"as"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M ()", "f = M.joi"]
(Position 3 10)
"join"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M (join)", "f = M.joi"]
, completionCommandTest
"multiple"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M ()", "import Control.Monad as N ()", "f = N.joi"]
(Position 4 10)
"join"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import Control.Monad as M ()", "import Control.Monad as N (join)", "f = N.joi"]
-- Regression test for https://github.com/haskell/haskell-language-server/issues/2824
, completionNoCommandTest
"explicit qualified"
["{-# LANGUAGE NoImplicitPrelude #-}",
"module A where", "import qualified Control.Monad as M (j)"]
(Position 2 38)
"join"
, completionNoCommandTest
"explicit qualified post"
["{-# LANGUAGE NoImplicitPrelude, ImportQualifiedPost #-}",
"module A where", "import Control.Monad qualified as M (j)"]
(Position 2 38)
"join"
, completionNoCommandTest
"multiline import"
[ "{-# LANGUAGE NoImplicitPrelude #-}"
, "module A where", "import Control.Monad", " (fore)"]
(Position 3 9)
"forever"
]
, testGroup "Data constructor"
[ completionCommandTest
"not imported"
["module A where", "import Text.Printf ()", "ZeroPad"]
(Position 2 4)
"ZeroPad"
["module A where", "import Text.Printf (FormatAdjustment (ZeroPad))", "ZeroPad"]
, completionCommandTest
"parent imported abs"
["module A where", "import Text.Printf (FormatAdjustment)", "ZeroPad"]
(Position 2 4)
"ZeroPad"
["module A where", "import Text.Printf (FormatAdjustment (ZeroPad))", "ZeroPad"]
, completionNoCommandTest
"parent imported all"
["module A where", "import Text.Printf (FormatAdjustment (..))", "ZeroPad"]
(Position 2 4)
"ZeroPad"
, completionNoCommandTest
"already imported"
["module A where", "import Text.Printf (FormatAdjustment (ZeroPad))", "ZeroPad"]
(Position 2 4)
"ZeroPad"
, completionNoCommandTest
"function from Prelude"
["module A where", "import Data.Maybe ()", "Nothing"]
(Position 2 4)
"Nothing"
, completionCommandTest
"type operator parent"
["module A where", "import Data.Type.Equality ()", "f = Ref"]
(Position 2 8)
"Refl"
["module A where", "import Data.Type.Equality (type (:~:) (Refl))", "f = Ref"]
]
, testGroup "Record completion"
[ completionCommandTest
"not imported"
["module A where", "import Text.Printf ()", "FormatParse"]
(Position 2 10)
"FormatParse"
["module A where", "import Text.Printf (FormatParse)", "FormatParse"]
, completionCommandTest
"parent imported"
["module A where", "import Text.Printf (FormatParse)", "FormatParse"]
(Position 2 10)
"FormatParse"
["module A where", "import Text.Printf (FormatParse (FormatParse))", "FormatParse"]
, completionNoCommandTest
"already imported"
["module A where", "import Text.Printf (FormatParse (FormatParse))", "FormatParse"]
(Position 2 10)
"FormatParse"
]
, testGroup "Package completion"
[ completionCommandTest
"import Data.Sequence"
["module A where", "foo :: Seq"]
(Position 1 9)
"Seq"
["module A where", "import Data.Sequence (Seq)", "foo :: Seq"]
, completionCommandTest
"qualified import"
["module A where", "foo :: Seq.Seq"]
(Position 1 13)
"Seq"
["module A where", "import qualified Data.Sequence as Seq", "foo :: Seq.Seq"]
]
]
completionCommandTest :: TestName -> [T.Text] -> Position -> T.Text -> [T.Text] -> TestTree
completionCommandTest name src pos wanted expected = testSession name $ do
docId <- createDoc "A.hs" "haskell" (T.unlines src)
_ <- waitForDiagnostics
compls <- skipManyTill anyMessage (getCompletions docId pos)
let wantedC = mapMaybe (\case
CompletionItem {_insertText = Just x, _command = Just cmd}
| wanted `T.isPrefixOf` x -> Just cmd
_ -> Nothing
) compls
case wantedC of
[] ->
liftIO $ assertFailure $ "Cannot find completion " <> show wanted <> " in: " <> show [_label | CompletionItem {_label} <- compls]
command:_ -> do
executeCommand command
if src /= expected
then do
modifiedCode <- skipManyTill anyMessage (getDocumentEdit docId)
liftIO $ modifiedCode @?= T.unlines expected
else do
expectMessages SMethod_WorkspaceApplyEdit 1 $ \edit ->
liftIO $ assertFailure $ "Expected no edit but got: " <> show edit
completionNoCommandTest :: TestName -> [T.Text] -> Position -> T.Text -> TestTree
completionNoCommandTest name src pos wanted = testSession name $ do
docId <- createDoc "A.hs" "haskell" (T.unlines src)
_ <- waitForDiagnostics
compls <- getCompletions docId pos
let isPrefixOfInsertOrLabel ci = any (wanted `T.isPrefixOf`) [fromMaybe "" (ci ^. L.insertText), ci ^. L.label]
case find isPrefixOfInsertOrLabel compls of
Nothing ->
liftIO $ assertFailure $ "Cannot find expected completion in: " <> show [_label | CompletionItem {_label} <- compls]
Just CompletionItem{..} -> liftIO . assertBool ("Expected no command but got: " <> show _command) $ null _command
codeActionTests :: TestTree
codeActionTests = testGroup "code actions"
[ suggestImportDisambiguationTests
, insertImportTests
, extendImportTests
, renameActionTests
, typeWildCardActionTests
, removeImportTests
, suggestImportClassMethodTests
, suggestImportTests
, suggestAddRecordFieldImportTests
, suggestHideShadowTests
, fixConstructorImportTests
, fixModuleImportTypoTests
, importRenameActionTests
, fillTypedHoleTests
, addSigActionTests
, insertNewDefinitionTests
, deleteUnusedDefinitionTests
, addInstanceConstraintTests
, addFunctionConstraintTests
, removeRedundantConstraintsTests
, addTypeAnnotationsToLiteralsTest
, exportUnusedTests
, addImplicitParamsConstraintTests
, removeExportTests
, Test.AddArgument.tests
]
insertImportTests :: TestTree
insertImportTests = testGroup "insert import"
[ checkImport
"module where keyword lower in file no exports"
"WhereKeywordLowerInFileNoExports.hs"
"WhereKeywordLowerInFileNoExports.expected.hs"
"import Data.Int"
, checkImport
"module where keyword lower in file with exports"
"WhereDeclLowerInFile.hs"
"WhereDeclLowerInFile.expected.hs"
"import Data.Int"
, checkImport
"module where keyword lower in file with comments before it"
"WhereDeclLowerInFileWithCommentsBeforeIt.hs"
"WhereDeclLowerInFileWithCommentsBeforeIt.expected.hs"
"import Data.Int"
, expectFailBecause
"'findNextPragmaPosition' function doesn't account for case when shebang is not placed at top of file"
(checkImport
"Shebang not at top with spaces"
"ShebangNotAtTopWithSpaces.hs"
"ShebangNotAtTopWithSpaces.expected.hs"
"import Data.Monoid")
, expectFailBecause
"'findNextPragmaPosition' function doesn't account for case when shebang is not placed at top of file"
(checkImport
"Shebang not at top no space"
"ShebangNotAtTopNoSpace.hs"
"ShebangNotAtTopNoSpace.expected.hs"
"import Data.Monoid")
, expectFailBecause
("'findNextPragmaPosition' function doesn't account for case "
++ "when OPTIONS_GHC pragma is not placed at top of file")
(checkImport
"OPTIONS_GHC pragma not at top with spaces"
"OptionsNotAtTopWithSpaces.hs"
"OptionsNotAtTopWithSpaces.expected.hs"
"import Data.Monoid")
, expectFailBecause
("'findNextPragmaPosition' function doesn't account for "
++ "case when shebang is not placed at top of file")
(checkImport
"Shebang not at top of file"
"ShebangNotAtTop.hs"
"ShebangNotAtTop.expected.hs"
"import Data.Monoid")
, expectFailBecause
("'findNextPragmaPosition' function doesn't account for case "
++ "when OPTIONS_GHC is not placed at top of file")
(checkImport
"OPTIONS_GHC pragma not at top of file"
"OptionsPragmaNotAtTop.hs"
"OptionsPragmaNotAtTop.expected.hs"
"import Data.Monoid")
, expectFailBecause
("'findNextPragmaPosition' function doesn't account for case when "
++ "OPTIONS_GHC pragma is not placed at top of file")
(checkImport
"pragma not at top with comment at top"
"PragmaNotAtTopWithCommentsAtTop.hs"
"PragmaNotAtTopWithCommentsAtTop.expected.hs"
"import Data.Monoid")
, expectFailBecause
("'findNextPragmaPosition' function doesn't account for case when "
++ "OPTIONS_GHC pragma is not placed at top of file")
(checkImport
"pragma not at top multiple comments"
"PragmaNotAtTopMultipleComments.hs"
"PragmaNotAtTopMultipleComments.expected.hs"
"import Data.Monoid")
, expectFailBecause
"'findNextPragmaPosition' function doesn't account for case of multiline pragmas"
(checkImport
"after multiline language pragmas"
"MultiLinePragma.hs"
"MultiLinePragma.expected.hs"
"import Data.Monoid")
, checkImport
"pragmas not at top with module declaration"
"PragmaNotAtTopWithModuleDecl.hs"
"PragmaNotAtTopWithModuleDecl.expected.hs"
"import Data.Monoid"
, checkImport
"pragmas not at top with imports"
"PragmaNotAtTopWithImports.hs"
"PragmaNotAtTopWithImports.expected.hs"
"import Data.Monoid"
, checkImport
"above comment at top of module"
"CommentAtTop.hs"
"CommentAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"above multiple comments below"
"CommentAtTopMultipleComments.hs"
"CommentAtTopMultipleComments.expected.hs"
"import Data.Monoid"
, checkImport
"above curly brace comment"
"CommentCurlyBraceAtTop.hs"
"CommentCurlyBraceAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"above multi-line comment"
"MultiLineCommentAtTop.hs"
"MultiLineCommentAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"above comment with no module explicit exports"
"NoExplicitExportCommentAtTop.hs"
"NoExplicitExportCommentAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"above two-dash comment with no pipe"
"TwoDashOnlyComment.hs"
"TwoDashOnlyComment.expected.hs"
"import Data.Monoid"
, checkImport
"above comment with no (module .. where) decl"
"NoModuleDeclarationCommentAtTop.hs"
"NoModuleDeclarationCommentAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"comment not at top with no (module .. where) decl"
"NoModuleDeclaration.hs"
"NoModuleDeclaration.expected.hs"
"import Data.Monoid"
, checkImport
"comment not at top (data dec is)"
"DataAtTop.hs"
"DataAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"comment not at top (newtype is)"
"NewTypeAtTop.hs"
"NewTypeAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"with no explicit module exports"
"NoExplicitExports.hs"
"NoExplicitExports.expected.hs"
"import Data.Monoid"
, checkImport
"add to correctly placed existing import"
"ImportAtTop.hs"
"ImportAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"add to multiple correctly placed existing imports"
"MultipleImportsAtTop.hs"
"MultipleImportsAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"with language pragma at top of module"
"LangPragmaModuleAtTop.hs"
"LangPragmaModuleAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"with language pragma and explicit module exports"
"LangPragmaModuleWithComment.hs"
"LangPragmaModuleWithComment.expected.hs"
"import Data.Monoid"
, checkImport
"with language pragma at top and no module declaration"
"LanguagePragmaAtTop.hs"
"LanguagePragmaAtTop.expected.hs"
"import Data.Monoid"
, checkImport
"with multiple lang pragmas and no module declaration"
"MultipleLanguagePragmasNoModuleDeclaration.hs"
"MultipleLanguagePragmasNoModuleDeclaration.expected.hs"
"import Data.Monoid"
, checkImport
"with pragmas and shebangs"
"LanguagePragmasThenShebangs.hs"
"LanguagePragmasThenShebangs.expected.hs"
"import Data.Monoid"
, checkImport
"with pragmas and shebangs but no comment at top"
"PragmasAndShebangsNoComment.hs"
"PragmasAndShebangsNoComment.expected.hs"
"import Data.Monoid"
, checkImport
"module decl no exports under pragmas and shebangs"
"PragmasShebangsAndModuleDecl.hs"
"PragmasShebangsAndModuleDecl.expected.hs"
"import Data.Monoid"
, checkImport
"module decl with explicit import under pragmas and shebangs"
"PragmasShebangsModuleExplicitExports.hs"
"PragmasShebangsModuleExplicitExports.expected.hs"
"import Data.Monoid"
, checkImport
"module decl and multiple imports"
"ModuleDeclAndImports.hs"
"ModuleDeclAndImports.expected.hs"
"import Data.Monoid"
, importQualifiedTests
]
importQualifiedTests :: TestTree
importQualifiedTests = testGroup "import qualified prefix suggestions"
[ checkImport'
"qualified import works with 3.8 code action kinds"
"ImportQualified.hs"
"ImportQualified.expected.hs"
"import qualified Control.Monad as Control"
["import Control.Monad (when)"]
, checkImport'
"qualified import in postfix position works with 3.8 code action kinds"
"ImportPostQualified.hs"
"ImportPostQualified.expected.hs"
"import Control.Monad qualified as Control"
["import qualified Control.Monad as Control", "import Control.Monad (when)"]
]
checkImport :: TestName -> FilePath -> FilePath -> T.Text -> TestTree
checkImport testName originalPath expectedPath action =
checkImport' testName originalPath expectedPath action []
checkImport' :: TestName -> FilePath -> FilePath -> T.Text -> [T.Text] -> TestTree
checkImport' testName originalPath expectedPath action excludedActions =
testSessionWithExtraFiles "import-placement" testName $ \dir ->
check (dir </> originalPath) (dir </> expectedPath) action
where
check :: FilePath -> FilePath -> T.Text -> Session ()
check originalPath expectedPath action = do
oSrc <- liftIO $ readFileUtf8 originalPath
shouldBeDocContents <- liftIO $ readFileUtf8 expectedPath
originalDoc <- createDoc originalPath "haskell" oSrc
_ <- waitForDiagnostics
actionsOrCommands <- getAllCodeActions originalDoc
for_ excludedActions (\a -> assertNoActionWithTitle a actionsOrCommands)
chosenAction <- pickActionWithTitle action actionsOrCommands
executeCodeAction chosenAction
originalDocAfterAction <- documentContents originalDoc
liftIO $ T.replace "\r\n" "\n" shouldBeDocContents @=? T.replace "\r\n" "\n" originalDocAfterAction
renameActionTests :: TestTree
renameActionTests = testGroup "rename actions"
[ check "change to local variable name"
[ "module Testing where"
, "foo :: Int -> Int"
, "foo argName = argNme"
]
("Replace with ‘argName’", R 2 14 2 20)
[ "module Testing where"
, "foo :: Int -> Int"
, "foo argName = argName"
]
, check "change to name of imported function"
[ "module Testing where"
, "import Data.Maybe (maybeToList)"
, "foo :: Maybe a -> [a]"
, "foo = maybToList"
]
("Replace with ‘maybeToList’", R 3 6 3 16)
[ "module Testing where"
, "import Data.Maybe (maybeToList)"
, "foo :: Maybe a -> [a]"
, "foo = maybeToList"
]
, check "change infix function"
[ "module Testing where"
, "monus :: Int -> Int"
, "monus x y = max 0 (x - y)"
, "foo x y = x `monnus` y"
]
("Replace with ‘monus’", R 3 12 3 20)
[ "module Testing where"
, "monus :: Int -> Int"
, "monus x y = max 0 (x - y)"
, "foo x y = x `monus` y"
]
, check "change template function"
[ "{-# LANGUAGE TemplateHaskellQuotes #-}"
, "module Testing where"
, "import Language.Haskell.TH (Name)"
, "foo :: Name"
, "foo = 'bread"
]
("Replace with ‘break’", R 4 6 4 12)
[ "{-# LANGUAGE TemplateHaskellQuotes #-}"
, "module Testing where"
, "import Language.Haskell.TH (Name)"
, "foo :: Name"
, "foo = 'break"
]
, testSession "suggest multiple local variable names" $ do
doc <- createDoc "Testing.hs" "haskell" $ T.unlines
[ "module Testing where"
, "foo :: Char -> Char -> Char -> Char"
, "foo argument1 argument2 argument3 = argumentX"
]
_ <- waitForDiagnostics
actions <- getCodeActions doc (R 2 36 2 45)
traverse_ (assertActionWithTitle actions)
[ "Replace with ‘argument1’"
, "Replace with ‘argument2’"
, "Replace with ‘argument3’"
]
]
where
check :: TestName -> [T.Text] -> (T.Text, Range) -> [T.Text] -> TestTree
check testName linesOrig (actionTitle, actionRange) linesExpected =
testSession testName $ do
let contentBefore = T.unlines linesOrig
doc <- createDoc "Testing.hs" "haskell" contentBefore
_ <- waitForDiagnostics
action <- pickActionWithTitle actionTitle =<< getCodeActions doc actionRange
executeCodeAction action
contentAfter <- documentContents doc
let expectedContent = T.unlines linesExpected
liftIO $ expectedContent @=? contentAfter
typeWildCardActionTests :: TestTree
typeWildCardActionTests = testGroup "type wildcard actions"
[ testUseTypeSignature "global signature"
[ "func :: _"
, "func x = x"
]
[ "func :: p -> p"
, "func x = x"
]
, testUseTypeSignature "local signature"
[ "func :: Int -> Int"
, "func x ="
, " let y :: _"
, " y = x * 2"
, " in y"
]
[ "func :: Int -> Int"
, "func x ="
, " let y :: Int"
, " y = x * 2"
, " in y"
]
, testUseTypeSignature "multi-line message 1"
[ "func :: _"
, "func x y = x + y"
]
[ if ghcVersion >= GHC98
then "func :: a -> a -> a" -- 9.8 has a different suggestion
else "func :: Integer -> Integer -> Integer"
, "func x y = x + y"
]
, testUseTypeSignature "type in parentheses"
[ "func :: a -> _"
, "func x = (x, const x)"
]
[ "func :: a -> (a, b -> a)"
, "func x = (x, const x)"
]
, testUseTypeSignature "type in brackets"
[ "func :: _ -> Maybe a"
, "func xs = head xs"
]
[ "func :: [Maybe a] -> Maybe a"
, "func xs = head xs"
]
, testUseTypeSignature "unit type"
[ "func :: IO _"
, "func = putChar 'H'"
]
[ "func :: IO ()"
, "func = putChar 'H'"
]
, testUseTypeSignature "no spaces around '::'"
[ "func::_"
, "func x y = x + y"
]
[ if ghcVersion >= GHC98
then "func::a -> a -> a" -- 9.8 has a different suggestion
else "func::Integer -> Integer -> Integer"
, "func x y = x + y"
]
, testGroup "add parens if hole is part of bigger type"
[ testUseTypeSignature "subtype 1"
[ "func :: _ -> Integer -> Integer"
, "func x y = x + y"
]
[ "func :: Integer -> Integer -> Integer"
, "func x y = x + y"
]
, testUseTypeSignature "subtype 2"
[ "func :: Integer -> _ -> Integer"
, "func x y = x + y"
]
[ "func :: Integer -> Integer -> Integer"
, "func x y = x + y"
]
, testUseTypeSignature "subtype 3"
[ "func :: Integer -> Integer -> _"
, "func x y = x + y"
]
[ "func :: Integer -> Integer -> Integer"
, "func x y = x + y"
]
, testUseTypeSignature "subtype 4"
[ "func :: Integer -> _"
, "func x y = x + y"
]
[ "func :: Integer -> (Integer -> Integer)"
, "func x y = x + y"
]
]
]
where
-- | Test session of given name, checking action "Use type signature..."
-- on a test file with given content and comparing to expected result.
testUseTypeSignature name textIn textOut = testSession name $ do
let fileStart = "module Testing where"
content = T.unlines $ fileStart : textIn
expectedContentAfterAction = T.unlines $ fileStart : textOut
doc <- createDoc "Testing.hs" "haskell" content
_ <- waitForDiagnostics
actionsOrCommands <- getAllCodeActions doc
[addSignature] <- pure [action | InR action@CodeAction { _title = actionTitle } <- actionsOrCommands
, "Use type signature" `T.isPrefixOf` actionTitle
]
executeCodeAction addSignature
contentAfterAction <- documentContents doc
liftIO $ expectedContentAfterAction @=? contentAfterAction
removeImportTests :: TestTree
removeImportTests = testGroup "remove import actions"
[ testSession "redundant" $ do
let contentA = T.unlines
[ "module ModuleA where"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA"
, "stuffB :: Integer"
, "stuffB = 123"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "stuffB :: Integer"
, "stuffB = 123"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "qualified redundant" $ do
let contentA = T.unlines
[ "module ModuleA where"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import qualified ModuleA"
, "stuffB :: Integer"
, "stuffB = 123"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "stuffB :: Integer"
, "stuffB = 123"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "redundant binding" $ do
let contentA = T.unlines
[ "module ModuleA where"
, "stuffA = False"
, "stuffB :: Integer"
, "stuffB = 123"
, "stuffC = ()"
, "_stuffD = '_'"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (stuffA, stuffB, _stuffD, stuffC, stuffA)"
, "main = print stuffB"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove _stuffD, stuffA, stuffC from import"
=<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (stuffB)"
, "main = print stuffB"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "redundant binding - unicode regression " $ do
let contentA = T.unlines
[ "module ModuleA where"
, "data A = A"
, "ε :: Double"
, "ε = 0.5"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (A(..), ε)"
, "a = A"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove ε from import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (A(..))"
, "a = A"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "redundant operator" $ do
let contentA = T.unlines
[ "module ModuleA where"
, "a !! _b = a"
, "a <?> _b = a"
, "stuffB :: Integer"
, "stuffB = 123"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import qualified ModuleA as A ((<?>), stuffB, (!!))"
, "main = print A.stuffB"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove !!, <?> from import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import qualified ModuleA as A (stuffB)"
, "main = print A.stuffB"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "redundant all import" $ do
let contentA = T.unlines
[ "module ModuleA where"
, "data A = A"
, "stuffB :: Integer"
, "stuffB = 123"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (A(..), stuffB)"
, "main = print stuffB"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove A from import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (stuffB)"
, "main = print stuffB"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "redundant constructor import" $ do
let contentA = T.unlines
[ "module ModuleA where"
, "data D = A | B"
, "data E = F"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (D(A,B), E(F))"
, "main = B"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove A, E, F from import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (D(B))"
, "main = B"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "import containing the identifier Strict" $ do
let contentA = T.unlines
[ "module Strict where"
]
_docA <- createDoc "Strict.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import Strict"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove import" =<< getCodeActions docB (R 2 0 2 5)
executeCodeAction action
contentAfterAction <- documentContents docB
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "remove all" $ do
let content = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleA where"
, "import Data.Function (fix, (&))"
, "import qualified Data.Functor.Const"
, "import Data.Functor.Identity"
, "import Data.Functor.Sum (Sum (InL, InR))"
, "import qualified Data.Kind as K (Constraint, Type)"
, "x = InL (Identity 123)"
, "y = fix id"
, "type T = K.Type"
]
doc <- createDoc "ModuleC.hs" "haskell" content
_ <- waitForDiagnostics
action <- pickActionWithTitle "Remove all redundant imports" =<< getAllCodeActions doc
executeCodeAction action
contentAfterAction <- documentContents doc
let expectedContentAfterAction = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleA where"
, "import Data.Function (fix)"
, "import Data.Functor.Identity"
, "import Data.Functor.Sum (Sum (InL))"
, "import qualified Data.Kind as K (Type)"
, "x = InL (Identity 123)"
, "y = fix id"
, "type T = K.Type"
]
liftIO $ expectedContentAfterAction @=? contentAfterAction
, testSession "remove unused operators whose name ends with '.'" $ do
let contentA = T.unlines
[ "module ModuleA where"
, "(@.) = 0 -- Must have an operator whose name ends with '.'"
, "a = 1 -- .. but also something else"
]
_docA <- createDoc "ModuleA.hs" "haskell" contentA
let contentB = T.unlines
[ "{-# OPTIONS_GHC -Wunused-imports #-}"
, "module ModuleB where"
, "import ModuleA (a, (@.))"
, "x = a -- Must use something from module A, but not (@.)"
]
docB <- createDoc "ModuleB.hs" "haskell" contentB
_ <- waitForDiagnostics