handle_operator.cpp 16 KB

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