handle_function.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. #include "toolchain/sem_ir/entry_point.h"
  7. namespace Carbon::Check {
  8. // Build a FunctionDeclaration describing the signature of a function. This
  9. // handles the common logic shared by function declaration syntax and function
  10. // definition syntax.
  11. static auto BuildFunctionDeclaration(Context& context)
  12. -> std::pair<SemIR::FunctionId, SemIR::NodeId> {
  13. // TODO: This contains the IR block for the parameters and return type. At
  14. // present, it's just loose, but it's not strictly required for parameter
  15. // refs; we should either stop constructing it completely or, if it turns out
  16. // to be needed, store it. Note, the underlying issue is that the LLVM IR has
  17. // nowhere clear to emit, so changing storage would require addressing that
  18. // problem. For comparison with function calls, the IR needs to be emitted
  19. // prior to the call.
  20. context.node_block_stack().Pop();
  21. auto return_type_id = SemIR::TypeId::Invalid;
  22. auto return_slot_id = SemIR::NodeId::Invalid;
  23. if (context.parse_tree().node_kind(context.node_stack().PeekParseNode()) ==
  24. Parse::NodeKind::ReturnType) {
  25. return_slot_id = context.node_stack().Pop<Parse::NodeKind::ReturnType>();
  26. return_type_id = context.semantics_ir().GetNode(return_slot_id).type_id();
  27. // The function only has a return slot if it uses in-place initialization.
  28. if (!SemIR::GetInitializingRepresentation(context.semantics_ir(),
  29. return_type_id)
  30. .has_return_slot()) {
  31. return_slot_id = SemIR::NodeId::Invalid;
  32. }
  33. }
  34. SemIR::NodeBlockId param_refs_id =
  35. context.node_stack().Pop<Parse::NodeKind::ParameterList>();
  36. auto name_context = context.declaration_name_stack().Pop();
  37. auto fn_node =
  38. context.node_stack()
  39. .PopForSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  40. // TODO: Support out-of-line definitions, which will have a resolved
  41. // name_context. Right now, those become errors in AddNameToLookup.
  42. // Add the callable.
  43. auto function_id = context.semantics_ir().AddFunction(
  44. {.name_id = name_context.state ==
  45. DeclarationNameStack::NameContext::State::Unresolved
  46. ? name_context.unresolved_name_id
  47. : SemIR::StringId(SemIR::StringId::InvalidIndex),
  48. .param_refs_id = param_refs_id,
  49. .return_type_id = return_type_id,
  50. .return_slot_id = return_slot_id,
  51. .body_block_ids = {}});
  52. auto decl_id = context.AddNode(
  53. SemIR::Node::FunctionDeclaration::Make(fn_node, function_id));
  54. context.declaration_name_stack().AddNameToLookup(name_context, decl_id);
  55. if (SemIR::IsEntryPoint(context.semantics_ir(), function_id)) {
  56. // TODO: Update this once valid signatures for the entry point are decided.
  57. if (!context.semantics_ir().GetNodeBlock(param_refs_id).empty() ||
  58. (return_slot_id.is_valid() &&
  59. return_type_id !=
  60. context.CanonicalizeType(SemIR::NodeId::BuiltinBoolType) &&
  61. return_type_id != context.CanonicalizeTupleType(fn_node, {}))) {
  62. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  63. "Invalid signature for `Main.Run` function. Expected "
  64. "`fn ()` or `fn () -> i32`.");
  65. context.emitter().Emit(fn_node, InvalidMainRunSignature);
  66. }
  67. }
  68. return {function_id, decl_id};
  69. }
  70. auto HandleFunctionDeclaration(Context& context, Parse::Node /*parse_node*/)
  71. -> bool {
  72. BuildFunctionDeclaration(context);
  73. return true;
  74. }
  75. auto HandleFunctionDefinition(Context& context, Parse::Node parse_node)
  76. -> bool {
  77. SemIR::FunctionId function_id =
  78. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  79. // If the `}` of the function is reachable, reject if we need a return value
  80. // and otherwise add an implicit `return;`.
  81. if (context.is_current_position_reachable()) {
  82. if (context.semantics_ir()
  83. .GetFunction(function_id)
  84. .return_type_id.is_valid()) {
  85. CARBON_DIAGNOSTIC(
  86. MissingReturnStatement, Error,
  87. "Missing `return` at end of function with declared return type.");
  88. context.emitter().Emit(parse_node, MissingReturnStatement);
  89. } else {
  90. context.AddNode(SemIR::Node::Return::Make(parse_node));
  91. }
  92. }
  93. context.PopScope();
  94. context.node_block_stack().Pop();
  95. context.return_scope_stack().pop_back();
  96. return true;
  97. }
  98. auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node)
  99. -> bool {
  100. // Process the declaration portion of the function.
  101. auto [function_id, decl_id] = BuildFunctionDeclaration(context);
  102. const auto& function = context.semantics_ir().GetFunction(function_id);
  103. // Create the function scope and the entry block.
  104. context.return_scope_stack().push_back(decl_id);
  105. context.node_block_stack().Push();
  106. context.PushScope();
  107. context.AddCurrentCodeBlockToFunction();
  108. // Bring the parameters into scope.
  109. for (auto ref_id :
  110. context.semantics_ir().GetNodeBlock(function.param_refs_id)) {
  111. auto ref = context.semantics_ir().GetNode(ref_id);
  112. auto name_id = ref.GetAsParameter();
  113. context.AddNameToLookup(ref.parse_node(), name_id, ref_id);
  114. }
  115. context.node_stack().Push(parse_node, function_id);
  116. return true;
  117. }
  118. auto HandleFunctionIntroducer(Context& context, Parse::Node parse_node)
  119. -> bool {
  120. // Create a node block to hold the nodes created as part of the function
  121. // signature, such as parameter and return types.
  122. context.node_block_stack().Push();
  123. // Push the bracketing node.
  124. context.node_stack().Push(parse_node);
  125. // A name should always follow.
  126. context.declaration_name_stack().Push();
  127. return true;
  128. }
  129. auto HandleReturnType(Context& context, Parse::Node parse_node) -> bool {
  130. // Propagate the type expression.
  131. auto [type_parse_node, type_node_id] =
  132. context.node_stack().PopExpressionWithParseNode();
  133. auto type_id = ExpressionAsType(context, type_parse_node, type_node_id);
  134. // TODO: Use a dedicated node rather than VarStorage here.
  135. context.AddNodeAndPush(
  136. parse_node,
  137. SemIR::Node::VarStorage::Make(
  138. parse_node, type_id, context.semantics_ir().AddString("return")));
  139. return true;
  140. }
  141. } // namespace Carbon::Check