Author: Jonathan Coe
Date: 2020-03-04T18:10:27Z
New Revision: fe61bc1a0b5a00badae9334e01e103769af4fa6c

URL: 
https://github.com/llvm/llvm-project/commit/fe61bc1a0b5a00badae9334e01e103769af4fa6c
DIFF: 
https://github.com/llvm/llvm-project/commit/fe61bc1a0b5a00badae9334e01e103769af4fa6c.diff

LOG: [clang-format] Improve identification of C# nullables

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

Added: 
    

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

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 493454eb2239..e491de85babd 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1011,7 +1011,12 @@ class AnnotatingParser {
           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;
         }

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 3f14de9b75da..7e60fdbdba26 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -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.
 }


        
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to