Skip to content

Commit 17fce67

Browse files
authored
Fix wrong extend import while type constuctor and data constructor have the same name (#1775)
* Fix wrong extend import while type constuctor and data constructor have the same name * Add description of sortedMatch
1 parent bd31213 commit 17fce67

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

ghcide/src/Development/IDE/Plugin/CodeAction.hs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -768,7 +768,7 @@ suggestExtendImport exportsMap (L _ HsModule {hsmodImports}) Diagnostic{_range=_
768768
| otherwise = []
769769
where
770770
suggestions decls binding mod srcspan
771-
| range <- case [ x | (x,"") <- readSrcSpan (T.unpack srcspan)] of
771+
| range <- case [ x | (x,"") <- readSrcSpan (T.unpack srcspan)] of
772772
[s] -> let x = realSrcSpanToRange s
773773
in x{_end = (_end x){_character = succ (_character (_end x))}}
774774
_ -> error "bug in srcspan parser",
@@ -783,8 +783,13 @@ suggestExtendImport exportsMap (L _ HsModule {hsmodImports}) Diagnostic{_range=_
783783
| otherwise = []
784784
lookupExportMap binding mod
785785
| Just match <- Map.lookup binding (getExportsMap exportsMap)
786-
, [ident] <- filter (\ident -> moduleNameText ident == mod) (Set.toList match)
787-
= Just ident
786+
-- Only for the situation that data constructor name is same as type constructor name,
787+
-- let ident with parent be in front of the one without.
788+
, sortedMatch <- sortBy (\ident1 ident2 -> parent ident2 `compare` parent ident1) (Set.toList match)
789+
, idents <- filter (\ident -> moduleNameText ident == mod) sortedMatch
790+
, (not . null) idents -- Ensure fallback while `idents` is empty
791+
, ident <- head idents
792+
= Just ident
788793

789794
-- fallback to using GHC suggestion even though it is not always correct
790795
| otherwise

ghcide/test/exe/Main.hs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1408,6 +1408,25 @@ extendImportTests = testGroup "extend import actions"
14081408
, "import A (pattern Some)"
14091409
, "k (Some x) = x"
14101410
])
1411+
, testSession "type constructor name same as data constructor name" $ template
1412+
[("ModuleA.hs", T.unlines
1413+
[ "module ModuleA where"
1414+
, "newtype Foo = Foo Int"
1415+
])]
1416+
("ModuleB.hs", T.unlines
1417+
[ "module ModuleB where"
1418+
, "import ModuleA(Foo)"
1419+
, "f :: Foo"
1420+
, "f = Foo 1"
1421+
])
1422+
(Range (Position 3 4) (Position 3 6))
1423+
["Add Foo(Foo) to the import list of ModuleA"]
1424+
(T.unlines
1425+
[ "module ModuleB where"
1426+
, "import ModuleA(Foo (Foo))"
1427+
, "f :: Foo"
1428+
, "f = Foo 1"
1429+
])
14111430
]
14121431
where
14131432
codeActionTitle CodeAction{_title=x} = x

0 commit comments

Comments
 (0)