This is an archive of the discontinued LLVM Phabricator instance.

clang-format: Add "AllowShortNamespacesOnASingleLine" option
Needs ReviewPublic

Authored by cbeck88 on Aug 7 2015, 4:04 PM.

Details

Reviewers
djasper
Summary

Rationale:

I sometimes use a different clang tool, iwyu ("include what you use"), to clean up header file inclusions in my C++ projects. Iwyu seeks to correct the includes of a header or cpp unit so that definitions which are needed are included, and definitions which only need to be forward declared are forward declared. It often generates code like this at the top of your file:

namespace foo { class bar; }
namespace baz { struct quaz; }
...

Unfortunately, clang-format dislikes braces which are arranged this way and always wants to break after them, and after the forward declaration, no matter what configuration options are used (as far as I can tell).

I wrote this small patch so that short namespaces like these can be set on a single line regardless of chosen brace-style if a boolean option "AllowShortNamespacesOnASingleLine" is enabled.

Diff Detail

Event Timeline

cbeck88 updated this revision to Diff 31554.Aug 7 2015, 4:04 PM
cbeck88 retitled this revision from to clang-format: Add "AllowShortNamespacesOnASingleLine" option.
cbeck88 updated this object.
cbeck88 added a reviewer: djasper.
cbeck88 set the repository for this revision to rL LLVM.
cbeck88 added a subscriber: cfe-commits.
djasper added inline comments.Aug 10 2015, 12:29 AM
include/clang/Format/Format.h
115

Don't use markup here. Use a \code block instead.

lib/Format/UnwrappedLineFormatter.cpp
204

No braces.

266

How is this different from tryMergeSimpleBlock, in particular, which behavior differences do you want?

unittests/Format/FormatTest.cpp
10441

Please insert a pair of quotes ("") after each '\n' and format, so that this becomes a concatenated multiline string.

What about:

namespace A { namespace B { class C; }}

I think this is what many people would use. It's fine not to fix this in this patch, but at least denote the behavior with a corresponding test.

cbeck88 updated this revision to Diff 32249.Aug 16 2015, 12:32 PM
cbeck88 removed rL LLVM as the repository for this revision.
  • Fixed formatting in header
  • Fixed handling of nested namespaces
  • Added unit tests

djasper: I thought about it, I guess I don't have a particularly good reason that the namespaces logic should be a separate function from "tryMergeSimpleBlock", and maybe it should indeed be refactored to be part of the case analysis of that function. When I began I thought this would just be simpler and make it easier to customize the namespace handling vs. other blocks, but now I'm less sure of this. At least with the way I'm now trying to handle the nested namespaces, this seems a bit simpler, but maybe that part should be changed.