File: ExtractionUtils.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (138 lines) | stat: -rw-r--r-- 4,739 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//===--- ExtractionUtils.cpp - Extraction helper functions ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "ExtractionUtils.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/SaveAndRestore.h"

using namespace clang;

std::optional<StringRef>
tooling::extract::nameForExtractedVariable(const Expr *E) {
  if (const auto *Call = dyn_cast<CallExpr>(E)) {
    if (const auto *Fn = Call->getDirectCallee())
      return Fn->getName();
  } else if (const auto *Msg = dyn_cast<ObjCMessageExpr>(E)) {
    if (const auto *M = Msg->getMethodDecl()) {
      if (M->getSelector().isUnarySelector())
        return M->getSelector().getNameForSlot(0);
    }
  } else if (const auto *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
    if (PRE->isImplicitProperty()) {
      if (const auto *M = PRE->getImplicitPropertyGetter())
        return M->getSelector().getNameForSlot(0);
    } else if (const auto *Prop = PRE->getExplicitProperty())
      return Prop->getName();
  }
  return std::nullopt;
}

namespace {

/// Checks if a set of expressions is directly contained in some AST region.
class StmtReachabilityChecker
    : public RecursiveASTVisitor<StmtReachabilityChecker> {
  const llvm::SmallPtrSetImpl<const Stmt *> &Expressions;
  unsigned Count = 0;

  StmtReachabilityChecker(
      const llvm::SmallPtrSetImpl<const Stmt *> &Expressions)
      : Expressions(Expressions) {}

  bool areAllExpressionsReached() const { return Count == Expressions.size(); }

public:
  bool VisitStmt(const Stmt *S) {
    if (Expressions.count(S)) {
      ++Count;
      if (areAllExpressionsReached())
        return false;
    }
    return true;
  }

  static bool areAllExpressionsReachableFrom(
      CompoundStmt *S, const llvm::SmallPtrSetImpl<const Stmt *> &Expressions) {
    StmtReachabilityChecker Checker(Expressions);
    Checker.TraverseStmt(S);
    return Checker.areAllExpressionsReached();
  }
};

/// Figures out where the extracted variable should go.
class ExtractedVariableInsertionLocFinder
    : public RecursiveASTVisitor<ExtractedVariableInsertionLocFinder> {
  llvm::SmallPtrSet<const Stmt *, 4> Expressions;
  llvm::SmallVector<std::pair<CompoundStmt *, const Stmt *>, 4>
      InsertionCandidateStack;
  bool IsPrevCompoundStmt = false;

public:
  SourceLocation Loc;

  /// Initializes the insertion location finder using the set of duplicate
  /// \p Expressions from one function.
  ExtractedVariableInsertionLocFinder(ArrayRef<const Expr *> Expressions) {
    for (const Expr *E : Expressions)
      this->Expressions.insert(E);
  }

  bool TraverseStmt(Stmt *S) {
    if (!S)
      return RecursiveASTVisitor::TraverseStmt(S);
    if (IsPrevCompoundStmt && !InsertionCandidateStack.empty())
      InsertionCandidateStack.back().second = S;
    llvm::SaveAndRestore<bool> IsPrevCompoundStmtTracker(IsPrevCompoundStmt,
                                                         false);
    if (auto *CS = dyn_cast<CompoundStmt>(S)) {
      IsPrevCompoundStmt = true;
      InsertionCandidateStack.emplace_back(CS, nullptr);
      RecursiveASTVisitor::TraverseStmt(S);
      InsertionCandidateStack.pop_back();
      return true;
    }
    return RecursiveASTVisitor::TraverseStmt(S);
  }

  bool VisitStmt(const Stmt *S) {
    if (Expressions.count(S)) {
      // The insertion location should be in the first compound statement that
      // includes all of the expressions as descendants as we want the new
      // variable to be visible to all uses.
      for (auto I = InsertionCandidateStack.rbegin(),
                E = InsertionCandidateStack.rend();
           I != E; ++I) {
        if (StmtReachabilityChecker::areAllExpressionsReachableFrom(
                I->first, Expressions) &&
            I->second) {
          Loc = I->second->getBeginLoc();
          break;
        }
      }
      return false;
    }
    return true;
  }
};

} // end anonymous namespace

SourceLocation tooling::extract::locationForExtractedVariableDeclaration(
    ArrayRef<const Expr *> Expressions, const Decl *ParentDecl,
    const SourceManager &SM) {
  ExtractedVariableInsertionLocFinder LocFinder(Expressions);
  LocFinder.TraverseDecl(const_cast<Decl *>(ParentDecl));
  SourceLocation Result = LocFinder.Loc;
  if (Result.isValid() && Result.isMacroID())
    return SM.getExpansionLoc(Result);
  return Result;
}