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::Node parse_node) -> bool {
  8. auto rhs_id = context.node_stack().PopExpression();
  9. auto [lhs_node, lhs_id] = context.node_stack().PopExpressionWithParseNode();
  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(
  17. context, parse_node, lhs_id,
  18. context.semantics_ir().GetNode(rhs_id).type_id());
  19. rhs_id = ConvertToValueExpression(context, rhs_id);
  20. context.AddNodeAndPush(
  21. parse_node,
  22. SemIR::BinaryOperatorAdd{
  23. parse_node, context.semantics_ir().GetNode(lhs_id).type_id(),
  24. lhs_id, rhs_id});
  25. return true;
  26. case Lex::TokenKind::And:
  27. case Lex::TokenKind::Or: {
  28. // The first operand is wrapped in a ShortCircuitOperand, which we
  29. // already handled by creating a RHS block and a resumption block, which
  30. // are the current block and its enclosing block.
  31. rhs_id = ConvertToBoolValue(context, parse_node, rhs_id);
  32. // When the second operand is evaluated, the result of `and` and `or` is
  33. // its value.
  34. auto resume_block_id = context.node_block_stack().PeekOrAdd(/*depth=*/1);
  35. context.AddNode(
  36. SemIR::BranchWithArg{parse_node, resume_block_id, rhs_id});
  37. context.node_block_stack().Pop();
  38. context.AddCurrentCodeBlockToFunction();
  39. // Collect the result from either the first or second operand.
  40. context.AddNodeAndPush(
  41. parse_node,
  42. SemIR::BlockArg{parse_node,
  43. context.semantics_ir().GetNode(rhs_id).type_id(),
  44. resume_block_id});
  45. return true;
  46. }
  47. case Lex::TokenKind::Equal: {
  48. // TODO: handle complex assignment expression such as `a += 1`.
  49. if (auto lhs_cat =
  50. SemIR::GetExpressionCategory(context.semantics_ir(), lhs_id);
  51. lhs_cat != SemIR::ExpressionCategory::DurableReference &&
  52. lhs_cat != SemIR::ExpressionCategory::Error) {
  53. CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error,
  54. "Expression is not assignable.");
  55. context.emitter().Emit(lhs_node, AssignmentToNonAssignable);
  56. }
  57. // TODO: Destroy the old value before reinitializing. This will require
  58. // building the destruction code before we build the RHS subexpression.
  59. rhs_id = Initialize(context, parse_node, lhs_id, rhs_id);
  60. context.AddNode(SemIR::Assign{parse_node, lhs_id, rhs_id});
  61. // We model assignment as an expression, so we need to push a value for
  62. // it, even though it doesn't produce a value.
  63. // TODO: Consider changing our parse tree to model assignment as a
  64. // different kind of statement than an expression statement.
  65. context.node_stack().Push(parse_node, lhs_id);
  66. return true;
  67. }
  68. default:
  69. return context.TODO(parse_node, llvm::formatv("Handle {0}", token_kind));
  70. }
  71. }
  72. auto HandlePostfixOperator(Context& context, Parse::Node parse_node) -> bool {
  73. auto value_id = context.node_stack().PopExpression();
  74. // Figure out the operator for the token.
  75. auto token = context.parse_tree().node_token(parse_node);
  76. switch (auto token_kind = context.tokens().GetKind(token)) {
  77. case Lex::TokenKind::Star: {
  78. auto inner_type_id = ExpressionAsType(context, parse_node, value_id);
  79. context.AddNodeAndPush(
  80. parse_node, SemIR::PointerType{parse_node, SemIR::TypeId::TypeType,
  81. inner_type_id});
  82. return true;
  83. }
  84. default:
  85. CARBON_FATAL() << "Unexpected postfix operator " << token_kind;
  86. }
  87. }
  88. auto HandlePrefixOperator(Context& context, Parse::Node parse_node) -> bool {
  89. auto value_id = context.node_stack().PopExpression();
  90. // Figure out the operator for the token.
  91. auto token = context.parse_tree().node_token(parse_node);
  92. switch (auto token_kind = context.tokens().GetKind(token)) {
  93. case Lex::TokenKind::Amp: {
  94. // Only durable reference expressions can have their address taken.
  95. switch (SemIR::GetExpressionCategory(context.semantics_ir(), value_id)) {
  96. case SemIR::ExpressionCategory::DurableReference:
  97. case SemIR::ExpressionCategory::Error:
  98. break;
  99. case SemIR::ExpressionCategory::EphemeralReference:
  100. CARBON_DIAGNOSTIC(AddressOfEphemeralReference, Error,
  101. "Cannot take the address of a temporary object.");
  102. context.emitter().Emit(parse_node, AddressOfEphemeralReference);
  103. break;
  104. default:
  105. CARBON_DIAGNOSTIC(
  106. AddressOfNonReference, Error,
  107. "Cannot take the address of non-reference expression.");
  108. context.emitter().Emit(parse_node, AddressOfNonReference);
  109. break;
  110. }
  111. context.AddNodeAndPush(
  112. parse_node,
  113. SemIR::AddressOf{
  114. parse_node,
  115. context.GetPointerType(
  116. parse_node,
  117. context.semantics_ir().GetNode(value_id).type_id()),
  118. value_id});
  119. return true;
  120. }
  121. case Lex::TokenKind::Const: {
  122. // `const (const T)` is probably not what the developer intended.
  123. // TODO: Detect `const (const T)*` and suggest moving the `*` inside the
  124. // parentheses.
  125. if (context.semantics_ir().GetNode(value_id).kind() ==
  126. SemIR::ConstType::Kind) {
  127. CARBON_DIAGNOSTIC(RepeatedConst, Warning,
  128. "`const` applied repeatedly to the same type has no "
  129. "additional effect.");
  130. context.emitter().Emit(parse_node, RepeatedConst);
  131. }
  132. auto inner_type_id = ExpressionAsType(context, parse_node, value_id);
  133. context.AddNodeAndPush(
  134. parse_node,
  135. SemIR::ConstType{parse_node, SemIR::TypeId::TypeType, inner_type_id});
  136. return true;
  137. }
  138. case Lex::TokenKind::Not:
  139. value_id = ConvertToBoolValue(context, parse_node, value_id);
  140. context.AddNodeAndPush(
  141. parse_node,
  142. SemIR::UnaryOperatorNot{
  143. parse_node, context.semantics_ir().GetNode(value_id).type_id(),
  144. value_id});
  145. return true;
  146. case Lex::TokenKind::Star: {
  147. value_id = ConvertToValueExpression(context, value_id);
  148. auto type_id = context.GetUnqualifiedType(
  149. context.semantics_ir().GetNode(value_id).type_id());
  150. auto type_node = context.semantics_ir().GetNode(
  151. context.semantics_ir().GetTypeAllowBuiltinTypes(type_id));
  152. auto result_type_id = SemIR::TypeId::Error;
  153. if (auto pointer_type = type_node.TryAs<SemIR::PointerType>()) {
  154. result_type_id = pointer_type->pointee_id;
  155. } else if (type_id != SemIR::TypeId::Error) {
  156. CARBON_DIAGNOSTIC(
  157. DereferenceOfNonPointer, Error,
  158. "Cannot dereference operand of non-pointer type `{0}`.",
  159. std::string);
  160. auto builder = context.emitter().Build(
  161. parse_node, DereferenceOfNonPointer,
  162. context.semantics_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. DereferenceOfType, Note,
  167. "To form a pointer type, write the `*` after the pointee type.");
  168. builder.Note(parse_node, DereferenceOfType);
  169. }
  170. builder.Emit();
  171. }
  172. context.AddNodeAndPush(
  173. parse_node, SemIR::Dereference{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::Node parse_node)
  181. -> bool {
  182. // Convert the condition to `bool`.
  183. auto cond_value_id = context.node_stack().PopExpression();
  184. cond_value_id = ConvertToBoolValue(context, parse_node, cond_value_id);
  185. auto bool_type_id = context.semantics_ir().GetNode(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::NodeId branch_value_id = SemIR::NodeId::Invalid;
  189. auto short_circuit_result_id = SemIR::NodeId::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.AddNode(SemIR::BoolLiteral{
  194. parse_node, bool_type_id, SemIR::BoolValue::False});
  195. break;
  196. case Lex::TokenKind::Or:
  197. branch_value_id = context.AddNode(
  198. SemIR::UnaryOperatorNot{parse_node, bool_type_id, cond_value_id});
  199. short_circuit_result_id = context.AddNode(
  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.node_block_stack().Pop();
  213. context.node_block_stack().Push(end_block_id);
  214. context.node_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