clang 20.0.0git
USRLocFinder.cpp
Go to the documentation of this file.
1//===--- USRLocFinder.cpp - Clang refactoring library ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Methods for finding all instances of a USR. Our strategy is very
11/// simple; we just compare the USR at every relevant AST node with the one
12/// provided.
13///
14//===----------------------------------------------------------------------===//
15
20#include "clang/Basic/LLVM.h"
23#include "clang/Lex/Lexer.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/Support/Casting.h"
30#include <cstddef>
31#include <set>
32#include <string>
33#include <vector>
34
35using namespace llvm;
36
37namespace clang {
38namespace tooling {
39
40namespace {
41
42// Returns true if the given Loc is valid for edit. We don't edit the
43// SourceLocations that are valid or in temporary buffer.
44bool IsValidEditLoc(const clang::SourceManager& SM, clang::SourceLocation Loc) {
45 if (Loc.isInvalid())
46 return false;
47 const clang::FullSourceLoc FullLoc(Loc, SM);
48 std::pair<clang::FileID, unsigned> FileIdAndOffset =
49 FullLoc.getSpellingLoc().getDecomposedLoc();
50 return SM.getFileEntryForID(FileIdAndOffset.first) != nullptr;
51}
52
53// This visitor recursively searches for all instances of a USR in a
54// translation unit and stores them for later usage.
55class USRLocFindingASTVisitor
56 : public RecursiveSymbolVisitor<USRLocFindingASTVisitor> {
57public:
58 explicit USRLocFindingASTVisitor(const std::vector<std::string> &USRs,
59 StringRef PrevName,
60 const ASTContext &Context)
61 : RecursiveSymbolVisitor(Context.getSourceManager(),
62 Context.getLangOpts()),
63 USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) {
64 }
65
66 bool visitSymbolOccurrence(const NamedDecl *ND,
67 ArrayRef<SourceRange> NameRanges) {
68 if (USRSet.find(getUSRForDecl(ND)) != USRSet.end()) {
69 assert(NameRanges.size() == 1 &&
70 "Multiple name pieces are not supported yet!");
71 SourceLocation