handle_function.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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/decl_state.h"
  8. #include "toolchain/check/function.h"
  9. #include "toolchain/check/interface.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/check/modifiers.h"
  12. #include "toolchain/parse/tree_node_diagnostic_converter.h"
  13. #include "toolchain/sem_ir/builtin_function_kind.h"
  14. #include "toolchain/sem_ir/entry_point.h"
  15. #include "toolchain/sem_ir/function.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. auto HandleFunctionIntroducer(Context& context,
  20. Parse::FunctionIntroducerId node_id) -> bool {
  21. // Create an instruction block to hold the instructions created as part of the
  22. // function signature, such as parameter and return types.
  23. context.inst_block_stack().Push();
  24. // Push the bracketing node.
  25. context.node_stack().Push(node_id);
  26. // Optional modifiers and the name follow.
  27. context.decl_state_stack().Push(DeclState::Fn);
  28. context.decl_name_stack().PushScopeAndStartName();
  29. return true;
  30. }
  31. auto HandleReturnType(Context& context, Parse::ReturnTypeId node_id) -> bool {
  32. // Propagate the type expression.
  33. auto [type_node_id, type_inst_id] = context.node_stack().PopExprWithNodeId();
  34. auto type_id = ExprAsType(context, type_node_id, type_inst_id);
  35. // TODO: Use a dedicated instruction rather than VarStorage here.
  36. context.AddInstAndPush(
  37. {node_id, SemIR::VarStorage{type_id, SemIR::NameId::ReturnSlot}});
  38. return true;
  39. }
  40. static auto DiagnoseModifiers(Context& context, bool is_definition,
  41. SemIR::NameScopeId target_scope_id)
  42. -> KeywordModifierSet {
  43. const Lex::TokenKind decl_kind = Lex::TokenKind::Fn;
  44. CheckAccessModifiersOnDecl(context, decl_kind, target_scope_id);
  45. if (is_definition) {
  46. ForbidExternModifierOnDefinition(context, decl_kind);
  47. }
  48. if (target_scope_id.is_valid()) {
  49. auto target_id = context.name_scopes().Get(target_scope_id).inst_id;
  50. if (target_id.is_valid() &&
  51. !context.insts().Is<SemIR::Namespace>(target_id)) {
  52. ForbidModifiersOnDecl(context, KeywordModifierSet::Extern, decl_kind,
  53. " that is a member");
  54. }
  55. }
  56. LimitModifiersOnDecl(context,
  57. KeywordModifierSet::Access | KeywordModifierSet::Extern |
  58. KeywordModifierSet::Method |
  59. KeywordModifierSet::Interface,
  60. decl_kind);
  61. CheckMethodModifiersOnFunction(context, target_scope_id);
  62. RequireDefaultFinalOnlyInInterfaces(context, decl_kind, target_scope_id);
  63. return context.decl_state_stack().innermost().modifier_set;
  64. }
  65. // Build a FunctionDecl describing the signature of a function. This
  66. // handles the common logic shared by function declaration syntax and function
  67. // definition syntax.
  68. static auto BuildFunctionDecl(Context& context,
  69. Parse::AnyFunctionDeclId node_id,
  70. bool is_definition)
  71. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  72. auto decl_block_id = context.inst_block_stack().Pop();
  73. auto return_type_id = SemIR::TypeId::Invalid;
  74. auto return_slot_id = SemIR::InstId::Invalid;
  75. if (auto [return_node, return_storage_id] =
  76. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  77. return_storage_id) {
  78. return_type_id = context.insts().Get(*return_storage_id).type_id();
  79. return_type_id = context.AsCompleteType(return_type_id, [&] {
  80. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  81. "Function returns incomplete type `{0}`.",
  82. SemIR::TypeId);
  83. return context.emitter().Build(
  84. return_node, IncompleteTypeInFunctionReturnType, return_type_id);
  85. });
  86. if (!SemIR::GetInitRepr(context.sem_ir(), return_type_id)
  87. .has_return_slot()) {
  88. // The function only has a return slot if it uses in-place initialization.
  89. } else {
  90. return_slot_id = *return_storage_id;
  91. }
  92. }
  93. SemIR::InstBlockId param_refs_id =
  94. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  95. SemIR::InstBlockId implicit_param_refs_id =
  96. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  97. SemIR::InstBlockId::Empty);
  98. auto name_context = context.decl_name_stack().FinishName();
  99. context.node_stack()
  100. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  101. // Process modifiers.
  102. auto modifiers =
  103. DiagnoseModifiers(context, is_definition, name_context.target_scope_id);
  104. if (!!(modifiers & KeywordModifierSet::Access)) {
  105. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  106. ModifierOrder::Access),
  107. "access modifier");
  108. }
  109. bool is_extern = !!(modifiers & KeywordModifierSet::Extern);
  110. if (!!(modifiers & KeywordModifierSet::Method)) {
  111. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  112. ModifierOrder::Decl),
  113. "method modifier");
  114. }
  115. if (!!(modifiers & KeywordModifierSet::Interface)) {
  116. // TODO: Once we are saving the modifiers for a function, add check that
  117. // the function may only be defined if it is marked `default` or `final`.
  118. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  119. ModifierOrder::Decl),
  120. "interface modifier");
  121. }
  122. context.decl_state_stack().Pop(DeclState::Fn);
  123. // Add the function declaration.
  124. auto function_decl = SemIR::FunctionDecl{
  125. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  126. SemIR::FunctionId::Invalid, decl_block_id};
  127. auto function_info = SemIR::Function{
  128. .name_id = name_context.name_id_for_new_inst(),
  129. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  130. .decl_id = context.AddPlaceholderInst({node_id, function_decl}),
  131. .implicit_param_refs_id = implicit_param_refs_id,
  132. .param_refs_id = param_refs_id,
  133. .return_type_id = return_type_id,
  134. .return_slot_id = return_slot_id,
  135. .is_extern = is_extern};
  136. if (is_definition) {
  137. function_info.definition_id = function_info.decl_id;
  138. }
  139. // At interface scope, a function declaration introduces an associated
  140. // function.
  141. auto lookup_result_id = function_info.decl_id;
  142. if (name_context.enclosing_scope_id_for_new_inst().is_valid() &&
  143. !name_context.has_qualifiers) {
  144. auto scope_inst_id = context.name_scopes().GetInstIdIfValid(
  145. name_context.enclosing_scope_id_for_new_inst());
  146. if (auto interface_scope =
  147. context.insts().TryGetAsIfValid<SemIR::InterfaceDecl>(
  148. scope_inst_id)) {
  149. lookup_result_id = BuildAssociatedEntity(
  150. context, interface_scope->interface_id, function_info.decl_id);
  151. }
  152. }
  153. // Check whether this is a redeclaration.
  154. auto prev_id =
  155. context.decl_name_stack().LookupOrAddName(name_context, lookup_result_id);
  156. if (prev_id.is_valid()) {
  157. auto prev_inst = ResolvePrevInstForMerge(context, node_id, prev_id);
  158. if (auto existing_function_decl =
  159. prev_inst.inst.TryAs<SemIR::FunctionDecl>()) {
  160. if (MergeFunctionRedecl(context, node_id, function_info,
  161. /*new_is_import=*/false, is_definition,
  162. existing_function_decl->function_id,
  163. prev_inst.is_import)) {
  164. // When merging, use the existing function rather than adding a new one.
  165. function_decl.function_id = existing_function_decl->function_id;
  166. }
  167. } else {
  168. // This is a redeclaration of something other than a function. This
  169. // includes the case where an associated function redeclares another
  170. // associated function.
  171. context.DiagnoseDuplicateName(function_info.decl_id, prev_id);
  172. }
  173. }
  174. // Create a new function if this isn't a valid redeclaration.
  175. if (!function_decl.function_id.is_valid()) {
  176. function_decl.function_id = context.functions().Add(function_info);
  177. }
  178. // Write the function ID into the FunctionDecl.
  179. context.ReplaceInstBeforeConstantUse(function_info.decl_id, function_decl);
  180. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  181. // TODO: Update this once valid signatures for the entry point are decided.
  182. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  183. !context.inst_blocks().Get(param_refs_id).empty() ||
  184. (return_slot_id.is_valid() &&
  185. return_type_id !=
  186. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  187. return_type_id != context.GetTupleType({}))) {
  188. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  189. "Invalid signature for `Main.Run` function. Expected "
  190. "`fn ()` or `fn () -> i32`.");
  191. context.emitter().Emit(node_id, InvalidMainRunSignature);
  192. }
  193. }
  194. return {function_decl.function_id, function_info.decl_id};
  195. }
  196. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId node_id)
  197. -> bool {
  198. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  199. context.decl_name_stack().PopScope();
  200. return true;
  201. }
  202. // Processes a function definition after a signature for which we have already
  203. // built a function ID. This logic is shared between processing regular function
  204. // definitions and delayed parsing of inline method definitions.
  205. static auto HandleFunctionDefinitionAfterSignature(
  206. Context& context, Parse::FunctionDefinitionStartId node_id,
  207. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  208. auto& function = context.functions().Get(function_id);
  209. // Create the function scope and the entry block.
  210. context.return_scope_stack().push_back({.decl_id = decl_id});
  211. context.inst_block_stack().Push();
  212. context.scope_stack().Push(decl_id);
  213. context.AddCurrentCodeBlockToFunction();
  214. // Check the parameter types are complete.
  215. for (auto param_id : llvm::concat<SemIR::InstId>(
  216. context.inst_blocks().Get(function.implicit_param_refs_id),
  217. context.inst_blocks().Get(function.param_refs_id))) {
  218. auto param = context.insts().Get(param_id);
  219. // Find the parameter in the pattern.
  220. // TODO: More general pattern handling?
  221. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  222. param_id = addr_pattern->inner_id;
  223. param = context.insts().Get(param_id);
  224. }
  225. // The parameter types need to be complete.
  226. context.TryToCompleteType(param.type_id(), [&] {
  227. CARBON_DIAGNOSTIC(
  228. IncompleteTypeInFunctionParam, Error,
  229. "Parameter has incomplete type `{0}` in function definition.",
  230. SemIR::TypeId);
  231. return context.emitter().Build(param_id, IncompleteTypeInFunctionParam,
  232. param.type_id());
  233. });
  234. }
  235. context.node_stack().Push(node_id, function_id);
  236. }
  237. auto HandleFunctionDefinitionSuspend(Context& context,
  238. Parse::FunctionDefinitionStartId node_id)
  239. -> SuspendedFunction {
  240. // Process the declaration portion of the function.
  241. auto [function_id, decl_id] =
  242. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  243. return {function_id, decl_id, context.decl_name_stack().Suspend()};
  244. }
  245. auto HandleFunctionDefinitionResume(Context& context,
  246. Parse::FunctionDefinitionStartId node_id,
  247. SuspendedFunction sus_fn) -> void {
  248. context.decl_name_stack().Restore(sus_fn.saved_name_state);
  249. HandleFunctionDefinitionAfterSignature(context, node_id, sus_fn.function_id,
  250. sus_fn.decl_id);
  251. }
  252. auto HandleFunctionDefinitionStart(Context& context,
  253. Parse::FunctionDefinitionStartId node_id)
  254. -> bool {
  255. // Process the declaration portion of the function.
  256. auto [function_id, decl_id] =
  257. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  258. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  259. decl_id);
  260. return true;
  261. }
  262. auto HandleFunctionDefinition(Context& context,
  263. Parse::FunctionDefinitionId node_id) -> bool {
  264. SemIR::FunctionId function_id =
  265. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  266. // If the `}` of the function is reachable, reject if we need a return value
  267. // and otherwise add an implicit `return;`.
  268. if (context.is_current_position_reachable()) {
  269. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  270. CARBON_DIAGNOSTIC(
  271. MissingReturnStatement, Error,
  272. "Missing `return` at end of function with declared return type.");
  273. context.emitter().Emit(TokenOnly(node_id), MissingReturnStatement);
  274. } else {
  275. context.AddInst({node_id, SemIR::Return{}});
  276. }
  277. }
  278. context.scope_stack().Pop();
  279. context.inst_block_stack().Pop();
  280. context.return_scope_stack().pop_back();
  281. context.decl_name_stack().PopScope();
  282. return true;
  283. }
  284. auto HandleBuiltinFunctionDefinitionStart(
  285. Context& context, Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  286. // Process the declaration portion of the function.
  287. auto [function_id, _] =
  288. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  289. context.node_stack().Push(node_id, function_id);
  290. return true;
  291. }
  292. auto HandleBuiltinName(Context& context, Parse::BuiltinNameId node_id) -> bool {
  293. context.node_stack().Push(node_id);
  294. return true;
  295. }
  296. // Looks up a builtin function kind given its name as a string.
  297. // TODO: Move this out to another file.
  298. static auto LookupBuiltinFunctionKind(Context& context,
  299. Parse::BuiltinNameId name_id)
  300. -> SemIR::BuiltinFunctionKind {
  301. auto builtin_name = context.string_literal_values().Get(
  302. context.tokens().GetStringLiteralValue(
  303. context.parse_tree().node_token(name_id)));
  304. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  305. if (kind == SemIR::BuiltinFunctionKind::None) {
  306. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  307. "Unknown builtin function name \"{0}\".", std::string);
  308. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  309. builtin_name.str());
  310. }
  311. return kind;
  312. }
  313. // Returns whether `function` is a valid declaration of the builtin
  314. // `builtin_kind`.
  315. static auto IsValidBuiltinDeclaration(Context& context,
  316. const SemIR::Function& function,
  317. SemIR::BuiltinFunctionKind builtin_kind)
  318. -> bool {
  319. // Form the list of parameter types for the declaration.
  320. llvm::SmallVector<SemIR::TypeId> param_type_ids;
  321. auto implicit_param_refs =
  322. context.inst_blocks().Get(function.implicit_param_refs_id);
  323. auto param_refs = context.inst_blocks().Get(function.param_refs_id);
  324. param_type_ids.reserve(implicit_param_refs.size() + param_refs.size());
  325. for (auto param_id :
  326. llvm::concat<SemIR::InstId>(implicit_param_refs, param_refs)) {
  327. // TODO: We also need to track whether the parameter is declared with
  328. // `var`.
  329. param_type_ids.push_back(context.insts().Get(param_id).type_id());
  330. }
  331. // Get the return type. This is `()` if none was specified.
  332. auto return_type_id = function.return_type_id;
  333. if (!return_type_id.is_valid()) {
  334. return_type_id = context.GetTupleType({});
  335. }
  336. return builtin_kind.IsValidType(context.sem_ir(), param_type_ids,
  337. return_type_id);
  338. }
  339. auto HandleBuiltinFunctionDefinition(
  340. Context& context, Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  341. auto name_id =
  342. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  343. auto [fn_node_id, function_id] =
  344. context.node_stack()
  345. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  346. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  347. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  348. auto& function = context.functions().Get(function_id);
  349. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  350. function.builtin_kind = builtin_kind;
  351. } else {
  352. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  353. "Invalid signature for builtin function \"{0}\".",
  354. std::string);
  355. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  356. builtin_kind.name().str());
  357. }
  358. }
  359. context.decl_name_stack().PopScope();
  360. return true;
  361. }
  362. } // namespace Carbon::Check