Skip to content

Commit bd65f74

Browse files
committed
[Diagnostics] Add fix-its to suggest explicit raw representable initialization
This makes logic in `ContextualFailure::tryRawRepresentableFixIts` partially obsolete.
1 parent 959c6d5 commit bd65f74

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

lib/Sema/CSDiagnostics.cpp

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6410,9 +6410,50 @@ bool MissingRawRepresentativeInitFailure::diagnoseAsError() {
64106410

64116411
if (auto *E = getAsExpr(getAnchor())) {
64126412
auto range = E->getSourceRange();
6413-
diagnostic
6414-
.fixItInsert(range.Start, RawReprType->getString() + "(rawValue: ")
6415-
.fixItInsertAfter(range.End, ") ?? <#default value#>");
6413+
auto rawReprObjType = RawReprType->getOptionalObjectType();
6414+
auto valueObjType = ValueType->getOptionalObjectType();
6415+
6416+
if (rawReprObjType && valueObjType) {
6417+
std::string mapCodeFix;
6418+
6419+
// Check whether expression has been be wrapped in parens first.
6420+
if (!E->canAppendPostfixExpression()) {
6421+
diagnostic.fixItInsert(range.Start, "(");
6422+
mapCodeFix += ")";
6423+
}
6424+
6425+
mapCodeFix += ".map { ";
6426+
mapCodeFix += rawReprObjType->getString();
6427+
mapCodeFix += "(rawValue: $0) }";
6428+
6429+
diagnostic.fixItInsertAfter(range.End, mapCodeFix);
6430+
} else if (rawReprObjType) {
6431+
diagnostic
6432+
.fixItInsert(range.Start, rawReprObjType->getString() + "(rawValue: ")
6433+
.fixItInsertAfter(range.End, ")");
6434+
} else if (valueObjType) {
6435+
diagnostic.flush();
6436+
6437+
std::string fixItBefore = RawReprType->getString() + "(rawValue: ";
6438+
std::string fixItAfter;
6439+
6440+
if (!E->canAppendPostfixExpression(true)) {
6441+
fixItBefore += "(";
6442+
fixItAfter += ")";
6443+
}
6444+
6445+
fixItAfter += "!) ?? <#default value#>";
6446+
6447+
emitDiagnostic(diag::construct_raw_representable_from_unwrapped_value,
6448+
RawReprType, valueObjType)
6449+
.highlight(range)
6450+
.fixItInsert(range.Start, fixItBefore)
6451+
.fixItInsertAfter(range.End, fixItAfter);
6452+
} else {
6453+
diagnostic
6454+
.fixItInsert(range.Start, RawReprType->getString() + "(rawValue: ")
6455+
.fixItInsertAfter(range.End, ") ?? <#default value#>");
6456+
}
64166457
}
64176458

64186459
return true;

0 commit comments

Comments
 (0)