name.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #ifndef CARBON_TOOLCHAIN_SEM_IR_NAME_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_NAME_H_
  6. #include "toolchain/base/value_ids.h"
  7. #include "toolchain/base/value_store.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. namespace Carbon::SemIR {
  10. // Provides a ValueStore-like interface for names.
  11. //
  12. // A name is either an identifier name or a special name such as `self` that
  13. // does not correspond to an identifier token. Identifier names are represented
  14. // as `NameId`s with the same non-negative index as the `IdentifierId` of the
  15. // identifier. Special names are represented as `NameId`s with a negative index.
  16. //
  17. // `SemIR::NameId` values should be obtained by using `NameId::ForIdentifier`
  18. // or the named constants such as `NameId::SelfValue`.
  19. //
  20. // As we do not require any additional explicit storage for names, this is
  21. // currently a wrapper around an identifier store that has no state of its own.
  22. class NameStoreWrapper {
  23. public:
  24. explicit NameStoreWrapper(
  25. const CanonicalValueStore<IdentifierId>* identifiers)
  26. : identifiers_(identifiers) {}
  27. // Returns the requested name as a string, if it is an identifier name. This
  28. // returns std::nullopt for special names.
  29. auto GetAsStringIfIdentifier(NameId name_id) const
  30. -> std::optional<llvm::StringRef> {
  31. if (auto identifier_id = name_id.AsIdentifierId();
  32. identifier_id.has_value()) {
  33. return identifiers_->Get(identifier_id);
  34. }
  35. return std::nullopt;
  36. }
  37. // Returns the requested name as a string for formatted output. This returns
  38. // `"r#name"` if `name` is a keyword.
  39. auto GetFormatted(NameId name_id) const -> llvm::StringRef;
  40. // Returns a best-effort name to use as the basis for SemIR and LLVM IR names.
  41. // This is always identifier-shaped, but may be ambiguous, for example if
  42. // there is both a `self` and an `r#self` in the same scope. Returns "" if
  43. // `name_id` is `None`.
  44. auto GetIRBaseName(NameId name_id) const -> llvm::StringRef;
  45. private:
  46. const CanonicalValueStore<IdentifierId>* identifiers_;
  47. };
  48. } // namespace Carbon::SemIR
  49. #endif // CARBON_TOOLCHAIN_SEM_IR_NAME_H_