handle_loop_statement.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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/call.h"
  5. #include "toolchain/check/context.h"
  6. #include "toolchain/check/control_flow.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/core_identifier.h"
  9. #include "toolchain/check/full_pattern_stack.h"
  10. #include "toolchain/check/handle.h"
  11. #include "toolchain/check/inst.h"
  12. #include "toolchain/check/member_access.h"
  13. #include "toolchain/check/operator.h"
  14. #include "toolchain/check/pattern.h"
  15. #include "toolchain/check/pattern_match.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/sem_ir/absolute_node_ref.h"
  18. #include "toolchain/sem_ir/expr_info.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. namespace Carbon::Check {
  21. // Starts emitting the loop header for a `while`-like looping construct. Returns
  22. // the loop header block ID.
  23. static auto StartLoopHeader(Context& context, Parse::NodeId node_id)
  24. -> SemIR::InstBlockId {
  25. // Branch to the loop header block. Note that we create a new block here even
  26. // if the current block is empty; this ensures that the loop always has a
  27. // preheader block.
  28. auto loop_header_id = AddDominatedBlockAndBranch(context, node_id);
  29. context.inst_block_stack().Pop();
  30. // Start emitting the loop header block.
  31. context.inst_block_stack().Push(loop_header_id);
  32. context.region_stack().AddToRegion(loop_header_id, node_id);
  33. return loop_header_id;
  34. }
  35. // Starts emitting the loop body for a `while`-like looping construct. Converts
  36. // `cond_value_id` to bool and branches to the loop body if it is `true` and to
  37. // the loop exit if it is `false`.
  38. static auto BranchAndStartLoopBody(Context& context, Parse::NodeId node_id,
  39. SemIR::InstBlockId loop_header_id,
  40. SemIR::InstId cond_value_id) -> void {
  41. cond_value_id = ConvertToBoolValue(context, node_id, cond_value_id);
  42. // Branch to either the loop body or the loop exit block.
  43. auto loop_body_id =
  44. AddDominatedBlockAndBranchIf(context, node_id, cond_value_id);
  45. auto loop_exit_id = AddDominatedBlockAndBranch(context, node_id);
  46. context.inst_block_stack().Pop();
  47. // Start emitting the loop body.
  48. context.inst_block_stack().Push(loop_body_id);
  49. context.region_stack().AddToRegion(loop_body_id, node_id);
  50. // Allow `break` and `continue` in this scope.
  51. context.break_continue_stack().push_back(
  52. {.break_target = loop_exit_id, .continue_target = loop_header_id});
  53. }
  54. // Finishes emitting the body for a `while`-like loop. Adds a back-edge to the
  55. // loop header, and starts emitting in the loop exit block.
  56. static auto FinishLoopBody(Context& context, Parse::NodeId node_id) -> void {
  57. auto blocks = context.break_continue_stack().pop_back_val();
  58. // Add the loop backedge.
  59. AddInst<SemIR::Branch>(context, node_id,
  60. {.target_id = blocks.continue_target});
  61. context.inst_block_stack().Pop();
  62. // Start emitting the loop exit block.
  63. context.inst_block_stack().Push(blocks.break_target);
  64. context.region_stack().AddToRegion(blocks.break_target, node_id);
  65. }
  66. // `while`
  67. // -------
  68. auto HandleParseNode(Context& context, Parse::WhileConditionStartId node_id)
  69. -> bool {
  70. context.node_stack().Push(node_id, StartLoopHeader(context, node_id));
  71. return true;
  72. }
  73. auto HandleParseNode(Context& context, Parse::WhileConditionId node_id)
  74. -> bool {
  75. auto cond_value_id = context.node_stack().PopExpr();
  76. auto loop_header_id =
  77. context.node_stack().Pop<Parse::NodeKind::WhileConditionStart>();
  78. // Branch to either the loop body or the loop exit block, and start emitting
  79. // the loop body.
  80. BranchAndStartLoopBody(context, node_id, loop_header_id, cond_value_id);
  81. return true;
  82. }
  83. auto HandleParseNode(Context& context, Parse::WhileStatementId node_id)
  84. -> bool {
  85. FinishLoopBody(context, node_id);
  86. return true;
  87. }
  88. // `for`
  89. // -----
  90. auto HandleParseNode(Context& context, Parse::ForHeaderStartId node_id)
  91. -> bool {
  92. // Create a nested scope to hold the cursor variable. This is also the lexical
  93. // scope that names in the pattern are added to, although they get rebound on
  94. // each loop iteration.
  95. context.scope_stack().PushForSameRegion();
  96. // Begin an implicit let declaration context for the pattern.
  97. context.decl_introducer_state_stack().Push<Lex::TokenKind::Let>();
  98. context.pattern_block_stack().Push();
  99. context.full_pattern_stack().PushNameBindingDecl();
  100. BeginSubpattern(context);
  101. context.node_stack().Push(node_id);
  102. return true;
  103. }
  104. auto HandleParseNode(Context& context, Parse::ForInId node_id) -> bool {
  105. EndSubpattern(context, context.node_stack());
  106. auto pattern_block_id = context.pattern_block_stack().Pop();
  107. AddInst<SemIR::NameBindingDecl>(context, node_id,
  108. {.pattern_block_id = pattern_block_id});
  109. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Let>();
  110. context.full_pattern_stack().StartPatternInitializer();
  111. context.node_stack().Push(node_id, pattern_block_id);
  112. return true;
  113. }
  114. // For a value or reference of type `Optional(T)`, call the given accessor.
  115. static auto CallOptionalAccessor(Context& context, Parse::NodeId node_id,
  116. SemIR::InstId optional_id,
  117. CoreIdentifier accessor_name)
  118. -> SemIR::InstId {
  119. auto accessor_name_id = context.core_identifiers().AddNameId(accessor_name);
  120. auto accessor_id =
  121. PerformMemberAccess(context, node_id, optional_id, accessor_name_id);
  122. return PerformCall(context, node_id, accessor_id, {});
  123. }
  124. auto HandleParseNode(Context& context, Parse::ForHeaderId node_id) -> bool {
  125. auto range_id = context.node_stack().PopExpr();
  126. auto pattern_block_id = context.node_stack().Pop<Parse::NodeKind::ForIn>();
  127. auto pattern_id = context.node_stack().PopPattern();
  128. auto start_node_id =
  129. context.node_stack().PopForSoloNodeId<Parse::NodeKind::ForHeaderStart>();
  130. // Convert the range expression to a value or reference so that we can use it
  131. // multiple times.
  132. // TODO: If this produces a temporary, its lifetime should presumably be
  133. // extended to cover the loop body.
  134. range_id = ConvertToValueOrRefExpr(context, range_id);
  135. // Create the cursor variable.
  136. // TODO: Produce a custom diagnostic if the range operand can't be used as a
  137. // range.
  138. // TODO: We need to allocate the `VarStorage` before building the operator.
  139. // The current order risks violating the preconditions on `Initialize` and
  140. // risks violating the topological ordering of insts.
  141. auto cursor_id =
  142. BuildUnaryOperator(context, node_id,
  143. {.interface_name = CoreIdentifier::Iterate,
  144. .op_name = CoreIdentifier::NewCursor},
  145. range_id);
  146. auto cursor_type_id = context.insts().Get(cursor_id).type_id();
  147. PendingBlock cursor_var_block(&context);
  148. auto cursor_var_id = cursor_var_block.AddInstWithCleanup<SemIR::VarStorage>(
  149. node_id,
  150. {.type_id = cursor_type_id, .pattern_id = SemIR::AbsoluteInstId::None});
  151. // Disable broken lint that suggests a "fix" that doesn't compile.
  152. auto init_result = Initialize(context, node_id,
  153. // NOLINTNEXTLINE(performance-move-const-arg)
  154. std::move(cursor_var_id),
  155. std::move(cursor_var_block), cursor_id);
  156. AddInst<SemIR::Assign>(
  157. context, node_id,
  158. {.lhs_id = init_result.storage_id, .rhs_id = init_result.init_id});
  159. cursor_var_id = init_result.storage_id;
  160. // Start emitting the loop header block.
  161. auto loop_header_id = StartLoopHeader(context, start_node_id);
  162. // Call `<range>.(Iterate.Next)(&cursor)`.
  163. auto cursor_type_inst_id = context.types().GetTypeInstId(cursor_type_id);
  164. auto cursor_addr_id = AddInst<SemIR::AddrOf>(
  165. context, node_id,
  166. {.type_id = GetPointerType(context, cursor_type_inst_id),
  167. .lvalue_id = cursor_var_id});
  168. auto element_id =
  169. BuildBinaryOperator(context, node_id,
  170. {.interface_name = CoreIdentifier::Iterate,
  171. .op_name = CoreIdentifier::Next},
  172. range_id, cursor_addr_id);
  173. // We need to convert away from an initializing expression in order to call
  174. // `HasValue` and then separately pattern-match against the element.
  175. // TODO: Instead, form a `.Some(pattern_id)` pattern and pattern-match against
  176. // that.
  177. element_id = ConvertToValueOrRefExpr(context, element_id);
  178. // Branch to the loop body if the optional element has a value.
  179. auto cond_value_id = CallOptionalAccessor(context, node_id, element_id,
  180. CoreIdentifier::HasValue);
  181. BranchAndStartLoopBody(context, node_id, loop_header_id, cond_value_id);
  182. // The loop pattern's initializer is now complete, and any bindings in it
  183. // should be in scope.
  184. context.full_pattern_stack().EndPatternInitializer();
  185. context.full_pattern_stack().PopFullPattern();
  186. // Create storage for var patterns now.
  187. AddPatternVarStorage(context, pattern_block_id, /*is_returned_var=*/false);
  188. // Initialize the pattern from `<element>.Get()`.
  189. auto element_value_id =
  190. CallOptionalAccessor(context, node_id, element_id, CoreIdentifier::Get);
  191. LocalPatternMatch(context, pattern_id, element_value_id);
  192. return true;
  193. }
  194. auto HandleParseNode(Context& context, Parse::ForStatementId node_id) -> bool {
  195. FinishLoopBody(context, node_id);
  196. return true;
  197. }
  198. // `break`
  199. // -------
  200. auto HandleParseNode(Context& context, Parse::BreakStatementStartId node_id)
  201. -> bool {
  202. auto& stack = context.break_continue_stack();
  203. if (stack.empty()) {
  204. CARBON_DIAGNOSTIC(BreakOutsideLoop, Error,
  205. "`break` can only be used in a loop");
  206. context.emitter().Emit(node_id, BreakOutsideLoop);
  207. } else {
  208. AddInst<SemIR::Branch>(context, node_id,
  209. {.target_id = stack.back().break_target});
  210. }
  211. context.inst_block_stack().Pop();
  212. context.inst_block_stack().PushUnreachable();
  213. return true;
  214. }
  215. auto HandleParseNode(Context& /*context*/, Parse::BreakStatementId /*node_id*/)
  216. -> bool {
  217. return true;
  218. }
  219. // `continue`
  220. // ----------
  221. auto HandleParseNode(Context& context, Parse::ContinueStatementStartId node_id)
  222. -> bool {
  223. auto& stack = context.break_continue_stack();
  224. if (stack.empty()) {
  225. CARBON_DIAGNOSTIC(ContinueOutsideLoop, Error,
  226. "`continue` can only be used in a loop");
  227. context.emitter().Emit(node_id, ContinueOutsideLoop);
  228. } else {
  229. AddInst<SemIR::Branch>(context, node_id,
  230. {.target_id = stack.back().continue_target});
  231. }
  232. context.inst_block_stack().Pop();
  233. context.inst_block_stack().PushUnreachable();
  234. return true;
  235. }
  236. auto HandleParseNode(Context& /*context*/,
  237. Parse::ContinueStatementId /*node_id*/) -> bool {
  238. return true;
  239. }
  240. } // namespace Carbon::Check