name.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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::Destroy:
  22. return "destroy";
  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. }
  38. }
  39. auto NameStoreWrapper::GetFormatted(NameId name_id) const -> llvm::StringRef {
  40. // If the name is an identifier name with a keyword spelling, format it with
  41. // an `r#` prefix. Format any other identifier name as just the identifier.
  42. if (auto string_name = GetAsStringIfIdentifier(name_id)) {
  43. return llvm::StringSwitch<llvm::StringRef>(*string_name)
  44. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, "r#" Spelling)
  45. #include "toolchain/lex/token_kind.def"
  46. .Default(*string_name);
  47. }
  48. return GetSpecialName(name_id, /*for_ir=*/false);
  49. }
  50. auto NameStoreWrapper::GetIRBaseName(NameId name_id) const -> llvm::StringRef {
  51. if (auto string_name = GetAsStringIfIdentifier(name_id)) {
  52. return *string_name;
  53. }
  54. return GetSpecialName(name_id, /*for_ir=*/true);
  55. }
  56. } // namespace Carbon::SemIR