name.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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::CppDestructor:
  24. return for_ir ? "cpp_destructor" : "<C++ destructor>";
  25. case NameId::SpecialNameId::CppOperator:
  26. return for_ir ? "cpp_operator" : "<C++ operator>";
  27. case NameId::SpecialNameId::MainPackage:
  28. return "Main";
  29. case NameId::SpecialNameId::PackageKeyword:
  30. return "package";
  31. case NameId::SpecialNameId::PeriodSelf:
  32. return ".Self";
  33. case NameId::SpecialNameId::ReturnSlot:
  34. return for_ir ? "return" : "<return slot>";
  35. case NameId::SpecialNameId::SelfType:
  36. return "Self";
  37. case NameId::SpecialNameId::SelfValue:
  38. return "self";
  39. case NameId::SpecialNameId::Underscore:
  40. return "_";
  41. case NameId::SpecialNameId::Vptr:
  42. return for_ir ? "vptr" : "<vptr>";
  43. }
  44. }
  45. auto NameStoreWrapper::GetFormatted(NameId name_id) const -> llvm::StringRef {
  46. // If the name is an identifier name with a keyword spelling, format it with
  47. // an `r#` prefix. Format any other identifier name as just the identifier.
  48. if (auto string_name = GetAsStringIfIdentifier(name_id)) {
  49. return llvm::StringSwitch<llvm::StringRef>(*string_name)
  50. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, "r#" Spelling)
  51. #include "toolchain/lex/token_kind.def"
  52. .Default(*string_name);
  53. }
  54. return GetSpecialName(name_id, /*for_ir=*/false);
  55. }
  56. auto NameStoreWrapper::GetIRBaseName(NameId name_id) const -> llvm::StringRef {
  57. if (auto string_name = GetAsStringIfIdentifier(name_id)) {
  58. return *string_name;
  59. }
  60. return GetSpecialName(name_id, /*for_ir=*/true);
  61. }
  62. } // namespace Carbon::SemIR