handle_function.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. auto HandleParseNode(Context& context, Parse::ReturnTypeId node_id) -> bool {
  48. auto [type_node_id, type_inst_id] = context.node_stack().PopExprWithNodeId();
  49. // If the previous node was `IdentifierNameBeforeParams`, then it would have
  50. // caused these entries to be pushed to the pattern stacks. But it's possible
  51. // to have a fn declaration without any parameters, in which case we find
  52. // `IdentifierNameNotBeforeParams` on the node stack. Then these entries are
  53. // not on the pattern stacks yet. They are only needed in that case if we have
  54. // a return type, which we now know that we do.
  55. if (context.node_stack().PeekNodeKind() ==
  56. Parse::NodeKind::IdentifierNameNotBeforeParams) {
  57. context.pattern_block_stack().Push();
  58. context.full_pattern_stack().PushFullPattern(
  59. FullPatternStack::Kind::ExplicitParamList);
  60. }
  61. // Propagate the type expression.
  62. auto form_expr = ExprAsReturnForm(context, type_node_id, type_inst_id);
  63. context.PushReturnForm(form_expr);
  64. auto return_patterns_id = AddReturnPatterns(context, node_id, form_expr);
  65. context.node_stack().Push(node_id, return_patterns_id);
  66. return true;
  67. }
  68. auto HandleParseNode(Context& context, Parse::ReturnFormId node_id) -> bool {
  69. return context.TODO(node_id, "Support ->?");
  70. }
  71. // Diagnoses issues with the modifiers, removing modifiers that shouldn't be
  72. // present.
  73. static auto DiagnoseModifiers(Context& context,
  74. Parse::AnyFunctionDeclId node_id,
  75. DeclIntroducerState& introducer,
  76. bool is_definition,
  77. SemIR::NameScopeId parent_scope_id,
  78. SemIR::InstId parent_scope_inst_id,
  79. std::optional<SemIR::Inst> parent_scope_inst,
  80. SemIR::InstId self_param_id) -> void {
  81. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  82. LimitModifiersOnDecl(
  83. context, introducer,
  84. KeywordModifierSet::Access | KeywordModifierSet::Extern |
  85. KeywordModifierSet::Export | KeywordModifierSet::Method |
  86. KeywordModifierSet::Interface | KeywordModifierSet::Evaluation);
  87. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  88. is_definition);
  89. CheckMethodModifiersOnFunction(context, introducer, parent_scope_inst_id,
  90. parent_scope_inst);
  91. RequireDefaultFinalOnlyInInterfaces(context, introducer, parent_scope_id);
  92. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Interface)) {
  93. // TODO: Once we are saving the modifiers for a function, add check that
  94. // the function may only be defined if it is marked `default` or `final`.
  95. context.TODO(introducer.modifier_node_id(ModifierOrder::Decl),
  96. "interface modifier");
  97. }
  98. if (!self_param_id.has_value() &&
  99. introducer.modifier_set.HasAnyOf(KeywordModifierSet::Method)) {
  100. CARBON_DIAGNOSTIC(VirtualWithoutSelf, Error, "virtual class function");
  101. context.emitter().Emit(node_id, VirtualWithoutSelf);
  102. introducer.modifier_set.Remove(KeywordModifierSet::Method);
  103. }
  104. }
  105. // Returns the virtual-family modifier as an enum.
  106. static auto GetVirtualModifier(const KeywordModifierSet& modifier_set)
  107. -> SemIR::Function::VirtualModifier {
  108. return modifier_set.ToEnum<SemIR::Function::VirtualModifier>()
  109. .Case(KeywordModifierSet::Virtual,
  110. SemIR::Function::VirtualModifier::Virtual)
  111. .Case(KeywordModifierSet::Abstract,
  112. SemIR::Function::VirtualModifier::Abstract)
  113. .Case(KeywordModifierSet::Override,
  114. SemIR::Function::VirtualModifier::Override)
  115. .Default(SemIR::Function::VirtualModifier::None);
  116. }
  117. // Returns the evaluation modifier as an enum.
  118. static auto GetEvaluationMode(const KeywordModifierSet& modifier_set)
  119. -> SemIR::Function::EvaluationMode {
  120. return modifier_set.ToEnum<SemIR::Function::EvaluationMode>()
  121. .Case(KeywordModifierSet::Eval, SemIR::Function::EvaluationMode::Eval)
  122. .Case(KeywordModifierSet::MustEval,
  123. SemIR::Function::EvaluationMode::MustEval)
  124. .Default(SemIR::Function::EvaluationMode::None);
  125. }
  126. // Tries to merge new_function into prev_function_id. Since new_function won't
  127. // have a definition even if one is upcoming, set is_definition to indicate the
  128. // planned result.
  129. //
  130. // If merging is successful, returns true and may update the previous function.
  131. // Otherwise, returns false. Prints a diagnostic when appropriate.
  132. static auto MergeFunctionRedecl(Context& context,
  133. Parse::AnyFunctionDeclId node_id,
  134. SemIR::Function& new_function,
  135. bool new_is_definition,
  136. SemIR::FunctionId prev_function_id,
  137. SemIR::ImportIRId prev_import_ir_id) -> bool {
  138. auto& prev_function = context.functions().Get(prev_function_id);
  139. if (!CheckFunctionTypeMatches(context, new_function, prev_function)) {
  140. return false;
  141. }
  142. DiagnoseIfInvalidRedecl(
  143. context, Lex::TokenKind::Fn, prev_function.name_id,
  144. RedeclInfo(new_function, node_id, new_is_definition),
  145. RedeclInfo(prev_function, SemIR::LocId(prev_function.latest_decl_id()),
  146. prev_function.has_definition_started()),
  147. prev_import_ir_id);
  148. if (new_is_definition && prev_function.has_definition_started()) {
  149. return false;
  150. }
  151. if (!prev_function.first_owning_decl_id.has_value()) {
  152. prev_function.first_owning_decl_id = new_function.first_owning_decl_id;
  153. }
  154. if (new_is_definition) {
  155. // Track the signature from the definition, so that IDs in the body
  156. // match IDs in the signature.
  157. prev_function.MergeDefinition(new_function);
  158. prev_function.call_param_patterns_id = new_function.call_param_patterns_id;
  159. prev_function.call_params_id = new_function.call_params_id;
  160. prev_function.return_type_inst_id = new_function.return_type_inst_id;
  161. prev_function.return_form_inst_id = new_function.return_form_inst_id;
  162. prev_function.return_patterns_id = new_function.return_patterns_id;
  163. prev_function.self_param_id = new_function.self_param_id;
  164. }
  165. if (prev_import_ir_id.has_value()) {
  166. ReplacePrevInstForMerge(context, new_function.parent_scope_id,
  167. prev_function.name_id,
  168. new_function.first_owning_decl_id);
  169. }
  170. return true;
  171. }
  172. // Check whether this is a redeclaration, merging if needed.
  173. static auto TryMergeRedecl(Context& context, Parse::AnyFunctionDeclId node_id,
  174. const DeclNameStack::NameContext& name_context,
  175. SemIR::FunctionDecl& function_decl,
  176. SemIR::Function& function_info, bool is_definition)
  177. -> void {
  178. if (name_context.state == DeclNameStack::NameContext::State::Poisoned) {
  179. DiagnosePoisonedName(context, name_context.name_id_for_new_inst(),
  180. name_context.poisoning_loc_id, name_context.loc_id);
  181. return;
  182. }
  183. auto prev_id = name_context.prev_inst_id();
  184. if (!prev_id.has_value()) {
  185. return;
  186. }
  187. auto prev_function_id = SemIR::FunctionId::None;
  188. auto prev_type_id = SemIR::TypeId::None;
  189. auto prev_import_ir_id = SemIR::ImportIRId::None;
  190. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  191. case CARBON_KIND(SemIR::AssociatedEntity assoc_entity): {
  192. // This is a function in an interface definition scope (see
  193. // NameScope::is_interface_definition()).
  194. auto function_decl =
  195. context.insts().GetAs<SemIR::FunctionDecl>(assoc_entity.decl_id);
  196. prev_function_id = function_decl.function_id;
  197. prev_type_id = function_decl.type_id;
  198. break;
  199. }
  200. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  201. prev_function_id = function_decl.function_id;
  202. prev_type_id = function_decl.type_id;
  203. break;
  204. }
  205. case SemIR::ImportRefLoaded::Kind: {
  206. auto import_ir_inst = GetCanonicalImportIRInst(context, prev_id);
  207. // Verify the decl so that things like aliases are name conflicts.
  208. const auto* import_ir =
  209. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  210. if (!import_ir->insts().Is<SemIR::FunctionDecl>(
  211. import_ir_inst.inst_id())) {
  212. break;
  213. }
  214. // Use the type to get the ID.
  215. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  216. context.constant_values().GetConstantInstId(prev_id))) {
  217. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  218. struct_value->type_id)) {
  219. prev_function_id = function_type->function_id;
  220. prev_type_id = struct_value->type_id;
  221. prev_import_ir_id = import_ir_inst.ir_id();
  222. }
  223. }
  224. break;
  225. }
  226. default:
  227. break;
  228. }
  229. if (!prev_function_id.has_value()) {
  230. DiagnoseDuplicateName(context, name_context.name_id, name_context.loc_id,
  231. SemIR::LocId(prev_id));
  232. return;
  233. }
  234. if (MergeFunctionRedecl(context, node_id, function_info, is_definition,
  235. prev_function_id, prev_import_ir_id)) {
  236. // When merging, use the existing function rather than adding a new one.
  237. function_decl.function_id = prev_function_id;
  238. function_decl.type_id = prev_type_id;
  239. }
  240. }
  241. // Adds the declaration to name lookup when appropriate.
  242. static auto MaybeAddToNameLookup(Context& context,
  243. const DeclNameStack::NameContext& name_context,
  244. const KeywordModifierSet& modifier_set,
  245. SemIR::NameScopeId parent_scope_id,
  246. SemIR::InstId decl_id) -> void {
  247. if (name_context.state == DeclNameStack::NameContext::State::Poisoned ||
  248. name_context.prev_inst_id().has_value()) {
  249. return;
  250. }
  251. // At interface scope, a function declaration introduces an associated
  252. // function.
  253. auto lookup_result_id = decl_id;
  254. if (parent_scope_id.has_value() && !name_context.has_qualifiers) {
  255. const auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  256. if (parent_scope.is_interface_definition()) {
  257. auto interface_decl = context.insts().GetAs<SemIR::InterfaceWithSelfDecl>(
  258. parent_scope.inst_id());
  259. lookup_result_id =
  260. BuildAssociatedEntity(context, interface_decl.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. name_context.parent_scope_id, parent_scope_inst_id,
  471. parent_scope_inst, self_param_id);
  472. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  473. auto virtual_modifier = GetVirtualModifier(introducer.modifier_set);
  474. auto evaluation_mode = GetEvaluationMode(introducer.modifier_set);
  475. // Add the function declaration.
  476. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  477. SemIR::FunctionId::None,
  478. context.inst_block_stack().Pop()};
  479. auto decl_id = AddPlaceholderInst(context, node_id, function_decl);
  480. // Build the function entity. This will be merged into an existing function if
  481. // there is one, or otherwise added to the function store.
  482. auto function_info =
  483. SemIR::Function{name_context.MakeEntityWithParamsBase(
  484. name, decl_id, is_extern, introducer.extern_library),
  485. {.call_param_patterns_id = name.call_param_patterns_id,
  486. .call_params_id = name.call_params_id,
  487. .return_type_inst_id = return_type_inst_id,
  488. .return_form_inst_id = return_form_inst_id,
  489. .return_patterns_id = return_patterns_id,
  490. .virtual_modifier = virtual_modifier,
  491. .evaluation_mode = evaluation_mode,
  492. .self_param_id = self_param_id}};
  493. if (is_definition) {
  494. function_info.definition_id = decl_id;
  495. }
  496. DiagnosePositionalParams(context, function_info);
  497. TryMergeRedecl(context, node_id, name_context, function_decl, function_info,
  498. is_definition);
  499. // Create a new function if this isn't a valid redeclaration.
  500. if (!function_decl.function_id.has_value()) {
  501. if (function_info.is_extern && context.sem_ir().is_impl()) {
  502. DiagnoseExternRequiresDeclInApiFile(context, node_id);
  503. }
  504. function_info.generic_id = BuildGenericDecl(context, decl_id);
  505. function_decl.function_id = context.functions().Add(function_info);
  506. function_decl.type_id =
  507. GetFunctionType(context, function_decl.function_id,
  508. context.scope_stack().PeekSpecificId());
  509. } else {
  510. auto prev_decl_generic_id =
  511. context.functions().Get(function_decl.function_id).generic_id;
  512. FinishGenericRedecl(context, prev_decl_generic_id);
  513. // TODO: Validate that the redeclaration doesn't set an access modifier.
  514. }
  515. RequestVtableIfVirtual(context, node_id, function_info.virtual_modifier,
  516. parent_scope_inst, decl_id, function_info.generic_id);
  517. // Write the function ID into the FunctionDecl.
  518. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  519. // Diagnose 'definition of `abstract` function' using the canonical Function's
  520. // modifiers.
  521. if (is_definition &&
  522. context.functions().Get(function_decl.function_id).virtual_modifier ==
  523. SemIR::Function::VirtualModifier::Abstract) {
  524. CARBON_DIAGNOSTIC(DefinedAbstractFunction, Error,
  525. "definition of `abstract` function");
  526. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  527. DefinedAbstractFunction);
  528. }
  529. // Add to name lookup if needed, now that the decl is built.
  530. MaybeAddToNameLookup(context, name_context, introducer.modifier_set,
  531. name_context.parent_scope_id, decl_id);
  532. ValidateForEntryPoint(context, node_id, function_decl.function_id,
  533. function_info);
  534. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  535. context.definitions_required_by_decl().push_back(decl_id);
  536. }
  537. return {function_decl.function_id, decl_id};
  538. }
  539. // Checks that "unused" marker is only used in definitions, and emits a
  540. // diagnostic for every binding that is marked unused.
  541. static auto CheckUnusedBindingsInPattern(Context& context,
  542. SemIR::InstId pattern_id) -> void {
  543. llvm::SmallVector<SemIR::InstId> work_list;
  544. work_list.push_back(pattern_id);
  545. while (!work_list.empty()) {
  546. auto current_id = work_list.pop_back_val();
  547. auto inst = context.insts().Get(current_id);
  548. CARBON_KIND_SWITCH(inst) {
  549. case SemIR::OutParamPattern::Kind:
  550. case SemIR::RefParamPattern::Kind:
  551. case SemIR::ValueParamPattern::Kind:
  552. case SemIR::VarParamPattern::Kind: {
  553. auto param = inst.As<SemIR::AnyParamPattern>();
  554. work_list.push_back(param.subpattern_id);
  555. break;
  556. }
  557. case SemIR::RefBindingPattern::Kind:
  558. case SemIR::SymbolicBindingPattern::Kind:
  559. case SemIR::ValueBindingPattern::Kind: {
  560. auto bind = inst.As<SemIR::AnyBindingPattern>();
  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. break;
  571. }
  572. case CARBON_KIND(SemIR::VarPattern var_pattern): {
  573. work_list.push_back(var_pattern.subpattern_id);
  574. break;
  575. }
  576. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  577. auto elements = context.inst_blocks().Get(tuple_pattern.elements_id);
  578. for (auto element_id : llvm::reverse(elements)) {
  579. work_list.push_back(element_id);
  580. }
  581. break;
  582. }
  583. default:
  584. break;
  585. }
  586. }
  587. }
  588. static auto DiagnoseUnusedMarkersInDeclaration(Context& context,
  589. SemIR::FunctionId function_id)
  590. -> void {
  591. const auto& function = context.functions().Get(function_id);
  592. if (function.param_patterns_id.has_value()) {
  593. for (auto pattern_id :
  594. context.inst_blocks().Get(function.param_patterns_id)) {
  595. CheckUnusedBindingsInPattern(context, pattern_id);
  596. }
  597. }
  598. }
  599. auto HandleParseNode(Context& context, Parse::FunctionDeclId node_id) -> bool {
  600. auto [function_id, decl_id] =
  601. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  602. DiagnoseUnusedMarkersInDeclaration(context, function_id);
  603. context.decl_name_stack().PopScope();
  604. return true;
  605. }
  606. // Processes a function definition after a signature for which we have already
  607. // built a function ID. This logic is shared between processing regular function
  608. // definitions and delayed parsing of inline method definitions.
  609. static auto HandleFunctionDefinitionAfterSignature(
  610. Context& context, Parse::FunctionDefinitionStartId node_id,
  611. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  612. StartFunctionDefinition(context, decl_id, function_id);
  613. context.node_stack().Push(node_id, function_id);
  614. }
  615. auto HandleFunctionDefinitionSuspend(Context& context,
  616. Parse::FunctionDefinitionStartId node_id)
  617. -> DeferredDefinitionWorklist::SuspendedFunction {
  618. // Process the declaration portion of the function.
  619. auto [function_id, decl_id] =
  620. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  621. return {.function_id = function_id,
  622. .decl_id = decl_id,
  623. .saved_name_state = context.decl_name_stack().Suspend()};
  624. }
  625. auto HandleFunctionDefinitionResume(
  626. Context& context, Parse::FunctionDefinitionStartId node_id,
  627. DeferredDefinitionWorklist::SuspendedFunction&& suspended_fn) -> void {
  628. context.decl_name_stack().Restore(std::move(suspended_fn.saved_name_state));
  629. HandleFunctionDefinitionAfterSignature(
  630. context, node_id, suspended_fn.function_id, suspended_fn.decl_id);
  631. }
  632. auto HandleParseNode(Context& context, Parse::FunctionDefinitionStartId node_id)
  633. -> bool {
  634. // Process the declaration portion of the function.
  635. auto [function_id, decl_id] =
  636. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  637. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  638. decl_id);
  639. return true;
  640. }
  641. auto HandleParseNode(Context& context, Parse::FunctionDefinitionId node_id)
  642. -> bool {
  643. SemIR::FunctionId function_id =
  644. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  645. // If the `}` of the function is reachable, reject if we need a return value
  646. // and otherwise add an implicit `return;`.
  647. if (IsCurrentPositionReachable(context)) {
  648. if (context.functions().Get(function_id).return_form_inst_id.has_value()) {
  649. CARBON_DIAGNOSTIC(
  650. MissingReturnStatement, Error,
  651. "missing `return` at end of function with declared return type");
  652. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  653. MissingReturnStatement);
  654. } else {
  655. AddReturnCleanupBlock(context, node_id);
  656. }
  657. }
  658. FinishFunctionDefinition(context, function_id);
  659. context.decl_name_stack().PopScope(/*check_unused=*/true);
  660. return true;
  661. }
  662. auto HandleParseNode(Context& context,
  663. Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  664. // Process the declaration portion of the function.
  665. auto [function_id, _] =
  666. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  667. context.node_stack().Push(node_id, function_id);
  668. return true;
  669. }
  670. auto HandleParseNode(Context& context, Parse::BuiltinNameId node_id) -> bool {
  671. context.node_stack().Push(node_id);
  672. return true;
  673. }
  674. // Looks up a builtin function kind given its name as a string.
  675. // TODO: Move this out to another file.
  676. static auto LookupBuiltinFunctionKind(Context& context,
  677. Parse::BuiltinNameId name_id)
  678. -> SemIR::BuiltinFunctionKind {
  679. auto builtin_name = context.string_literal_values().Get(
  680. context.tokens().GetStringLiteralValue(
  681. context.parse_tree().node_token(name_id)));
  682. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  683. if (kind == SemIR::BuiltinFunctionKind::None) {
  684. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  685. "unknown builtin function name \"{0}\"", std::string);
  686. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  687. builtin_name.str());
  688. }
  689. return kind;
  690. }
  691. auto HandleParseNode(Context& context,
  692. Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  693. auto name_id =
  694. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  695. auto [fn_node_id, function_id] =
  696. context.node_stack()
  697. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  698. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  699. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  700. CheckFunctionDefinitionSignature(context, function_id);
  701. auto& function = context.functions().Get(function_id);
  702. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  703. function.SetBuiltinFunction(builtin_kind);
  704. // Build an empty generic definition if this is a generic builtin.
  705. StartGenericDefinition(context, function.generic_id);
  706. FinishGenericDefinition(context, function.generic_id);
  707. } else {
  708. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  709. "invalid signature for builtin function \"{0}\"",
  710. std::string);
  711. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  712. builtin_kind.name().str());
  713. }
  714. }
  715. context.decl_name_stack().PopScope();
  716. return true;
  717. }
  718. auto HandleParseNode(Context& context, Parse::FunctionTerseDefinitionId node_id)
  719. -> bool {
  720. return context.TODO(node_id, "HandleFunctionTerseDefinition");
  721. }
  722. } // namespace Carbon::Check