handle_function.cpp 9.3 KB

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