handle_function.cpp 32 KB

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