handle_function.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 pattern_type_id = GetPatternType(context, as_type.type_id);
  69. auto return_slot_pattern_id = AddPatternInst<SemIR::ReturnSlotPattern>(
  70. context, node_id,
  71. {.type_id = pattern_type_id, .type_inst_id = as_type.inst_id});
  72. auto param_pattern_id = AddPatternInst<SemIR::OutParamPattern>(
  73. context, node_id,
  74. {.type_id = pattern_type_id,
  75. .subpattern_id = return_slot_pattern_id,
  76. .index = SemIR::CallParamIndex::None});
  77. context.node_stack().Push(node_id, param_pattern_id);
  78. return true;
  79. }
  80. // Returns the ID of the self parameter pattern, or None.
  81. // TODO: Do this during initial traversal of implicit params.
  82. static auto FindSelfPattern(Context& context,
  83. SemIR::InstBlockId implicit_param_patterns_id)
  84. -> SemIR::InstId {
  85. auto implicit_param_patterns =
  86. context.inst_blocks().GetOrEmpty(implicit_param_patterns_id);
  87. return FindIfOrNone(implicit_param_patterns, [&](auto implicit_param_id) {
  88. return SemIR::IsSelfPattern(context.sem_ir(), implicit_param_id);
  89. });
  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, SemIR::LocId(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>(
  207. import_ir_inst.inst_id())) {
  208. break;
  209. }
  210. // Use the type to get the ID.
  211. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  212. context.constant_values().GetConstantInstId(prev_id))) {
  213. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  214. struct_value->type_id)) {
  215. prev_function_id = function_type->function_id;
  216. prev_type_id = struct_value->type_id;
  217. prev_import_ir_id = import_ir_inst.ir_id();
  218. }
  219. }
  220. break;
  221. }
  222. default:
  223. break;
  224. }
  225. if (!prev_function_id.has_value()) {
  226. DiagnoseDuplicateName(context, name_context.name_id, name_context.loc_id,
  227. SemIR::LocId(prev_id));
  228. return;
  229. }
  230. if (MergeFunctionRedecl(context, node_id, function_info, is_definition,
  231. prev_function_id, prev_import_ir_id)) {
  232. // When merging, use the existing function rather than adding a new one.
  233. function_decl.function_id = prev_function_id;
  234. function_decl.type_id = prev_type_id;
  235. }
  236. }
  237. // Adds the declaration to name lookup when appropriate.
  238. static auto MaybeAddToNameLookup(
  239. Context& context, const DeclNameStack::NameContext& name_context,
  240. const KeywordModifierSet& modifier_set,
  241. const std::optional<SemIR::Inst>& parent_scope_inst, SemIR::InstId decl_id)
  242. -> void {
  243. if (name_context.state == DeclNameStack::NameContext::State::Poisoned ||
  244. name_context.prev_inst_id().has_value()) {
  245. return;
  246. }
  247. // At interface scope, a function declaration introduces an associated
  248. // function.
  249. auto lookup_result_id = decl_id;
  250. if (parent_scope_inst && !name_context.has_qualifiers) {
  251. if (auto interface_scope =
  252. parent_scope_inst->TryAs<SemIR::InterfaceDecl>()) {
  253. lookup_result_id = BuildAssociatedEntity(
  254. context, interface_scope->interface_id, decl_id);
  255. }
  256. }
  257. context.decl_name_stack().AddName(name_context, lookup_result_id,
  258. modifier_set.GetAccessKind());
  259. }
  260. // If the function is the entry point, do corresponding validation.
  261. static auto ValidateForEntryPoint(Context& context,
  262. Parse::AnyFunctionDeclId node_id,
  263. SemIR::FunctionId function_id,
  264. const SemIR::Function& function_info)
  265. -> void {
  266. if (!SemIR::IsEntryPoint(context.sem_ir(), function_id)) {
  267. return;
  268. }
  269. auto return_type_id = function_info.GetDeclaredReturnType(context.sem_ir());
  270. // TODO: Update this once valid signatures for the entry point are decided.
  271. if (function_info.implicit_param_patterns_id.has_value() ||
  272. !function_info.param_patterns_id.has_value() ||
  273. !context.inst_blocks().Get(function_info.param_patterns_id).empty() ||
  274. (return_type_id.has_value() &&
  275. return_type_id != GetTupleType(context, {}) &&
  276. // TODO: Decide on valid return types for `Main.Run`. Perhaps we should
  277. // have an interface for this.
  278. return_type_id != MakeIntType(context, node_id, SemIR::IntKind::Signed,
  279. context.ints().Add(32)))) {
  280. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  281. "invalid signature for `Main.Run` function; expected "
  282. "`fn ()` or `fn () -> i32`");
  283. context.emitter().Emit(node_id, InvalidMainRunSignature);
  284. }
  285. }
  286. static auto IsGenericFunction(Context& context,
  287. SemIR::GenericId function_generic_id,
  288. SemIR::GenericId class_generic_id) -> bool {
  289. if (function_generic_id == SemIR::GenericId::None) {
  290. return false;
  291. }
  292. if (class_generic_id == SemIR::GenericId::None) {
  293. return true;
  294. }
  295. const auto& function_generic = context.generics().Get(function_generic_id);
  296. const auto& class_generic = context.generics().Get(class_generic_id);
  297. auto function_bindings =
  298. context.inst_blocks().Get(function_generic.bindings_id);
  299. auto class_bindings = context.inst_blocks().Get(class_generic.bindings_id);
  300. // If the function's bindings are the same size as the class's bindings,
  301. // then there are no extra bindings for the function, so it is effectively
  302. // non-generic within the scope of a specific of the class.
  303. return class_bindings.size() != function_bindings.size();
  304. }
  305. // Requests a vtable be created when processing a virtual function.
  306. static auto RequestVtableIfVirtual(
  307. Context& context, Parse::AnyFunctionDeclId node_id,
  308. SemIR::Function::VirtualModifier virtual_modifier,
  309. const std::optional<SemIR::Inst>& parent_scope_inst, SemIR::InstId decl_id,
  310. SemIR::GenericId generic_id) -> void {
  311. // In order to request a vtable, the function must be virtual, and in a class
  312. // scope.
  313. if (virtual_modifier == SemIR::Function::VirtualModifier::None ||
  314. !parent_scope_inst) {
  315. return;
  316. }
  317. auto class_decl = parent_scope_inst->TryAs<SemIR::ClassDecl>();
  318. if (!class_decl) {
  319. return;
  320. }
  321. auto& class_info = context.classes().Get(class_decl->class_id);
  322. if (virtual_modifier == SemIR::Function::VirtualModifier::Impl &&
  323. !class_info.base_id.has_value()) {
  324. CARBON_DIAGNOSTIC(ImplWithoutBase, Error, "impl without base class");
  325. context.emitter().Emit(node_id, ImplWithoutBase);
  326. }
  327. if (IsGenericFunction(context, generic_id, class_info.generic_id)) {
  328. CARBON_DIAGNOSTIC(GenericVirtual, Error, "generic virtual function");
  329. context.emitter().Emit(node_id, GenericVirtual);
  330. return;
  331. }
  332. // TODO: If this is an `impl` function, check there's a matching base
  333. // function that's impl or virtual.
  334. class_info.is_dynamic = true;
  335. context.vtable_stack().AddInstId(decl_id);
  336. }
  337. // Validates the `destroy` function's signature. May replace invalid values for
  338. // recovery.
  339. static auto ValidateIfDestroy(Context& context, bool is_redecl,
  340. std::optional<SemIR::Inst> parent_scope_inst,
  341. SemIR::Function& function_info) -> void {
  342. if (function_info.name_id != SemIR::NameId::Destroy) {
  343. return;
  344. }
  345. // For recovery, always force explicit parameters to be empty. We do this
  346. // before any of the returns for simplicity.
  347. auto orig_param_patterns_id = function_info.param_patterns_id;
  348. function_info.param_patterns_id = SemIR::InstBlockId::Empty;
  349. // Use differences on merge to diagnose remaining issues.
  350. if (is_redecl) {
  351. return;
  352. }
  353. if (!parent_scope_inst || !parent_scope_inst->Is<SemIR::ClassDecl>()) {
  354. CARBON_DIAGNOSTIC(DestroyFunctionOutsideClass, Error,
  355. "declaring `fn destroy` in non-class scope");
  356. context.emitter().Emit(function_info.latest_decl_id(),
  357. DestroyFunctionOutsideClass);
  358. return;
  359. }
  360. if (!function_info.self_param_id.has_value()) {
  361. CARBON_DIAGNOSTIC(DestroyFunctionMissingSelf, Error,
  362. "missing implicit `self` parameter");
  363. context.emitter().Emit(function_info.latest_decl_id(),
  364. DestroyFunctionMissingSelf);
  365. return;
  366. }
  367. // `self` must be the only implicit parameter.
  368. if (auto block =
  369. context.inst_blocks().Get(function_info.implicit_param_patterns_id);
  370. block.size() > 1) {
  371. // Point at the first non-`self` parameter.
  372. auto param_id = block[function_info.self_param_id == block[0] ? 1 : 0];
  373. CARBON_DIAGNOSTIC(DestroyFunctionUnexpectedImplicitParam, Error,
  374. "unexpected implicit parameter");
  375. context.emitter().Emit(param_id, DestroyFunctionUnexpectedImplicitParam);
  376. return;
  377. }
  378. if (!orig_param_patterns_id.has_value()) {
  379. CARBON_DIAGNOSTIC(DestroyFunctionPositionalParams, Error,
  380. "missing empty explicit parameter list");
  381. context.emitter().Emit(function_info.latest_decl_id(),
  382. DestroyFunctionPositionalParams);
  383. return;
  384. }
  385. if (orig_param_patterns_id != SemIR::InstBlockId::Empty) {
  386. CARBON_DIAGNOSTIC(DestroyFunctionNonEmptyExplicitParams, Error,
  387. "unexpected parameter");
  388. context.emitter().Emit(context.inst_blocks().Get(orig_param_patterns_id)[0],
  389. DestroyFunctionNonEmptyExplicitParams);
  390. return;
  391. }
  392. if (auto return_type_id =
  393. function_info.GetDeclaredReturnType(context.sem_ir());
  394. return_type_id.has_value() &&
  395. return_type_id != GetTupleType(context, {})) {
  396. CARBON_DIAGNOSTIC(DestroyFunctionIncorrectReturnType, Error,
  397. "incorrect return type; must be unspecified or `()`");
  398. context.emitter().Emit(function_info.return_slot_pattern_id,
  399. DestroyFunctionIncorrectReturnType);
  400. return;
  401. }
  402. }
  403. // Diagnoses when positional params aren't supported. Reassigns the pattern
  404. // block if needed.
  405. static auto DiagnosePositionalParams(Context& context,
  406. SemIR::Function& function_info) -> void {
  407. if (function_info.param_patterns_id.has_value()) {
  408. return;
  409. }
  410. context.TODO(function_info.latest_decl_id(),
  411. "function with positional parameters");
  412. function_info.param_patterns_id = SemIR::InstBlockId::Empty;
  413. }
  414. // Build a FunctionDecl describing the signature of a function. This
  415. // handles the common logic shared by function declaration syntax and function
  416. // definition syntax.
  417. static auto BuildFunctionDecl(Context& context,
  418. Parse::AnyFunctionDeclId node_id,
  419. bool is_definition)
  420. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  421. auto return_slot_pattern_id = SemIR::InstId::None;
  422. if (auto [return_node, maybe_return_slot_pattern_id] =
  423. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  424. maybe_return_slot_pattern_id) {
  425. return_slot_pattern_id = *maybe_return_slot_pattern_id;
  426. }
  427. auto name = PopNameComponent(context, return_slot_pattern_id);
  428. auto name_context = context.decl_name_stack().FinishName(name);
  429. context.node_stack()
  430. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  431. auto self_param_id =
  432. FindSelfPattern(context, name.implicit_param_patterns_id);
  433. // Process modifiers.
  434. auto [parent_scope_inst_id, parent_scope_inst] =
  435. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  436. auto introducer =
  437. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Fn>();
  438. DiagnoseModifiers(context, node_id, introducer, is_definition,
  439. parent_scope_inst_id, parent_scope_inst, self_param_id);
  440. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  441. auto virtual_modifier = GetVirtualModifier(introducer.modifier_set);
  442. // Add the function declaration.
  443. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  444. SemIR::FunctionId::None,
  445. context.inst_block_stack().Pop()};
  446. auto decl_id = AddPlaceholderInst(context, node_id, function_decl);
  447. // Build the function entity. This will be merged into an existing function if
  448. // there is one, or otherwise added to the function store.
  449. auto function_info =
  450. SemIR::Function{name_context.MakeEntityWithParamsBase(
  451. name, decl_id, is_extern, introducer.extern_library),
  452. {.call_params_id = name.call_params_id,
  453. .return_slot_pattern_id = name.return_slot_pattern_id,
  454. .virtual_modifier = virtual_modifier,
  455. .self_param_id = self_param_id}};
  456. if (is_definition) {
  457. function_info.definition_id = decl_id;
  458. }
  459. // Analyze standard function signatures before positional parameters, so that
  460. // we can have more specific diagnostics and recovery.
  461. bool is_redecl =
  462. name_context.state == DeclNameStack::NameContext::State::Resolved;
  463. ValidateIfDestroy(context, is_redecl, parent_scope_inst, function_info);
  464. DiagnosePositionalParams(context, function_info);
  465. TryMergeRedecl(context, node_id, name_context, function_decl, function_info,
  466. is_definition);
  467. // Create a new function if this isn't a valid redeclaration.
  468. if (!function_decl.function_id.has_value()) {
  469. if (function_info.is_extern && context.sem_ir().is_impl()) {
  470. DiagnoseExternRequiresDeclInApiFile(context, node_id);
  471. }
  472. function_info.generic_id = BuildGenericDecl(context, decl_id);
  473. function_decl.function_id = context.functions().Add(function_info);
  474. function_decl.type_id =
  475. GetFunctionType(context, function_decl.function_id,
  476. context.scope_stack().PeekSpecificId());
  477. } else {
  478. auto prev_decl_generic_id =
  479. context.functions().Get(function_decl.function_id).generic_id;
  480. FinishGenericRedecl(context, prev_decl_generic_id);
  481. // TODO: Validate that the redeclaration doesn't set an access modifier.
  482. }
  483. RequestVtableIfVirtual(context, node_id, virtual_modifier, parent_scope_inst,
  484. decl_id, function_info.generic_id);
  485. // Write the function ID into the FunctionDecl.
  486. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  487. // Diagnose 'definition of `abstract` function' using the canonical Function's
  488. // modifiers.
  489. if (is_definition &&
  490. context.functions().Get(function_decl.function_id).virtual_modifier ==
  491. SemIR::Function::VirtualModifier::Abstract) {
  492. CARBON_DIAGNOSTIC(DefinedAbstractFunction, Error,
  493. "definition of `abstract` function");
  494. context.emitter().Emit(SemIR::LocId(node_id).ToTokenOnly(),
  495. DefinedAbstractFunction);
  496. }
  497. // Add to name lookup if needed, now that the decl is built.
  498. MaybeAddToNameLookup(context, name_context, introducer.modifier_set,
  499. parent_scope_inst, decl_id);
  500. ValidateForEntryPoint(context, node_id, function_decl.function_id,
  501. function_info);
  502. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  503. context.definitions_required_by_decl().push_back(decl_id);
  504. }
  505. return {function_decl.function_id, decl_id};
  506. }
  507. auto HandleParseNode(Context& context, Parse::FunctionDeclId node_id) -> bool {
  508. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  509. context.decl_name_stack().PopScope();
  510. return true;
  511. }
  512. static auto CheckFunctionDefinitionSignature(Context& context,
  513. SemIR::Function& function)
  514. -> void {
  515. auto params_to_complete =
  516. context.inst_blocks().GetOrEmpty(function.call_params_id);
  517. // Check the return type is complete.
  518. if (function.return_slot_pattern_id.has_value()) {
  519. CheckFunctionReturnType(context,
  520. SemIR::LocId(function.return_slot_pattern_id),
  521. function, SemIR::SpecificId::None);
  522. params_to_complete = params_to_complete.drop_back();
  523. }
  524. // Check the parameter types are complete.
  525. for (auto param_ref_id : params_to_complete) {
  526. if (param_ref_id == SemIR::ErrorInst::InstId) {
  527. continue;
  528. }
  529. // The parameter types need to be complete.
  530. RequireCompleteType(
  531. context, context.insts().GetAs<SemIR::AnyParam>(param_ref_id).type_id,
  532. SemIR::LocId(param_ref_id), [&] {
  533. CARBON_DIAGNOSTIC(
  534. IncompleteTypeInFunctionParam, Error,
  535. "parameter has incomplete type {0} in function definition",
  536. TypeOfInstId);
  537. return context.emitter().Build(
  538. param_ref_id, IncompleteTypeInFunctionParam, param_ref_id);
  539. });
  540. }
  541. }
  542. // Processes a function definition after a signature for which we have already
  543. // built a function ID. This logic is shared between processing regular function
  544. // definitions and delayed parsing of inline method definitions.
  545. static auto HandleFunctionDefinitionAfterSignature(
  546. Context& context, Parse::FunctionDefinitionStartId node_id,
  547. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  548. auto& function = context.functions().Get(function_id);
  549. // Create the function scope and the entry block.
  550. context.scope_stack().PushForFunctionBody(decl_id);
  551. context.inst_block_stack().Push();
  552. context.region_stack().PushRegion(context.inst_block_stack().PeekOrAdd());
  553. StartGenericDefinition(context, function.generic_id);
  554. CheckFunctionDefinitionSignature(context, function);
  555. context.node_stack().Push(node_id, function_id);
  556. }
  557. auto HandleFunctionDefinitionSuspend(Context& context,
  558. Parse::FunctionDefinitionStartId node_id)
  559. -> SuspendedFunction {
  560. // Process the declaration portion of the function.
  561. auto [function_id, decl_id] =
  562. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  563. return {.function_id = function_id,
  564. .decl_id = decl_id,
  565. .saved_name_state = context.decl_name_stack().Suspend()};
  566. }
  567. auto HandleFunctionDefinitionResume(Context& context,
  568. Parse::FunctionDefinitionStartId node_id,
  569. SuspendedFunction suspended_fn) -> void {
  570. context.decl_name_stack().Restore(suspended_fn.saved_name_state);
  571. HandleFunctionDefinitionAfterSignature(
  572. context, node_id, suspended_fn.function_id, suspended_fn.decl_id);
  573. }
  574. auto HandleParseNode(Context& context, Parse::FunctionDefinitionStartId node_id)
  575. -> bool {
  576. // Process the declaration portion of the function.
  577. auto [function_id, decl_id] =
  578. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  579. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  580. decl_id);
  581. return true;
  582. }
  583. auto HandleParseNode(Context& context, Parse::FunctionDefinitionId node_id)
  584. -> bool {
  585. SemIR::FunctionId function_id =
  586. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  587. // If the `}` of the function is reachable, reject if we need a return value
  588. // and otherwise add an implicit `return;`.
  589. if (IsCurrentPositionReachable(context)) {
  590. if (context.functions()
  591. .Get(function_id)
  592. .return_slot_pattern_id.has_value()) {
  593. CARBON_DIAGNOSTIC(
  594. MissingReturnStatement, Error,
  595. "missing `return` at end of function with declared return type");
  596. context.emitter().Emit(SemIR::LocId(node_id).ToTokenOnly(),
  597. MissingReturnStatement);
  598. } else {
  599. AddReturnCleanupBlock(context, node_id);
  600. }
  601. }
  602. context.inst_block_stack().Pop();
  603. context.scope_stack().Pop();
  604. context.decl_name_stack().PopScope();
  605. auto& function = context.functions().Get(function_id);
  606. function.body_block_ids = context.region_stack().PopRegion();
  607. // If this is a generic function, collect information about the definition.
  608. FinishGenericDefinition(context, function.generic_id);
  609. return true;
  610. }
  611. auto HandleParseNode(Context& context,
  612. Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  613. // Process the declaration portion of the function.
  614. auto [function_id, _] =
  615. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  616. context.node_stack().Push(node_id, function_id);
  617. return true;
  618. }
  619. auto HandleParseNode(Context& context, Parse::BuiltinNameId node_id) -> bool {
  620. context.node_stack().Push(node_id);
  621. return true;
  622. }
  623. // Looks up a builtin function kind given its name as a string.
  624. // TODO: Move this out to another file.
  625. static auto LookupBuiltinFunctionKind(Context& context,
  626. Parse::BuiltinNameId name_id)
  627. -> SemIR::BuiltinFunctionKind {
  628. auto builtin_name = context.string_literal_values().Get(
  629. context.tokens().GetStringLiteralValue(
  630. context.parse_tree().node_token(name_id)));
  631. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  632. if (kind == SemIR::BuiltinFunctionKind::None) {
  633. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  634. "unknown builtin function name \"{0}\"", std::string);
  635. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  636. builtin_name.str());
  637. }
  638. return kind;
  639. }
  640. // Returns whether `function` is a valid declaration of `builtin_kind`.
  641. static auto IsValidBuiltinDeclaration(Context& context,
  642. const SemIR::Function& function,
  643. SemIR::BuiltinFunctionKind builtin_kind)
  644. -> bool {
  645. // Find the list of call parameters other than the implicit return slot.
  646. auto call_params = context.inst_blocks().Get(function.call_params_id);
  647. if (function.return_slot_pattern_id.has_value()) {
  648. call_params = call_params.drop_back();
  649. }
  650. // Form the list of parameter types for the declaration.
  651. llvm::SmallVector<SemIR::TypeId> param_type_ids;
  652. param_type_ids.reserve(call_params.size());
  653. for (auto param_id : call_params) {
  654. // TODO: We also need to track whether the parameter is declared with
  655. // `var`.
  656. param_type_ids.push_back(context.insts().Get(param_id).type_id());
  657. }
  658. // Get the return type. This is `()` if none was specified.
  659. auto return_type_id = function.GetDeclaredReturnType(context.sem_ir());
  660. if (!return_type_id.has_value()) {
  661. return_type_id = GetTupleType(context, {});
  662. }
  663. return builtin_kind.IsValidType(context.sem_ir(), param_type_ids,
  664. return_type_id);
  665. }
  666. auto HandleParseNode(Context& context,
  667. Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  668. auto name_id =
  669. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  670. auto [fn_node_id, function_id] =
  671. context.node_stack()
  672. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  673. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  674. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  675. auto& function = context.functions().Get(function_id);
  676. CheckFunctionDefinitionSignature(context, function);
  677. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  678. function.builtin_function_kind = builtin_kind;
  679. // Build an empty generic definition if this is a generic builtin.
  680. StartGenericDefinition(context, function.generic_id);
  681. FinishGenericDefinition(context, function.generic_id);
  682. } else {
  683. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  684. "invalid signature for builtin function \"{0}\"",
  685. std::string);
  686. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  687. builtin_kind.name().str());
  688. }
  689. }
  690. context.decl_name_stack().PopScope();
  691. return true;
  692. }
  693. } // namespace Carbon::Check