Skip to content

Commit fe61bc1

Browse files
author
Jonathan Coe
committed
[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
1 parent 133db44 commit fe61bc1

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

clang/lib/Format/TokenAnnotator.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1011,7 +1011,12 @@ class AnnotatingParser {
10111011
Style.Language == FormatStyle::LK_JavaScript)
10121012
break;
10131013
if (Style.isCSharp()) {
1014-
if (Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1014+
// `Type? name;` and `Type? name =` can only be nullable types.
1015+
// Line.MustBeDeclaration will be true for `Type? name;`.
1016+
if (!Contexts.back().IsExpression &&
1017+
(Line.MustBeDeclaration ||
1018+
(Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
1019+
Tok->Next->Next->is(tok::equal)))) {
10151020
Tok->Type = TT_CSharpNullable;
10161021
break;
10171022
}

clang/unittests/Format/FormatTestCSharp.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,17 @@ TEST_F(FormatTestCSharp, CSharpNullableTypes) {
631631
FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
632632
Style.SpacesInSquareBrackets = false;
633633

634+
verifyFormat(R"(//
635+
public class A {
636+
void foo() { int? value = some.bar(); }
637+
})",
638+
Style); // int? is nullable not a conditional expression.
639+
640+
verifyFormat(R"(void foo(int? x, int? y, int? z) {})",
641+
Style); // Nullables in function definitions.
642+
634643
verifyFormat(R"(public float? Value;)", Style); // no space before `?`.
644+
635645
verifyFormat(R"(int?[] arr = new int?[10];)",
636646
Style); // An array of a nullable type.
637647
}

0 commit comments

Comments
 (0)