handle_function.cpp 31 KB

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