handle_operator.cpp 17 KB

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