[cfe-dev] Extending clang-format

Andrew Hankins via cfe-dev cfe-dev at lists.llvm.org
Fri Oct 30 18:23:18 PDT 2015


Hi all,

First post.

I've found clang-format to be a very powerful and useful tool and I'd like
to start extending it to support some other formatting styles that I have
to work with. The two changes I'd like to start with are to namespaces and
function parameters.
For namespaces I'd like create a configuration parameter that would allow
nested namespaces all on one line.

Rather than

namespace a {
namespace b {
namespace c{
}
}
};

Support

namespace a { namespace b { namespace c {
}}};

and for functions rather than

int foo(int param1,
          int param2)
{
}

Support

int foo
(
    int param1,
    int pararm2
)
{
}


I've started to poke around in the clang lib/Format code but I'm finding it
difficult to figure out where the best place to make the changes is and
there isn't much documentation on the clang-format design/code I can find.
I think the rough idea in clang-format is to use the UnwrappedLineParser to
separate the code into the appropriate lines, then using the
UnwrappedLineFormatter annotate the tokens, merge lines where possible and
delete unnecessary lines then finally dump it all.

Taking my namespace change for example I've made modifications to the
UnwrappedLineParser::parseBlock so it won't always add a newline from
parseNamespace

-----------------------------------------------------
@@ -399,7 +399,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool
ExpectClassBody) {
 }

 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
-                                     bool MunchSemi) {
+                                     bool MunchSemi, bool AddLine) {
   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
          "'{' or macro block token expected");
   const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
@@ -410,7 +410,7 @@ void UnwrappedLineParser::parseBlock(bool
MustBeDeclaration, bool AddLevel,
   if (MacroBlock && FormatTok->is(tok::l_paren))
     parseParens();

-  addUnwrappedLine();
+  if (AddLine) addUnwrappedLine();

   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
                                           MustBeDeclaration);
---------------------------------

and this works somewhat but the namespaces are now missing whitespaces and
you get

namespace a{namespace b{namespace c{
}
}
}

So instead should I write a line merger for namespaces? Or should I find a
way to update the insert whitespace before/after flag?

I guess I'm just looking for some guidance on how to best approach this
kind of work or to be pointed in the direction of more doco.

Thanks in advance,

Andrew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20151031/8d619c9e/attachment.html>


More information about the cfe-dev mailing list