handle_operator.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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/control_flow.h"
  6. #include "toolchain/check/convert.h"
  7. #include "toolchain/check/handle.h"
  8. #include "toolchain/check/inst.h"
  9. #include "toolchain/check/operator.h"
  10. #include "toolchain/check/pointer_dereference.h"
  11. #include "toolchain/check/type.h"
  12. #include "toolchain/diagnostics/diagnostic_emitter.h"
  13. #include "toolchain/sem_ir/expr_info.h"
  14. namespace Carbon::Check {
  15. // Common logic for unary operator handlers.
  16. static auto HandleUnaryOperator(Context& context, Parse::AnyExprId expr_node_id,
  17. Operator op) -> bool {
  18. auto operand_id = context.node_stack().PopExpr();
  19. auto result_id = BuildUnaryOperator(context, expr_node_id, op, operand_id);
  20. context.node_stack().Push(expr_node_id, result_id);
  21. return true;
  22. }
  23. // Common logic for binary operator handlers.
  24. static auto HandleBinaryOperator(Context& context,
  25. Parse::AnyExprId expr_node_id, Operator op)
  26. -> bool {
  27. auto rhs_id = context.node_stack().PopExpr();
  28. auto lhs_id = context.node_stack().PopExpr();
  29. auto result_id =
  30. BuildBinaryOperator(context, expr_node_id, op, lhs_id, rhs_id);
  31. context.node_stack().Push(expr_node_id, result_id);
  32. return true;
  33. }
  34. auto HandleParseNode(Context& context, Parse::InfixOperatorAmpId node_id)
  35. -> bool {
  36. // TODO: Facet type intersection may need to be handled directly.
  37. return HandleBinaryOperator(context, node_id, {"BitAnd"});
  38. }
  39. auto HandleParseNode(Context& context, Parse::InfixOperatorAmpEqualId node_id)
  40. -> bool {
  41. return HandleBinaryOperator(context, node_id, {"BitAndAssign"});
  42. }
  43. auto HandleParseNode(Context& context, Parse::InfixOperatorAsId node_id)
  44. -> bool {
  45. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  46. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
  47. auto rhs_type_id = ExprAsType(context, rhs_node, rhs_id).type_id;
  48. context.node_stack().Push(
  49. node_id, ConvertForExplicitAs(context, node_id, lhs_id, rhs_type_id));
  50. return true;
  51. }
  52. auto HandleParseNode(Context& context, Parse::InfixOperatorCaretId node_id)
  53. -> bool {
  54. return HandleBinaryOperator(context, node_id, {"BitXor"});
  55. }
  56. auto HandleParseNode(Context& context, Parse::InfixOperatorCaretEqualId node_id)
  57. -> bool {
  58. return HandleBinaryOperator(context, node_id, {"BitXorAssign"});
  59. }
  60. auto HandleParseNode(Context& context, Parse::InfixOperatorEqualId node_id)
  61. -> bool {
  62. // TODO: Switch to using assignment interface for most assignment. Some cases
  63. // may need to be handled directly.
  64. //
  65. // return HandleBinaryOperator(context, node_id, {"Assign"});
  66. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  67. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
  68. if (auto lhs_cat = SemIR::GetExprCategory(context.sem_ir(), lhs_id);
  69. lhs_cat != SemIR::ExprCategory::DurableRef &&
  70. lhs_cat != SemIR::ExprCategory::Error) {
  71. CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error,
  72. "expression is not assignable");
  73. context.emitter().Emit(lhs_node, AssignmentToNonAssignable);
  74. }
  75. // TODO: Destroy the old value before reinitializing. This will require
  76. // building the destruction code before we build the RHS subexpression.
  77. rhs_id = Initialize(context, node_id, lhs_id, rhs_id);
  78. AddInst<SemIR::Assign>(context, node_id,
  79. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  80. // We model assignment as an expression, so we need to push a value for
  81. // it, even though it doesn't produce a value.
  82. // TODO: Consider changing our parse tree to model assignment as a
  83. // different kind of statement than an expression statement.
  84. context.node_stack().Push(node_id, lhs_id);
  85. return true;
  86. }
  87. auto HandleParseNode(Context& context, Parse::InfixOperatorEqualEqualId node_id)
  88. -> bool {
  89. return HandleBinaryOperator(context, node_id, {"Eq", {}, "Equal"});
  90. }
  91. auto HandleParseNode(Context& context,
  92. Parse::InfixOperatorExclaimEqualId node_id) -> bool {
  93. return HandleBinaryOperator(context, node_id, {"Eq", {}, "NotEqual"});
  94. }
  95. auto HandleParseNode(Context& context, Parse::InfixOperatorGreaterId node_id)
  96. -> bool {
  97. return HandleBinaryOperator(context, node_id, {"Ordered", {}, "Greater"});
  98. }
  99. auto HandleParseNode(Context& context,
  100. Parse::InfixOperatorGreaterEqualId node_id) -> bool {
  101. return HandleBinaryOperator(context, node_id,
  102. {"Ordered", {}, "GreaterOrEquivalent"});
  103. }
  104. auto HandleParseNode(Context& context,
  105. Parse::InfixOperatorGreaterGreaterId node_id) -> bool {
  106. return HandleBinaryOperator(context, node_id, {"RightShift"});
  107. }
  108. auto HandleParseNode(Context& context,
  109. Parse::InfixOperatorGreaterGreaterEqualId node_id)
  110. -> bool {
  111. return HandleBinaryOperator(context, node_id, {"RightShiftAssign"});
  112. }
  113. auto HandleParseNode(Context& context, Parse::InfixOperatorLessId node_id)
  114. -> bool {
  115. return HandleBinaryOperator(context, node_id, {"Ordered", {}, "Less"});
  116. }
  117. auto HandleParseNode(Context& context, Parse::InfixOperatorLessEqualId node_id)
  118. -> bool {
  119. return HandleBinaryOperator(context, node_id,
  120. {"Ordered", {}, "LessOrEquivalent"});
  121. }
  122. auto HandleParseNode(Context& context,
  123. Parse::InfixOperatorLessEqualGreaterId node_id) -> bool {
  124. return context.TODO(node_id, "remove <=> operator that is not in the design");
  125. }
  126. auto HandleParseNode(Context& context, Parse::InfixOperatorLessLessId node_id)
  127. -> bool {
  128. return HandleBinaryOperator(context, node_id, {"LeftShift"});
  129. }
  130. auto HandleParseNode(Context& context,
  131. Parse::InfixOperatorLessLessEqualId node_id) -> bool {
  132. return HandleBinaryOperator(context, node_id, {"LeftShiftAssign"});
  133. }
  134. auto HandleParseNode(Context& context, Parse::InfixOperatorMinusId node_id)
  135. -> bool {
  136. return HandleBinaryOperator(context, node_id, {"Sub"});
  137. }
  138. auto HandleParseNode(Context& context, Parse::InfixOperatorMinusEqualId node_id)
  139. -> bool {
  140. return HandleBinaryOperator(context, node_id, {"SubAssign"});
  141. }
  142. auto HandleParseNode(Context& context, Parse::InfixOperatorPercentId node_id)
  143. -> bool {
  144. return HandleBinaryOperator(context, node_id, {"Mod"});
  145. }
  146. auto HandleParseNode(Context& context,
  147. Parse::InfixOperatorPercentEqualId node_id) -> bool {
  148. return HandleBinaryOperator(context, node_id, {"ModAssign"});
  149. }
  150. auto HandleParseNode(Context& context, Parse::InfixOperatorPipeId node_id)
  151. -> bool {
  152. return HandleBinaryOperator(context, node_id, {"BitOr"});
  153. }
  154. auto HandleParseNode(Context& context, Parse::InfixOperatorPipeEqualId node_id)
  155. -> bool {
  156. return HandleBinaryOperator(context, node_id, {"BitOrAssign"});
  157. }
  158. auto HandleParseNode(Context& context, Parse::InfixOperatorPlusId node_id)
  159. -> bool {
  160. return HandleBinaryOperator(context, node_id, {"Add"});
  161. }
  162. auto HandleParseNode(Context& context, Parse::InfixOperatorPlusEqualId node_id)
  163. -> bool {
  164. return HandleBinaryOperator(context, node_id, {"AddAssign"});
  165. }
  166. auto HandleParseNode(Context& context, Parse::InfixOperatorSlashId node_id)
  167. -> bool {
  168. return HandleBinaryOperator(context, node_id, {"Div"});
  169. }
  170. auto HandleParseNode(Context& context, Parse::InfixOperatorSlashEqualId node_id)
  171. -> bool {
  172. return HandleBinaryOperator(context, node_id, {"DivAssign"});
  173. }
  174. auto HandleParseNode(Context& context, Parse::InfixOperatorStarId node_id)
  175. -> bool {
  176. return HandleBinaryOperator(context, node_id, {"Mul"});
  177. }
  178. auto HandleParseNode(Context& context, Parse::InfixOperatorStarEqualId node_id)
  179. -> bool {
  180. return HandleBinaryOperator(context, node_id, {"MulAssign"});
  181. }
  182. auto HandleParseNode(Context& context, Parse::PostfixOperatorStarId node_id)
  183. -> bool {
  184. auto value_id = context.node_stack().PopExpr();
  185. auto inner_type = ExprAsType(context, node_id, value_id);
  186. AddInstAndPush<SemIR::PointerType>(
  187. context, node_id,
  188. {.type_id = SemIR::TypeType::TypeId, .pointee_id = inner_type.inst_id});
  189. return true;
  190. }
  191. auto HandleParseNode(Context& context, Parse::PrefixOperatorAmpId node_id)
  192. -> bool {
  193. auto value_id = context.node_stack().PopExpr();
  194. auto type_id = context.insts().Get(value_id).type_id();
  195. // Only durable reference expressions can have their address taken.
  196. switch (SemIR::GetExprCategory(context.sem_ir(), value_id)) {
  197. case SemIR::ExprCategory::DurableRef:
  198. case SemIR::ExprCategory::Error:
  199. break;
  200. case SemIR::ExprCategory::EphemeralRef:
  201. CARBON_DIAGNOSTIC(AddrOfEphemeralRef, Error,
  202. "cannot take the address of a temporary object");
  203. context.emitter().Emit(SemIR::LocId(node_id).ToTokenOnly(),
  204. AddrOfEphemeralRef);
  205. value_id = SemIR::ErrorInst::InstId;
  206. break;
  207. default:
  208. CARBON_DIAGNOSTIC(AddrOfNonRef, Error,
  209. "cannot take the address of non-reference expression");
  210. context.emitter().Emit(SemIR::LocId(node_id).ToTokenOnly(), AddrOfNonRef);
  211. value_id = SemIR::ErrorInst::InstId;
  212. break;
  213. }
  214. // TODO: Preserve spelling of type of operand where possible.
  215. auto type_inst_id = context.types().GetInstId(type_id);
  216. AddInstAndPush<SemIR::AddrOf>(
  217. context, node_id,
  218. SemIR::AddrOf{.type_id = GetPointerType(context, type_inst_id),
  219. .lvalue_id = value_id});
  220. return true;
  221. }
  222. auto HandleParseNode(Context& context, Parse::PrefixOperatorCaretId node_id)
  223. -> bool {
  224. return HandleUnaryOperator(context, node_id, {"BitComplement"});
  225. }
  226. auto HandleParseNode(Context& context, Parse::PrefixOperatorConstId node_id)
  227. -> bool {
  228. auto value_id = context.node_stack().PopExpr();
  229. // `const (const T)` is probably not what the developer intended.
  230. // TODO: Detect `const (const T)*` and suggest moving the `*` inside the
  231. // parentheses.
  232. if (context.insts().Get(value_id).kind() == SemIR::ConstType::Kind) {
  233. CARBON_DIAGNOSTIC(RepeatedConst, Warning,
  234. "`const` applied repeatedly to the same type has no "
  235. "additional effect");
  236. context.emitter().Emit(node_id, RepeatedConst);
  237. }
  238. auto inner_type = ExprAsType(context, node_id, value_id);
  239. AddInstAndPush<SemIR::ConstType>(
  240. context, node_id,
  241. {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_type.inst_id});
  242. return true;
  243. }
  244. auto HandleParseNode(Context& context, Parse::PrefixOperatorMinusId node_id)
  245. -> bool {
  246. return HandleUnaryOperator(context, node_id, {"Negate"});
  247. }
  248. auto HandleParseNode(Context& context,
  249. Parse::PrefixOperatorMinusMinusId node_id) -> bool {
  250. return HandleUnaryOperator(context, node_id, {"Dec"});
  251. }
  252. auto HandleParseNode(Context& context, Parse::PrefixOperatorNotId node_id)
  253. -> bool {
  254. auto value_id = context.node_stack().PopExpr();
  255. value_id = ConvertToBoolValue(context, node_id, value_id);
  256. AddInstAndPush<SemIR::UnaryOperatorNot>(
  257. context, node_id,
  258. {.type_id = context.insts().Get(value_id).type_id(),
  259. .operand_id = value_id});
  260. return true;
  261. }
  262. auto HandleParseNode(Context& context, Parse::PrefixOperatorPartialId node_id)
  263. -> bool {
  264. return context.TODO(node_id, "partial operator");
  265. }
  266. auto HandleParseNode(Context& context, Parse::PrefixOperatorPlusPlusId node_id)
  267. -> bool {
  268. return HandleUnaryOperator(context, node_id, {"Inc"});
  269. }
  270. auto HandleParseNode(Context& context, Parse::PrefixOperatorStarId node_id)
  271. -> bool {
  272. auto base_id = context.node_stack().PopExpr();
  273. auto deref_base_id = PerformPointerDereference(
  274. context, node_id, base_id,
  275. [&context, &node_id](SemIR::TypeId not_pointer_type_id) {
  276. // TODO: Pass in the expression we're trying to dereference to produce a
  277. // better diagnostic.
  278. CARBON_DIAGNOSTIC(DerefOfNonPointer, Error,
  279. "cannot dereference operand of non-pointer type {0}",
  280. SemIR::TypeId);
  281. auto builder =
  282. context.emitter().Build(SemIR::LocId(node_id).ToTokenOnly(),
  283. DerefOfNonPointer, not_pointer_type_id);
  284. // TODO: Check for any facet here, rather than only a type.
  285. if (not_pointer_type_id == SemIR::TypeType::TypeId) {
  286. CARBON_DIAGNOSTIC(
  287. DerefOfType, Note,
  288. "to form a pointer type, write the `*` after the pointee type");
  289. builder.Note(SemIR::LocId(node_id).ToTokenOnly(), DerefOfType);
  290. }
  291. builder.Emit();
  292. });
  293. context.node_stack().Push(node_id, deref_base_id);
  294. return true;
  295. }
  296. // Adds the branch for a short circuit operand.
  297. static auto HandleShortCircuitOperand(Context& context, Parse::NodeId node_id,
  298. bool is_or) -> bool {
  299. // Convert the condition to `bool`.
  300. auto [cond_node, cond_value_id] = context.node_stack().PopExprWithNodeId();
  301. cond_value_id = ConvertToBoolValue(context, node_id, cond_value_id);
  302. auto bool_type_id = context.insts().Get(cond_value_id).type_id();
  303. // Compute the branch value: the condition for `and`, inverted for `or`.
  304. SemIR::InstId branch_value_id =
  305. is_or ? AddInst<SemIR::UnaryOperatorNot>(
  306. context, node_id,
  307. {.type_id = bool_type_id, .operand_id = cond_value_id})
  308. : cond_value_id;
  309. auto short_circuit_result_id = AddInst<SemIR::BoolLiteral>(
  310. context, node_id,
  311. {.type_id = bool_type_id, .value = SemIR::BoolValue::From(is_or)});
  312. // Create a block for the right-hand side and for the continuation.
  313. auto rhs_block_id =
  314. AddDominatedBlockAndBranchIf(context, node_id, branch_value_id);
  315. auto end_block_id = AddDominatedBlockAndBranchWithArg(
  316. context, node_id, short_circuit_result_id);
  317. // Push the branch condition and result for use when handling the complete
  318. // expression.
  319. context.node_stack().Push(cond_node, branch_value_id);
  320. context.node_stack().Push(cond_node, short_circuit_result_id);
  321. // Push the resumption and the right-hand side blocks, and start emitting the
  322. // right-hand operand.
  323. context.inst_block_stack().Pop();
  324. context.inst_block_stack().Push(end_block_id);
  325. context.inst_block_stack().Push(rhs_block_id);
  326. context.region_stack().AddToRegion(rhs_block_id, node_id);
  327. // HandleShortCircuitOperator will follow, and doesn't need the operand on the
  328. // node stack.
  329. return true;
  330. }
  331. auto HandleParseNode(Context& context, Parse::ShortCircuitOperandAndId node_id)
  332. -> bool {
  333. return HandleShortCircuitOperand(context, node_id, /*is_or=*/false);
  334. }
  335. auto HandleParseNode(Context& context, Parse::ShortCircuitOperandOrId node_id)
  336. -> bool {
  337. return HandleShortCircuitOperand(context, node_id, /*is_or=*/true);
  338. }
  339. // Short circuit operator handling is uniform because the branching logic
  340. // occurs during operand handling.
  341. static auto HandleShortCircuitOperator(Context& context, Parse::NodeId node_id)
  342. -> bool {
  343. if (!context.scope_stack().IsInFunctionScope()) {
  344. return context.TODO(node_id,
  345. "Control flow expressions are currently only supported "
  346. "inside functions.");
  347. }
  348. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  349. auto short_circuit_result_id = context.node_stack().PopExpr();
  350. auto branch_value_id = context.node_stack().PopExpr();
  351. // The first operand is wrapped in a ShortCircuitOperand, which we
  352. // already handled by creating a RHS block and a resumption block, which
  353. // are the current block and its enclosing block.
  354. rhs_id = ConvertToBoolValue(context, node_id, rhs_id);
  355. // When the second operand is evaluated, the result of `and` and `or` is
  356. // its value.
  357. auto resume_block_id = context.inst_block_stack().PeekOrAdd(/*depth=*/1);
  358. AddInst<SemIR::BranchWithArg>(
  359. context, node_id, {.target_id = resume_block_id, .arg_id = rhs_id});
  360. context.inst_block_stack().Pop();
  361. context.region_stack().AddToRegion(resume_block_id, node_id);
  362. // Collect the result from either the first or second operand.
  363. auto result_id = AddInst<SemIR::BlockArg>(
  364. context, node_id,
  365. {.type_id = context.insts().Get(rhs_id).type_id(),
  366. .block_id = resume_block_id});
  367. SetBlockArgResultBeforeConstantUse(context, result_id, branch_value_id,
  368. rhs_id, short_circuit_result_id);
  369. context.node_stack().Push(node_id, result_id);
  370. return true;
  371. }
  372. auto HandleParseNode(Context& context, Parse::ShortCircuitOperatorAndId node_id)
  373. -> bool {
  374. return HandleShortCircuitOperator(context, node_id);
  375. }
  376. auto HandleParseNode(Context& context, Parse::ShortCircuitOperatorOrId node_id)
  377. -> bool {
  378. return HandleShortCircuitOperator(context, node_id);
  379. }
  380. } // namespace Carbon::Check