Skip to content

Reject bad string interpolations #17074

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -1226,6 +1226,16 @@ ERROR(expected_type_after_as,none,
ERROR(string_interpolation_extra,none,
"extra tokens after interpolated string expression", ())

// Interpolated value accidentally forms a tuple.
ERROR(string_interpolation_single_expr,none,
"interpolations should be a single expression", ())
NOTE(string_interpolation_form_tuple,none,
"insert parentheses to form a tuple", ())
NOTE(string_interpolation_delete_empty,none,
"delete empty interpolation", ())
ERROR(string_interpolation_keyword_argument,PointsToFirstBadToken,
"interpolations cannot start with a keyword argument", ())

// Keypath expressions.
ERROR(expr_keypath_expected_lparen,PointsToFirstBadToken,
"expected '(' following '#keyPath'", ())
Expand Down
44 changes: 44 additions & 0 deletions lib/Parse/ParseExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1927,6 +1927,50 @@ parseStringSegments(SmallVectorImpl<Lexer::StringSegment> &Segments,
Status |= E;
if (E.isNonNull()) {
Exprs.push_back(E.get());

if (auto tuple = dyn_cast<TupleExpr>(Exprs.back())) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the expression ever not a TupleExpr? Maybe use cast<> here instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The expression actually should be a ParenExpr. I don’t know of a reason it should be a TupleExpr without one of the nested conditions being true, but if it ever was, as far as I know it would be valid.

// If parseExprList() returns a TupleExpr instead of a ParenExpr,
// the interpolation must have had an argument label, or the wrong
// number of elements, or both. Reject these.
if (tuple->getNumElements() > 1) {
SourceLoc StartLoc = tuple->getStartLoc();
SourceLoc SecondExprLoc = tuple->getElement(1)->getStartLoc();
SourceLoc EndLoc = tuple->getEndLoc();

diagnose(SecondExprLoc, diag::string_interpolation_single_expr);
diagnose(StartLoc, diag::string_interpolation_form_tuple)
.fixItInsert(StartLoc, "(")
.fixItInsertAfter(EndLoc, ")");

Exprs.back() =
new (Context) ParenExpr(SourceLoc(), tuple, SourceLoc(),
/*hasTrailingClosure=*/false);
} else if (tuple->getNumElements() == 1 &&
!tuple->getElementName(0).empty()) {
SourceLoc NameStart = tuple->getElementNameLoc(0);
SourceLoc ArgStart = tuple->getElement(0)->getStartLoc();

diagnose(NameStart, diag::string_interpolation_keyword_argument)
.fixItRemoveChars(NameStart, ArgStart);

Exprs.back() =
new (Context) ParenExpr(tuple->getLParenLoc(), tuple->getElement(0),
tuple->getRParenLoc(), /*hasTrailingClosure=*/false);
} else if (tuple->getNumElements() == 0 && !Status.isError()) {
SourceLoc StartLoc = tuple->getStartLoc();
SourceLoc EndLoc = tuple->getEndLoc();
SourceLoc SlashLoc = StartLoc.getAdvancedLocOrInvalid(-1);

diagnose(EndLoc, diag::string_interpolation_single_expr);
diagnose(SlashLoc, diag::string_interpolation_delete_empty)
.fixItRemoveChars(SlashLoc, EndLoc.getAdvancedLocOrInvalid(1));

auto Error = new (Context) ErrorExpr(SourceRange(EndLoc, EndLoc));
Exprs.back() =
new (Context) ParenExpr(SourceLoc(), Error, SourceLoc(),
/*hasTrailingClosure=*/false);
}
}

if (!Tok.is(tok::eof)) {
diagnose(Tok, diag::string_interpolation_extra);
Expand Down
10 changes: 9 additions & 1 deletion lib/Parse/Parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,10 @@ ParserStatus
Parser::parseList(tok RightK, SourceLoc LeftLoc, SourceLoc &RightLoc,
bool AllowSepAfterLast, Diag<> ErrorDiag, SyntaxKind Kind,
llvm::function_ref<ParserStatus()> callback) {
auto TokIsStringInterpolationEOF = [&]() -> bool {
return Tok.is(tok::eof) && Tok.getText() == ")" && RightK == tok::r_paren;
};

llvm::Optional<SyntaxParsingContext> ListContext;
ListContext.emplace(SyntaxContext, Kind);
if (Kind == SyntaxKind::Unknown)
Expand All @@ -914,6 +918,10 @@ Parser::parseList(tok RightK, SourceLoc LeftLoc, SourceLoc &RightLoc,
RightLoc = consumeToken(RightK);
return makeParserSuccess();
}
if (TokIsStringInterpolationEOF()) {
RightLoc = Tok.getLoc();
return makeParserSuccess();
}

ParserStatus Status;
while (true) {
Expand All @@ -933,7 +941,7 @@ Parser::parseList(tok RightK, SourceLoc LeftLoc, SourceLoc &RightLoc,
// If the lexer stopped with an EOF token whose spelling is ")", then this
// is actually the tuple that is a string literal interpolation context.
// Just accept the ")" and build the tuple as we usually do.
if (Tok.is(tok::eof) && Tok.getText() == ")" && RightK == tok::r_paren) {
if (TokIsStringInterpolationEOF()) {
RightLoc = Tok.getLoc();
return Status;
}
Expand Down
26 changes: 26 additions & 0 deletions test/Parse/interpolation_tuple_errors.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// RUN: %target-typecheck-verify-swift

let str = "a"

// Test with too many interpolated values.
func papaBear() {
_ = "\(str, str)" // expected-error{{interpolations should be a single expression}} expected-note {{insert parentheses to form a tuple}} {{9-9=(}} {{19-19=)}}
}

// Test with too few interpolated values.
func mamaBear() {
_ = "\()" // expected-error{{interpolations should be a single expression}} expected-note {{delete empty interpolation}} {{8-11=}}
}

// Test with the correct number of interpolated values.
func babyBear() {
_ = "\(str)"
}

// Test with an argument label
func funkyBear() {
_ = "\(describing: str)" // expected-error{{interpolations cannot start with a keyword argument}} {{10-22=}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A suggestion: Try another String initializer or two.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

_ = "\(format: str)" // expected-error{{interpolations cannot start with a keyword argument}} {{10-18=}}
_ = "\(validatingUTF8: str)" // expected-error{{interpolations cannot start with a keyword argument}} {{10-26=}}
_ = "\(fnord: str)" // expected-error{{interpolations cannot start with a keyword argument}} {{10-17=}}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// RUN: not --crash %target-swift-frontend %s -emit-ir
// RUN: not %target-swift-frontend %s -emit-ir

func foo<U>(_ x: U?) {
_ = "\(anyLabelHere: x)"
Expand Down