handle_operator.cpp 17 KB

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