Index: clang/lib/Format/TokenAnnotator.cpp =================================================================== --- clang/lib/Format/TokenAnnotator.cpp +++ clang/lib/Format/TokenAnnotator.cpp @@ -1312,11 +1312,34 @@ if (Style.isCSharp()) { // `Type?)`, `Type?>`, `Type? name;` and `Type? name =` can only be // nullable types. + + // `Type?)`, `Type?>`, `Type? name;` + if (Tok->Next && + (Tok->Next->startsSequence(tok::question, tok::r_paren) || + Tok->Next->startsSequence(tok::question, tok::greater) || + Tok->Next->startsSequence(tok::question, tok::identifier, + tok::semi))) { + Tok->setType(TT_CSharpNullable); + break; + } + + // `Type? name =` + if (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next && + Tok->Next->Next->is(tok::equal)) { + Tok->setType(TT_CSharpNullable); + break; + } + // Line.MustBeDeclaration will be true for `Type? name;`. - if ((!Contexts.back().IsExpression && Line.MustBeDeclaration) || - (Tok->Next && Tok->Next->isOneOf(tok::r_paren, tok::greater)) || - (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next && - Tok->Next->Next->is(tok::equal))) { + // But not + // cond ? "A" : "B"; + // cond ? id : "B"; + // cond ? cond2 ? "A" : "B" : "C"; + if (!Contexts.back().IsExpression && Line.MustBeDeclaration && + (!Tok->Next || + !Tok->Next->isOneOf(tok::identifier, tok::string_literal) || + !Tok->Next->Next || + !Tok->Next->Next->isOneOf(tok::colon, tok::question))) { Tok->setType(TT_CSharpNullable); break; } Index: clang/unittests/Format/TokenAnnotatorTest.cpp =================================================================== --- clang/unittests/Format/TokenAnnotatorTest.cpp +++ clang/unittests/Format/TokenAnnotatorTest.cpp @@ -1724,6 +1724,34 @@ EXPECT_TOKEN(Tokens[8], tok::l_paren, TT_ConditionLParen); } +TEST_F(TokenAnnotatorTest, CSharpNullableTypes) { + FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); + + auto Tokens = annotate("int? a;\n", Style); + EXPECT_EQ(Tokens.size(), 5u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::question, TT_CSharpNullable); + + Tokens = annotate("int? a = 1;\n", Style); + EXPECT_EQ(Tokens.size(), 7u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::question, TT_CSharpNullable); + + Tokens = annotate("int?)\n", Style); + EXPECT_EQ(Tokens.size(), 4u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::question, TT_CSharpNullable); + + Tokens = annotate("int?>\n", Style); + EXPECT_EQ(Tokens.size(), 4u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::question, TT_CSharpNullable); + + Tokens = annotate("cond? id : id2\n", Style); + EXPECT_EQ(Tokens.size(), 6u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::question, TT_ConditionalExpr); + + Tokens = annotate("cond ? cond2 ? : id1 : id2\n", Style); + EXPECT_EQ(Tokens.size(), 9u) << Tokens; + EXPECT_TOKEN(Tokens[1], tok::question, TT_ConditionalExpr); +} + } // namespace } // namespace format } // namespace clang