handle_loop_statement.cpp 9.9 KB

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