[Diag] Make fixItReplace slightly smart

When replace something with a punctuator, we often prefer adding spaces around it.
For instance,

   func foo(): bar {}
   // fix it
   func foo() -> bar {}

In this case we want to add a space before '->', but not after that.

With this change, we can simply `fixItReplace(ColonLoc, " -> ")`.
`fixItReplace()` automatically adjust the spaces around it.
This commit is contained in:
Rintaro Ishizaki
2016-07-21 01:14:01 +09:00
parent 35f3f7169b
commit ba982bc01c
6 changed files with 45 additions and 26 deletions

View File

@@ -696,7 +696,7 @@ Parser::parseFunctionSignature(Identifier SimpleName,
if (!consumeIf(tok::arrow, arrowLoc)) {
// FixIt ':' to '->'.
diagnose(Tok, diag::func_decl_expected_arrow)
.fixItReplace(SourceRange(Tok.getLoc()), "->");
.fixItReplace(Tok.getLoc(), " -> ");
arrowLoc = consumeToken(tok::colon);
}
@@ -787,12 +787,10 @@ ParserResult<Pattern> Parser::parseTypedPattern() {
// Now parse an optional type annotation.
if (Tok.is(tok::colon)) {
SourceLoc pastEndOfPrevLoc = getEndOfPreviousLoc();
SourceLoc colonLoc = consumeToken(tok::colon);
SourceLoc startOfNextLoc = Tok.getLoc();
if (result.isNull()) // Recover by creating AnyPattern.
result = makeParserErrorResult(new (Context) AnyPattern(PreviousLoc));
result = makeParserErrorResult(new (Context) AnyPattern(colonLoc));
ParserResult<TypeRepr> Ty = parseType();
if (Ty.hasCodeCompletion())
@@ -824,19 +822,10 @@ ParserResult<Pattern> Parser::parseTypedPattern() {
if (status.isSuccess()) {
backtrack.cancelBacktrack();
// Suggest replacing ':' with '=' (ensuring proper whitespace).
bool needSpaceBefore = (pastEndOfPrevLoc == colonLoc);
bool needSpaceAfter =
SourceMgr.getByteDistance(colonLoc, startOfNextLoc) <= 1;
StringRef replacement = " = ";
if (!needSpaceBefore) replacement = replacement.drop_front();
if (!needSpaceAfter) replacement = replacement.drop_back();
// Suggest replacing ':' with '='
diagnose(lParenLoc, diag::initializer_as_typed_pattern)
.highlight({Ty.get()->getStartLoc(), rParenLoc})
.fixItReplace(colonLoc, replacement);
.fixItReplace(colonLoc, " = ");
result.setIsParseError();
}
}