[clang-format] Improve identification of C# nullables
authorJonathan Coe <jbcoe@google.com>
Wed, 4 Mar 2020 18:09:26 +0000 (18:09 +0000)
committerJonathan Coe <jbcoe@google.com>
Wed, 4 Mar 2020 18:10:27 +0000 (18:10 +0000)
Summary: Consider `? identifier =` and `? identifier;` to be nullable within function bodies.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits, MyDeveloperDay

Tags: #clang-format, #clang

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

clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

index 493454e..e491de8 100644 (file)
@@ -1011,7 +1011,12 @@ private:
           Style.Language == FormatStyle::LK_JavaScript)
         break;
       if (Style.isCSharp()) {
-        if (Line.MustBeDeclaration && !Contexts.back().IsExpression) {
+        // `Type? name;` and `Type? name =` can only be nullable types.
+        // Line.MustBeDeclaration will be true for `Type? name;`.
+        if (!Contexts.back().IsExpression &&
+            (Line.MustBeDeclaration ||
+             (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
+              Tok->Next->Next->is(tok::equal)))) {
           Tok->Type = TT_CSharpNullable;
           break;
         }
index 3f14de9..7e60fdb 100644 (file)
@@ -631,7 +631,17 @@ TEST_F(FormatTestCSharp, CSharpNullableTypes) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
   Style.SpacesInSquareBrackets = false;
 
+  verifyFormat(R"(//
+public class A {
+  void foo() { int? value = some.bar(); }
+})",
+               Style); // int? is nullable not a conditional expression.
+
+  verifyFormat(R"(void foo(int? x, int? y, int? z) {})",
+               Style); // Nullables in function definitions.
+
   verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
+
   verifyFormat(R"(int?[] arr = new int?[10];)",
                Style); // An array of a nullable type.
 }