handle_function.cpp 12 KB

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