builtins.cpp 1.4 KB

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