LibFormat usage question

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 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.
}

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.

Ok, so how do I do that? I'm afraid that I'm too new to Clang to understand how things fit together here.

/Jesper

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.

-- Sean Silva

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.