name.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/sem_ir/name.h"
  5. #include "llvm/ADT/StringSwitch.h"
  6. namespace Carbon::SemIR {
  7. // Get the spelling to use for a special name.
  8. static auto GetSpecialName(NameId name_id, bool for_ir) -> llvm::StringRef {
  9. if (name_id == NameId::None) {
  10. return for_ir ? "" : "<none>";
  11. }
  12. auto special_name_id = name_id.AsSpecialNameId();
  13. CARBON_CHECK(special_name_id, "Not a special name");
  14. switch (*special_name_id) {
  15. case NameId::SpecialNameId::Base:
  16. return "base";
  17. case NameId::SpecialNameId::ChoiceDiscriminant:
  18. return "discriminant";
  19. case NameId::SpecialNameId::Core:
  20. return "Core";
  21. case NameId::SpecialNameId::Cpp:
  22. return "Cpp";
  23. case NameId::SpecialNameId::PackageNamespace:
  24. return "package";
  25. case NameId::SpecialNameId::PeriodSelf:
  26. return ".Self";
  27. case NameId::SpecialNameId::ReturnSlot:
  28. return for_ir ? "return" : "<return slot>";
  29. case NameId::SpecialNameId::SelfType:
  30. return "Self";
  31. case NameId::SpecialNameId::SelfValue:
  32. return "self";
  33. case NameId::SpecialNameId::Underscore:
  34. return "_";
  35. case NameId::SpecialNameId::Vptr:
  36. return for_ir ? "vptr" : "<vptr>";
  37. case NameId::SpecialNameId::CppOperator:
  38. return for_ir ? "cpp_operator" : "<C++ operator>";
  39. }
  40. }
  41. auto NameStoreWrapper::GetFormatted(NameId name_id) const -> llvm::StringRef {
  42. // If the name is an identifier name with a keyword spelling, format it with
  43. // an `r#` prefix. Format any other identifier name as just the identifier.
  44. if (auto string_name = GetAsStringIfIdentifier(name_id)) {
  45. return llvm::StringSwitch<llvm::StringRef>(*string_name)
  46. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, "r#" Spelling)
  47. #include "toolchain/lex/token_kind.def"
  48. .Default(*string_name);
  49. }
  50. return GetSpecialName(name_id, /*for_ir=*/false);
  51. }
  52. auto NameStoreWrapper::GetIRBaseName(NameId name_id) const -> llvm::StringRef {
  53. if (auto string_name = GetAsStringIfIdentifier(name_id)) {
  54. return *string_name;
  55. }
  56. return GetSpecialName(name_id, /*for_ir=*/true);
  57. }
  58. } // namespace Carbon::SemIR