handle_function.cpp 11 KB

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