handle_array.cpp 2.1 KB

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