handle_function.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. auto [return_node, return_storage_id] =
  26. context.node_stack().PopWithParseNode<Parse::NodeKind::ReturnType>();
  27. auto return_node_copy = return_node;
  28. return_type_id =
  29. context.semantics_ir().GetNode(return_storage_id).type_id();
  30. if (!context.TryToCompleteType(return_type_id, [&] {
  31. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  32. "Function returns incomplete type `{0}`.",
  33. std::string);
  34. return context.emitter().Build(
  35. return_node_copy, IncompleteTypeInFunctionReturnType,
  36. context.semantics_ir().StringifyType(return_type_id, true));
  37. })) {
  38. return_type_id = SemIR::TypeId::Error;
  39. } else if (!SemIR::GetInitializingRepresentation(context.semantics_ir(),
  40. return_type_id)
  41. .has_return_slot()) {
  42. // The function only has a return slot if it uses in-place initialization.
  43. } else {
  44. return_slot_id = return_storage_id;
  45. }
  46. }
  47. SemIR::NodeBlockId param_refs_id =
  48. context.node_stack().Pop<Parse::NodeKind::ParameterList>();
  49. auto name_context = context.declaration_name_stack().Pop();
  50. auto fn_node =
  51. context.node_stack()
  52. .PopForSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  53. // TODO: Support out-of-line definitions, which will have a resolved
  54. // name_context. Right now, those become errors in AddNameToLookup.
  55. // Add the callable.
  56. auto function_id = context.semantics_ir().AddFunction(
  57. {.name_id = name_context.state ==
  58. DeclarationNameStack::NameContext::State::Unresolved
  59. ? name_context.unresolved_name_id
  60. : SemIR::StringId(SemIR::StringId::InvalidIndex),
  61. .param_refs_id = param_refs_id,
  62. .return_type_id = return_type_id,
  63. .return_slot_id = return_slot_id,
  64. .body_block_ids = {}});
  65. auto decl_id = context.AddNode(SemIR::FunctionDeclaration(
  66. fn_node, context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  67. function_id));
  68. context.declaration_name_stack().AddNameToLookup(name_context, decl_id);
  69. if (SemIR::IsEntryPoint(context.semantics_ir(), function_id)) {
  70. // TODO: Update this once valid signatures for the entry point are decided.
  71. if (!context.semantics_ir().GetNodeBlock(param_refs_id).empty() ||
  72. (return_slot_id.is_valid() &&
  73. return_type_id !=
  74. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  75. return_type_id != context.CanonicalizeTupleType(fn_node, {}))) {
  76. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  77. "Invalid signature for `Main.Run` function. Expected "
  78. "`fn ()` or `fn () -> i32`.");
  79. context.emitter().Emit(fn_node, InvalidMainRunSignature);
  80. }
  81. }
  82. return {function_id, decl_id};
  83. }
  84. auto HandleFunctionDeclaration(Context& context, Parse::Node /*parse_node*/)
  85. -> bool {
  86. BuildFunctionDeclaration(context);
  87. return true;
  88. }
  89. auto HandleFunctionDefinition(Context& context, Parse::Node parse_node)
  90. -> bool {
  91. SemIR::FunctionId function_id =
  92. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  93. // If the `}` of the function is reachable, reject if we need a return value
  94. // and otherwise add an implicit `return;`.
  95. if (context.is_current_position_reachable()) {
  96. if (context.semantics_ir()
  97. .GetFunction(function_id)
  98. .return_type_id.is_valid()) {
  99. CARBON_DIAGNOSTIC(
  100. MissingReturnStatement, Error,
  101. "Missing `return` at end of function with declared return type.");
  102. context.emitter().Emit(parse_node, MissingReturnStatement);
  103. } else {
  104. context.AddNode(SemIR::Return(parse_node));
  105. }
  106. }
  107. context.PopScope();
  108. context.node_block_stack().Pop();
  109. context.return_scope_stack().pop_back();
  110. return true;
  111. }
  112. auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node)
  113. -> bool {
  114. // Process the declaration portion of the function.
  115. auto [function_id, decl_id] = BuildFunctionDeclaration(context);
  116. const auto& function = context.semantics_ir().GetFunction(function_id);
  117. // Create the function scope and the entry block.
  118. context.return_scope_stack().push_back(decl_id);
  119. context.node_block_stack().Push();
  120. context.PushScope();
  121. context.AddCurrentCodeBlockToFunction();
  122. // Bring the parameters into scope.
  123. for (auto param_id :
  124. context.semantics_ir().GetNodeBlock(function.param_refs_id)) {
  125. auto param = context.semantics_ir().GetNodeAs<SemIR::Parameter>(param_id);
  126. // The parameter types need to be complete.
  127. context.TryToCompleteType(param.type_id, [&] {
  128. CARBON_DIAGNOSTIC(
  129. IncompleteTypeInFunctionParam, Error,
  130. "Parameter has incomplete type `{0}` in function definition.",
  131. std::string);
  132. return context.emitter().Build(
  133. param.parse_node, IncompleteTypeInFunctionParam,
  134. context.semantics_ir().StringifyType(param.type_id, true));
  135. });
  136. context.AddNameToLookup(param.parse_node, param.name_id, param_id);
  137. }
  138. context.node_stack().Push(parse_node, function_id);
  139. return true;
  140. }
  141. auto HandleFunctionIntroducer(Context& context, Parse::Node parse_node)
  142. -> bool {
  143. // Create a node block to hold the nodes created as part of the function
  144. // signature, such as parameter and return types.
  145. context.node_block_stack().Push();
  146. // Push the bracketing node.
  147. context.node_stack().Push(parse_node);
  148. // A name should always follow.
  149. context.declaration_name_stack().Push();
  150. return true;
  151. }
  152. auto HandleReturnType(Context& context, Parse::Node parse_node) -> bool {
  153. // Propagate the type expression.
  154. auto [type_parse_node, type_node_id] =
  155. context.node_stack().PopExpressionWithParseNode();
  156. auto type_id = ExpressionAsType(context, type_parse_node, type_node_id);
  157. // TODO: Use a dedicated node rather than VarStorage here.
  158. context.AddNodeAndPush(
  159. parse_node,
  160. SemIR::VarStorage(parse_node, type_id,
  161. context.semantics_ir().AddString("return")));
  162. return true;
  163. }
  164. } // namespace Carbon::Check