handle_array.cpp 2.4 KB

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