handle_operator.cpp 16 KB

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