handle_index.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 <optional>
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/handle.h"
  9. #include "toolchain/check/literal.h"
  10. #include "toolchain/check/name_lookup.h"
  11. #include "toolchain/check/operator.h"
  12. #include "toolchain/diagnostics/diagnostic.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. auto HandleParseNode(Context& /*context*/, Parse::IndexExprStartId /*node_id*/)
  17. -> bool {
  18. // Leave the expression on the stack for IndexExpr.
  19. return true;
  20. }
  21. // Returns the argument values of the `IndexWith` interface. Arguments
  22. // correspond to the `SubscriptType` and the `ElementType`. If no arguments are
  23. // used to define `IndexWith`, this returns an empty array reference. If the
  24. // class does not implement the said interface, this returns a `std::nullopt`.
  25. // TODO: Switch to using an associated type instead of a parameter for the
  26. // `ElementType`.
  27. static auto GetIndexWithArgs(Context& context, Parse::NodeId node_id,
  28. SemIR::TypeId self_id)
  29. -> std::optional<llvm::ArrayRef<SemIR::InstId>> {
  30. auto index_with_inst_id = LookupNameInCore(context, node_id, "IndexWith");
  31. // If the `IndexWith` interface doesn't have generic arguments then return an
  32. // empty reference.
  33. if (context.insts().Is<SemIR::FacetType>(index_with_inst_id)) {
  34. return llvm::ArrayRef<SemIR::InstId>();
  35. }
  36. auto index_with_inst =
  37. context.insts().TryGetAsIfValid<SemIR::StructValue>(index_with_inst_id);
  38. if (!index_with_inst) {
  39. return std::nullopt;
  40. }
  41. auto index_with_interface =
  42. context.types().TryGetAs<SemIR::GenericInterfaceType>(
  43. index_with_inst->type_id);
  44. if (!index_with_interface) {
  45. return std::nullopt;
  46. }
  47. for (const auto& impl : context.impls().array_ref()) {
  48. auto impl_self_type_id = context.GetTypeIdForTypeInst(impl.self_id);
  49. auto impl_constraint_type_id =
  50. context.GetTypeIdForTypeInst(impl.constraint_id);
  51. if (impl_self_type_id != self_id) {
  52. continue;
  53. }
  54. auto facet_type =
  55. context.types().TryGetAs<SemIR::FacetType>(impl_constraint_type_id);
  56. if (!facet_type) {
  57. continue;
  58. }
  59. const auto& facet_type_info =
  60. context.facet_types().Get(facet_type->facet_type_id);
  61. auto interface_type = facet_type_info.TryAsSingleInterface();
  62. if (!interface_type) {
  63. continue;
  64. }
  65. if (index_with_interface->interface_id != interface_type->interface_id) {
  66. continue;
  67. }
  68. return context.inst_blocks().GetOrEmpty(
  69. context.specifics().Get(interface_type->specific_id).args_id);
  70. }
  71. return std::nullopt;
  72. }
  73. // Performs an index with base expression `operand_inst_id` and
  74. // `operand_type_id` for types that are not an array. This checks if
  75. // the base expression implements the `IndexWith` interface; if so, uses the
  76. // `At` associative method, otherwise prints a diagnostic.
  77. static auto PerformIndexWith(Context& context, Parse::NodeId node_id,
  78. SemIR::InstId operand_inst_id,
  79. SemIR::TypeId operand_type_id,
  80. SemIR::InstId index_inst_id) -> SemIR::InstId {
  81. auto args = GetIndexWithArgs(context, node_id, operand_type_id);
  82. // If the type does not implement the `IndexWith` interface, then return
  83. // an error.
  84. if (!args) {
  85. CARBON_DIAGNOSTIC(TypeNotIndexable, Error,
  86. "type {0} does not support indexing", SemIR::TypeId);
  87. context.emitter().Emit(node_id, TypeNotIndexable, operand_type_id);
  88. return SemIR::ErrorInst::SingletonInstId;
  89. }
  90. Operator op{
  91. .interface_name = "IndexWith",
  92. .interface_args_ref = *args,
  93. .op_name = "At",
  94. };
  95. // IndexWith is defined without generic arguments.
  96. if (args->empty()) {
  97. return BuildBinaryOperator(context, node_id, op, operand_inst_id,
  98. index_inst_id);
  99. }
  100. // The first argument of the `IndexWith` interface corresponds to the
  101. // `SubscriptType`, so first cast `index_inst_id` to that type.
  102. auto subscript_type_id = context.GetTypeIdForTypeInst((*args)[0]);
  103. auto cast_index_id =
  104. ConvertToValueOfType(context, node_id, index_inst_id, subscript_type_id);
  105. return BuildBinaryOperator(context, node_id, op, operand_inst_id,
  106. cast_index_id);
  107. }
  108. auto HandleParseNode(Context& context, Parse::IndexExprId node_id) -> bool {
  109. auto index_inst_id = context.node_stack().PopExpr();
  110. auto operand_inst_id = context.node_stack().PopExpr();
  111. operand_inst_id = ConvertToValueOrRefExpr(context, operand_inst_id);
  112. auto operand_inst = context.insts().Get(operand_inst_id);
  113. auto operand_type_id = operand_inst.type_id();
  114. CARBON_KIND_SWITCH(context.types().GetAsInst(operand_type_id)) {
  115. case CARBON_KIND(SemIR::ArrayType array_type): {
  116. auto index_loc_id = context.insts().GetLocId(index_inst_id);
  117. auto cast_index_id = ConvertToValueOfType(
  118. context, index_loc_id, index_inst_id,
  119. // TODO: Replace this with impl lookup rather than hardcoding `i32`.
  120. MakeIntType(context, node_id, SemIR::IntKind::Signed,
  121. context.ints().Add(32)));
  122. auto array_cat =
  123. SemIR::GetExprCategory(context.sem_ir(), operand_inst_id);
  124. if (array_cat == SemIR::ExprCategory::Value) {
  125. // If the operand is an array value, convert it to an ephemeral
  126. // reference to an array so we can perform a primitive indexing into it.
  127. operand_inst_id = context.AddInst<SemIR::ValueAsRef>(
  128. node_id, {.type_id = operand_type_id, .value_id = operand_inst_id});
  129. }
  130. // Constant evaluation will perform a bounds check on this array indexing
  131. // if the index is constant.
  132. auto elem_id = context.AddInst<SemIR::ArrayIndex>(
  133. node_id, {.type_id = array_type.element_type_id,
  134. .array_id = operand_inst_id,
  135. .index_id = cast_index_id});
  136. if (array_cat != SemIR::ExprCategory::DurableRef) {
  137. // Indexing a durable reference gives a durable reference expression.
  138. // Indexing anything else gives a value expression.
  139. // TODO: This should be replaced by a choice between using `IndexWith`
  140. // and `IndirectIndexWith`.
  141. elem_id = ConvertToValueExpr(context, elem_id);
  142. }
  143. context.node_stack().Push(node_id, elem_id);
  144. return true;
  145. }
  146. default: {
  147. auto elem_id = SemIR::ErrorInst::SingletonInstId;
  148. if (operand_type_id != SemIR::ErrorInst::SingletonTypeId) {
  149. elem_id = PerformIndexWith(context, node_id, operand_inst_id,
  150. operand_type_id, index_inst_id);
  151. }
  152. context.node_stack().Push(node_id, elem_id);
  153. return true;
  154. }
  155. }
  156. }
  157. } // namespace Carbon::Check