Skip to content

Commit 873523b

Browse files
author
Ondrej Sebek
committed
Avoid extra parens for wildcard type signature
+ avoid parens in simple cases (a, Char, [a], (),...) - change one test - (Int)/Int
1 parent 30b3fec commit 873523b

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

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

+15-7
Original file line numberDiff line numberDiff line change
@@ -1529,14 +1529,22 @@ mkRenameEdit contents range name =
15291529
curr <- textInRange range <$> contents
15301530
pure $ "`" `T.isPrefixOf` curr && "`" `T.isSuffixOf` curr
15311531

1532+
1533+
-- | Extract the type and surround it in parentheses except in obviously safe cases.
1534+
--
1535+
-- Inferring when parentheses are actually needed around the type signature would
1536+
-- require understanding both the precedence of the context of the hole and of
1537+
-- the signature itself. Inserting them (almost) unconditionally is ugly but safe.
15321538
extractWildCardTypeSignature :: T.Text -> T.Text
1533-
extractWildCardTypeSignature =
1534-
-- inferring when parens are actually needed around the type signature would
1535-
-- require understanding both the precedence of the context of the _ and of
1536-
-- the signature itself. Inserting them unconditionally is ugly but safe.
1537-
("(" `T.append`) . (`T.append` ")") .
1538-
T.takeWhile (/='') . T.dropWhile (=='') . T.dropWhile (/='') .
1539-
snd . T.breakOnEnd "standing for "
1539+
extractWildCardTypeSignature msg = (if enclosed || not application then id else bracket) signature
1540+
where
1541+
msgSigPart = snd $ T.breakOnEnd "standing for " msg
1542+
signature = T.takeWhile (/='') . T.dropWhile (=='') . T.dropWhile (/='') $ msgSigPart
1543+
-- parenthesize type applications, e.g. (Maybe Char)
1544+
application = any isSpace . T.unpack $ signature
1545+
-- do not add extra parentheses to lists, tuples and already parenthesized types
1546+
enclosed = not (T.null signature) && (T.head signature, T.last signature) `elem` [('(',')'), ('[',']')]
1547+
bracket = ("(" `T.append`) . (`T.append` ")")
15401548

15411549
extractRenamableTerms :: T.Text -> [T.Text]
15421550
extractRenamableTerms msg

ghcide/test/exe/Main.hs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1249,7 +1249,7 @@ typeWildCardActionTests = testGroup "type wildcard actions"
12491249
[ "module Testing where"
12501250
, "func :: Int -> Int"
12511251
, "func x ="
1252-
, " let y :: (Int)"
1252+
, " let y :: Int"
12531253
, " y = x * 2"
12541254
, " in y"
12551255
]

0 commit comments

Comments
 (0)