handle_function.cpp 10 KB

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