operator.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 "toolchain/check/operator.h"
  5. #include "toolchain/check/call.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/member_access.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. #include "toolchain/sem_ir/typed_insts.h"
  11. namespace Carbon::Check {
  12. // Returns the `Op` function for the specified operator.
  13. static auto GetOperatorOpFunction(Context& context, SemIR::LocId loc_id,
  14. Operator op) -> SemIR::InstId {
  15. // Look up the interface, and pass it any generic arguments.
  16. auto interface_id = context.LookupNameInCore(loc_id, op.interface_name);
  17. if (!op.interface_args_ref.empty()) {
  18. interface_id =
  19. PerformCall(context, loc_id, interface_id, op.interface_args_ref);
  20. }
  21. // Look up the interface member.
  22. auto op_name_id =
  23. SemIR::NameId::ForIdentifier(context.identifiers().Add(op.op_name));
  24. return PerformMemberAccess(context, loc_id, interface_id, op_name_id);
  25. }
  26. auto BuildUnaryOperator(
  27. Context& context, SemIR::LocId loc_id, Operator op,
  28. SemIR::InstId operand_id,
  29. std::optional<Context::BuildDiagnosticFn> missing_impl_diagnoser)
  30. -> SemIR::InstId {
  31. // Look up the operator function.
  32. auto op_fn = GetOperatorOpFunction(context, loc_id, op);
  33. // Form `operand.(Op)`.
  34. auto bound_op_id = PerformCompoundMemberAccess(context, loc_id, operand_id,
  35. op_fn, missing_impl_diagnoser);
  36. if (bound_op_id == SemIR::InstId::BuiltinError) {
  37. return SemIR::InstId::BuiltinError;
  38. }
  39. // Form `bound_op()`.
  40. return PerformCall(context, loc_id, bound_op_id, {});
  41. }
  42. auto BuildBinaryOperator(
  43. Context& context, SemIR::LocId loc_id, Operator op, SemIR::InstId lhs_id,
  44. SemIR::InstId rhs_id,
  45. std::optional<Context::BuildDiagnosticFn> missing_impl_diagnoser)
  46. -> SemIR::InstId {
  47. // Look up the operator function.
  48. auto op_fn = GetOperatorOpFunction(context, loc_id, op);
  49. // Form `lhs.(Op)`.
  50. auto bound_op_id = PerformCompoundMemberAccess(context, loc_id, lhs_id, op_fn,
  51. missing_impl_diagnoser);
  52. if (bound_op_id == SemIR::InstId::BuiltinError) {
  53. return SemIR::InstId::BuiltinError;
  54. }
  55. // Form `bound_op(rhs)`.
  56. return PerformCall(context, loc_id, bound_op_id, {rhs_id});
  57. }
  58. } // namespace Carbon::Check