handle_function.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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().Pop();
  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. return true;
  121. }
  122. auto HandleFunctionDefinition(Context& context, Parse::Node parse_node)
  123. -> bool {
  124. SemIR::FunctionId function_id =
  125. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  126. // If the `}` of the function is reachable, reject if we need a return value
  127. // and otherwise add an implicit `return;`.
  128. if (context.is_current_position_reachable()) {
  129. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  130. CARBON_DIAGNOSTIC(
  131. MissingReturnStatement, Error,
  132. "Missing `return` at end of function with declared return type.");
  133. context.emitter().Emit(parse_node, MissingReturnStatement);
  134. } else {
  135. context.AddInst(SemIR::Return{parse_node});
  136. }
  137. }
  138. context.PopScope();
  139. context.inst_block_stack().Pop();
  140. context.return_scope_stack().pop_back();
  141. return true;
  142. }
  143. auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node)
  144. -> bool {
  145. // Process the declaration portion of the function.
  146. auto [function_id, decl_id] =
  147. BuildFunctionDeclaration(context, /*is_definition=*/true);
  148. auto& function = context.functions().Get(function_id);
  149. // Track that this declaration is the definition.
  150. if (function.definition_id.is_valid()) {
  151. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  152. "Redefinition of function {0}.", llvm::StringRef);
  153. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  154. "Previous definition was here.");
  155. context.emitter()
  156. .Build(parse_node, FunctionRedefinition,
  157. context.identifiers().Get(function.name_id))
  158. .Note(context.insts().Get(function.definition_id).parse_node(),
  159. FunctionPreviousDefinition)
  160. .Emit();
  161. } else {
  162. function.definition_id = decl_id;
  163. }
  164. // Create the function scope and the entry block.
  165. context.return_scope_stack().push_back(decl_id);
  166. context.inst_block_stack().Push();
  167. context.PushScope(decl_id);
  168. context.AddCurrentCodeBlockToFunction();
  169. // Bring the implicit and explicit parameters into scope.
  170. for (auto param_id : llvm::concat<SemIR::InstId>(
  171. context.inst_blocks().Get(function.implicit_param_refs_id),
  172. context.inst_blocks().Get(function.param_refs_id))) {
  173. auto param = context.insts().Get(param_id);
  174. // The parameter types need to be complete.
  175. context.TryToCompleteType(param.type_id(), [&] {
  176. CARBON_DIAGNOSTIC(
  177. IncompleteTypeInFunctionParam, Error,
  178. "Parameter has incomplete type `{0}` in function definition.",
  179. std::string);
  180. return context.emitter().Build(
  181. param.parse_node(), IncompleteTypeInFunctionParam,
  182. context.sem_ir().StringifyType(param.type_id(), true));
  183. });
  184. if (auto fn_param = param.TryAs<SemIR::Parameter>()) {
  185. context.AddNameToLookup(fn_param->parse_node, fn_param->name_id,
  186. param_id);
  187. } else if (auto self_param = param.TryAs<SemIR::SelfParameter>()) {
  188. // TODO: This will shadow a local variable named `r#self`, but should
  189. // not. See #2984 and the corresponding code in
  190. // HandleSelfTypeNameExpression.
  191. context.AddNameToLookup(
  192. self_param->parse_node,
  193. context.identifiers().Add(SemIR::SelfParameter::Name), param_id);
  194. } else {
  195. CARBON_FATAL() << "Unexpected kind of parameter in function definition "
  196. << param;
  197. }
  198. }
  199. context.node_stack().Push(parse_node, function_id);
  200. return true;
  201. }
  202. auto HandleFunctionIntroducer(Context& context, Parse::Node parse_node)
  203. -> bool {
  204. // Create an instruction block to hold the instructions created as part of the
  205. // function signature, such as parameter and return types.
  206. context.inst_block_stack().Push();
  207. // Push the bracketing node.
  208. context.node_stack().Push(parse_node);
  209. // A name should always follow.
  210. context.declaration_name_stack().Push();
  211. return true;
  212. }
  213. auto HandleReturnType(Context& context, Parse::Node parse_node) -> bool {
  214. // Propagate the type expression.
  215. auto [type_parse_node, type_inst_id] =
  216. context.node_stack().PopExpressionWithParseNode();
  217. auto type_id = ExpressionAsType(context, type_parse_node, type_inst_id);
  218. // TODO: Use a dedicated instruction rather than VarStorage here.
  219. context.AddInstAndPush(
  220. parse_node, SemIR::VarStorage{parse_node, type_id,
  221. context.identifiers().Add("return")});
  222. return true;
  223. }
  224. } // namespace Carbon::Check