[clang] clang-format: Add "AllowShortNamespacesOnASingleLine" option (PR #105597)

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Sun Sep 22 17:59:22 PDT 2024


================
@@ -616,6 +626,62 @@ class LineJoiner {
     return 1;
   }
 
+  unsigned tryMergeNamespace(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
+                             SmallVectorImpl<AnnotatedLine *>::const_iterator E,
+                             unsigned Limit) {
+    if (Limit == 0)
+      return 0;
+    if (I[1]->InPPDirective != (*I)->InPPDirective ||
+        (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
+      return 0;
+    }
+    if (I + 2 == E || I[2]->Type == LT_Invalid)
+      return 0;
+
+    Limit = limitConsideringMacros(I + 1, E, Limit);
+
+    if (!nextTwoLinesFitInto(I, Limit))
+      return 0;
+
+    // Check if it's a namespace inside a namespace, and call recursively if so
+    // '3' is the sizes of the whitespace and closing brace for " _inner_ }".
+    if (I[1]->First->is(tok::kw_namespace)) {
+      if (I[1]->Last->is(TT_LineComment))
+        return 0;
+
+      const unsigned InnerLimit = Limit - I[1]->Last->TotalLength - 3;
+      const unsigned MergedLines = tryMergeNamespace(I + 1, E, InnerLimit);
+      if (!MergedLines)
+        return 0;
+      // Check if there is even a line after the inner result.
+      if (std::distance(I, E) <= MergedLines + 2)
+        return 0;
+      // Check that the line after the inner result starts with a closing brace
+      // which we are permitted to merge into one line.
+      if (I[2 + MergedLines]->First->is(tok::r_brace) &&
+          !I[2 + MergedLines]->First->MustBreakBefore &&
+          !I[1 + MergedLines]->Last->is(TT_LineComment) &&
+          nextNLinesFitInto(I, I + 2 + MergedLines + 1, Limit)) {
+        return 2 + MergedLines;
----------------
owenca wrote:

```suggestion
      if (I[N]->First->is(tok::r_brace) &&
          !I[N]->First->MustBreakBefore &&
          I[MergedLines + 1]->Last->isNot(tok::comment) &&
          nextNLinesFitInto(I, I + N + 1, Limit)) {
        return N;
```

https://github.com/llvm/llvm-project/pull/105597


More information about the cfe-commits mailing list