handle_array.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 HandleParseNode(Context& /*context*/, Parse::ArrayExprStartId /*node_id*/)
  10. -> bool {
  11. return true;
  12. }
  13. auto HandleParseNode(Context& context, Parse::ArrayExprSemiId node_id) -> bool {
  14. context.node_stack().Push(node_id);
  15. return true;
  16. }
  17. auto HandleParseNode(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. auto element_type_id =
  30. ExprAsType(context, element_type_node_id, element_type_inst_id).type_id;
  31. // The array bound must be a constant. Diagnose this prior to conversion
  32. // because conversion to `IntLiteral` will produce a generic "non-constant
  33. // call to compile-time-only function" error.
  34. //
  35. // TODO: Should we support runtime-phase bounds in cases such as:
  36. // comptime fn F(n: i32) -> type { return [i32; n]; }
  37. if (!context.constant_values().Get(bound_inst_id).is_constant()) {
  38. CARBON_DIAGNOSTIC(InvalidArrayExpr, Error, "array bound is not a constant");
  39. context.emitter().Emit(bound_inst_id, InvalidArrayExpr);
  40. context.node_stack().Push(node_id, SemIR::ErrorInst::SingletonInstId);
  41. return true;
  42. }
  43. bound_inst_id = ConvertToValueOfType(
  44. context, context.insts().GetLocId(bound_inst_id), bound_inst_id,
  45. context.GetSingletonType(SemIR::IntLiteralType::SingletonInstId));
  46. context.AddInstAndPush<SemIR::ArrayType>(
  47. node_id, {.type_id = SemIR::TypeType::SingletonTypeId,
  48. .bound_id = bound_inst_id,
  49. .element_type_id = element_type_id});
  50. return true;
  51. }
  52. } // namespace Carbon::Check