handle_operator.cpp 9.9 KB

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