[cfe-dev] LibFormat usage question

Jesper Eskilson Jesper.Eskilson at iar.com
Thu Oct 31 06:32:00 PDT 2013


Hi,

I'm trying to figure out how to programmatically invoke clang-format to 
format code. I would like to get from a declaration ("Decl *") to a 
plain string containing the reformatted source code.

Here's my feeble initial attempt:


/*
  * Non-functioning attempt att trying to extract the source code of
  * 'decl' formatted using LLVM style.
  */
std::string get_formatted_source(SourceManager &mgr, const Decl *decl)
{
   StringRef code = get_source(mgr, decl); // implemented elsewhere
   std::vector<Range> ranges;
   LangOptions lo;
   Rewriter rw(mgr, lo);

   Range range(0, src.size());
   ranges.push_back(range);

   // Do the reformat
   auto repl = reformat(getLLVMStyle(), code, ranges);

   // Apply the replacements
   for (auto it = repl.begin(); it != repl.end(); ++it) {
     it->apply(rw);
   }

   // Extract the reformatted source code.
   auto formatted_source = rw.getRewrittenText(decl->getSourceRange());

   // I would have expected 'formatted_source' to be the formatted source
   // here, but it is always the same as the original, as if the
   // replacements where never applied.
}


-- 
*Jesper Eskilson* /Development Engineer/
IAR Systems AB
Box 23051, Strandbodgatan 1
SE-750 23 Uppsala, SWEDEN
E-mail: jesper.eskilson at iar.com <mailto:jesper.eskilson at iar.com> 
Website: www.iar.com
<http://www.iar.com> Twitter: www.twitter.com/iarsystems 
<http://www.twitter.com/iarsystems>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131031/46d78d2e/attachment.html>


More information about the cfe-dev mailing list