name.h 2.1 KB

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