handle_operator.cpp 16 KB

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