handle_operator.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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<SemIR::Assign>(node_id, {.lhs_id = lhs_id, .rhs_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<SemIR::PointerType>(
  194. node_id,
  195. {.type_id = SemIR::TypeId::TypeType, .pointee_id = inner_type_id});
  196. return true;
  197. }
  198. auto HandlePrefixOperatorAmp(Context& context,
  199. Parse::PrefixOperatorAmpId node_id) -> bool {
  200. auto value_id = context.node_stack().PopExpr();
  201. auto type_id = context.insts().Get(value_id).type_id();
  202. // Only durable reference expressions can have their address taken.
  203. switch (SemIR::GetExprCategory(context.sem_ir(), value_id)) {
  204. case SemIR::ExprCategory::DurableRef:
  205. case SemIR::ExprCategory::Error:
  206. break;
  207. case SemIR::ExprCategory::EphemeralRef:
  208. CARBON_DIAGNOSTIC(AddrOfEphemeralRef, Error,
  209. "Cannot take the address of a temporary object.");
  210. context.emitter().Emit(TokenOnly(node_id), AddrOfEphemeralRef);
  211. value_id = SemIR::InstId::BuiltinError;
  212. break;
  213. default:
  214. CARBON_DIAGNOSTIC(AddrOfNonRef, Error,
  215. "Cannot take the address of non-reference expression.");
  216. context.emitter().Emit(TokenOnly(node_id), AddrOfNonRef);
  217. value_id = SemIR::InstId::BuiltinError;
  218. break;
  219. }
  220. context.AddInstAndPush<SemIR::AddrOf>(
  221. node_id, SemIR::AddrOf{.type_id = context.GetPointerType(type_id),
  222. .lvalue_id = value_id});
  223. return true;
  224. }
  225. auto HandlePrefixOperatorCaret(Context& context,
  226. Parse::PrefixOperatorCaretId node_id) -> bool {
  227. return HandleUnaryOperator(context, node_id, {"BitComplement"});
  228. }
  229. auto HandlePrefixOperatorConst(Context& context,
  230. Parse::PrefixOperatorConstId node_id) -> bool {
  231. auto value_id = context.node_stack().PopExpr();
  232. // `const (const T)` is probably not what the developer intended.
  233. // TODO: Detect `const (const T)*` and suggest moving the `*` inside the
  234. // parentheses.
  235. if (context.insts().Get(value_id).kind() == SemIR::ConstType::Kind) {
  236. CARBON_DIAGNOSTIC(RepeatedConst, Warning,
  237. "`const` applied repeatedly to the same type has no "
  238. "additional effect.");
  239. context.emitter().Emit(node_id, RepeatedConst);
  240. }
  241. auto inner_type_id = ExprAsType(context, node_id, value_id);
  242. context.AddInstAndPush<SemIR::ConstType>(
  243. node_id, {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  244. return true;
  245. }
  246. auto HandlePrefixOperatorMinus(Context& context,
  247. Parse::PrefixOperatorMinusId node_id) -> bool {
  248. return HandleUnaryOperator(context, node_id, {"Negate"});
  249. }
  250. auto HandlePrefixOperatorMinusMinus(Context& context,
  251. Parse::PrefixOperatorMinusMinusId node_id)
  252. -> bool {
  253. return HandleUnaryOperator(context, node_id, {"Dec"});
  254. }
  255. auto HandlePrefixOperatorNot(Context& context,
  256. Parse::PrefixOperatorNotId node_id) -> bool {
  257. auto value_id = context.node_stack().PopExpr();
  258. value_id = ConvertToBoolValue(context, node_id, value_id);
  259. context.AddInstAndPush<SemIR::UnaryOperatorNot>(
  260. node_id, {.type_id = context.insts().Get(value_id).type_id(),
  261. .operand_id = value_id});
  262. return true;
  263. }
  264. auto HandlePrefixOperatorPlusPlus(Context& context,
  265. Parse::PrefixOperatorPlusPlusId node_id)
  266. -> bool {
  267. return HandleUnaryOperator(context, node_id, {"Inc"});
  268. }
  269. auto HandlePrefixOperatorStar(Context& context,
  270. Parse::PrefixOperatorStarId node_id) -> bool {
  271. auto base_id = context.node_stack().PopExpr();
  272. auto deref_base_id = PerformPointerDereference(
  273. context, node_id, base_id,
  274. [&context, &node_id](SemIR::TypeId not_pointer_type_id) {
  275. CARBON_DIAGNOSTIC(
  276. DerefOfNonPointer, Error,
  277. "Cannot dereference operand of non-pointer type `{0}`.",
  278. SemIR::TypeId);
  279. auto builder = context.emitter().Build(
  280. TokenOnly(node_id), DerefOfNonPointer, not_pointer_type_id);
  281. // TODO: Check for any facet here, rather than only a type.
  282. if (not_pointer_type_id == SemIR::TypeId::TypeType) {
  283. CARBON_DIAGNOSTIC(
  284. DerefOfType, Note,
  285. "To form a pointer type, write the `*` after the pointee type.");
  286. builder.Note(TokenOnly(node_id), DerefOfType);
  287. }
  288. builder.Emit();
  289. });
  290. context.node_stack().Push(node_id, deref_base_id);
  291. return true;
  292. }
  293. // Adds the branch for a short circuit operand.
  294. static auto HandleShortCircuitOperand(Context& context, Parse::NodeId node_id,
  295. bool is_or) -> bool {
  296. // Convert the condition to `bool`.
  297. auto [cond_node, cond_value_id] = context.node_stack().PopExprWithNodeId();
  298. cond_value_id = ConvertToBoolValue(context, node_id, cond_value_id);
  299. auto bool_type_id = context.insts().Get(cond_value_id).type_id();
  300. // Compute the branch value: the condition for `and`, inverted for `or`.
  301. SemIR::InstId branch_value_id =
  302. is_or
  303. ? context.AddInst<SemIR::UnaryOperatorNot>(
  304. node_id, {.type_id = bool_type_id, .operand_id = cond_value_id})
  305. : cond_value_id;
  306. auto short_circuit_result_id = context.AddInst<SemIR::BoolLiteral>(
  307. node_id,
  308. {.type_id = bool_type_id, .value = SemIR::BoolValue::From(is_or)});
  309. // Create a block for the right-hand side and for the continuation.
  310. auto rhs_block_id =
  311. context.AddDominatedBlockAndBranchIf(node_id, branch_value_id);
  312. auto end_block_id = context.AddDominatedBlockAndBranchWithArg(
  313. node_id, short_circuit_result_id);
  314. // Push the branch condition and result for use when handling the complete
  315. // expression.
  316. context.node_stack().Push(cond_node, branch_value_id);
  317. context.node_stack().Push(cond_node, short_circuit_result_id);
  318. // Push the resumption and the right-hand side blocks, and start emitting the
  319. // right-hand operand.
  320. context.inst_block_stack().Pop();
  321. context.inst_block_stack().Push(end_block_id);
  322. context.inst_block_stack().Push(rhs_block_id);
  323. context.AddCurrentCodeBlockToFunction(node_id);
  324. // HandleShortCircuitOperator will follow, and doesn't need the operand on the
  325. // node stack.
  326. return true;
  327. }
  328. auto HandleShortCircuitOperandAnd(Context& context,
  329. Parse::ShortCircuitOperandAndId node_id)
  330. -> bool {
  331. return HandleShortCircuitOperand(context, node_id, /*is_or=*/false);
  332. }
  333. auto HandleShortCircuitOperandOr(Context& context,
  334. Parse::ShortCircuitOperandOrId node_id)
  335. -> bool {
  336. return HandleShortCircuitOperand(context, node_id, /*is_or=*/true);
  337. }
  338. // Short circuit operator handling is uniform because the branching logic
  339. // occurs during operand handling.
  340. static auto HandleShortCircuitOperator(Context& context, Parse::NodeId node_id)
  341. -> bool {
  342. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  343. auto short_circuit_result_id = context.node_stack().PopExpr();
  344. auto branch_value_id = context.node_stack().PopExpr();
  345. // The first operand is wrapped in a ShortCircuitOperand, which we
  346. // already handled by creating a RHS block and a resumption block, which
  347. // are the current block and its enclosing block.
  348. rhs_id = ConvertToBoolValue(context, node_id, rhs_id);
  349. // When the second operand is evaluated, the result of `and` and `or` is
  350. // its value.
  351. auto resume_block_id = context.inst_block_stack().PeekOrAdd(/*depth=*/1);
  352. context.AddInst<SemIR::BranchWithArg>(
  353. node_id, {.target_id = resume_block_id, .arg_id = rhs_id});
  354. context.inst_block_stack().Pop();
  355. context.AddCurrentCodeBlockToFunction(node_id);
  356. // Collect the result from either the first or second operand.
  357. auto result_id = context.AddInst<SemIR::BlockArg>(
  358. node_id, {.type_id = context.insts().Get(rhs_id).type_id(),
  359. .block_id = resume_block_id});
  360. context.SetBlockArgResultBeforeConstantUse(result_id, branch_value_id, rhs_id,
  361. short_circuit_result_id);
  362. context.node_stack().Push(node_id, result_id);
  363. return true;
  364. }
  365. auto HandleShortCircuitOperatorAnd(Context& context,
  366. Parse::ShortCircuitOperatorAndId node_id)
  367. -> bool {
  368. return HandleShortCircuitOperator(context, node_id);
  369. }
  370. auto HandleShortCircuitOperatorOr(Context& context,
  371. Parse::ShortCircuitOperatorOrId node_id)
  372. -> bool {
  373. return HandleShortCircuitOperator(context, node_id);
  374. }
  375. } // namespace Carbon::Check