handle_function.cpp 31 KB

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