handle_operator.cpp 17 KB

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