handle_array.cpp 2.5 KB

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