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