handle_array.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/check/handle.h"
  7. #include "toolchain/parse/node_kind.h"
  8. namespace Carbon::Check {
  9. auto HandleArrayExprStart(Context& /*context*/,
  10. Parse::ArrayExprStartId /*node_id*/) -> bool {
  11. return true;
  12. }
  13. auto HandleArrayExprSemi(Context& context, Parse::ArrayExprSemiId node_id)
  14. -> bool {
  15. context.node_stack().Push(node_id);
  16. return true;
  17. }
  18. auto HandleArrayExpr(Context& context, Parse::ArrayExprId node_id) -> bool {
  19. // TODO: Handle array type with undefined bound.
  20. if (context.node_stack()
  21. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::ArrayExprSemi>()) {
  22. context.node_stack().PopAndIgnore();
  23. return context.TODO(node_id, "HandleArrayExprWithoutBounds");
  24. }
  25. auto bound_inst_id = context.node_stack().PopExpr();
  26. context.node_stack()
  27. .PopAndDiscardSoloNodeId<Parse::NodeKind::ArrayExprSemi>();
  28. auto [element_type_node_id, element_type_inst_id] =
  29. context.node_stack().PopExprWithNodeId();
  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(node_id, SemIR::InstId::BuiltinError);
  40. return true;
  41. }
  42. context.AddInstAndPush<SemIR::ArrayType>(
  43. node_id, {.type_id = SemIR::TypeId::TypeType,
  44. .bound_id = bound_inst_id,
  45. .element_type_id = ExprAsType(context, element_type_node_id,
  46. element_type_inst_id)});
  47. return true;
  48. }
  49. } // namespace Carbon::Check