handle_function.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. // TODO: This contains the IR block for the parameters and return type. At
  57. // present, it's just loose, but it's not strictly required for parameter
  58. // refs; we should either stop constructing it completely or, if it turns out
  59. // to be needed, store it. Note, the underlying issue is that the LLVM IR has
  60. // nowhere clear to emit, so changing storage would require addressing that
  61. // problem. For comparison with function calls, the IR needs to be emitted
  62. // prior to the call.
  63. context.inst_block_stack().Pop();
  64. auto return_type_id = SemIR::TypeId::Invalid;
  65. auto return_slot_id = SemIR::InstId::Invalid;
  66. if (auto [return_node, return_storage_id] =
  67. context.node_stack()
  68. .PopWithParseNodeIf<Parse::NodeKind::ReturnType>();
  69. return_storage_id) {
  70. return_type_id = context.insts().Get(*return_storage_id).type_id();
  71. return_type_id = context.AsCompleteType(return_type_id, [&] {
  72. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  73. "Function returns incomplete type `{0}`.",
  74. SemIR::TypeId);
  75. return context.emitter().Build(
  76. return_node, IncompleteTypeInFunctionReturnType, return_type_id);
  77. });
  78. if (!SemIR::GetInitRepr(context.sem_ir(), return_type_id)
  79. .has_return_slot()) {
  80. // The function only has a return slot if it uses in-place initialization.
  81. } else {
  82. return_slot_id = *return_storage_id;
  83. }
  84. }
  85. SemIR::InstBlockId param_refs_id =
  86. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  87. SemIR::InstBlockId implicit_param_refs_id =
  88. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  89. SemIR::InstBlockId::Empty);
  90. auto name_context = context.decl_name_stack().FinishName();
  91. context.node_stack()
  92. .PopAndDiscardSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  93. // Process modifiers.
  94. auto modifiers = DiagnoseModifiers(context, name_context.target_scope_id);
  95. if (!!(modifiers & KeywordModifierSet::Access)) {
  96. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  97. "access modifier");
  98. }
  99. if (!!(modifiers & KeywordModifierSet::Method)) {
  100. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  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().saw_decl_modifier,
  107. "interface modifier");
  108. }
  109. context.decl_state_stack().Pop(DeclState::Fn);
  110. // Add the function declaration.
  111. auto function_decl = SemIR::FunctionDecl{
  112. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  113. SemIR::FunctionId::Invalid};
  114. auto function_decl_id =
  115. context.AddPlaceholderInst({parse_node, function_decl});
  116. // At interface scope, a function declaration introduces an associated
  117. // function.
  118. auto lookup_result_id = function_decl_id;
  119. if (name_context.enclosing_scope_id_for_new_inst().is_valid() &&
  120. !name_context.has_qualifiers) {
  121. auto scope_inst_id = context.name_scopes().GetInstIdIfValid(
  122. name_context.enclosing_scope_id_for_new_inst());
  123. if (auto interface_scope =
  124. context.insts().TryGetAsIfValid<SemIR::InterfaceDecl>(
  125. scope_inst_id)) {
  126. lookup_result_id = BuildAssociatedEntity(
  127. context, interface_scope->interface_id, function_decl_id);
  128. }
  129. }
  130. // Check whether this is a redeclaration.
  131. auto existing_id =
  132. context.decl_name_stack().LookupOrAddName(name_context, lookup_result_id);
  133. if (existing_id.is_valid()) {
  134. if (auto existing_function_decl =
  135. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  136. // This is a redeclaration of an existing function.
  137. function_decl.function_id = existing_function_decl->function_id;
  138. // TODO: Check that the signature matches!
  139. // TODO: Disallow redeclarations within classes?
  140. // Track the signature from the definition, so that IDs in the body match
  141. // IDs in the signature.
  142. if (is_definition) {
  143. auto& function_info =
  144. context.functions().Get(function_decl.function_id);
  145. function_info.implicit_param_refs_id = implicit_param_refs_id;
  146. function_info.param_refs_id = param_refs_id;
  147. function_info.return_type_id = return_type_id;
  148. function_info.return_slot_id = return_slot_id;
  149. }
  150. } else {
  151. // This is a redeclaration of something other than a function.
  152. // This includes the case where an associated function redeclares another
  153. // associated function.
  154. context.DiagnoseDuplicateName(function_decl_id, existing_id);
  155. }
  156. }
  157. // Create a new function if this isn't a valid redeclaration.
  158. if (!function_decl.function_id.is_valid()) {
  159. function_decl.function_id = context.functions().Add(
  160. {.name_id = name_context.name_id_for_new_inst(),
  161. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  162. .decl_id = function_decl_id,
  163. .implicit_param_refs_id = implicit_param_refs_id,
  164. .param_refs_id = param_refs_id,
  165. .return_type_id = return_type_id,
  166. .return_slot_id = return_slot_id});
  167. }
  168. // Write the function ID into the FunctionDecl.
  169. context.ReplaceInstBeforeConstantUse(function_decl_id,
  170. {parse_node, function_decl});
  171. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  172. // TODO: Update this once valid signatures for the entry point are decided.
  173. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  174. !context.inst_blocks().Get(param_refs_id).empty() ||
  175. (return_slot_id.is_valid() &&
  176. return_type_id !=
  177. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  178. return_type_id != context.GetTupleType({}))) {
  179. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  180. "Invalid signature for `Main.Run` function. Expected "
  181. "`fn ()` or `fn () -> i32`.");
  182. context.emitter().Emit(parse_node, InvalidMainRunSignature);
  183. }
  184. }
  185. return {function_decl.function_id, function_decl_id};
  186. }
  187. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId parse_node)
  188. -> bool {
  189. BuildFunctionDecl(context, parse_node, /*is_definition=*/false);
  190. context.decl_name_stack().PopScope();
  191. return true;
  192. }
  193. auto HandleFunctionDefinitionStart(Context& context,
  194. Parse::FunctionDefinitionStartId parse_node)
  195. -> bool {
  196. // Process the declaration portion of the function.
  197. auto [function_id, decl_id] =
  198. BuildFunctionDecl(context, parse_node, /*is_definition=*/true);
  199. auto& function = context.functions().Get(function_id);
  200. // Track that this declaration is the definition.
  201. if (function.definition_id.is_valid()) {
  202. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  203. "Redefinition of function {0}.", SemIR::NameId);
  204. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  205. "Previous definition was here.");
  206. context.emitter()
  207. .Build(parse_node, FunctionRedefinition, function.name_id)
  208. .Note(function.definition_id, FunctionPreviousDefinition)
  209. .Emit();
  210. } else {
  211. function.definition_id = decl_id;
  212. }
  213. // Create the function scope and the entry block.
  214. context.return_scope_stack().push_back({.decl_id = decl_id});
  215. context.inst_block_stack().Push();
  216. context.scope_stack().Push(decl_id);
  217. context.AddCurrentCodeBlockToFunction();
  218. // Bring the implicit and explicit parameters into scope.
  219. for (auto param_id : llvm::concat<SemIR::InstId>(
  220. context.inst_blocks().Get(function.implicit_param_refs_id),
  221. context.inst_blocks().Get(function.param_refs_id))) {
  222. auto param = context.insts().Get(param_id);
  223. // Find the parameter in the pattern.
  224. // TODO: More general pattern handling?
  225. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  226. param_id = addr_pattern->inner_id;
  227. param = context.insts().Get(param_id);
  228. }
  229. // The parameter types need to be complete.
  230. context.TryToCompleteType(param.type_id(), [&] {
  231. CARBON_DIAGNOSTIC(
  232. IncompleteTypeInFunctionParam, Error,
  233. "Parameter has incomplete type `{0}` in function definition.",
  234. SemIR::TypeId);
  235. return context.emitter().Build(param_id, IncompleteTypeInFunctionParam,
  236. param.type_id());
  237. });
  238. }
  239. context.node_stack().Push(parse_node, function_id);
  240. return true;
  241. }
  242. auto HandleFunctionDefinition(Context& context,
  243. Parse::FunctionDefinitionId parse_node) -> bool {
  244. SemIR::FunctionId function_id =
  245. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  246. // If the `}` of the function is reachable, reject if we need a return value
  247. // and otherwise add an implicit `return;`.
  248. if (context.is_current_position_reachable()) {
  249. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  250. CARBON_DIAGNOSTIC(
  251. MissingReturnStatement, Error,
  252. "Missing `return` at end of function with declared return type.");
  253. context.emitter().Emit(TokenOnly(parse_node), MissingReturnStatement);
  254. } else {
  255. context.AddInst({parse_node, SemIR::Return{}});
  256. }
  257. }
  258. context.scope_stack().Pop();
  259. context.inst_block_stack().Pop();
  260. context.return_scope_stack().pop_back();
  261. context.decl_name_stack().PopScope();
  262. return true;
  263. }
  264. } // namespace Carbon::Check