This is an archive of the discontinued LLVM Phabricator instance.

[Tooling] Avoid boilerplate in common cases
Needs ReviewPublic

Authored by sammccall on Jul 15 2023, 2:36 AM.

Details

Reviewers
hokein
usaxena95
Summary

The tooling APIs have a lot of extension points for customization:
e.g. Executor, FrontendActionFactory, FrontendAction, ASTConsumer.
This customization is often not needed, and makes the APIs unergonomic.

This change introduces some shortcuts to bypass them, while attempting
not to add more concepts/complexity to the APIs.

main() entrypoint

Today tools are expected to create an executor (which can fail), then
use it to execute their action (which can report errors).
Errors are reported with llvm::Error, which is not what main() needs
(exit codes) but must be handled.

This patch adds executeFromCommandLineArgs(), which wraps this in a
single function which returns an exit code.

(It also tweaks ToolExecutor's execute() API to avoid replicating several
overloads here).

Skipping over FrontendAction to ASTConsumer

Tools that override ASTConsumer must provide two factory indirections:

FrontendActionFactory -> FrontendAction -> ASTConsumer.

These are sometimes meaningful, but often not.
newFrontendActionFactory<ActionT>() already lets you skip the first.

Now newFrontendActionFactory<ConsumerT>() lets you skip the second, too.

Implementing simple actions as lambdas

A large fraction of tools simply want to consume the final AST and do
something with it. Even ASTConsumer is too heavyweight an abstraction.

This patch adds consumeASTs(), which is a FrontendActionFactory that
calls a function once for each parsed AST:

Exec->execute(consumeASTs([&](ASTContext &Ctx) {
  ... process AST ...
}));

Bonus: through lambda captures, state can be easily shared across TUs.
(This otherwise tends to require plumbing, or use of global variables)

Diff Detail

Event Timeline

sammccall created this revision.Jul 15 2023, 2:36 AM
Herald added a project: Restricted Project. · View Herald TranscriptJul 15 2023, 2:36 AM
sammccall requested review of this revision.Jul 15 2023, 2:36 AM
Herald added a project: Restricted Project. · View Herald TranscriptJul 15 2023, 2:36 AM
Herald added a subscriber: cfe-commits. · View Herald Transcript
sammccall updated this revision to Diff 540656.Jul 15 2023, 2:38 AM
sammccall edited the summary of this revision. (Show Details)

update description

sammccall updated this revision to Diff 540657.Jul 15 2023, 2:41 AM

tweak comment, remove unused overload

sammccall updated this revision to Diff 540659.Jul 15 2023, 2:43 AM

squash commits

sammccall added a comment.EditedJul 20 2023, 12:40 AM

Example of using conusmeASTs + executeFromCommandLine: https://github.com/sam-mccall/crubit/commit/37295cfeb67be7154e2ec87c8a2c27c860b59049

(It's not that many extra lines of code, but they're not really easy ones to write, and to work out whether they're minimal/correct)