[clang-format] Disallow templates to be followed by literal
authorEmilia Dreamer <emilia@rymiel.space>
Fri, 27 Jan 2023 01:56:11 +0000 (03:56 +0200)
committerEmilia Dreamer <emilia@rymiel.space>
Fri, 27 Jan 2023 02:01:11 +0000 (04:01 +0200)
There should not be any cases where the angle brackets of template
parameters are directly followed by a literal. It is more likely that a
comparison is taking place instead.

This patch makes the TokenAnnotator prefer to annotate < and > as
operators when directly followed by a literal. A similar check already
exists for literals directly *before* potential template args.

Fixes https://github.com/llvm/llvm-project/issues/60140

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D142139

clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

index 49c30ca78debf90dd214f8e172111643b4b22494..1b1123fa36456865211af0d514f9b8ec554ea8b5 100644 (file)
@@ -185,6 +185,8 @@ private:
         } else {
           CurrentToken->setType(TT_TemplateCloser);
         }
+        if (CurrentToken->Next && CurrentToken->Next->Tok.isLiteral())
+          return false;
         next();
         return true;
       }
index 6530e2005e4c4bcfdc130db79f024407ed2387de..1d71bc909e8c6d145a27dff0c757bc6583a78d7f 100644 (file)
@@ -10365,6 +10365,7 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) {
 
   // Not template parameters.
   verifyFormat("return a < b && c > d;");
+  verifyFormat("a < 0 ? b : a > 0 ? c : d;");
   verifyFormat("void f() {\n"
                "  while (a < b && c > d) {\n"
                "  }\n"