handle_function.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 <optional>
  5. #include <utility>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/control_flow.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/decl_introducer_state.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/function.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/handle.h"
  15. #include "toolchain/check/import.h"
  16. #include "toolchain/check/import_ref.h"
  17. #include "toolchain/check/inst.h"
  18. #include "toolchain/check/interface.h"
  19. #include "toolchain/check/keyword_modifier_set.h"
  20. #include "toolchain/check/literal.h"
  21. #include "toolchain/check/merge.h"
  22. #include "toolchain/check/modifiers.h"
  23. #include "toolchain/check/name_component.h"
  24. #include "toolchain/check/name_lookup.h"
  25. #include "toolchain/check/type.h"
  26. #include "toolchain/check/type_completion.h"
  27. #include "toolchain/lex/token_kind.h"
  28. #include "toolchain/parse/node_ids.h"
  29. #include "toolchain/sem_ir/builtin_function_kind.h"
  30. #include "toolchain/sem_ir/entry_point.h"
  31. #include "toolchain/sem_ir/function.h"
  32. #include "toolchain/sem_ir/ids.h"
  33. #include "toolchain/sem_ir/inst.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. auto HandleParseNode(Context& context, Parse::FunctionIntroducerId node_id)
  37. -> bool {
  38. // The function is potentially generic.
  39. StartGenericDecl(context);
  40. // Create an instruction block to hold the instructions created as part of the
  41. // function signature, such as parameter and return types.
  42. context.inst_block_stack().Push();
  43. // Push the bracketing node.
  44. context.node_stack().Push(node_id);
  45. // Optional modifiers and the name follow.
  46. context.decl_introducer_state_stack().Push<Lex::TokenKind::Fn>();
  47. context.decl_name_stack().PushScopeAndStartName();
  48. return true;
  49. }
  50. auto HandleParseNode(Context& context, Parse::ReturnTypeId node_id) -> bool {
  51. auto [type_node_id, type_inst_id] = context.node_stack().PopExprWithNodeId();
  52. // If the previous node was `IdentifierNameBeforeParams`, then it would have
  53. // caused these entries to be pushed to the pattern stacks. But it's possible
  54. // to have a fn declaration without any parameters, in which case we find
  55. // `IdentifierNameNotBeforeParams` on the node stack. Then these entries are
  56. // not on the pattern stacks yet. They are only needed in that case if we have
  57. // a return type, which we now know that we do.
  58. if (context.node_stack().PeekNodeKind() ==
  59. Parse::NodeKind::IdentifierNameNotBeforeParams) {
  60. context.pattern_block_stack().Push();
  61. context.full_pattern_stack().PushFullPattern(
  62. FullPatternStack::Kind::ExplicitParamList);
  63. }
  64. // Propagate the type expression.
  65. auto form_expr = ExprAsReturnForm(context, type_node_id, type_inst_id);
  66. context.PushReturnForm(form_expr);
  67. auto return_patterns_id = AddReturnPatterns(context, node_id, form_expr);
  68. context.node_stack().Push(node_id, return_patterns_id);
  69. return true;
  70. }
  71. auto HandleParseNode(Context& context, Parse::ReturnFormId node_id) -> bool {
  72. return context.TODO(node_id, "Support ->?");
  73. }
  74. // Diagnoses issues with the modifiers, removing modifiers that shouldn't be
  75. // present.
  76. static auto DiagnoseModifiers(Context& context,
  77. Parse::AnyFunctionDeclId node_id,
  78. DeclIntroducerState& introducer,
  79. bool is_definition,
  80. SemIR::InstId parent_scope_inst_id,
  81. std::optional<SemIR::Inst> parent_scope_inst,
  82. SemIR::InstId self_param_id) -> void {
  83. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  84. LimitModifiersOnDecl(context, introducer,
  85. KeywordModifierSet::Access | KeywordModifierSet::Extern |
  86. KeywordModifierSet::Method |
  87. KeywordModifierSet::Interface);
  88. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  89. is_definition);
  90. CheckMethodModifiersOnFunction(context, introducer, parent_scope_inst_id,
  91. parent_scope_inst);
  92. RequireDefaultFinalOnlyInInterfaces(context, introducer, parent_scope_inst);
  93. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Interface)) {
  94. // TODO: Once we are saving the modifiers for a function, add check that
  95. // the function may only be defined if it is marked `default` or `final`.
  96. context.TODO(introducer.modifier_node_id(ModifierOrder::Decl),
  97. "interface modifier");
  98. }
  99. if (!self_param_id.has_value() &&
  100. introducer.modifier_set.HasAnyOf(KeywordModifierSet::Method)) {
  101. CARBON_DIAGNOSTIC(VirtualWithoutSelf, Error, "virtual class function");
  102. context.emitter().Emit(node_id, VirtualWithoutSelf);
  103. introducer.modifier_set.Remove(KeywordModifierSet::Method);
  104. }
  105. }
  106. // Returns the virtual-family modifier as an enum.
  107. static auto GetVirtualModifier(const KeywordModifierSet& modifier_set)
  108. -> SemIR::Function::VirtualModifier {
  109. return modifier_set.ToEnum<SemIR::Function::VirtualModifier>()
  110. .Case(KeywordModifierSet::Virtual,
  111. SemIR::Function::VirtualModifier::Virtual)
  112. .Case(KeywordModifierSet::Abstract,
  113. SemIR::Function::VirtualModifier::Abstract)
  114. .Case(KeywordModifierSet::Override,
  115. SemIR::Function::VirtualModifier::Override)
  116. .Default(SemIR::Function::VirtualModifier::None);
  117. }
  118. // Tries to merge new_function into prev_function_id. Since new_function won't
  119. // have a definition even if one is upcoming, set is_definition to indicate the
  120. // planned result.
  121. //
  122. // If merging is successful, returns true and may update the previous function.
  123. // Otherwise, returns false. Prints a diagnostic when appropriate.
  124. static auto MergeFunctionRedecl(Context& context,
  125. Parse::AnyFunctionDeclId node_id,
  126. SemIR::Function& new_function,
  127. bool new_is_definition,
  128. SemIR::FunctionId prev_function_id,
  129. SemIR::ImportIRId prev_import_ir_id) -> bool {
  130. auto& prev_function = context.functions().Get(prev_function_id);
  131. if (!CheckFunctionTypeMatches(context, new_function, prev_function)) {
  132. return false;
  133. }
  134. DiagnoseIfInvalidRedecl(
  135. context, Lex::TokenKind::Fn, prev_function.name_id,
  136. RedeclInfo(new_function, node_id, new_is_definition),
  137. RedeclInfo(prev_function, SemIR::LocId(prev_function.latest_decl_id()),
  138. prev_function.has_definition_started()),
  139. prev_import_ir_id);
  140. if (new_is_definition && prev_function.has_definition_started()) {
  141. return false;
  142. }
  143. if (!prev_function.first_owning_decl_id.has_value()) {
  144. prev_function.first_owning_decl_id = new_function.first_owning_decl_id;
  145. }
  146. if (new_is_definition) {
  147. // Track the signature from the definition, so that IDs in the body
  148. // match IDs in the signature.
  149. prev_function.MergeDefinition(new_function);
  150. prev_function.call_param_patterns_id = new_function.call_param_patterns_id;
  151. prev_function.call_params_id = new_function.call_params_id;
  152. prev_function.return_type_inst_id = new_function.return_type_inst_id;
  153. prev_function.return_form_inst_id = new_function.return_form_inst_id;
  154. prev_function.return_patterns_id = new_function.return_patterns_id;
  155. prev_function.self_param_id = new_function.self_param_id;
  156. }
  157. if (prev_import_ir_id.has_value()) {
  158. ReplacePrevInstForMerge(context, new_function.parent_scope_id,
  159. prev_function.name_id,
  160. new_function.first_owning_decl_id);
  161. }
  162. return true;
  163. }
  164. // Check whether this is a redeclaration, merging if needed.
  165. static auto TryMergeRedecl(Context& context, Parse::AnyFunctionDeclId node_id,
  166. const DeclNameStack::NameContext& name_context,
  167. SemIR::FunctionDecl& function_decl,
  168. SemIR::Function& function_info, bool is_definition)
  169. -> void {
  170. if (name_context.state == DeclNameStack::NameContext::State::Poisoned) {
  171. DiagnosePoisonedName(context, name_context.name_id_for_new_inst(),
  172. name_context.poisoning_loc_id, name_context.loc_id);
  173. return;
  174. }
  175. auto prev_id = name_context.prev_inst_id();
  176. if (!prev_id.has_value()) {
  177. return;
  178. }
  179. auto prev_function_id = SemIR::FunctionId::None;
  180. auto prev_type_id = SemIR::TypeId::None;
  181. auto prev_import_ir_id = SemIR::ImportIRId::None;
  182. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  183. case CARBON_KIND(SemIR::AssociatedEntity assoc_entity): {
  184. // This is a function in an interface definition scope (see
  185. // NameScope::is_interface_definition()).
  186. auto function_decl =
  187. context.insts().GetAs<SemIR::FunctionDecl>(assoc_entity.decl_id);
  188. prev_function_id = function_decl.function_id;
  189. prev_type_id = function_decl.type_id;
  190. break;
  191. }
  192. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  193. prev_function_id = function_decl.function_id;
  194. prev_type_id = function_decl.type_id;
  195. break;
  196. }
  197. case SemIR::ImportRefLoaded::Kind: {
  198. auto import_ir_inst = GetCanonicalImportIRInst(context, prev_id);
  199. // Verify the decl so that things like aliases are name conflicts.
  200. const auto* import_ir =
  201. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  202. if (!import_ir->insts().Is<SemIR::FunctionDecl>(
  203. import_ir_inst.inst_id())) {
  204. break;
  205. }
  206. // Use the type to get the ID.
  207. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  208. context.constant_values().GetConstantInstId(prev_id))) {
  209. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  210. struct_value->type_id)) {
  211. prev_function_id = function_type->function_id;
  212. prev_type_id = struct_value->type_id;
  213. prev_import_ir_id = import_ir_inst.ir_id();
  214. }
  215. }
  216. break;
  217. }
  218. default:
  219. break;
  220. }
  221. if (!prev_function_id.has_value()) {
  222. DiagnoseDuplicateName(context, name_context.name_id, name_context.loc_id,
  223. SemIR::LocId(prev_id));
  224. return;
  225. }
  226. if (MergeFunctionRedecl(context, node_id, function_info, is_definition,
  227. prev_function_id, prev_import_ir_id)) {
  228. // When merging, use the existing function rather than adding a new one.
  229. function_decl.function_id = prev_function_id;
  230. function_decl.type_id = prev_type_id;
  231. }
  232. }
  233. // Adds the declaration to name lookup when appropriate.
  234. static auto MaybeAddToNameLookup(
  235. Context& context, const DeclNameStack::NameContext& name_context,
  236. const KeywordModifierSet& modifier_set,
  237. const std::optional<SemIR::Inst>& parent_scope_inst, SemIR::InstId decl_id)
  238. -> void {
  239. if (name_context.state == DeclNameStack::NameContext::State::Poisoned ||
  240. name_context.prev_inst_id().has_value()) {
  241. return;
  242. }
  243. // At interface scope, a function declaration introduces an associated
  244. // function.
  245. auto lookup_result_id = decl_id;
  246. if (parent_scope_inst && !name_context.has_qualifiers) {
  247. if (auto interface_scope =
  248. parent_scope_inst->TryAs<SemIR::InterfaceDecl>()) {
  249. lookup_result_id = BuildAssociatedEntity(
  250. context, interface_scope->interface_id, decl_id);
  251. }
  252. }
  253. context.decl_name_stack().AddName(name_context, lookup_result_id,
  254. modifier_set.GetAccessKind());
  255. }
  256. // If the function is the entry point, do corresponding validation.
  257. static auto ValidateForEntryPoint(Context& context,
  258. Parse::AnyFunctionDeclId node_id,
  259. SemIR::FunctionId function_id,
  260. const SemIR::Function& function_info)
  261. -> void {
  262. if (!SemIR::IsEntryPoint(context.sem_ir(), function_id)) {
  263. return;
  264. }
  265. auto return_type_id = function_info.GetDeclaredReturnType(context.sem_ir());
  266. // TODO: Update this once valid signatures for the entry point are decided.
  267. if (function_info.implicit_param_patterns_id.has_value() ||
  268. !function_info.param_patterns_id.has_value() ||
  269. !context.inst_blocks().Get(function_info.param_patterns_id).empty() ||
  270. (return_type_id.has_value() &&
  271. return_type_id != GetTupleType(context, {}) &&
  272. // TODO: Decide on valid return types for `Main.Run`. Perhaps we should
  273. // have an interface for this.
  274. return_type_id != MakeIntType(context, node_id, SemIR::IntKind::Signed,
  275. context.ints().Add(32)))) {
  276. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  277. "invalid signature for `Main.Run` function; expected "
  278. "`fn ()` or `fn () -> i32`");
  279. context.emitter().Emit(node_id, InvalidMainRunSignature);
  280. }
  281. }
  282. static auto IsGenericFunction(Context& context,
  283. SemIR::GenericId function_generic_id,
  284. SemIR::GenericId class_generic_id) -> bool {
  285. if (function_generic_id == SemIR::GenericId::None) {
  286. return false;
  287. }
  288. if (class_generic_id == SemIR::GenericId::None) {
  289. return true;
  290. }
  291. const auto& function_generic = context.generics().Get(function_generic_id);
  292. const auto& class_generic = context.generics().Get(class_generic_id);
  293. auto function_bindings =
  294. context.inst_blocks().Get(function_generic.bindings_id);
  295. auto class_bindings = context.inst_blocks().Get(class_generic.bindings_id);
  296. // If the function's bindings are the same size as the class's bindings,
  297. // then there are no extra bindings for the function, so it is effectively
  298. // non-generic within the scope of a specific of the class.
  299. return class_bindings.size() != function_bindings.size();
  300. }
  301. // Requests a vtable be created when processing a virtual function.
  302. static auto RequestVtableIfVirtual(
  303. Context& context, Parse::AnyFunctionDeclId node_id,
  304. SemIR::Function::VirtualModifier& virtual_modifier,
  305. const std::optional<SemIR::Inst>& parent_scope_inst, SemIR::InstId decl_id,
  306. SemIR::GenericId generic_id) -> void {
  307. // In order to request a vtable, the function must be virtual, and in a class
  308. // scope.
  309. if (virtual_modifier == SemIR::Function::VirtualModifier::None ||
  310. !parent_scope_inst) {
  311. return;
  312. }
  313. auto class_decl = parent_scope_inst->TryAs<SemIR::ClassDecl>();
  314. if (!class_decl) {
  315. return;
  316. }
  317. auto& class_info = context.classes().Get(class_decl->class_id);
  318. if (virtual_modifier == SemIR::Function::VirtualModifier::Override &&
  319. !class_info.base_id.has_value()) {
  320. CARBON_DIAGNOSTIC(OverrideWithoutBase, Error,
  321. "override without base class");
  322. context.emitter().Emit(node_id, OverrideWithoutBase);
  323. virtual_modifier = SemIR::Function::VirtualModifier::None;
  324. return;
  325. }
  326. if (IsGenericFunction(context, generic_id, class_info.generic_id)) {
  327. CARBON_DIAGNOSTIC(GenericVirtual, Error, "generic virtual function");
  328. context.emitter().Emit(node_id, GenericVirtual);
  329. virtual_modifier = SemIR::Function::VirtualModifier::None;
  330. return;
  331. }
  332. // TODO: If this is an `impl` function, check there's a matching base
  333. // function that's impl or virtual.
  334. class_info.is_dynamic = true;
  335. context.vtable_stack().AddInstId(decl_id);
  336. }
  337. // Diagnoses when positional params aren't supported. Reassigns the pattern
  338. // block if needed.
  339. static auto DiagnosePositionalParams(Context& context,
  340. SemIR::Function& function_info) -> void {
  341. if (function_info.param_patterns_id.has_value()) {
  342. return;
  343. }
  344. context.TODO(function_info.latest_decl_id(),
  345. "function with positional parameters");
  346. function_info.param_patterns_id = SemIR::InstBlockId::Empty;
  347. }
  348. // Build a FunctionDecl describing the signature of a function. This
  349. // handles the common logic shared by function declaration syntax and function
  350. // definition syntax.
  351. static auto BuildFunctionDecl(Context& context,
  352. Parse::AnyFunctionDeclId node_id,
  353. bool is_definition)
  354. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  355. auto return_patterns_id = SemIR::InstBlockId::None;
  356. auto return_type_inst_id = SemIR::TypeInstId::None;
  357. auto return_form_inst_id = SemIR::InstId::None;
  358. if (auto [return_node, maybe_return_patterns_id] =
  359. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  360. maybe_return_patterns_id) {
  361. return_patterns_id = *maybe_return_patterns_id;
  362. auto return_form = context.PopReturnForm();
  363. return_type_inst_id = return_form.type_component_id;
  364. return_form_inst_id = return_form.form_inst_id;
  365. }
  366. auto name = PopNameComponent(context, return_patterns_id);
  367. auto name_context = context.decl_name_stack().FinishName(name);
  368. context.node_stack()
  369. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  370. auto self_param_id =
  371. FindSelfPattern(context, name.implicit_param_patterns_id);
  372. // Process modifiers.
  373. auto [parent_scope_inst_id, parent_scope_inst] =
  374. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  375. auto introducer =
  376. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Fn>();
  377. DiagnoseModifiers(context, node_id, introducer, is_definition,
  378. parent_scope_inst_id, parent_scope_inst, self_param_id);
  379. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  380. auto virtual_modifier = GetVirtualModifier(introducer.modifier_set);
  381. // Add the function declaration.
  382. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  383. SemIR::FunctionId::None,
  384. context.inst_block_stack().Pop()};
  385. auto decl_id = AddPlaceholderInst(context, node_id, function_decl);
  386. // Build the function entity. This will be merged into an existing function if
  387. // there is one, or otherwise added to the function store.
  388. auto function_info =
  389. SemIR::Function{name_context.MakeEntityWithParamsBase(
  390. name, decl_id, is_extern, introducer.extern_library),
  391. {.call_param_patterns_id = name.call_param_patterns_id,
  392. .call_params_id = name.call_params_id,
  393. .return_type_inst_id = return_type_inst_id,
  394. .return_form_inst_id = return_form_inst_id,
  395. .return_patterns_id = return_patterns_id,
  396. .virtual_modifier = virtual_modifier,
  397. .self_param_id = self_param_id}};
  398. if (is_definition) {
  399. function_info.definition_id = decl_id;
  400. }
  401. DiagnosePositionalParams(context, function_info);
  402. TryMergeRedecl(context, node_id, name_context, function_decl, function_info,
  403. is_definition);
  404. // Create a new function if this isn't a valid redeclaration.
  405. if (!function_decl.function_id.has_value()) {
  406. if (function_info.is_extern && context.sem_ir().is_impl()) {
  407. DiagnoseExternRequiresDeclInApiFile(context, node_id);
  408. }
  409. function_info.generic_id = BuildGenericDecl(context, decl_id);
  410. function_decl.function_id = context.functions().Add(function_info);
  411. function_decl.type_id =
  412. GetFunctionType(context, function_decl.function_id,
  413. context.scope_stack().PeekSpecificId());
  414. } else {
  415. auto prev_decl_generic_id =
  416. context.functions().Get(function_decl.function_id).generic_id;
  417. FinishGenericRedecl(context, prev_decl_generic_id);
  418. // TODO: Validate that the redeclaration doesn't set an access modifier.
  419. }
  420. RequestVtableIfVirtual(context, node_id, function_info.virtual_modifier,
  421. parent_scope_inst, decl_id, function_info.generic_id);
  422. // Write the function ID into the FunctionDecl.
  423. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  424. // Diagnose 'definition of `abstract` function' using the canonical Function's
  425. // modifiers.
  426. if (is_definition &&
  427. context.functions().Get(function_decl.function_id).virtual_modifier ==
  428. SemIR::Function::VirtualModifier::Abstract) {
  429. CARBON_DIAGNOSTIC(DefinedAbstractFunction, Error,
  430. "definition of `abstract` function");
  431. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  432. DefinedAbstractFunction);
  433. }
  434. // Add to name lookup if needed, now that the decl is built.
  435. MaybeAddToNameLookup(context, name_context, introducer.modifier_set,
  436. parent_scope_inst, decl_id);
  437. ValidateForEntryPoint(context, node_id, function_decl.function_id,
  438. function_info);
  439. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  440. context.definitions_required_by_decl().push_back(decl_id);
  441. }
  442. return {function_decl.function_id, decl_id};
  443. }
  444. auto HandleParseNode(Context& context, Parse::FunctionDeclId node_id) -> bool {
  445. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  446. context.decl_name_stack().PopScope();
  447. return true;
  448. }
  449. // Processes a function definition after a signature for which we have already
  450. // built a function ID. This logic is shared between processing regular function
  451. // definitions and delayed parsing of inline method definitions.
  452. static auto HandleFunctionDefinitionAfterSignature(
  453. Context& context, Parse::FunctionDefinitionStartId node_id,
  454. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  455. StartFunctionDefinition(context, decl_id, function_id);
  456. context.node_stack().Push(node_id, function_id);
  457. }
  458. auto HandleFunctionDefinitionSuspend(Context& context,
  459. Parse::FunctionDefinitionStartId node_id)
  460. -> DeferredDefinitionWorklist::SuspendedFunction {
  461. // Process the declaration portion of the function.
  462. auto [function_id, decl_id] =
  463. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  464. return {.function_id = function_id,
  465. .decl_id = decl_id,
  466. .saved_name_state = context.decl_name_stack().Suspend()};
  467. }
  468. auto HandleFunctionDefinitionResume(
  469. Context& context, Parse::FunctionDefinitionStartId node_id,
  470. DeferredDefinitionWorklist::SuspendedFunction&& suspended_fn) -> void {
  471. context.decl_name_stack().Restore(std::move(suspended_fn.saved_name_state));
  472. HandleFunctionDefinitionAfterSignature(
  473. context, node_id, suspended_fn.function_id, suspended_fn.decl_id);
  474. }
  475. auto HandleParseNode(Context& context, Parse::FunctionDefinitionStartId node_id)
  476. -> bool {
  477. // Process the declaration portion of the function.
  478. auto [function_id, decl_id] =
  479. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  480. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  481. decl_id);
  482. return true;
  483. }
  484. auto HandleParseNode(Context& context, Parse::FunctionDefinitionId node_id)
  485. -> bool {
  486. SemIR::FunctionId function_id =
  487. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  488. // If the `}` of the function is reachable, reject if we need a return value
  489. // and otherwise add an implicit `return;`.
  490. if (IsCurrentPositionReachable(context)) {
  491. if (context.functions().Get(function_id).return_form_inst_id.has_value()) {
  492. CARBON_DIAGNOSTIC(
  493. MissingReturnStatement, Error,
  494. "missing `return` at end of function with declared return type");
  495. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  496. MissingReturnStatement);
  497. } else {
  498. AddReturnCleanupBlock(context, node_id);
  499. }
  500. }
  501. FinishFunctionDefinition(context, function_id);
  502. context.decl_name_stack().PopScope();
  503. return true;
  504. }
  505. auto HandleParseNode(Context& context,
  506. Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  507. // Process the declaration portion of the function.
  508. auto [function_id, _] =
  509. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  510. context.node_stack().Push(node_id, function_id);
  511. return true;
  512. }
  513. auto HandleParseNode(Context& context, Parse::BuiltinNameId node_id) -> bool {
  514. context.node_stack().Push(node_id);
  515. return true;
  516. }
  517. // Looks up a builtin function kind given its name as a string.
  518. // TODO: Move this out to another file.
  519. static auto LookupBuiltinFunctionKind(Context& context,
  520. Parse::BuiltinNameId name_id)
  521. -> SemIR::BuiltinFunctionKind {
  522. auto builtin_name = context.string_literal_values().Get(
  523. context.tokens().GetStringLiteralValue(
  524. context.parse_tree().node_token(name_id)));
  525. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  526. if (kind == SemIR::BuiltinFunctionKind::None) {
  527. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  528. "unknown builtin function name \"{0}\"", std::string);
  529. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  530. builtin_name.str());
  531. }
  532. return kind;
  533. }
  534. auto HandleParseNode(Context& context,
  535. Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  536. auto name_id =
  537. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  538. auto [fn_node_id, function_id] =
  539. context.node_stack()
  540. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  541. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  542. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  543. CheckFunctionDefinitionSignature(context, function_id);
  544. auto& function = context.functions().Get(function_id);
  545. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  546. function.SetBuiltinFunction(builtin_kind);
  547. // Build an empty generic definition if this is a generic builtin.
  548. StartGenericDefinition(context, function.generic_id);
  549. FinishGenericDefinition(context, function.generic_id);
  550. } else {
  551. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  552. "invalid signature for builtin function \"{0}\"",
  553. std::string);
  554. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  555. builtin_kind.name().str());
  556. }
  557. }
  558. context.decl_name_stack().PopScope();
  559. return true;
  560. }
  561. auto HandleParseNode(Context& context, Parse::FunctionTerseDefinitionId node_id)
  562. -> bool {
  563. return context.TODO(node_id, "HandleFunctionTerseDefinition");
  564. }
  565. } // namespace Carbon::Check