handle_function.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 FunctionDecl 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 BuildFunctionDecl(Context& context, bool is_definition)
  12. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  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.inst_block_stack().Pop();
  21. auto return_type_id = SemIR::TypeId::Invalid;
  22. auto return_slot_id = SemIR::InstId::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.insts().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::InstBlockId param_refs_id =
  47. context.node_stack().Pop<Parse::NodeKind::ParamList>();
  48. SemIR::InstBlockId implicit_param_refs_id =
  49. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  50. SemIR::InstBlockId::Empty);
  51. auto name_context = context.decl_name_stack().FinishName();
  52. auto fn_node =
  53. context.node_stack()
  54. .PopForSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  55. // Add the function declaration.
  56. auto function_decl = SemIR::FunctionDecl{
  57. fn_node, context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  58. SemIR::FunctionId::Invalid};
  59. auto function_decl_id = context.AddInst(function_decl);
  60. // Check whether this is a redeclaration.
  61. auto existing_id =
  62. context.decl_name_stack().LookupOrAddName(name_context, function_decl_id);
  63. if (existing_id.is_valid()) {
  64. if (auto existing_function_decl =
  65. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  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.functions().Get(function_decl.function_id);
  74. function_info.implicit_param_refs_id = implicit_param_refs_id;
  75. function_info.param_refs_id = param_refs_id;
  76. function_info.return_type_id = return_type_id;
  77. function_info.return_slot_id = return_slot_id;
  78. }
  79. } else {
  80. // This is a redeclaration of something other than a function.
  81. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  82. }
  83. }
  84. // Create a new function if this isn't a valid redeclaration.
  85. if (!function_decl.function_id.is_valid()) {
  86. function_decl.function_id = context.functions().Add(
  87. {.name_id =
  88. name_context.state == DeclNameStack::NameContext::State::Unresolved
  89. ? name_context.unresolved_name_id
  90. : SemIR::NameId::Invalid,
  91. .decl_id = function_decl_id,
  92. .implicit_param_refs_id = implicit_param_refs_id,
  93. .param_refs_id = param_refs_id,
  94. .return_type_id = return_type_id,
  95. .return_slot_id = return_slot_id});
  96. }
  97. // Write the function ID into the FunctionDecl.
  98. context.insts().Set(function_decl_id, function_decl);
  99. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  100. // TODO: Update this once valid signatures for the entry point are decided.
  101. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  102. !context.inst_blocks().Get(param_refs_id).empty() ||
  103. (return_slot_id.is_valid() &&
  104. return_type_id !=
  105. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  106. return_type_id != context.CanonicalizeTupleType(fn_node, {}))) {
  107. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  108. "Invalid signature for `Main.Run` function. Expected "
  109. "`fn ()` or `fn () -> i32`.");
  110. context.emitter().Emit(fn_node, InvalidMainRunSignature);
  111. }
  112. }
  113. return {function_decl.function_id, function_decl_id};
  114. }
  115. auto HandleFunctionDecl(Context& context, Parse::Node /*parse_node*/) -> bool {
  116. BuildFunctionDecl(context, /*is_definition=*/false);
  117. context.decl_name_stack().PopScope();
  118. return true;
  119. }
  120. auto HandleFunctionDefinition(Context& context, Parse::Node parse_node)
  121. -> bool {
  122. SemIR::FunctionId function_id =
  123. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  124. // If the `}` of the function is reachable, reject if we need a return value
  125. // and otherwise add an implicit `return;`.
  126. if (context.is_current_position_reachable()) {
  127. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  128. CARBON_DIAGNOSTIC(
  129. MissingReturnStatement, Error,
  130. "Missing `return` at end of function with declared return type.");
  131. context.emitter().Emit(parse_node, MissingReturnStatement);
  132. } else {
  133. context.AddInst(SemIR::Return{parse_node});
  134. }
  135. }
  136. context.PopScope();
  137. context.inst_block_stack().Pop();
  138. context.return_scope_stack().pop_back();
  139. context.decl_name_stack().PopScope();
  140. return true;
  141. }
  142. auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node)
  143. -> bool {
  144. // Process the declaration portion of the function.
  145. auto [function_id, decl_id] =
  146. BuildFunctionDecl(context, /*is_definition=*/true);
  147. auto& function = context.functions().Get(function_id);
  148. // Track that this declaration is the definition.
  149. if (function.definition_id.is_valid()) {
  150. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  151. "Redefinition of function {0}.", std::string);
  152. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  153. "Previous definition was here.");
  154. context.emitter()
  155. .Build(parse_node, FunctionRedefinition,
  156. context.names().GetFormatted(function.name_id).str())
  157. .Note(context.insts().Get(function.definition_id).parse_node(),
  158. FunctionPreviousDefinition)
  159. .Emit();
  160. } else {
  161. function.definition_id = decl_id;
  162. }
  163. // Create the function scope and the entry block.
  164. context.return_scope_stack().push_back({.decl_id = decl_id});
  165. context.inst_block_stack().Push();
  166. context.PushScope(decl_id);
  167. context.AddCurrentCodeBlockToFunction();
  168. // Bring the implicit and explicit parameters into scope.
  169. for (auto param_id : llvm::concat<SemIR::InstId>(
  170. context.inst_blocks().Get(function.implicit_param_refs_id),
  171. context.inst_blocks().Get(function.param_refs_id))) {
  172. auto param = context.insts().Get(param_id);
  173. // The parameter types need to be complete.
  174. context.TryToCompleteType(param.type_id(), [&] {
  175. CARBON_DIAGNOSTIC(
  176. IncompleteTypeInFunctionParam, Error,
  177. "Parameter has incomplete type `{0}` in function definition.",
  178. std::string);
  179. return context.emitter().Build(
  180. param.parse_node(), IncompleteTypeInFunctionParam,
  181. context.sem_ir().StringifyType(param.type_id(), true));
  182. });
  183. if (auto fn_param = param.TryAs<SemIR::Param>()) {
  184. context.AddNameToLookup(fn_param->parse_node, fn_param->name_id,
  185. param_id);
  186. } else if (auto self_param = param.TryAs<SemIR::SelfParam>()) {
  187. context.AddNameToLookup(self_param->parse_node, SemIR::NameId::SelfValue,
  188. param_id);
  189. } else {
  190. CARBON_FATAL() << "Unexpected kind of parameter in function definition "
  191. << param;
  192. }
  193. }
  194. context.node_stack().Push(parse_node, function_id);
  195. return true;
  196. }
  197. auto HandleFunctionIntroducer(Context& context, Parse::Node parse_node)
  198. -> bool {
  199. // Create an instruction block to hold the instructions created as part of the
  200. // function signature, such as parameter and return types.
  201. context.inst_block_stack().Push();
  202. // Push the bracketing node.
  203. context.node_stack().Push(parse_node);
  204. // A name should always follow.
  205. context.decl_name_stack().PushScopeAndStartName();
  206. return true;
  207. }
  208. auto HandleReturnType(Context& context, Parse::Node parse_node) -> bool {
  209. // Propagate the type expression.
  210. auto [type_parse_node, type_inst_id] =
  211. context.node_stack().PopExprWithParseNode();
  212. auto type_id = ExprAsType(context, type_parse_node, type_inst_id);
  213. // TODO: Use a dedicated instruction rather than VarStorage here.
  214. context.AddInstAndPush(
  215. parse_node,
  216. SemIR::VarStorage{parse_node, type_id, SemIR::NameId::ReturnSlot});
  217. return true;
  218. }
  219. } // namespace Carbon::Check