handle_operator.cpp 19 KB

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