[cfe-dev] LibFormat usage question

David Blaikie dblaikie at gmail.com
Thu Oct 31 15:25:21 PDT 2013


On Thu, Oct 31, 2013 at 3:22 PM, Sean Silva <silvas at purdue.edu> wrote:

>
>
>
> On Thu, Oct 31, 2013 at 12:59 PM, David Blaikie <dblaikie at gmail.com>wrote:
>
>>
>>
>>
>> On Thu, Oct 31, 2013 at 6:32 AM, Jesper Eskilson <Jesper.Eskilson at iar.com
>> > wrote:
>>
>>>
>>> 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.
>>>
>>
>> It's generally advised that one should not attempt to round trip source
>> code through the AST. Use the AST to inform mutations of the original
>> source (by using source locations to identify pieces to move, insert, or
>> remove), rather than to produce new source from the parsed AST.
>>
>
> We really need to put this in an FAQ. It seems like it gets reiterated at
> least once a week.
>

Agreed.


>
> -- Sean Silva
>
>
>>
>>
>>>
>>> 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 Website: www.iar.com
>>>  Twitter: www.twitter.com/iarsystems
>>>
>>> _______________________________________________
>>> cfe-dev mailing list
>>> cfe-dev at cs.uiuc.edu
>>> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>>>
>>>
>>
>> _______________________________________________
>> cfe-dev mailing list
>> cfe-dev at cs.uiuc.edu
>> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131031/f403a582/attachment.html>


More information about the cfe-dev mailing list