blob: 5b6ebb4138a33851485022d19e7518e60ebdbdf0 [file] [log] [blame]
Avi Drissmandfd880852022-09-15 20:11:091// Copyright 2018 The Chromium Authors
Daniel Cheng657bf202018-04-26 21:50:022// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "Util.h"
6
7#include "clang/AST/Decl.h"
Xianzhu Wang86b11462022-09-24 22:00:128#include "clang/Basic/SourceManager.h"
Daniel Cheng657bf202018-04-26 21:50:029#include "llvm/Support/Casting.h"
10#include "llvm/Support/raw_ostream.h"
11
12namespace {
13
14std::string GetNamespaceImpl(const clang::DeclContext* context,
15 const std::string& candidate) {
16 switch (context->getDeclKind()) {
17 case clang::Decl::TranslationUnit: {
18 return candidate;
19 }
20 case clang::Decl::Namespace: {
21 const auto* decl = llvm::dyn_cast<clang::NamespaceDecl>(context);
22 std::string name_str;
23 llvm::raw_string_ostream OS(name_str);
24 if (decl->isAnonymousNamespace())
25 OS << "<anonymous namespace>";
26 else
27 OS << *decl;
28 return GetNamespaceImpl(context->getParent(), OS.str());
29 }
30 default: { return GetNamespaceImpl(context->getParent(), candidate); }
31 }
32}
33
34} // namespace
35
36std::string GetNamespace(const clang::Decl* record) {
37 return GetNamespaceImpl(record->getDeclContext(), std::string());
38}
Xianzhu Wang86b11462022-09-24 22:00:1239
Keishi Hattori615f8fa2022-11-07 23:50:1440std::string GetFilename(const clang::SourceManager& source_manager,
Xianzhu Wang86b11462022-09-24 22:00:1241 clang::SourceLocation location) {
Xianzhu Wang86b11462022-09-24 22:00:1242 clang::SourceLocation spelling_location =
43 source_manager.getSpellingLoc(location);
44 clang::PresumedLoc ploc = source_manager.getPresumedLoc(spelling_location);
45 if (ploc.isInvalid()) {
46 // If we're in an invalid location, we're looking at things that aren't
47 // actually stated in the source.
48 return "";
49 }
50
51 return ploc.getFilename();
52}