12#include "clang/AST/ASTContext.h"
13#include "clang/AST/Stmt.h"
14#include "clang/Basic/LangOptions.h"
15#include "clang/Basic/SourceLocation.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Tooling/Core/Replacement.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Support/Error.h"
31class SwapIfBranches :
public Tweak {
33 const char *id() const final;
35 bool prepare(const Selection &Inputs) override;
36 Expected<Effect> apply(const Selection &Inputs) override;
37 std::
string title()
const override {
return "Swap if branches"; }
38 llvm::StringLiteral kind()
const override {
41 bool hidden()
const override {
return true; }
44 const IfStmt *If =
nullptr;
49bool SwapIfBranches::prepare(
const Selection &Inputs) {
50 for (
const SelectionTree::Node *N = Inputs.ASTSelection.commonAncestor();
51 N && !If; N = N->Parent) {
53 if (llvm::isa_and_nonnull<CompoundStmt>(N->ASTNode.get<Stmt>()))
55 If = dyn_cast_or_null<IfStmt>(N->ASTNode.get<Stmt>());
59 return If && isa_and_nonnull<CompoundStmt>(If->getThen()) &&
60 isa_and_nonnull<CompoundStmt>(If->getElse());
63Expected<Tweak::Effect> SwapIfBranches::apply(
const Selection &Inputs) {
64 auto &Ctx = Inputs.AST->getASTContext();
65 auto &SrcMgr = Inputs.AST->getSourceManager();
68 If->getThen()->getSourceRange());
70 return error(
"Could not obtain range of the 'then' branch. Macros?");
72 If->getElse()->getSourceRange());
74 return error(
"Could not obtain range of the 'else' branch. Macros?");
79 tooling::Replacements Result;
80 if (
auto Err = Result.add(tooling::Replacement(Ctx.getSourceManager(),
82 ThenCode.size(), ElseCode)))
83 return std::move(Err);
84 if (
auto Err = Result.add(tooling::Replacement(Ctx.getSourceManager(),
86 ElseCode.size(), ThenCode)))
87 return std::move(Err);
88 return Effect::mainFileEdit(SrcMgr, std::move(Result));
std::vector< const char * > Expected
#define REGISTER_TWEAK(Subclass)
std::optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const llvm::StringLiteral REFACTOR_KIND