From fe61bc1a0b5a00badae9334e01e103769af4fa6c Mon Sep 17 00:00:00 2001 From: Jonathan Coe Date: Wed, 4 Mar 2020 18:09:26 +0000 Subject: [PATCH] [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 --- clang/lib/Format/TokenAnnotator.cpp | 7 ++++++- clang/unittests/Format/FormatTestCSharp.cpp | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) 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 @@ 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; } 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. }