handle_function.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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/check/decl_name_stack.h"
  7. #include "toolchain/check/function.h"
  8. #include "toolchain/check/interface.h"
  9. #include "toolchain/check/modifiers.h"
  10. #include "toolchain/parse/tree_node_location_translator.h"
  11. #include "toolchain/sem_ir/entry_point.h"
  12. #include "toolchain/sem_ir/function.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. auto HandleFunctionIntroducer(Context& context,
  17. Parse::FunctionIntroducerId node_id) -> bool {
  18. // Create an instruction block to hold the instructions created as part of the
  19. // function signature, such as parameter and return types.
  20. context.inst_block_stack().Push();
  21. // Push the bracketing node.
  22. context.node_stack().Push(node_id);
  23. // Optional modifiers and the name follow.
  24. context.decl_state_stack().Push(DeclState::Fn);
  25. context.decl_name_stack().PushScopeAndStartName();
  26. return true;
  27. }
  28. auto HandleReturnType(Context& context, Parse::ReturnTypeId node_id) -> bool {
  29. // Propagate the type expression.
  30. auto [type_node_id, type_inst_id] = context.node_stack().PopExprWithNodeId();
  31. auto type_id = ExprAsType(context, type_node_id, type_inst_id);
  32. // TODO: Use a dedicated instruction rather than VarStorage here.
  33. context.AddInstAndPush(
  34. {node_id, SemIR::VarStorage{type_id, SemIR::NameId::ReturnSlot}});
  35. return true;
  36. }
  37. static auto DiagnoseModifiers(Context& context,
  38. SemIR::NameScopeId target_scope_id)
  39. -> KeywordModifierSet {
  40. const Lex::TokenKind decl_kind = Lex::TokenKind::Fn;
  41. CheckAccessModifiersOnDecl(context, decl_kind, target_scope_id);
  42. LimitModifiersOnDecl(context,
  43. KeywordModifierSet::Access | KeywordModifierSet::Method |
  44. KeywordModifierSet::Interface,
  45. decl_kind);
  46. CheckMethodModifiersOnFunction(context, target_scope_id);
  47. RequireDefaultFinalOnlyInInterfaces(context, decl_kind, target_scope_id);
  48. return context.decl_state_stack().innermost().modifier_set;
  49. }
  50. // Build a FunctionDecl describing the signature of a function. This
  51. // handles the common logic shared by function declaration syntax and function
  52. // definition syntax.
  53. static auto BuildFunctionDecl(Context& context,
  54. Parse::AnyFunctionDeclId node_id,
  55. bool is_definition)
  56. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  57. auto decl_block_id = context.inst_block_stack().Pop();
  58. auto return_type_id = SemIR::TypeId::Invalid;
  59. auto return_slot_id = SemIR::InstId::Invalid;
  60. if (auto [return_node, return_storage_id] =
  61. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  62. return_storage_id) {
  63. return_type_id = context.insts().Get(*return_storage_id).type_id();
  64. return_type_id = context.AsCompleteType(return_type_id, [&] {
  65. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  66. "Function returns incomplete type `{0}`.",
  67. SemIR::TypeId);
  68. return context.emitter().Build(
  69. return_node, IncompleteTypeInFunctionReturnType, return_type_id);
  70. });
  71. if (!SemIR::GetInitRepr(context.sem_ir(), return_type_id)
  72. .has_return_slot()) {
  73. // The function only has a return slot if it uses in-place initialization.
  74. } else {
  75. return_slot_id = *return_storage_id;
  76. }
  77. }
  78. SemIR::InstBlockId param_refs_id =
  79. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  80. SemIR::InstBlockId implicit_param_refs_id =
  81. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  82. SemIR::InstBlockId::Empty);
  83. auto name_context = context.decl_name_stack().FinishName();
  84. context.node_stack()
  85. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  86. // Process modifiers.
  87. auto modifiers = DiagnoseModifiers(context, name_context.target_scope_id);
  88. if (!!(modifiers & KeywordModifierSet::Access)) {
  89. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  90. ModifierOrder::Access),
  91. "access modifier");
  92. }
  93. if (!!(modifiers & KeywordModifierSet::Extern)) {
  94. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  95. ModifierOrder::Extern),
  96. "extern modifier");
  97. }
  98. if (!!(modifiers & KeywordModifierSet::Method)) {
  99. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  100. ModifierOrder::Decl),
  101. "method modifier");
  102. }
  103. if (!!(modifiers & KeywordModifierSet::Interface)) {
  104. // TODO: Once we are saving the modifiers for a function, add check that
  105. // the function may only be defined if it is marked `default` or `final`.
  106. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  107. ModifierOrder::Decl),
  108. "interface modifier");
  109. }
  110. context.decl_state_stack().Pop(DeclState::Fn);
  111. // Add the function declaration.
  112. auto function_decl = SemIR::FunctionDecl{
  113. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  114. SemIR::FunctionId::Invalid, decl_block_id};
  115. auto function_info = SemIR::Function{
  116. .name_id = name_context.name_id_for_new_inst(),
  117. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  118. .decl_id = context.AddPlaceholderInst({node_id, function_decl}),
  119. .implicit_param_refs_id = implicit_param_refs_id,
  120. .param_refs_id = param_refs_id,
  121. .return_type_id = return_type_id,
  122. .return_slot_id = return_slot_id};
  123. if (is_definition) {
  124. function_info.definition_id = function_info.decl_id;
  125. }
  126. // At interface scope, a function declaration introduces an associated
  127. // function.
  128. auto lookup_result_id = function_info.decl_id;
  129. if (name_context.enclosing_scope_id_for_new_inst().is_valid() &&
  130. !name_context.has_qualifiers) {
  131. auto scope_inst_id = context.name_scopes().GetInstIdIfValid(
  132. name_context.enclosing_scope_id_for_new_inst());
  133. if (auto interface_scope =
  134. context.insts().TryGetAsIfValid<SemIR::InterfaceDecl>(
  135. scope_inst_id)) {
  136. lookup_result_id = BuildAssociatedEntity(
  137. context, interface_scope->interface_id, function_info.decl_id);
  138. }
  139. }
  140. // Check whether this is a redeclaration.
  141. auto existing_id =
  142. context.decl_name_stack().LookupOrAddName(name_context, lookup_result_id);
  143. if (existing_id.is_valid()) {
  144. if (auto existing_function_decl =
  145. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  146. if (MergeFunctionRedecl(context, node_id, function_info,
  147. existing_function_decl->function_id,
  148. is_definition)) {
  149. // When merging, use the existing function rather than adding a new one.
  150. function_decl.function_id = existing_function_decl->function_id;
  151. }
  152. } else {
  153. // This is a redeclaration of something other than a function. This
  154. // includes the case where an associated function redeclares another
  155. // associated function.
  156. context.DiagnoseDuplicateName(function_info.decl_id, existing_id);
  157. }
  158. }
  159. // Create a new function if this isn't a valid redeclaration.
  160. if (!function_decl.function_id.is_valid()) {
  161. function_decl.function_id = context.functions().Add(function_info);
  162. }
  163. // Write the function ID into the FunctionDecl.
  164. context.ReplaceInstBeforeConstantUse(function_info.decl_id,
  165. {node_id, function_decl});
  166. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  167. // TODO: Update this once valid signatures for the entry point are decided.
  168. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  169. !context.inst_blocks().Get(param_refs_id).empty() ||
  170. (return_slot_id.is_valid() &&
  171. return_type_id !=
  172. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  173. return_type_id != context.GetTupleType({}))) {
  174. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  175. "Invalid signature for `Main.Run` function. Expected "
  176. "`fn ()` or `fn () -> i32`.");
  177. context.emitter().Emit(node_id, InvalidMainRunSignature);
  178. }
  179. }
  180. return {function_decl.function_id, function_info.decl_id};
  181. }
  182. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId node_id)
  183. -> bool {
  184. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  185. context.decl_name_stack().PopScope();
  186. return true;
  187. }
  188. auto HandleFunctionDefinitionStart(Context& context,
  189. Parse::FunctionDefinitionStartId node_id)
  190. -> bool {
  191. // Process the declaration portion of the function.
  192. auto [function_id, decl_id] =
  193. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  194. auto& function = context.functions().Get(function_id);
  195. // Create the function scope and the entry block.
  196. context.return_scope_stack().push_back({.decl_id = decl_id});
  197. context.inst_block_stack().Push();
  198. context.scope_stack().Push(decl_id);
  199. context.AddCurrentCodeBlockToFunction();
  200. // Bring the implicit and explicit parameters into scope.
  201. for (auto param_id : llvm::concat<SemIR::InstId>(
  202. context.inst_blocks().Get(function.implicit_param_refs_id),
  203. context.inst_blocks().Get(function.param_refs_id))) {
  204. auto param = context.insts().Get(param_id);
  205. // Find the parameter in the pattern.
  206. // TODO: More general pattern handling?
  207. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  208. param_id = addr_pattern->inner_id;
  209. param = context.insts().Get(param_id);
  210. }
  211. // The parameter types need to be complete.
  212. context.TryToCompleteType(param.type_id(), [&] {
  213. CARBON_DIAGNOSTIC(
  214. IncompleteTypeInFunctionParam, Error,
  215. "Parameter has incomplete type `{0}` in function definition.",
  216. SemIR::TypeId);
  217. return context.emitter().Build(param_id, IncompleteTypeInFunctionParam,
  218. param.type_id());
  219. });
  220. }
  221. context.node_stack().Push(node_id, function_id);
  222. return true;
  223. }
  224. auto HandleFunctionDefinition(Context& context,
  225. Parse::FunctionDefinitionId node_id) -> bool {
  226. SemIR::FunctionId function_id =
  227. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  228. // If the `}` of the function is reachable, reject if we need a return value
  229. // and otherwise add an implicit `return;`.
  230. if (context.is_current_position_reachable()) {
  231. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  232. CARBON_DIAGNOSTIC(
  233. MissingReturnStatement, Error,
  234. "Missing `return` at end of function with declared return type.");
  235. context.emitter().Emit(TokenOnly(node_id), MissingReturnStatement);
  236. } else {
  237. context.AddInst({node_id, SemIR::Return{}});
  238. }
  239. }
  240. context.scope_stack().Pop();
  241. context.inst_block_stack().Pop();
  242. context.return_scope_stack().pop_back();
  243. context.decl_name_stack().PopScope();
  244. return true;
  245. }
  246. } // namespace Carbon::Check