handle_function.cpp 30 KB

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