handle_function.cpp 30 KB

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