handle_function.cpp 32 KB

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