handle_function.cpp 27 KB

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