r361119 - Added a better diagnostic when using the delete operator with lambdas

Nicolas Lesser via cfe-commits cfe-commits at lists.llvm.org
Sun May 19 08:07:58 PDT 2019


Author: rakete1111
Date: Sun May 19 08:07:58 2019
New Revision: 361119

URL: http://llvm.org/viewvc/llvm-project?rev=361119&view=rev
Log:
Added a better diagnostic when using the delete operator with lambdas

Summary:
This adds a new error for missing parentheses around lambdas in delete operators.

```
int main() {
  delete []() { return new int(); }();
}
```

This will result in:

```
test.cpp:2:3: error: '[]' after delete interpreted as 'delete[]'
  delete []() { return new int(); }();
  ^~~~~~~~~
test.cpp:2:9: note: add parentheses around the lambda
  delete []() { return new int(); }();
        ^
        (                          )
```

Reviewers: rsmith

Reviewed By: rsmith

Subscribers: riccibruno, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D36357

Modified:
    cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
    cfe/trunk/lib/Parse/ParseExprCXX.cpp
    cfe/trunk/test/FixIt/fixit-cxx0x.cpp
    cfe/trunk/test/Parser/cxx0x-lambda-expressions.cpp
    cfe/trunk/test/SemaCXX/new-delete-0x.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td?rev=361119&r1=361118&r2=361119&view=diff
==============================================================================
--- cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td Sun May 19 08:07:58 2019
@@ -109,6 +109,8 @@ def warn_cxx98_compat_alignof : Warning<
   InGroup<CXX98Compat>, DefaultIgnore;
 def ext_alignof_expr : ExtWarn<
   "%0 applied to an expression is a GNU extension">, InGroup<GNUAlignofExpression>;
+def err_lambda_after_delete : Error<
+  "'[]' after delete interpreted as 'delete[]'; add parentheses to treat this as a lambda-expression">;
 
 def warn_microsoft_dependent_exists : Warning<
   "dependent %select{__if_not_exists|__if_exists}0 declarations are ignored">,

Modified: cfe/trunk/lib/Parse/ParseExprCXX.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseExprCXX.cpp?rev=361119&r1=361118&r2=361119&view=diff
==============================================================================
--- cfe/trunk/lib/Parse/ParseExprCXX.cpp (original)
+++ cfe/trunk/lib/Parse/ParseExprCXX.cpp Sun May 19 08:07:58 2019
@@ -3034,8 +3034,58 @@ Parser::ParseCXXDeleteExpression(bool Us
     //   [Footnote: A lambda expression with a lambda-introducer that consists
     //              of empty square brackets can follow the delete keyword if
     //              the lambda expression is enclosed in parentheses.]
-    // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
-    //        lambda-introducer.
+
+    const Token Next = GetLookAheadToken(2);
+
+    // Basic lookahead to check if we have a lambda expression.
+    if (Next.isOneOf(tok::l_brace, tok::less) ||
+        (Next.is(tok::l_paren) &&
+         (GetLookAheadToken(3).is(tok::r_paren) ||
+          (GetLookAheadToken(3).is(tok::identifier) &&
+           GetLookAheadToken(4).is(tok::identifier))))) {
+      TentativeParsingAction TPA(*this);
+      SourceLocation LSquareLoc = Tok.getLocation();
+      SourceLocation RSquareLoc = NextToken().getLocation();
+
+      // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
+      // case.
+      SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
+      SourceLocation RBraceLoc;
+      bool EmitFixIt = false;
+      if (TryConsumeToken(tok::l_brace)) {
+        SkipUntil(tok::r_brace, StopBeforeMatch);
+        RBraceLoc = Tok.getLocation();
+        EmitFixIt = true;
+      }
+
+      TPA.Revert();
+
+      if (EmitFixIt)
+        Diag(Start, diag::err_lambda_after_delete)
+            << SourceRange(Start, RSquareLoc)
+            << FixItHint::CreateInsertion(LSquareLoc, "(")
+            << FixItHint::CreateInsertion(
+                   Lexer::getLocForEndOfToken(
+                       RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
+                   ")");
+      else
+        Diag(Start, diag::err_lambda_after_delete)
+            << SourceRange(Start, RSquareLoc);
+
+      // Warn that the non-capturing lambda isn't surrounded by parentheses
+      // to disambiguate it from 'delete[]'.
+      ExprResult Lambda = ParseLambdaExpression();
+      if (Lambda.isInvalid())
+        return ExprError();
+
+      // Evaluate any postfix expressions used on the lambda.
+      Lambda = ParsePostfixExpressionSuffix(Lambda);
+      if (Lambda.isInvalid())
+        return ExprError();
+      return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
+                                    Lambda.get());
+    }
+
     ArrayDelete = true;
     BalancedDelimiterTracker T(*this, tok::l_square);
 

Modified: cfe/trunk/test/FixIt/fixit-cxx0x.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/fixit-cxx0x.cpp?rev=361119&r1=361118&r2=361119&view=diff
==============================================================================
--- cfe/trunk/test/FixIt/fixit-cxx0x.cpp (original)
+++ cfe/trunk/test/FixIt/fixit-cxx0x.cpp Sun May 19 08:07:58 2019
@@ -58,6 +58,9 @@ void S2::f(int i) {
   (void)[&, i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
   (void)[] mutable { }; // expected-error{{lambda requires '()' before 'mutable'}}
   (void)[] -> int { }; // expected-error{{lambda requires '()' before return type}}
+
+  delete []() { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
+  delete [] { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
 }
 
 #define bar "bar"

Modified: cfe/trunk/test/Parser/cxx0x-lambda-expressions.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/cxx0x-lambda-expressions.cpp?rev=361119&r1=361118&r2=361119&view=diff
==============================================================================
--- cfe/trunk/test/Parser/cxx0x-lambda-expressions.cpp (original)
+++ cfe/trunk/test/Parser/cxx0x-lambda-expressions.cpp Sun May 19 08:07:58 2019
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -verify -std=c++2a %s
 
 enum E { e };
 
@@ -43,31 +44,57 @@ class C {
     int a4[1] = {[&b] = 1 }; // expected-error{{integral constant expression must have integral or unscoped enumeration type, not 'const int *'}}
     int a5[3] = { []{return 0;}() };
     int a6[1] = {[this] = 1 }; // expected-error{{integral constant expression must have integral or unscoped enumeration type, not 'C *'}}
-    int a7[1] = {[d(0)] { return d; } ()}; // expected-warning{{extension}}
-    int a8[1] = {[d = 0] { return d; } ()}; // expected-warning{{extension}}
+    int a7[1] = {[d(0)] { return d; } ()};
+    int a8[1] = {[d = 0] { return d; } ()};
+    int a10[1] = {[id(0)] { return id; } ()};
+#if __cplusplus <= 201103L
+    // expected-warning at -4{{extension}}
+    // expected-warning at -4{{extension}}
+    // expected-warning at -4{{extension}}
+#endif
     int a9[1] = {[d = 0] = 1}; // expected-error{{is not an integral constant expression}}
-    int a10[1] = {[id(0)] { return id; } ()}; // expected-warning{{extension}}
+#if __cplusplus >= 201402L
+    // expected-note at -2{{constant expression cannot modify an object that is visible outside that expression}}
+#endif
     int a11[1] = {[id(0)] = 1};
   }
 
   void delete_lambda(int *p) {
     delete [] p;
     delete [] (int*) { new int }; // ok, compound-literal, not lambda
-    delete [] { return new int; } (); // expected-error{{expected expression}}
+    delete [] { return new int; } (); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
     delete [&] { return new int; } (); // ok, lambda
+
+    delete []() { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
+    delete [](E Enum) { return new int((int)Enum); }(e); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
+#if __cplusplus > 201703L
+    delete []<int = 0>() { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
+#endif
   }
 
   // We support init-captures in C++11 as an extension.
   int z;
   void init_capture() {
-    [n(0)] () mutable -> int { return ++n; }; // expected-warning{{extension}}
-    [n{0}] { return; }; // expected-warning{{extension}}
-    [n = 0] { return ++n; }; // expected-error {{captured by copy in a non-mutable}} expected-warning{{extension}}
-    [n = {0}] { return; }; // expected-error {{<initializer_list>}} expected-warning{{extension}}
-    [a([&b = z]{})](){}; // expected-warning 2{{extension}}
+    [n(0)] () mutable -> int { return ++n; };
+    [n{0}] { return; };
+    [a([&b = z]{})](){};
+    [n = 0] { return ++n; }; // expected-error {{captured by copy in a non-mutable}}
+    [n = {0}] { return; }; // expected-error {{<initializer_list>}}
+#if __cplusplus <= 201103L
+    // expected-warning at -6{{extension}}
+    // expected-warning at -6{{extension}}
+    // expected-warning at -6{{extension}}
+    // expected-warning at -7{{extension}}
+    // expected-warning at -7{{extension}}
+    // expected-warning at -7{{extension}}
+#endif
 
     int x = 4;
-    auto y = [&r = x, x = x + 1]() -> int { // expected-warning 2{{extension}}
+    auto y = [&r = x, x = x + 1]() -> int {
+#if __cplusplus <= 201103L
+      // expected-warning at -2{{extension}}
+      // expected-warning at -3{{extension}}
+#endif
       r += 2;
       return x + 2;
     } ();

Modified: cfe/trunk/test/SemaCXX/new-delete-0x.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/new-delete-0x.cpp?rev=361119&r1=361118&r2=361119&view=diff
==============================================================================
--- cfe/trunk/test/SemaCXX/new-delete-0x.cpp (original)
+++ cfe/trunk/test/SemaCXX/new-delete-0x.cpp Sun May 19 08:07:58 2019
@@ -34,6 +34,5 @@ void good_deletes()
 void bad_deletes()
 {
   // 'delete []' is always array delete, per [expr.delete]p1.
-  // FIXME: Give a better diagnostic.
-  delete []{ return (int*)0; }(); // expected-error {{expected expression}}
+  delete []{ return (int*)0; }(); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
 }




More information about the cfe-commits mailing list