handle_function.cpp 28 KB

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