builtins.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 "explorer/interpreter/builtins.h"
  5. #include "explorer/base/error_builders.h"
  6. using llvm::dyn_cast;
  7. namespace Carbon {
  8. CARBON_DEFINE_ENUM_CLASS_NAMES(Builtin) = {
  9. #define CARBON_BUILTIN(Name) CARBON_ENUM_CLASS_NAME_STRING(Name)
  10. #include "explorer/interpreter/builtins.def"
  11. };
  12. void Builtins::Register(Nonnull<const Declaration*> decl) {
  13. if (const auto* interface = dyn_cast<InterfaceDeclaration>(decl)) {
  14. if (interface->name().is_qualified()) {
  15. return;
  16. }
  17. static std::map<std::string, int, std::less<>>* builtin_indexes = [] {
  18. std::map<std::string, int, std::less<>> builtin_indexes;
  19. for (int index = 0; index < Builtin::NumBuiltins; ++index) {
  20. builtin_indexes.emplace(Builtin::FromInt(index).name(), index);
  21. }
  22. return new auto(std::move(builtin_indexes));
  23. }();
  24. auto it = builtin_indexes->find(interface->name().inner_name());
  25. if (it != builtin_indexes->end()) {
  26. builtins_[it->second] = interface;
  27. }
  28. }
  29. }
  30. auto Builtins::Get(SourceLocation source_loc, Builtin builtin) const
  31. -> ErrorOr<Nonnull<const Declaration*>> {
  32. std::optional<const Declaration*> result = builtins_[builtin.AsInt()];
  33. if (!result.has_value()) {
  34. return ProgramError(source_loc)
  35. << "missing declaration for builtin `" << builtin << "`";
  36. }
  37. return result.value();
  38. }
  39. } // namespace Carbon