Avi Drissman | dfd88085 | 2022-09-15 20:11:09 | [diff] [blame] | 1 | // Copyright 2018 The Chromium Authors |
Daniel Cheng | 657bf20 | 2018-04-26 21:50:02 | [diff] [blame] | 2 | // 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 Wang | 86b1146 | 2022-09-24 22:00:12 | [diff] [blame] | 8 | #include "clang/Basic/SourceManager.h" |
Daniel Cheng | 657bf20 | 2018-04-26 21:50:02 | [diff] [blame] | 9 | #include "llvm/Support/Casting.h" |
| 10 | #include "llvm/Support/raw_ostream.h" |
| 11 | |
| 12 | namespace { |
| 13 | |
| 14 | std::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 | |
| 36 | std::string GetNamespace(const clang::Decl* record) { |
| 37 | return GetNamespaceImpl(record->getDeclContext(), std::string()); |
| 38 | } |
Xianzhu Wang | 86b1146 | 2022-09-24 22:00:12 | [diff] [blame] | 39 | |
Keishi Hattori | 615f8fa | 2022-11-07 23:50:14 | [diff] [blame^] | 40 | std::string GetFilename(const clang::SourceManager& source_manager, |
Xianzhu Wang | 86b1146 | 2022-09-24 22:00:12 | [diff] [blame] | 41 | clang::SourceLocation location) { |
Xianzhu Wang | 86b1146 | 2022-09-24 22:00:12 | [diff] [blame] | 42 | 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 | } |