builtins.cpp 1.3 KB

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