name.cpp 2.4 KB

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