Skip to content

Commit

Permalink
[clang-format] Improve identification of C# nullables
Browse files Browse the repository at this point in the history
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
  • Loading branch information
jbcoe committed Mar 4, 2020
1 parent 133db44 commit fe61bc1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
7 changes: 6 additions & 1 deletion clang/lib/Format/TokenAnnotator.cpp
Expand Up @@ -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;
}
Expand Down
10 changes: 10 additions & 0 deletions clang/unittests/Format/FormatTestCSharp.cpp
Expand Up @@ -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.
}
Expand Down

0 comments on commit fe61bc1

Please sign in to comment.