handle_function.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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, bool is_definition)
  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 = context.nodes().Get(return_storage_id).type_id();
  29. if (!context.TryToCompleteType(return_type_id, [&] {
  30. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  31. "Function returns incomplete type `{0}`.",
  32. std::string);
  33. return context.emitter().Build(
  34. return_node_copy, IncompleteTypeInFunctionReturnType,
  35. context.sem_ir().StringifyType(return_type_id, true));
  36. })) {
  37. return_type_id = SemIR::TypeId::Error;
  38. } else if (!SemIR::GetInitializingRepresentation(context.sem_ir(),
  39. return_type_id)
  40. .has_return_slot()) {
  41. // The function only has a return slot if it uses in-place initialization.
  42. } else {
  43. return_slot_id = return_storage_id;
  44. }
  45. }
  46. SemIR::NodeBlockId param_refs_id =
  47. context.node_stack().Pop<Parse::NodeKind::ParameterList>();
  48. auto name_context = context.declaration_name_stack().Pop();
  49. auto fn_node =
  50. context.node_stack()
  51. .PopForSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  52. // Add the function declaration.
  53. auto function_decl = SemIR::FunctionDeclaration{
  54. fn_node, context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  55. SemIR::FunctionId::Invalid};
  56. auto function_decl_id = context.AddNode(function_decl);
  57. // Check whether this is a redeclaration.
  58. auto existing_id = context.declaration_name_stack().LookupOrAddName(
  59. name_context, function_decl_id);
  60. if (existing_id.is_valid()) {
  61. if (auto existing_function_decl =
  62. context.nodes()
  63. .Get(existing_id)
  64. .TryAs<SemIR::FunctionDeclaration>()) {
  65. // This is a redeclaration of an existing function.
  66. function_decl.function_id = existing_function_decl->function_id;
  67. // TODO: Check that the signature matches!
  68. // Track the signature from the definition, so that IDs in the body match
  69. // IDs in the signature.
  70. if (is_definition) {
  71. auto& function_info =
  72. context.functions().Get(function_decl.function_id);
  73. function_info.param_refs_id = param_refs_id;
  74. function_info.return_type_id = return_type_id;
  75. function_info.return_slot_id = return_slot_id;
  76. }
  77. } else {
  78. // This is a redeclaration of something other than a function.
  79. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  80. }
  81. }
  82. // Create a new function if this isn't a valid redeclaration.
  83. if (!function_decl.function_id.is_valid()) {
  84. function_decl.function_id = context.functions().Add(
  85. {.name_id = name_context.state ==
  86. DeclarationNameStack::NameContext::State::Unresolved
  87. ? name_context.unresolved_name_id
  88. : StringId::Invalid,
  89. .param_refs_id = param_refs_id,
  90. .return_type_id = return_type_id,
  91. .return_slot_id = return_slot_id});
  92. }
  93. // Write the function ID into the FunctionDeclaration.
  94. context.nodes().Set(function_decl_id, function_decl);
  95. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  96. // TODO: Update this once valid signatures for the entry point are decided.
  97. if (!context.node_blocks().Get(param_refs_id).empty() ||
  98. (return_slot_id.is_valid() &&
  99. return_type_id !=
  100. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  101. return_type_id != context.CanonicalizeTupleType(fn_node, {}))) {
  102. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  103. "Invalid signature for `Main.Run` function. Expected "
  104. "`fn ()` or `fn () -> i32`.");
  105. context.emitter().Emit(fn_node, InvalidMainRunSignature);
  106. }
  107. }
  108. return {function_decl.function_id, function_decl_id};
  109. }
  110. auto HandleFunctionDeclaration(Context& context, Parse::Node /*parse_node*/)
  111. -> bool {
  112. BuildFunctionDeclaration(context, /*is_definition=*/false);
  113. return true;
  114. }
  115. auto HandleFunctionDefinition(Context& context, Parse::Node parse_node)
  116. -> bool {
  117. SemIR::FunctionId function_id =
  118. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  119. // If the `}` of the function is reachable, reject if we need a return value
  120. // and otherwise add an implicit `return;`.
  121. if (context.is_current_position_reachable()) {
  122. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  123. CARBON_DIAGNOSTIC(
  124. MissingReturnStatement, Error,
  125. "Missing `return` at end of function with declared return type.");
  126. context.emitter().Emit(parse_node, MissingReturnStatement);
  127. } else {
  128. context.AddNode(SemIR::Return{parse_node});
  129. }
  130. }
  131. context.PopScope();
  132. context.node_block_stack().Pop();
  133. context.return_scope_stack().pop_back();
  134. return true;
  135. }
  136. auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node)
  137. -> bool {
  138. // Process the declaration portion of the function.
  139. auto [function_id, decl_id] =
  140. BuildFunctionDeclaration(context, /*is_definition=*/true);
  141. auto& function = context.functions().Get(function_id);
  142. // Track that this declaration is the definition.
  143. if (function.definition_id.is_valid()) {
  144. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  145. "Redefinition of function {0}.", llvm::StringRef);
  146. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  147. "Previous definition was here.");
  148. context.emitter()
  149. .Build(parse_node, FunctionRedefinition,
  150. context.strings().Get(function.name_id))
  151. .Note(context.nodes().Get(function.definition_id).parse_node(),
  152. FunctionPreviousDefinition)
  153. .Emit();
  154. } else {
  155. function.definition_id = decl_id;
  156. }
  157. // Create the function scope and the entry block.
  158. context.return_scope_stack().push_back(decl_id);
  159. context.node_block_stack().Push();
  160. context.PushScope(decl_id);
  161. context.AddCurrentCodeBlockToFunction();
  162. // Bring the parameters into scope.
  163. for (auto param_id : context.node_blocks().Get(function.param_refs_id)) {
  164. auto param = context.nodes().GetAs<SemIR::Parameter>(param_id);
  165. // The parameter types need to be complete.
  166. context.TryToCompleteType(param.type_id, [&] {
  167. CARBON_DIAGNOSTIC(
  168. IncompleteTypeInFunctionParam, Error,
  169. "Parameter has incomplete type `{0}` in function definition.",
  170. std::string);
  171. return context.emitter().Build(
  172. param.parse_node, IncompleteTypeInFunctionParam,
  173. context.sem_ir().StringifyType(param.type_id, true));
  174. });
  175. context.AddNameToLookup(param.parse_node, param.name_id, param_id);
  176. }
  177. context.node_stack().Push(parse_node, function_id);
  178. return true;
  179. }
  180. auto HandleFunctionIntroducer(Context& context, Parse::Node parse_node)
  181. -> bool {
  182. // Create a node block to hold the nodes created as part of the function
  183. // signature, such as parameter and return types.
  184. context.node_block_stack().Push();
  185. // Push the bracketing node.
  186. context.node_stack().Push(parse_node);
  187. // A name should always follow.
  188. context.declaration_name_stack().Push();
  189. return true;
  190. }
  191. auto HandleReturnType(Context& context, Parse::Node parse_node) -> bool {
  192. // Propagate the type expression.
  193. auto [type_parse_node, type_node_id] =
  194. context.node_stack().PopExpressionWithParseNode();
  195. auto type_id = ExpressionAsType(context, type_parse_node, type_node_id);
  196. // TODO: Use a dedicated node rather than VarStorage here.
  197. context.AddNodeAndPush(
  198. parse_node,
  199. SemIR::VarStorage{parse_node, type_id, context.strings().Add("return")});
  200. return true;
  201. }
  202. } // namespace Carbon::Check