handle_function.cpp 31 KB

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