handle_array.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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_id =
  28. ExprAsType(context, element_type_node_id, element_type_inst_id).type_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::SingletonInstId);
  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::SingletonInstId));
  44. AddInstAndPush<SemIR::ArrayType>(context, node_id,
  45. {.type_id = SemIR::TypeType::SingletonTypeId,
  46. .bound_id = bound_inst_id,
  47. .element_type_id = element_type_id});
  48. return true;
  49. }
  50. } // namespace Carbon::Check