handle_function.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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/modifiers.h"
  8. #include "toolchain/parse/tree_node_location_translator.h"
  9. #include "toolchain/sem_ir/entry_point.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. namespace Carbon::Check {
  12. auto HandleFunctionIntroducer(Context& context,
  13. Parse::FunctionIntroducerId parse_node) -> bool {
  14. // Create an instruction block to hold the instructions created as part of the
  15. // function signature, such as parameter and return types.
  16. context.inst_block_stack().Push();
  17. // Push the bracketing node.
  18. context.node_stack().Push(parse_node);
  19. // Optional modifiers and the name follow.
  20. context.decl_state_stack().Push(DeclState::Fn);
  21. context.decl_name_stack().PushScopeAndStartName();
  22. return true;
  23. }
  24. auto HandleReturnType(Context& context, Parse::ReturnTypeId parse_node)
  25. -> bool {
  26. // Propagate the type expression.
  27. auto [type_parse_node, type_inst_id] =
  28. context.node_stack().PopExprWithParseNode();
  29. auto type_id = ExprAsType(context, type_parse_node, type_inst_id);
  30. // TODO: Use a dedicated instruction rather than VarStorage here.
  31. context.AddInstAndPush(
  32. {parse_node, SemIR::VarStorage{type_id, SemIR::NameId::ReturnSlot}});
  33. return true;
  34. }
  35. static auto DiagnoseModifiers(Context& context,
  36. SemIR::NameScopeId target_scope_id)
  37. -> KeywordModifierSet {
  38. const Lex::TokenKind decl_kind = Lex::TokenKind::Fn;
  39. CheckAccessModifiersOnDecl(context, decl_kind, target_scope_id);
  40. LimitModifiersOnDecl(context,
  41. KeywordModifierSet::Access | KeywordModifierSet::Method |
  42. KeywordModifierSet::Interface,
  43. decl_kind);
  44. CheckMethodModifiersOnFunction(context, target_scope_id);
  45. RequireDefaultFinalOnlyInInterfaces(context, decl_kind, target_scope_id);
  46. return context.decl_state_stack().innermost().modifier_set;
  47. }
  48. // Build a FunctionDecl describing the signature of a function. This
  49. // handles the common logic shared by function declaration syntax and function
  50. // definition syntax.
  51. static auto BuildFunctionDecl(Context& context,
  52. Parse::AnyFunctionDeclId parse_node,
  53. bool is_definition)
  54. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  55. // TODO: This contains the IR block for the parameters and return type. At
  56. // present, it's just loose, but it's not strictly required for parameter
  57. // refs; we should either stop constructing it completely or, if it turns out
  58. // to be needed, store it. Note, the underlying issue is that the LLVM IR has
  59. // nowhere clear to emit, so changing storage would require addressing that
  60. // problem. For comparison with function calls, the IR needs to be emitted
  61. // prior to the call.
  62. context.inst_block_stack().Pop();
  63. auto return_type_id = SemIR::TypeId::Invalid;
  64. auto return_slot_id = SemIR::InstId::Invalid;
  65. if (auto return_node_and_id =
  66. context.node_stack()
  67. .PopWithParseNodeIf<Parse::NodeKind::ReturnType>()) {
  68. auto return_storage_id = return_node_and_id->second;
  69. return_type_id = context.insts().Get(return_storage_id).type_id();
  70. return_type_id = context.AsCompleteType(return_type_id, [&] {
  71. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  72. "Function returns incomplete type `{0}`.",
  73. SemIR::TypeId);
  74. return context.emitter().Build(return_node_and_id->first,
  75. IncompleteTypeInFunctionReturnType,
  76. 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. // Check whether this is a redeclaration.
  117. auto existing_id =
  118. context.decl_name_stack().LookupOrAddName(name_context, function_decl_id);
  119. if (existing_id.is_valid()) {
  120. if (auto existing_function_decl =
  121. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  122. // This is a redeclaration of an existing function.
  123. function_decl.function_id = existing_function_decl->function_id;
  124. // TODO: Check that the signature matches!
  125. // Track the signature from the definition, so that IDs in the body match
  126. // IDs in the signature.
  127. if (is_definition) {
  128. auto& function_info =
  129. context.functions().Get(function_decl.function_id);
  130. function_info.implicit_param_refs_id = implicit_param_refs_id;
  131. function_info.param_refs_id = param_refs_id;
  132. function_info.return_type_id = return_type_id;
  133. function_info.return_slot_id = return_slot_id;
  134. }
  135. } else {
  136. // This is a redeclaration of something other than a function.
  137. context.DiagnoseDuplicateName(function_decl_id, existing_id);
  138. }
  139. }
  140. // Create a new function if this isn't a valid redeclaration.
  141. if (!function_decl.function_id.is_valid()) {
  142. function_decl.function_id = context.functions().Add(
  143. {.name_id = name_context.name_id_for_new_inst(),
  144. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  145. .decl_id = function_decl_id,
  146. .implicit_param_refs_id = implicit_param_refs_id,
  147. .param_refs_id = param_refs_id,
  148. .return_type_id = return_type_id,
  149. .return_slot_id = return_slot_id});
  150. }
  151. // Write the function ID into the FunctionDecl.
  152. context.ReplaceInstBeforeConstantUse(function_decl_id,
  153. {parse_node, function_decl});
  154. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  155. // TODO: Update this once valid signatures for the entry point are decided.
  156. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  157. !context.inst_blocks().Get(param_refs_id).empty() ||
  158. (return_slot_id.is_valid() &&
  159. return_type_id !=
  160. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  161. return_type_id != context.GetTupleType({}))) {
  162. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  163. "Invalid signature for `Main.Run` function. Expected "
  164. "`fn ()` or `fn () -> i32`.");
  165. context.emitter().Emit(parse_node, InvalidMainRunSignature);
  166. }
  167. }
  168. return {function_decl.function_id, function_decl_id};
  169. }
  170. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId parse_node)
  171. -> bool {
  172. BuildFunctionDecl(context, parse_node, /*is_definition=*/false);
  173. context.decl_name_stack().PopScope();
  174. return true;
  175. }
  176. auto HandleFunctionDefinitionStart(Context& context,
  177. Parse::FunctionDefinitionStartId parse_node)
  178. -> bool {
  179. // Process the declaration portion of the function.
  180. auto [function_id, decl_id] =
  181. BuildFunctionDecl(context, parse_node, /*is_definition=*/true);
  182. auto& function = context.functions().Get(function_id);
  183. // Track that this declaration is the definition.
  184. if (function.definition_id.is_valid()) {
  185. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  186. "Redefinition of function {0}.", std::string);
  187. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  188. "Previous definition was here.");
  189. context.emitter()
  190. .Build(parse_node, FunctionRedefinition,
  191. context.names().GetFormatted(function.name_id).str())
  192. .Note(function.definition_id, FunctionPreviousDefinition)
  193. .Emit();
  194. } else {
  195. function.definition_id = decl_id;
  196. }
  197. // Create the function scope and the entry block.
  198. context.return_scope_stack().push_back({.decl_id = decl_id});
  199. context.inst_block_stack().Push();
  200. context.scope_stack().Push(decl_id);
  201. context.AddCurrentCodeBlockToFunction();
  202. // Bring the implicit and explicit parameters into scope.
  203. for (auto param_id : llvm::concat<SemIR::InstId>(
  204. context.inst_blocks().Get(function.implicit_param_refs_id),
  205. context.inst_blocks().Get(function.param_refs_id))) {
  206. auto param = context.insts().Get(param_id);
  207. // Find the parameter in the pattern.
  208. // TODO: More general pattern handling?
  209. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  210. param_id = addr_pattern->inner_id;
  211. param = context.insts().Get(param_id);
  212. }
  213. // The parameter types need to be complete.
  214. context.TryToCompleteType(param.type_id(), [&] {
  215. CARBON_DIAGNOSTIC(
  216. IncompleteTypeInFunctionParam, Error,
  217. "Parameter has incomplete type `{0}` in function definition.",
  218. SemIR::TypeId);
  219. return context.emitter().Build(param_id, IncompleteTypeInFunctionParam,
  220. param.type_id());
  221. });
  222. }
  223. context.node_stack().Push(parse_node, function_id);
  224. return true;
  225. }
  226. auto HandleFunctionDefinition(Context& context,
  227. Parse::FunctionDefinitionId parse_node) -> bool {
  228. SemIR::FunctionId function_id =
  229. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  230. // If the `}` of the function is reachable, reject if we need a return value
  231. // and otherwise add an implicit `return;`.
  232. if (context.is_current_position_reachable()) {
  233. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  234. CARBON_DIAGNOSTIC(
  235. MissingReturnStatement, Error,
  236. "Missing `return` at end of function with declared return type.");
  237. context.emitter().Emit(TokenOnly(parse_node), MissingReturnStatement);
  238. } else {
  239. context.AddInst({parse_node, SemIR::Return{}});
  240. }
  241. }
  242. context.scope_stack().Pop();
  243. context.inst_block_stack().Pop();
  244. context.return_scope_stack().pop_back();
  245. context.decl_name_stack().PopScope();
  246. return true;
  247. }
  248. } // namespace Carbon::Check