handle_function.cpp 31 KB

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