handle_operator.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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/inst.h"
  9. #include "toolchain/check/operator.h"
  10. #include "toolchain/check/pointer_dereference.h"
  11. #include "toolchain/check/type.h"
  12. #include "toolchain/diagnostics/diagnostic_emitter.h"
  13. #include "toolchain/parse/typed_nodes.h"
  14. #include "toolchain/sem_ir/expr_info.h"
  15. namespace Carbon::Check {
  16. // Common logic for unary operator handlers.
  17. static auto HandleUnaryOperator(Context& context, Parse::AnyExprId expr_node_id,
  18. Operator op) -> bool {
  19. auto operand_id = context.node_stack().PopExpr();
  20. auto result_id = BuildUnaryOperator(context, expr_node_id, op, operand_id);
  21. context.node_stack().Push(expr_node_id, result_id);
  22. return true;
  23. }
  24. // Common logic for binary operator handlers.
  25. static auto HandleBinaryOperator(Context& context,
  26. Parse::AnyExprId expr_node_id, Operator op)
  27. -> bool {
  28. auto rhs_id = context.node_stack().PopExpr();
  29. auto lhs_id = context.node_stack().PopExpr();
  30. // All the `*With` binary operator interfaces take a single argument that is
  31. // the type of the RHS operand. `as` has different rules and we don't call
  32. // this function for it.
  33. SemIR::InstId args[] = {
  34. context.types().GetInstId(context.insts().Get(rhs_id).type_id())};
  35. op.interface_args_ref = args;
  36. auto result_id =
  37. BuildBinaryOperator(context, expr_node_id, op, lhs_id, rhs_id);
  38. context.node_stack().Push(expr_node_id, result_id);
  39. return true;
  40. }
  41. auto HandleParseNode(Context& context, Parse::InfixOperatorAmpId node_id)
  42. -> bool {
  43. // TODO: Facet type intersection may need to be handled directly.
  44. return HandleBinaryOperator(context, node_id, {"BitAndWith"});
  45. }
  46. auto HandleParseNode(Context& context, Parse::InfixOperatorAmpEqualId node_id)
  47. -> bool {
  48. return HandleBinaryOperator(context, node_id, {"BitAndAssignWith"});
  49. }
  50. auto HandleParseNode(Context& context, Parse::UnsafeModifierId node_id)
  51. -> bool {
  52. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  53. context.node_stack().Push(node_id, rhs_id);
  54. return true;
  55. }
  56. auto HandleParseNode(Context& context, Parse::InfixOperatorAsId node_id)
  57. -> bool {
  58. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  59. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
  60. bool unsafe = context.parse_tree().node_kind(lhs_node) ==
  61. Parse::NodeKind::UnsafeModifier;
  62. auto rhs_type_id = ExprAsType(context, rhs_node, rhs_id).type_id;
  63. context.node_stack().Push(
  64. node_id,
  65. ConvertForExplicitAs(context, node_id, lhs_id, rhs_type_id, unsafe));
  66. return true;
  67. }
  68. auto HandleParseNode(Context& context, Parse::InfixOperatorCaretId node_id)
  69. -> bool {
  70. return HandleBinaryOperator(context, node_id, {"BitXorWith"});
  71. }
  72. auto HandleParseNode(Context& context, Parse::InfixOperatorCaretEqualId node_id)
  73. -> bool {
  74. return HandleBinaryOperator(context, node_id, {"BitXorAssignWith"});
  75. }
  76. auto HandleParseNode(Context& context, Parse::InfixOperatorEqualId node_id)
  77. -> bool {
  78. // TODO: Switch to using assignment interface for most assignment. Some cases
  79. // may need to be handled directly.
  80. //
  81. // return HandleBinaryOperator(context, node_id, {"AssignWith"});
  82. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  83. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
  84. if (auto lhs_cat = SemIR::GetExprCategory(context.sem_ir(), lhs_id);
  85. lhs_cat != SemIR::ExprCategory::DurableRef &&
  86. lhs_cat != SemIR::ExprCategory::Error) {
  87. CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error,
  88. "expression is not assignable");
  89. context.emitter().Emit(lhs_node, AssignmentToNonAssignable);
  90. }
  91. // TODO: Destroy the old value before reinitializing. This will require
  92. // building the destruction code before we build the RHS subexpression.
  93. rhs_id = Initialize(context, node_id, lhs_id, rhs_id);
  94. AddInst<SemIR::Assign>(context, node_id,
  95. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  96. // We model assignment as an expression, so we need to push a value for
  97. // it, even though it doesn't produce a value.
  98. // TODO: Consider changing our parse tree to model assignment as a
  99. // different kind of statement than an expression statement.
  100. context.node_stack().Push(node_id, lhs_id);
  101. return true;
  102. }
  103. auto HandleParseNode(Context& context, Parse::InfixOperatorEqualEqualId node_id)
  104. -> bool {
  105. return HandleBinaryOperator(context, node_id, {"EqWith", {}, "Equal"});
  106. }
  107. auto HandleParseNode(Context& context,
  108. Parse::InfixOperatorExclaimEqualId node_id) -> bool {
  109. return HandleBinaryOperator(context, node_id, {"EqWith", {}, "NotEqual"});
  110. }
  111. auto HandleParseNode(Context& context, Parse::InfixOperatorGreaterId node_id)
  112. -> bool {
  113. return HandleBinaryOperator(context, node_id, {"OrderedWith", {}, "Greater"});
  114. }
  115. auto HandleParseNode(Context& context,
  116. Parse::InfixOperatorGreaterEqualId node_id) -> bool {
  117. return HandleBinaryOperator(context, node_id,
  118. {"OrderedWith", {}, "GreaterOrEquivalent"});
  119. }
  120. auto HandleParseNode(Context& context,
  121. Parse::InfixOperatorGreaterGreaterId node_id) -> bool {
  122. return HandleBinaryOperator(context, node_id, {"RightShiftWith"});
  123. }
  124. auto HandleParseNode(Context& context,
  125. Parse::InfixOperatorGreaterGreaterEqualId node_id)
  126. -> bool {
  127. return HandleBinaryOperator(context, node_id, {"RightShiftAssignWith"});
  128. }
  129. auto HandleParseNode(Context& context, Parse::InfixOperatorLessId node_id)
  130. -> bool {
  131. return HandleBinaryOperator(context, node_id, {"OrderedWith", {}, "Less"});
  132. }
  133. auto HandleParseNode(Context& context, Parse::InfixOperatorLessEqualId node_id)
  134. -> bool {
  135. return HandleBinaryOperator(context, node_id,
  136. {"OrderedWith", {}, "LessOrEquivalent"});
  137. }
  138. auto HandleParseNode(Context& context,
  139. Parse::InfixOperatorLessEqualGreaterId node_id) -> bool {
  140. return context.TODO(node_id, "remove <=> operator that is not in the design");
  141. }
  142. auto HandleParseNode(Context& context, Parse::InfixOperatorLessLessId node_id)
  143. -> bool {
  144. return HandleBinaryOperator(context, node_id, {"LeftShiftWith"});
  145. }
  146. auto HandleParseNode(Context& context,
  147. Parse::InfixOperatorLessLessEqualId node_id) -> bool {
  148. return HandleBinaryOperator(context, node_id, {"LeftShiftAssignWith"});
  149. }
  150. auto HandleParseNode(Context& context, Parse::InfixOperatorMinusId node_id)
  151. -> bool {
  152. return HandleBinaryOperator(context, node_id, {"SubWith"});
  153. }
  154. auto HandleParseNode(Context& context, Parse::InfixOperatorMinusEqualId node_id)
  155. -> bool {
  156. return HandleBinaryOperator(context, node_id, {"SubAssignWith"});
  157. }
  158. auto HandleParseNode(Context& context, Parse::InfixOperatorPercentId node_id)
  159. -> bool {
  160. return HandleBinaryOperator(context, node_id, {"ModWith"});
  161. }
  162. auto HandleParseNode(Context& context,
  163. Parse::InfixOperatorPercentEqualId node_id) -> bool {
  164. return HandleBinaryOperator(context, node_id, {"ModAssignWith"});
  165. }
  166. auto HandleParseNode(Context& context, Parse::InfixOperatorPipeId node_id)
  167. -> bool {
  168. return HandleBinaryOperator(context, node_id, {"BitOrWith"});
  169. }
  170. auto HandleParseNode(Context& context, Parse::InfixOperatorPipeEqualId node_id)
  171. -> bool {
  172. return HandleBinaryOperator(context, node_id, {"BitOrAssignWith"});
  173. }
  174. auto HandleParseNode(Context& context, Parse::InfixOperatorPlusId node_id)
  175. -> bool {
  176. return HandleBinaryOperator(context, node_id, {"AddWith"});
  177. }
  178. auto HandleParseNode(Context& context, Parse::InfixOperatorPlusEqualId node_id)
  179. -> bool {
  180. return HandleBinaryOperator(context, node_id, {"AddAssignWith"});
  181. }
  182. auto HandleParseNode(Context& context, Parse::InfixOperatorSlashId node_id)
  183. -> bool {
  184. return HandleBinaryOperator(context, node_id, {"DivWith"});
  185. }
  186. auto HandleParseNode(Context& context, Parse::InfixOperatorSlashEqualId node_id)
  187. -> bool {
  188. return HandleBinaryOperator(context, node_id, {"DivAssignWith"});
  189. }
  190. auto HandleParseNode(Context& context, Parse::InfixOperatorStarId node_id)
  191. -> bool {
  192. return HandleBinaryOperator(context, node_id, {"MulWith"});
  193. }
  194. auto HandleParseNode(Context& context, Parse::InfixOperatorStarEqualId node_id)
  195. -> bool {
  196. return HandleBinaryOperator(context, node_id, {"MulAssignWith"});
  197. }
  198. auto HandleParseNode(Context& context, Parse::PostfixOperatorStarId node_id)
  199. -> bool {
  200. auto value_id = context.node_stack().PopExpr();
  201. auto inner_type = ExprAsType(context, node_id, value_id);
  202. AddInstAndPush<SemIR::PointerType>(
  203. context, node_id,
  204. {.type_id = SemIR::TypeType::TypeId, .pointee_id = inner_type.inst_id});
  205. return true;
  206. }
  207. auto HandleParseNode(Context& context, Parse::PrefixOperatorAmpId node_id)
  208. -> bool {
  209. auto value_id = context.node_stack().PopExpr();
  210. auto type_id = context.insts().Get(value_id).type_id();
  211. // Only durable reference expressions can have their address taken.
  212. switch (SemIR::GetExprCategory(context.sem_ir(), value_id)) {
  213. case SemIR::ExprCategory::DurableRef:
  214. case SemIR::ExprCategory::Error:
  215. break;
  216. default:
  217. CARBON_DIAGNOSTIC(AddrOfNonRef, Error,
  218. "cannot take the address of non-reference expression");
  219. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  220. AddrOfNonRef);
  221. value_id = SemIR::ErrorInst::InstId;
  222. break;
  223. }
  224. // TODO: Preserve spelling of type of operand where possible.
  225. auto type_inst_id = context.types().GetInstId(type_id);
  226. AddInstAndPush<SemIR::AddrOf>(
  227. context, node_id,
  228. SemIR::AddrOf{.type_id = GetPointerType(context, type_inst_id),
  229. .lvalue_id = value_id});
  230. return true;
  231. }
  232. auto HandleParseNode(Context& context, Parse::PrefixOperatorCaretId node_id)
  233. -> bool {
  234. return HandleUnaryOperator(context, node_id, {"BitComplement"});
  235. }
  236. auto HandleParseNode(Context& context, Parse::PrefixOperatorConstId node_id)
  237. -> bool {
  238. auto value_id = context.node_stack().PopExpr();
  239. // `const (const T)` is probably not what the developer intended.
  240. // TODO: Detect `const (const T)*` and suggest moving the `*` inside the
  241. // parentheses.
  242. if (context.insts().Get(value_id).kind() == SemIR::ConstType::Kind) {
  243. CARBON_DIAGNOSTIC(RepeatedConst, Warning,
  244. "`const` applied repeatedly to the same type has no "
  245. "additional effect");
  246. context.emitter().Emit(node_id, RepeatedConst);
  247. }
  248. auto inner_type = ExprAsType(context, node_id, value_id);
  249. AddInstAndPush<SemIR::ConstType>(
  250. context, node_id,
  251. {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_type.inst_id});
  252. return true;
  253. }
  254. auto HandleParseNode(Context& context, Parse::PrefixOperatorMinusId node_id)
  255. -> bool {
  256. return HandleUnaryOperator(context, node_id, {"Negate"});
  257. }
  258. auto HandleParseNode(Context& context,
  259. Parse::PrefixOperatorMinusMinusId node_id) -> bool {
  260. return HandleUnaryOperator(context, node_id, {"Dec"});
  261. }
  262. auto HandleParseNode(Context& context, Parse::PrefixOperatorNotId node_id)
  263. -> bool {
  264. auto value_id = context.node_stack().PopExpr();
  265. value_id = ConvertToBoolValue(context, node_id, value_id);
  266. AddInstAndPush<SemIR::UnaryOperatorNot>(
  267. context, node_id,
  268. {.type_id = context.insts().Get(value_id).type_id(),
  269. .operand_id = value_id});
  270. return true;
  271. }
  272. auto HandleParseNode(Context& context, Parse::PrefixOperatorPartialId node_id)
  273. -> bool {
  274. auto value_id = context.node_stack().PopExpr();
  275. auto inner_type = ExprAsType(context, node_id, value_id);
  276. auto class_type =
  277. context.types().TryGetAs<SemIR::ClassType>(inner_type.type_id);
  278. if (!class_type ||
  279. context.classes().Get(class_type->class_id).inheritance_kind ==
  280. SemIR::Class::InheritanceKind::Final) {
  281. CARBON_DIAGNOSTIC(PartialOnFinal, Error,
  282. "`partial` applied to final type {0}", SemIR::TypeId);
  283. context.emitter().Emit(node_id, PartialOnFinal, inner_type.type_id);
  284. }
  285. AddInstAndPush<SemIR::PartialType>(
  286. context, node_id,
  287. {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_type.inst_id});
  288. return true;
  289. }
  290. auto HandleParseNode(Context& context, Parse::PrefixOperatorPlusPlusId node_id)
  291. -> bool {
  292. return HandleUnaryOperator(context, node_id, {"Inc"});
  293. }
  294. auto HandleParseNode(Context& context, Parse::PrefixOperatorStarId node_id)
  295. -> bool {
  296. auto base_id = context.node_stack().PopExpr();
  297. auto deref_base_id = PerformPointerDereference(
  298. context, node_id, base_id,
  299. [&context, &node_id](SemIR::TypeId not_pointer_type_id) {
  300. // TODO: Pass in the expression we're trying to dereference to produce a
  301. // better diagnostic.
  302. CARBON_DIAGNOSTIC(DerefOfNonPointer, Error,
  303. "cannot dereference operand of non-pointer type {0}",
  304. SemIR::TypeId);
  305. auto builder =
  306. context.emitter().Build(LocIdForDiagnostics::TokenOnly(node_id),
  307. DerefOfNonPointer, not_pointer_type_id);
  308. // TODO: Check for any facet here, rather than only a type.
  309. if (not_pointer_type_id == SemIR::TypeType::TypeId) {
  310. CARBON_DIAGNOSTIC(
  311. DerefOfType, Note,
  312. "to form a pointer type, write the `*` after the pointee type");
  313. builder.Note(LocIdForDiagnostics::TokenOnly(node_id), DerefOfType);
  314. }
  315. builder.Emit();
  316. });
  317. context.node_stack().Push(node_id, deref_base_id);
  318. return true;
  319. }
  320. // Adds the branch for a short circuit operand.
  321. static auto HandleShortCircuitOperand(Context& context, Parse::NodeId node_id,
  322. bool is_or) -> bool {
  323. // Convert the condition to `bool`.
  324. auto [cond_node, cond_value_id] = context.node_stack().PopExprWithNodeId();
  325. cond_value_id = ConvertToBoolValue(context, node_id, cond_value_id);
  326. auto bool_type_id = context.insts().Get(cond_value_id).type_id();
  327. // Compute the branch value: the condition for `and`, inverted for `or`.
  328. SemIR::InstId branch_value_id =
  329. is_or ? AddInst<SemIR::UnaryOperatorNot>(
  330. context, node_id,
  331. {.type_id = bool_type_id, .operand_id = cond_value_id})
  332. : cond_value_id;
  333. auto short_circuit_result_id = AddInst<SemIR::BoolLiteral>(
  334. context, node_id,
  335. {.type_id = bool_type_id, .value = SemIR::BoolValue::From(is_or)});
  336. // Create a block for the right-hand side and for the continuation.
  337. auto rhs_block_id =
  338. AddDominatedBlockAndBranchIf(context, node_id, branch_value_id);
  339. auto end_block_id = AddDominatedBlockAndBranchWithArg(
  340. context, node_id, short_circuit_result_id);
  341. // Push the branch condition and result for use when handling the complete
  342. // expression.
  343. context.node_stack().Push(cond_node, branch_value_id);
  344. context.node_stack().Push(cond_node, short_circuit_result_id);
  345. // Push the resumption and the right-hand side blocks, and start emitting the
  346. // right-hand operand.
  347. context.inst_block_stack().Pop();
  348. context.inst_block_stack().Push(end_block_id);
  349. context.inst_block_stack().Push(rhs_block_id);
  350. context.region_stack().AddToRegion(rhs_block_id, node_id);
  351. // HandleShortCircuitOperator will follow, and doesn't need the operand on the
  352. // node stack.
  353. return true;
  354. }
  355. auto HandleParseNode(Context& context, Parse::ShortCircuitOperandAndId node_id)
  356. -> bool {
  357. return HandleShortCircuitOperand(context, node_id, /*is_or=*/false);
  358. }
  359. auto HandleParseNode(Context& context, Parse::ShortCircuitOperandOrId node_id)
  360. -> bool {
  361. return HandleShortCircuitOperand(context, node_id, /*is_or=*/true);
  362. }
  363. // Short circuit operator handling is uniform because the branching logic
  364. // occurs during operand handling.
  365. static auto HandleShortCircuitOperator(Context& context, Parse::NodeId node_id)
  366. -> bool {
  367. if (!context.scope_stack().IsInFunctionScope()) {
  368. return context.TODO(node_id,
  369. "Control flow expressions are currently only supported "
  370. "inside functions.");
  371. }
  372. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
  373. auto short_circuit_result_id = context.node_stack().PopExpr();
  374. auto branch_value_id = context.node_stack().PopExpr();
  375. // The first operand is wrapped in a ShortCircuitOperand, which we
  376. // already handled by creating a RHS block and a resumption block, which
  377. // are the current block and its enclosing block.
  378. rhs_id = ConvertToBoolValue(context, node_id, rhs_id);
  379. // When the second operand is evaluated, the result of `and` and `or` is
  380. // its value.
  381. auto resume_block_id = context.inst_block_stack().PeekOrAdd(/*depth=*/1);
  382. AddInst<SemIR::BranchWithArg>(
  383. context, node_id, {.target_id = resume_block_id, .arg_id = rhs_id});
  384. context.inst_block_stack().Pop();
  385. context.region_stack().AddToRegion(resume_block_id, node_id);
  386. // Collect the result from either the first or second operand.
  387. auto result_id = AddInst<SemIR::BlockArg>(
  388. context, node_id,
  389. {.type_id = context.insts().Get(rhs_id).type_id(),
  390. .block_id = resume_block_id});
  391. SetBlockArgResultBeforeConstantUse(context, result_id, branch_value_id,
  392. rhs_id, short_circuit_result_id);
  393. context.node_stack().Push(node_id, result_id);
  394. return true;
  395. }
  396. auto HandleParseNode(Context& context, Parse::ShortCircuitOperatorAndId node_id)
  397. -> bool {
  398. return HandleShortCircuitOperator(context, node_id);
  399. }
  400. auto HandleParseNode(Context& context, Parse::ShortCircuitOperatorOrId node_id)
  401. -> bool {
  402. return HandleShortCircuitOperator(context, node_id);
  403. }
  404. } // namespace Carbon::Check