handle_array.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/parse/node_kind.h"
  7. #include "toolchain/sem_ir/inst.h"
  8. namespace Carbon::Check {
  9. auto HandleArrayExprStart(Context& /*context*/,
  10. Parse::ArrayExprStartId /*parse_node*/) -> bool {
  11. return true;
  12. }
  13. auto HandleArrayExprSemi(Context& context, Parse::ArrayExprSemiId parse_node)
  14. -> bool {
  15. context.node_stack().Push(parse_node);
  16. return true;
  17. }
  18. auto HandleArrayExpr(Context& context, Parse::ArrayExprId parse_node) -> bool {
  19. // TODO: Handle array type with undefined bound.
  20. if (context.node_stack()
  21. .PopAndDiscardSoloParseNodeIf<Parse::NodeKind::ArrayExprSemi>()) {
  22. context.node_stack().PopAndIgnore();
  23. return context.TODO(parse_node, "HandleArrayExprWithoutBounds");
  24. }
  25. auto bound_inst_id = context.node_stack().PopExpr();
  26. context.node_stack()
  27. .PopAndDiscardSoloParseNode<Parse::NodeKind::ArrayExprSemi>();
  28. auto [element_type_node_id, element_type_inst_id] =
  29. context.node_stack().PopExprWithParseNode();
  30. // The array bound must be a constant.
  31. //
  32. // TODO: Should we support runtime-phase bounds in cases such as:
  33. // comptime fn F(n: i32) -> type { return [i32; n]; }
  34. auto bound_inst = context.constant_values().Get(bound_inst_id);
  35. if (!bound_inst.is_constant()) {
  36. CARBON_DIAGNOSTIC(InvalidArrayExpr, Error,
  37. "Array bound is not a constant.");
  38. context.emitter().Emit(bound_inst_id, InvalidArrayExpr);
  39. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  40. return true;
  41. }
  42. context.AddInstAndPush(
  43. {parse_node, SemIR::ArrayType{SemIR::TypeId::TypeType, bound_inst_id,
  44. ExprAsType(context, element_type_node_id,
  45. element_type_inst_id)}});
  46. return true;
  47. }
  48. } // namespace Carbon::Check