handle_operator.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. namespace Carbon::Check {
  7. auto HandleInfixOperator(Context& context, Parse::NodeId parse_node) -> bool {
  8. auto [rhs_node, rhs_id] = context.node_stack().PopExprWithParseNode();
  9. auto [lhs_node, lhs_id] = context.node_stack().PopExprWithParseNode();
  10. // Figure out the operator for the token.
  11. auto token = context.parse_tree().node_token(parse_node);
  12. switch (auto token_kind = context.tokens().GetKind(token)) {
  13. case Lex::TokenKind::Plus:
  14. // TODO: This should search for a compatible interface. For now, it's a
  15. // very trivial check of validity on the operation.
  16. lhs_id = ConvertToValueOfType(context, parse_node, lhs_id,
  17. context.insts().Get(rhs_id).type_id());
  18. rhs_id = ConvertToValueExpr(context, rhs_id);
  19. context.AddInstAndPush(
  20. parse_node, SemIR::BinaryOperatorAdd{
  21. parse_node, context.insts().Get(lhs_id).type_id(),
  22. lhs_id, rhs_id});
  23. return true;
  24. case Lex::TokenKind::And:
  25. case Lex::TokenKind::Or: {
  26. // The first operand is wrapped in a ShortCircuitOperand, which we
  27. // already handled by creating a RHS block and a resumption block, which
  28. // are the current block and its enclosing block.
  29. rhs_id = ConvertToBoolValue(context, parse_node, rhs_id);
  30. // When the second operand is evaluated, the result of `and` and `or` is
  31. // its value.
  32. auto resume_block_id = context.inst_block_stack().PeekOrAdd(/*depth=*/1);
  33. context.AddInst(
  34. SemIR::BranchWithArg{parse_node, resume_block_id, rhs_id});
  35. context.inst_block_stack().Pop();
  36. context.AddCurrentCodeBlockToFunction();
  37. // Collect the result from either the first or second operand.
  38. context.AddInstAndPush(
  39. parse_node,
  40. SemIR::BlockArg{parse_node, context.insts().Get(rhs_id).type_id(),
  41. resume_block_id});
  42. return true;
  43. }
  44. case Lex::TokenKind::As: {
  45. auto rhs_type_id = ExprAsType(context, rhs_node, rhs_id);
  46. context.node_stack().Push(
  47. parse_node,
  48. ConvertForExplicitAs(context, parse_node, lhs_id, rhs_type_id));
  49. return true;
  50. }
  51. case Lex::TokenKind::Equal: {
  52. // TODO: handle complex assignment expression such as `a += 1`.
  53. if (auto lhs_cat = SemIR::GetExprCategory(context.sem_ir(), lhs_id);
  54. lhs_cat != SemIR::ExprCategory::DurableRef &&
  55. lhs_cat != SemIR::ExprCategory::Error) {
  56. CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error,
  57. "Expression is not assignable.");
  58. context.emitter().Emit(lhs_node, AssignmentToNonAssignable);
  59. }
  60. // TODO: Destroy the old value before reinitializing. This will require
  61. // building the destruction code before we build the RHS subexpression.
  62. rhs_id = Initialize(context, parse_node, lhs_id, rhs_id);
  63. context.AddInst(SemIR::Assign{parse_node, lhs_id, rhs_id});
  64. // We model assignment as an expression, so we need to push a value for
  65. // it, even though it doesn't produce a value.
  66. // TODO: Consider changing our parse tree to model assignment as a
  67. // different kind of statement than an expression statement.
  68. context.node_stack().Push(parse_node, lhs_id);
  69. return true;
  70. }
  71. default:
  72. return context.TODO(parse_node, llvm::formatv("Handle {0}", token_kind));
  73. }
  74. }
  75. auto HandlePostfixOperator(Context& context, Parse::NodeId parse_node) -> bool {
  76. auto value_id = context.node_stack().PopExpr();
  77. // Figure out the operator for the token.
  78. auto token = context.parse_tree().node_token(parse_node);
  79. switch (auto token_kind = context.tokens().GetKind(token)) {
  80. case Lex::TokenKind::Star: {
  81. auto inner_type_id = ExprAsType(context, parse_node, value_id);
  82. context.AddInstAndPush(
  83. parse_node, SemIR::PointerType{parse_node, SemIR::TypeId::TypeType,
  84. inner_type_id});
  85. return true;
  86. }
  87. default:
  88. CARBON_FATAL() << "Unexpected postfix operator " << token_kind;
  89. }
  90. }
  91. auto HandlePrefixOperator(Context& context, Parse::NodeId parse_node) -> bool {
  92. auto value_id = context.node_stack().PopExpr();
  93. // Figure out the operator for the token.
  94. auto token = context.parse_tree().node_token(parse_node);
  95. switch (auto token_kind = context.tokens().GetKind(token)) {
  96. case Lex::TokenKind::Amp: {
  97. // Only durable reference expressions can have their address taken.
  98. switch (SemIR::GetExprCategory(context.sem_ir(), value_id)) {
  99. case SemIR::ExprCategory::DurableRef:
  100. case SemIR::ExprCategory::Error:
  101. break;
  102. case SemIR::ExprCategory::EphemeralRef:
  103. CARBON_DIAGNOSTIC(AddressOfEphemeralRef, Error,
  104. "Cannot take the address of a temporary object.");
  105. context.emitter().Emit(parse_node, AddressOfEphemeralRef);
  106. break;
  107. default:
  108. CARBON_DIAGNOSTIC(
  109. AddressOfNonRef, Error,
  110. "Cannot take the address of non-reference expression.");
  111. context.emitter().Emit(parse_node, AddressOfNonRef);
  112. break;
  113. }
  114. context.AddInstAndPush(
  115. parse_node,
  116. SemIR::AddressOf{
  117. parse_node,
  118. context.GetPointerType(parse_node,
  119. context.insts().Get(value_id).type_id()),
  120. value_id});
  121. return true;
  122. }
  123. case Lex::TokenKind::Const: {
  124. // `const (const T)` is probably not what the developer intended.
  125. // TODO: Detect `const (const T)*` and suggest moving the `*` inside the
  126. // parentheses.
  127. if (context.insts().Get(value_id).kind() == SemIR::ConstType::Kind) {
  128. CARBON_DIAGNOSTIC(RepeatedConst, Warning,
  129. "`const` applied repeatedly to the same type has no "
  130. "additional effect.");
  131. context.emitter().Emit(parse_node, RepeatedConst);
  132. }
  133. auto inner_type_id = ExprAsType(context, parse_node, value_id);
  134. context.AddInstAndPush(
  135. parse_node,
  136. SemIR::ConstType{parse_node, SemIR::TypeId::TypeType, inner_type_id});
  137. return true;
  138. }
  139. case Lex::TokenKind::Not:
  140. value_id = ConvertToBoolValue(context, parse_node, value_id);
  141. context.AddInstAndPush(
  142. parse_node,
  143. SemIR::UnaryOperatorNot{
  144. parse_node, context.insts().Get(value_id).type_id(), value_id});
  145. return true;
  146. case Lex::TokenKind::Star: {
  147. value_id = ConvertToValueExpr(context, value_id);
  148. auto type_id =
  149. context.GetUnqualifiedType(context.insts().Get(value_id).type_id());
  150. auto type_inst = context.insts().Get(
  151. context.sem_ir().GetTypeAllowBuiltinTypes(type_id));
  152. auto result_type_id = SemIR::TypeId::Error;
  153. if (auto pointer_type = type_inst.TryAs<SemIR::PointerType>()) {
  154. result_type_id = pointer_type->pointee_id;
  155. } else if (type_id != SemIR::TypeId::Error) {
  156. CARBON_DIAGNOSTIC(
  157. DerefOfNonPointer, Error,
  158. "Cannot dereference operand of non-pointer type `{0}`.",
  159. std::string);
  160. auto builder =
  161. context.emitter().Build(parse_node, DerefOfNonPointer,
  162. context.sem_ir().StringifyType(type_id));
  163. // TODO: Check for any facet here, rather than only a type.
  164. if (type_id == SemIR::TypeId::TypeType) {
  165. CARBON_DIAGNOSTIC(
  166. DerefOfType, Note,
  167. "To form a pointer type, write the `*` after the pointee type.");
  168. builder.Note(parse_node, DerefOfType);
  169. }
  170. builder.Emit();
  171. }
  172. context.AddInstAndPush(
  173. parse_node, SemIR::Deref{parse_node, result_type_id, value_id});
  174. return true;
  175. }
  176. default:
  177. return context.TODO(parse_node, llvm::formatv("Handle {0}", token_kind));
  178. }
  179. }
  180. auto HandleShortCircuitOperand(Context& context, Parse::NodeId parse_node)
  181. -> bool {
  182. // Convert the condition to `bool`.
  183. auto cond_value_id = context.node_stack().PopExpr();
  184. cond_value_id = ConvertToBoolValue(context, parse_node, cond_value_id);
  185. auto bool_type_id = context.insts().Get(cond_value_id).type_id();
  186. // Compute the branch value: the condition for `and`, inverted for `or`.
  187. auto token = context.parse_tree().node_token(parse_node);
  188. SemIR::InstId branch_value_id = SemIR::InstId::Invalid;
  189. auto short_circuit_result_id = SemIR::InstId::Invalid;
  190. switch (auto token_kind = context.tokens().GetKind(token)) {
  191. case Lex::TokenKind::And:
  192. branch_value_id = cond_value_id;
  193. short_circuit_result_id = context.AddInst(SemIR::BoolLiteral{
  194. parse_node, bool_type_id, SemIR::BoolValue::False});
  195. break;
  196. case Lex::TokenKind::Or:
  197. branch_value_id = context.AddInst(
  198. SemIR::UnaryOperatorNot{parse_node, bool_type_id, cond_value_id});
  199. short_circuit_result_id = context.AddInst(
  200. SemIR::BoolLiteral{parse_node, bool_type_id, SemIR::BoolValue::True});
  201. break;
  202. default:
  203. CARBON_FATAL() << "Unexpected short-circuiting operator " << token_kind;
  204. }
  205. // Create a block for the right-hand side and for the continuation.
  206. auto rhs_block_id =
  207. context.AddDominatedBlockAndBranchIf(parse_node, branch_value_id);
  208. auto end_block_id = context.AddDominatedBlockAndBranchWithArg(
  209. parse_node, short_circuit_result_id);
  210. // Push the resumption and the right-hand side blocks, and start emitting the
  211. // right-hand operand.
  212. context.inst_block_stack().Pop();
  213. context.inst_block_stack().Push(end_block_id);
  214. context.inst_block_stack().Push(rhs_block_id);
  215. context.AddCurrentCodeBlockToFunction();
  216. // Put the condition back on the stack for HandleInfixOperator.
  217. context.node_stack().Push(parse_node, cond_value_id);
  218. return true;
  219. }
  220. } // namespace Carbon::Check