handle_operator.cpp 17 KB

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