@@ -234,8 +234,8 @@ findDeclContainingLoc loc = find (\(L l _) -> loc `isInsideSrcSpan` l)
234234-- imported from ‘Data.ByteString’ at B.hs:6:1-22
235235-- imported from ‘Data.ByteString.Lazy’ at B.hs:8:1-27
236236-- imported from ‘Data.Text’ at B.hs:7:1-16
237- suggestHideShadow :: ParsedSource -> Maybe TcModuleResult -> Maybe HieAstResult -> Diagnostic -> [(T. Text , [Either TextEdit Rewrite ])]
238- suggestHideShadow ps@ (L _ HsModule {hsmodImports}) mTcM mHar Diagnostic {_message, _range}
237+ suggestHideShadow :: ParsedSource -> T. Text -> Maybe TcModuleResult -> Maybe HieAstResult -> Diagnostic -> [(T. Text , [Either TextEdit Rewrite ])]
238+ suggestHideShadow ps@ (L _ HsModule {hsmodImports}) fileContents mTcM mHar Diagnostic {_message, _range}
239239 | Just [identifier, modName, s] <-
240240 matchRegexUnifySpaces
241241 _message
@@ -260,7 +260,7 @@ suggestHideShadow ps@(L _ HsModule {hsmodImports}) mTcM mHar Diagnostic {_messag
260260 mDecl <- findImportDeclByModuleName hsmodImports $ T. unpack modName,
261261 title <- " Hide " <> identifier <> " from " <> modName =
262262 if modName == " Prelude" && null mDecl
263- then maybeToList $ (\ (_, te) -> (title, [Left te])) <$> newImportToEdit (hideImplicitPreludeSymbol identifier) ps
263+ then maybeToList $ (\ (_, te) -> (title, [Left te])) <$> newImportToEdit (hideImplicitPreludeSymbol identifier) ps fileContents
264264 else maybeToList $ (title,) . pure . pure . hideSymbol (T. unpack identifier) <$> mDecl
265265 | otherwise = []
266266
@@ -887,9 +887,10 @@ suggestImportDisambiguation ::
887887 DynFlags ->
888888 Maybe T. Text ->
889889 ParsedSource ->
890+ T. Text ->
890891 Diagnostic ->
891892 [(T. Text , [Either TextEdit Rewrite ])]
892- suggestImportDisambiguation df (Just txt) ps@ (L _ HsModule {hsmodImports}) diag@ Diagnostic {.. }
893+ suggestImportDisambiguation df (Just txt) ps@ (L _ HsModule {hsmodImports}) fileContents diag@ Diagnostic {.. }
893894 | Just [ambiguous] <-
894895 matchRegexUnifySpaces
895896 _message
@@ -930,7 +931,7 @@ suggestImportDisambiguation df (Just txt) ps@(L _ HsModule {hsmodImports}) diag@
930931 suggestionsImpl symbol targetsWithRestImports =
931932 sortOn fst
932933 [ ( renderUniquify mode modNameText symbol
933- , disambiguateSymbol ps diag symbol mode
934+ , disambiguateSymbol ps fileContents diag symbol mode
934935 )
935936 | (modTarget, restImports) <- targetsWithRestImports
936937 , let modName = targetModuleName modTarget
@@ -964,7 +965,7 @@ suggestImportDisambiguation df (Just txt) ps@(L _ HsModule {hsmodImports}) diag@
964965 <> T. pack (moduleNameString qual)
965966 <> " ."
966967 <> symbol
967- suggestImportDisambiguation _ _ _ _ = []
968+ suggestImportDisambiguation _ _ _ _ _ = []
968969
969970occursUnqualified :: T. Text -> ImportDecl GhcPs -> Bool
970971occursUnqualified symbol ImportDecl {.. }
@@ -989,19 +990,20 @@ targetModuleName (ExistingImp _) =
989990
990991disambiguateSymbol ::
991992 ParsedSource ->
993+ T. Text ->
992994 Diagnostic ->
993995 T. Text ->
994996 HidingMode ->
995997 [Either TextEdit Rewrite ]
996- disambiguateSymbol pm Diagnostic {.. } (T. unpack -> symbol) = \ case
998+ disambiguateSymbol pm fileContents Diagnostic {.. } (T. unpack -> symbol) = \ case
997999 (HideOthers hiddens0) ->
9981000 [ Right $ hideSymbol symbol idecl
9991001 | ExistingImp idecls <- hiddens0
10001002 , idecl <- NE. toList idecls
10011003 ]
10021004 ++ mconcat
10031005 [ if null imps
1004- then maybeToList $ Left . snd <$> newImportToEdit (hideImplicitPreludeSymbol $ T. pack symbol) pm
1006+ then maybeToList $ Left . snd <$> newImportToEdit (hideImplicitPreludeSymbol $ T. pack symbol) pm fileContents
10051007 else Right . hideSymbol symbol <$> imps
10061008 | ImplicitPrelude imps <- hiddens0
10071009 ]
@@ -1203,8 +1205,8 @@ removeRedundantConstraints df (L _ HsModule {hsmodDecls}) Diagnostic{..}
12031205
12041206-------------------------------------------------------------------------------------------------
12051207
1206- suggestNewOrExtendImportForClassMethod :: ExportsMap -> ParsedSource -> Diagnostic -> [(T. Text , CodeActionKind , [Either TextEdit Rewrite ])]
1207- suggestNewOrExtendImportForClassMethod packageExportsMap ps Diagnostic {_message}
1208+ suggestNewOrExtendImportForClassMethod :: ExportsMap -> ParsedSource -> T. Text -> Diagnostic -> [(T. Text , CodeActionKind , [Either TextEdit Rewrite ])]
1209+ suggestNewOrExtendImportForClassMethod packageExportsMap ps fileContents Diagnostic {_message}
12081210 | Just [methodName, className] <-
12091211 matchRegexUnifySpaces
12101212 _message
@@ -1229,7 +1231,7 @@ suggestNewOrExtendImportForClassMethod packageExportsMap ps Diagnostic {_message
12291231 ]
12301232 -- new
12311233 _
1232- | Just (range, indent) <- newImportInsertRange ps
1234+ | Just (range, indent) <- newImportInsertRange ps fileContents
12331235 ->
12341236 (\ (kind, unNewImport -> x) -> (x, kind, [Left $ TextEdit range (x <> " \n " <> T. replicate indent " " )])) <$>
12351237 [ (quickFixImportKind' " new" style, newUnqualImport moduleNameText rendered False )
@@ -1239,8 +1241,8 @@ suggestNewOrExtendImportForClassMethod packageExportsMap ps Diagnostic {_message
12391241 <> [(quickFixImportKind " new.all" , newImportAll moduleNameText)]
12401242 | otherwise -> []
12411243
1242- suggestNewImport :: ExportsMap -> ParsedSource -> Diagnostic -> [(T. Text , CodeActionKind , TextEdit )]
1243- suggestNewImport packageExportsMap ps@ (L _ HsModule {.. }) Diagnostic {_message}
1244+ suggestNewImport :: ExportsMap -> ParsedSource -> T. Text -> Diagnostic -> [(T. Text , CodeActionKind , TextEdit )]
1245+ suggestNewImport packageExportsMap ps@ (L _ HsModule {.. }) fileContents Diagnostic {_message}
12441246 | msg <- unifySpaces _message
12451247 , Just thingMissing <- extractNotInScopeName msg
12461248 , qual <- extractQualifiedModuleName msg
@@ -1249,13 +1251,13 @@ suggestNewImport packageExportsMap ps@(L _ HsModule {..}) Diagnostic{_message}
12491251 >>= (findImportDeclByModuleName hsmodImports . T. unpack)
12501252 >>= ideclAs . unLoc
12511253 <&> T. pack . moduleNameString . unLoc
1252- , Just (range, indent) <- newImportInsertRange ps
1254+ , Just (range, indent) <- newImportInsertRange ps fileContents
12531255 , extendImportSuggestions <- matchRegexUnifySpaces msg
12541256 " Perhaps you want to add ‘[^’]*’ to the import list in the import of ‘([^’]*)’"
12551257 = sortOn fst3 [(imp, kind, TextEdit range (imp <> " \n " <> T. replicate indent " " ))
12561258 | (kind, unNewImport -> imp) <- constructNewImportSuggestions packageExportsMap (qual <|> qual', thingMissing) extendImportSuggestions
12571259 ]
1258- suggestNewImport _ _ _ = []
1260+ suggestNewImport _ _ _ _ = []
12591261
12601262constructNewImportSuggestions
12611263 :: ExportsMap -> (Maybe T. Text , NotInScope ) -> Maybe [T. Text ] -> [(CodeActionKind , NewImport )]
@@ -1282,26 +1284,70 @@ constructNewImportSuggestions exportsMap (qual, thingMissing) notTheseModules =
12821284newtype NewImport = NewImport { unNewImport :: T. Text}
12831285 deriving (Show , Eq , Ord )
12841286
1285- newImportToEdit :: NewImport -> ParsedSource -> Maybe (T. Text , TextEdit )
1286- newImportToEdit (unNewImport -> imp) ps
1287- | Just (range, indent) <- newImportInsertRange ps
1287+ newImportToEdit :: NewImport -> ParsedSource -> T. Text -> Maybe (T. Text , TextEdit )
1288+ newImportToEdit (unNewImport -> imp) ps fileContents
1289+ | Just (range, indent) <- newImportInsertRange ps fileContents
12881290 = Just (imp, TextEdit range (imp <> " \n " <> T. replicate indent " " ))
12891291 | otherwise = Nothing
12901292
1291- newImportInsertRange :: ParsedSource -> Maybe (Range , Int )
1292- newImportInsertRange (L _ HsModule {.. })
1293+ -- | Finds the next valid position for inserting a new import declaration
1294+ -- * If the file already has existing imports it will be inserted under the last of these,
1295+ -- it is assumed that the existing last import declaration is in a valid position
1296+ -- * If the file does not have existing imports, but has a (module ... where) declaration,
1297+ -- the new import will be inserted directly under this declaration (accounting for explicit exports)
1298+ -- * If the file has neither existing imports nor a module declaration,
1299+ -- the import will be inserted at line zero if there are no pragmas,
1300+ -- * otherwise inserted one line after the last file-header pragma
1301+ newImportInsertRange :: ParsedSource -> T. Text -> Maybe (Range , Int )
1302+ newImportInsertRange (L _ HsModule {.. }) fileContents
12931303 | Just (uncurry Position -> insertPos, col) <- case hsmodImports of
1294- [] -> case getLoc (head hsmodDecls) of
1295- OldRealSrcSpan s -> let col = srcLocCol (realSrcSpanStart s) - 1
1296- in Just ((srcLocLine (realSrcSpanStart s) - 1 , col), col)
1297- _ -> Nothing
1298- _ -> case getLoc (last hsmodImports) of
1299- OldRealSrcSpan s -> let col = srcLocCol (realSrcSpanStart s) - 1
1300- in Just ((srcLocLine $ realSrcSpanEnd s,col), col)
1301- _ -> Nothing
1304+ [] -> findPositionNoImports hsmodName hsmodExports fileContents
1305+ _ -> findPositionFromImportsOrModuleDecl hsmodImports last True
13021306 = Just (Range insertPos insertPos, col)
13031307 | otherwise = Nothing
13041308
1309+ -- | Insert the import under the Module declaration exports if they exist, otherwise just under the module declaration.
1310+ -- If no module declaration exists, then no exports will exist either, in that case
1311+ -- insert the import after any file-header pragmas or at position zero if there are no pragmas
1312+ findPositionNoImports :: Maybe (Located ModuleName ) -> Maybe (Located [LIE name ]) -> T. Text -> Maybe ((Int , Int ), Int )
1313+ findPositionNoImports Nothing _ fileContents = findNextPragmaPosition fileContents
1314+ findPositionNoImports _ (Just hsmodExports) _ = findPositionFromImportsOrModuleDecl hsmodExports id False
1315+ findPositionNoImports (Just hsmodName) _ _ = findPositionFromImportsOrModuleDecl hsmodName id False
1316+
1317+ findPositionFromImportsOrModuleDecl :: HasSrcSpan a => t -> (t -> a ) -> Bool -> Maybe ((Int , Int ), Int )
1318+ findPositionFromImportsOrModuleDecl hsField f hasImports = case getLoc (f hsField) of
1319+ OldRealSrcSpan s ->
1320+ let col = calcCol s
1321+ in Just ((srcLocLine (realSrcSpanEnd s), col), col)
1322+ _ -> Nothing
1323+ where calcCol s = if hasImports then srcLocCol (realSrcSpanStart s) - 1 else 0
1324+
1325+ -- | Find the position one after the last file-header pragma
1326+ -- Defaults to zero if there are no pragmas in file
1327+ findNextPragmaPosition :: T. Text -> Maybe ((Int , Int ), Int )
1328+ findNextPragmaPosition contents = Just ((lineNumber, 0 ), 0 )
1329+ where
1330+ lineNumber = afterLangPragma . afterOptsGhc $ afterShebang
1331+ afterLangPragma = afterPragma " LANGUAGE" contents'
1332+ afterOptsGhc = afterPragma " OPTIONS_GHC" contents'
1333+ afterShebang = lastLineWithPrefix (T. isPrefixOf " #!" ) contents' 0
1334+ contents' = T. lines contents
1335+
1336+ afterPragma :: T. Text -> [T. Text ] -> Int -> Int
1337+ afterPragma name contents lineNum = lastLineWithPrefix (checkPragma name) contents lineNum
1338+
1339+ lastLineWithPrefix :: (T. Text -> Bool ) -> [T. Text ] -> Int -> Int
1340+ lastLineWithPrefix p contents lineNum = max lineNum next
1341+ where
1342+ next = maybe lineNum succ $ listToMaybe . reverse $ findIndices p contents
1343+
1344+ checkPragma :: T. Text -> T. Text -> Bool
1345+ checkPragma name = check
1346+ where
1347+ check l = isPragma l && getName l == name
1348+ getName l = T. take (T. length name) $ T. dropWhile isSpace $ T. drop 3 l
1349+ isPragma = T. isPrefixOf " {-#"
1350+
13051351-- | Construct an import declaration with at most one symbol
13061352newImport
13071353 :: T. Text -- ^ module name
0 commit comments