handle_function.cpp 27 KB

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