handle_function.cpp 27 KB

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