1 // Copyright 2018 The Chromium Authors. All rights reserved.
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"
8 #include "llvm/Support/Casting.h"
9 #include "llvm/Support/raw_ostream.h"
10 
11 namespace {
12 
GetNamespaceImpl(const clang::DeclContext * context,const std::string & candidate)13 std::string GetNamespaceImpl(const clang::DeclContext* context,
14                              const std::string& candidate) {
15   switch (context->getDeclKind()) {
16     case clang::Decl::TranslationUnit: {
17       return candidate;
18     }
19     case clang::Decl::Namespace: {
20       const auto* decl = llvm::dyn_cast<clang::NamespaceDecl>(context);
21       std::string name_str;
22       llvm::raw_string_ostream OS(name_str);
23       if (decl->isAnonymousNamespace())
24         OS << "<anonymous namespace>";
25       else
26         OS << *decl;
27       return GetNamespaceImpl(context->getParent(), OS.str());
28     }
29     default: { return GetNamespaceImpl(context->getParent(), candidate); }
30   }
31 }
32 
33 }  // namespace
34 
GetNamespace(const clang::Decl * record)35 std::string GetNamespace(const clang::Decl* record) {
36   return GetNamespaceImpl(record->getDeclContext(), std::string());
37 }
38