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}`.", std::string);
  73. return context.emitter().Build(
  74. return_node_and_id->first, IncompleteTypeInFunctionReturnType,
  75. context.sem_ir().StringifyType(return_type_id));
  76. });
  77. if (!SemIR::GetInitRepr(context.sem_ir(), return_type_id)
  78. .has_return_slot()) {
  79. // The function only has a return slot if it uses in-place initialization.
  80. } else {
  81. return_slot_id = return_storage_id;
  82. }
  83. }
  84. SemIR::InstBlockId param_refs_id =
  85. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  86. SemIR::InstBlockId implicit_param_refs_id =
  87. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  88. SemIR::InstBlockId::Empty);
  89. auto name_context = context.decl_name_stack().FinishName();
  90. context.node_stack()
  91. .PopAndDiscardSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  92. // Process modifiers.
  93. auto modifiers = DiagnoseModifiers(context, name_context.target_scope_id);
  94. if (!!(modifiers & KeywordModifierSet::Access)) {
  95. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  96. "access modifier");
  97. }
  98. if (!!(modifiers & KeywordModifierSet::Method)) {
  99. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  100. "method modifier");
  101. }
  102. if (!!(modifiers & KeywordModifierSet::Interface)) {
  103. // TODO: Once we are saving the modifiers for a function, add check that
  104. // the function may only be defined if it is marked `default` or `final`.
  105. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  106. "interface modifier");
  107. }
  108. context.decl_state_stack().Pop(DeclState::Fn);
  109. // Add the function declaration.
  110. auto function_decl = SemIR::FunctionDecl{
  111. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  112. SemIR::FunctionId::Invalid};
  113. auto function_decl_id =
  114. context.AddPlaceholderInst({parse_node, function_decl});
  115. // Check whether this is a redeclaration.
  116. auto existing_id =
  117. context.decl_name_stack().LookupOrAddName(name_context, function_decl_id);
  118. if (existing_id.is_valid()) {
  119. if (auto existing_function_decl =
  120. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  121. // This is a redeclaration of an existing function.
  122. function_decl.function_id = existing_function_decl->function_id;
  123. // TODO: Check that the signature matches!
  124. // Track the signature from the definition, so that IDs in the body match
  125. // IDs in the signature.
  126. if (is_definition) {
  127. auto& function_info =
  128. context.functions().Get(function_decl.function_id);
  129. function_info.implicit_param_refs_id = implicit_param_refs_id;
  130. function_info.param_refs_id = param_refs_id;
  131. function_info.return_type_id = return_type_id;
  132. function_info.return_slot_id = return_slot_id;
  133. }
  134. } else {
  135. // This is a redeclaration of something other than a function.
  136. context.DiagnoseDuplicateName(function_decl_id, existing_id);
  137. }
  138. }
  139. // Create a new function if this isn't a valid redeclaration.
  140. if (!function_decl.function_id.is_valid()) {
  141. function_decl.function_id = context.functions().Add(
  142. {.name_id = name_context.name_id_for_new_inst(),
  143. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  144. .decl_id = function_decl_id,
  145. .implicit_param_refs_id = implicit_param_refs_id,
  146. .param_refs_id = param_refs_id,
  147. .return_type_id = return_type_id,
  148. .return_slot_id = return_slot_id});
  149. }
  150. // Write the function ID into the FunctionDecl.
  151. context.ReplaceInstBeforeConstantUse(function_decl_id,
  152. {parse_node, function_decl});
  153. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  154. // TODO: Update this once valid signatures for the entry point are decided.
  155. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  156. !context.inst_blocks().Get(param_refs_id).empty() ||
  157. (return_slot_id.is_valid() &&
  158. return_type_id !=
  159. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  160. return_type_id != context.GetTupleType({}))) {
  161. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  162. "Invalid signature for `Main.Run` function. Expected "
  163. "`fn ()` or `fn () -> i32`.");
  164. context.emitter().Emit(parse_node, InvalidMainRunSignature);
  165. }
  166. }
  167. return {function_decl.function_id, function_decl_id};
  168. }
  169. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId parse_node)
  170. -> bool {
  171. BuildFunctionDecl(context, parse_node, /*is_definition=*/false);
  172. context.decl_name_stack().PopScope();
  173. return true;
  174. }
  175. auto HandleFunctionDefinitionStart(Context& context,
  176. Parse::FunctionDefinitionStartId parse_node)
  177. -> bool {
  178. // Process the declaration portion of the function.
  179. auto [function_id, decl_id] =
  180. BuildFunctionDecl(context, parse_node, /*is_definition=*/true);
  181. auto& function = context.functions().Get(function_id);
  182. // Track that this declaration is the definition.
  183. if (function.definition_id.is_valid()) {
  184. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  185. "Redefinition of function {0}.", std::string);
  186. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  187. "Previous definition was here.");
  188. context.emitter()
  189. .Build(parse_node, FunctionRedefinition,
  190. context.names().GetFormatted(function.name_id).str())
  191. .Note(function.definition_id, FunctionPreviousDefinition)
  192. .Emit();
  193. } else {
  194. function.definition_id = decl_id;
  195. }
  196. // Create the function scope and the entry block.
  197. context.return_scope_stack().push_back({.decl_id = decl_id});
  198. context.inst_block_stack().Push();
  199. context.scope_stack().Push(decl_id);
  200. context.AddCurrentCodeBlockToFunction();
  201. // Bring the implicit and explicit parameters into scope.
  202. for (auto param_id : llvm::concat<SemIR::InstId>(
  203. context.inst_blocks().Get(function.implicit_param_refs_id),
  204. context.inst_blocks().Get(function.param_refs_id))) {
  205. auto param = context.insts().Get(param_id);
  206. // Find the parameter in the pattern.
  207. // TODO: More general pattern handling?
  208. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  209. param_id = addr_pattern->inner_id;
  210. param = context.insts().Get(param_id);
  211. }
  212. // The parameter types need to be complete.
  213. context.TryToCompleteType(param.type_id(), [&] {
  214. CARBON_DIAGNOSTIC(
  215. IncompleteTypeInFunctionParam, Error,
  216. "Parameter has incomplete type `{0}` in function definition.",
  217. std::string);
  218. return context.emitter().Build(
  219. param_id, IncompleteTypeInFunctionParam,
  220. context.sem_ir().StringifyType(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