handle_function.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. context.node_stack().Push(node_id,
  60. AddReturnPattern(context, node_id, form_expr));
  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. }
  157. if (prev_import_ir_id.has_value()) {
  158. ReplacePrevInstForMerge(context, new_function.parent_scope_id,
  159. prev_function.name_id,
  160. new_function.first_owning_decl_id);
  161. }
  162. return true;
  163. }
  164. // Check whether this is a redeclaration, merging if needed.
  165. static auto TryMergeRedecl(Context& context, Parse::AnyFunctionDeclId node_id,
  166. const DeclNameStack::NameContext& name_context,
  167. SemIR::FunctionDecl& function_decl,
  168. SemIR::Function& function_info, bool is_definition)
  169. -> void {
  170. if (name_context.state == DeclNameStack::NameContext::State::Poisoned) {
  171. DiagnosePoisonedName(context, name_context.name_id_for_new_inst(),
  172. name_context.poisoning_loc_id, name_context.loc_id);
  173. return;
  174. }
  175. auto prev_id = name_context.prev_inst_id();
  176. if (!prev_id.has_value()) {
  177. return;
  178. }
  179. auto prev_function_id = SemIR::FunctionId::None;
  180. auto prev_type_id = SemIR::TypeId::None;
  181. auto prev_import_ir_id = SemIR::ImportIRId::None;
  182. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  183. case CARBON_KIND(SemIR::AssociatedEntity assoc_entity): {
  184. // This is a function in an interface definition scope (see
  185. // NameScope::is_interface_definition()).
  186. auto function_decl =
  187. context.insts().GetAs<SemIR::FunctionDecl>(assoc_entity.decl_id);
  188. prev_function_id = function_decl.function_id;
  189. prev_type_id = function_decl.type_id;
  190. break;
  191. }
  192. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  193. prev_function_id = function_decl.function_id;
  194. prev_type_id = function_decl.type_id;
  195. break;
  196. }
  197. case SemIR::ImportRefLoaded::Kind: {
  198. auto import_ir_inst = GetCanonicalImportIRInst(context, prev_id);
  199. // Verify the decl so that things like aliases are name conflicts.
  200. const auto* import_ir =
  201. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  202. if (!import_ir->insts().Is<SemIR::FunctionDecl>(
  203. import_ir_inst.inst_id())) {
  204. break;
  205. }
  206. // Use the type to get the ID.
  207. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  208. context.constant_values().GetConstantInstId(prev_id))) {
  209. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  210. struct_value->type_id)) {
  211. prev_function_id = function_type->function_id;
  212. prev_type_id = struct_value->type_id;
  213. prev_import_ir_id = import_ir_inst.ir_id();
  214. }
  215. }
  216. break;
  217. }
  218. default:
  219. break;
  220. }
  221. if (!prev_function_id.has_value()) {
  222. DiagnoseDuplicateName(context, name_context.name_id, name_context.loc_id,
  223. SemIR::LocId(prev_id));
  224. return;
  225. }
  226. if (MergeFunctionRedecl(context, node_id, function_info, is_definition,
  227. prev_function_id, prev_import_ir_id)) {
  228. // When merging, use the existing function rather than adding a new one.
  229. function_decl.function_id = prev_function_id;
  230. function_decl.type_id = prev_type_id;
  231. }
  232. }
  233. // Adds the declaration to name lookup when appropriate.
  234. static auto MaybeAddToNameLookup(Context& context,
  235. const DeclNameStack::NameContext& name_context,
  236. const KeywordModifierSet& modifier_set,
  237. SemIR::NameScopeId parent_scope_id,
  238. SemIR::InstId decl_id) -> void {
  239. if (name_context.state == DeclNameStack::NameContext::State::Poisoned ||
  240. name_context.prev_inst_id().has_value()) {
  241. return;
  242. }
  243. // At interface scope, a function declaration introduces an associated
  244. // function.
  245. auto lookup_result_id = decl_id;
  246. if (parent_scope_id.has_value() && !name_context.has_qualifiers) {
  247. const auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  248. if (parent_scope.is_interface_definition()) {
  249. auto interface_decl = context.insts().GetAs<SemIR::InterfaceWithSelfDecl>(
  250. parent_scope.inst_id());
  251. lookup_result_id =
  252. BuildAssociatedEntity(context, interface_decl.interface_id, decl_id);
  253. }
  254. }
  255. context.decl_name_stack().AddName(name_context, lookup_result_id,
  256. modifier_set.GetAccessKind());
  257. }
  258. // Returns whether the given type is `i32`.
  259. static auto IsI32(Context& context, Parse::NodeId node_id,
  260. SemIR::TypeId type_id) -> bool {
  261. return type_id == MakeIntType(context, node_id, SemIR::IntKind::Signed,
  262. context.ints().Add(32));
  263. }
  264. // Returns whether the given parameter list is valid for the entry point
  265. // function `Main.Run`.
  266. static auto IsValidEntryPointParamList(Context& context, Parse::NodeId node_id,
  267. SemIR::InstBlockId param_patterns_id)
  268. -> bool {
  269. if (!param_patterns_id.has_value()) {
  270. // Positional parameters for are not supported.
  271. return false;
  272. }
  273. for (auto [index, param_pattern_id] :
  274. llvm::enumerate(context.inst_blocks().Get(param_patterns_id))) {
  275. if (param_pattern_id == SemIR::ErrorInst::InstId) {
  276. // Ignore erroneous parameters.
  277. continue;
  278. }
  279. // Validate that this is a by-value parameter, which is represented as an
  280. // WrapperBindingPattern wrapping a ValueParamPattern.
  281. auto type_id = SemIR::TypeId::None;
  282. if (auto binding = context.insts().TryGetAs<SemIR::WrapperBindingPattern>(
  283. param_pattern_id)) {
  284. if (auto param_pattern =
  285. context.insts().TryGetAs<SemIR::ValueParamPattern>(
  286. binding->subpattern_id)) {
  287. type_id = param_pattern->type_id;
  288. }
  289. }
  290. if (!type_id.has_value()) {
  291. return false;
  292. }
  293. if (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>(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_pattern_id = SemIR::InstId::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_pattern_id] =
  451. context.node_stack()
  452. .PopWithNodeIdIf<Parse::NodeCategory::ReturnDecl>();
  453. maybe_return_pattern_id) {
  454. return_pattern_id = *maybe_return_pattern_id;
  455. auto return_form = context.PopReturnForm();
  456. return_type_inst_id = return_form.type_component_inst_id;
  457. return_form_inst_id = return_form.form_inst_id;
  458. }
  459. auto name = PopNameComponent(context, return_pattern_id);
  460. auto name_context = context.decl_name_stack().FinishName(name);
  461. context.node_stack()
  462. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  463. auto self_param_id =
  464. FindSelfPattern(context, name.implicit_param_patterns_id);
  465. // Process modifiers.
  466. auto [parent_scope_inst_id, parent_scope_inst] =
  467. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  468. auto introducer =
  469. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Fn>();
  470. DiagnoseModifiers(context, node_id, introducer, is_definition,
  471. name_context.parent_scope_id, parent_scope_inst_id,
  472. parent_scope_inst, self_param_id);
  473. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  474. auto virtual_modifier = GetVirtualModifier(introducer.modifier_set);
  475. auto evaluation_mode = GetEvaluationMode(introducer.modifier_set);
  476. // Add the function declaration.
  477. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  478. SemIR::FunctionId::None,
  479. context.inst_block_stack().Pop()};
  480. auto decl_id = AddPlaceholderInst(context, node_id, function_decl);
  481. // Build the function entity. This will be merged into an existing function if
  482. // there is one, or otherwise added to the function store.
  483. auto function_info =
  484. SemIR::Function{name_context.MakeEntityWithParamsBase(
  485. name, decl_id, is_extern, introducer.extern_library),
  486. {.call_param_patterns_id = name.call_param_patterns_id,
  487. .call_params_id = name.call_params_id,
  488. .call_param_ranges = name.param_ranges,
  489. .return_type_inst_id = return_type_inst_id,
  490. .return_form_inst_id = return_form_inst_id,
  491. .return_pattern_id = return_pattern_id,
  492. .virtual_modifier = virtual_modifier,
  493. .evaluation_mode = evaluation_mode,
  494. .self_param_id = self_param_id}};
  495. if (is_definition) {
  496. function_info.definition_id = decl_id;
  497. }
  498. DiagnosePositionalParams(context, function_info);
  499. TryMergeRedecl(context, node_id, name_context, function_decl, function_info,
  500. is_definition);
  501. // Create a new function if this isn't a valid redeclaration.
  502. if (!function_decl.function_id.has_value()) {
  503. if (function_info.is_extern && context.sem_ir().is_impl()) {
  504. DiagnoseExternRequiresDeclInApiFile(context, node_id);
  505. }
  506. function_info.generic_id = BuildGenericDecl(context, decl_id);
  507. function_decl.function_id = context.functions().Add(function_info);
  508. function_decl.type_id =
  509. GetFunctionType(context, function_decl.function_id,
  510. context.scope_stack().PeekSpecificId());
  511. } else {
  512. auto prev_decl_generic_id =
  513. context.functions().Get(function_decl.function_id).generic_id;
  514. FinishGenericRedecl(context, prev_decl_generic_id);
  515. // TODO: Validate that the redeclaration doesn't set an access modifier.
  516. }
  517. RequestVtableIfVirtual(context, node_id, function_info.virtual_modifier,
  518. parent_scope_inst, decl_id, function_info.generic_id);
  519. // Write the function ID into the FunctionDecl.
  520. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  521. // Diagnose 'definition of `abstract` function' using the canonical Function's
  522. // modifiers.
  523. if (is_definition &&
  524. context.functions().Get(function_decl.function_id).virtual_modifier ==
  525. SemIR::Function::VirtualModifier::Abstract) {
  526. CARBON_DIAGNOSTIC(DefinedAbstractFunction, Error,
  527. "definition of `abstract` function");
  528. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  529. DefinedAbstractFunction);
  530. }
  531. // Add to name lookup if needed, now that the decl is built.
  532. MaybeAddToNameLookup(context, name_context, introducer.modifier_set,
  533. name_context.parent_scope_id, decl_id);
  534. ValidateForEntryPoint(context, node_id, function_decl.function_id,
  535. function_info);
  536. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  537. context.definitions_required_by_decl().push_back(decl_id);
  538. }
  539. return {function_decl.function_id, decl_id};
  540. }
  541. // Checks that "unused" marker is only used in definitions, and emits a
  542. // diagnostic for every binding that is marked unused.
  543. static auto CheckUnusedBindingsInPattern(Context& context,
  544. SemIR::InstId pattern_id) -> void {
  545. llvm::SmallVector<SemIR::InstId> work_list;
  546. work_list.push_back(pattern_id);
  547. while (!work_list.empty()) {
  548. auto current_id = work_list.pop_back_val();
  549. auto inst = context.insts().Get(current_id);
  550. CARBON_KIND_SWITCH(inst) {
  551. case CARBON_KIND_ANY(SemIR::AnyLeafParamPattern, _): {
  552. break;
  553. }
  554. case CARBON_KIND_ANY(SemIR::AnyBindingPattern, bind): {
  555. auto& entity_name = context.entity_names().Get(bind.entity_name_id);
  556. // We need special treatment for the name "_" which is implicitly
  557. // unused but actually permitted in declarations.
  558. if (entity_name.is_unused &&
  559. entity_name.name_id != SemIR::NameId::Underscore) {
  560. CARBON_DIAGNOSTIC(UnusedModifierOnDeclaration, Error,
  561. "`unused` modifier on declaration");
  562. context.emitter().Emit(current_id, UnusedModifierOnDeclaration);
  563. }
  564. if (bind.kind == SemIR::WrapperBindingPattern::Kind) {
  565. work_list.push_back(bind.subpattern_id);
  566. }
  567. break;
  568. }
  569. case CARBON_KIND_ANY(SemIR::AnyVarPattern, var_pattern): {
  570. work_list.push_back(var_pattern.subpattern_id);
  571. break;
  572. }
  573. case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
  574. auto elements = context.inst_blocks().Get(tuple_pattern.elements_id);
  575. for (auto element_id : llvm::reverse(elements)) {
  576. work_list.push_back(element_id);
  577. }
  578. break;
  579. }
  580. default:
  581. break;
  582. }
  583. }
  584. }
  585. static auto DiagnoseUnusedMarkersInDeclaration(Context& context,
  586. SemIR::FunctionId function_id)
  587. -> void {
  588. const auto& function = context.functions().Get(function_id);
  589. if (function.param_patterns_id.has_value()) {
  590. for (auto pattern_id :
  591. context.inst_blocks().Get(function.param_patterns_id)) {
  592. CheckUnusedBindingsInPattern(context, pattern_id);
  593. }
  594. }
  595. }
  596. auto HandleParseNode(Context& context, Parse::FunctionDeclId node_id) -> bool {
  597. auto [function_id, decl_id] =
  598. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  599. DiagnoseUnusedMarkersInDeclaration(context, function_id);
  600. context.decl_name_stack().PopScope();
  601. return true;
  602. }
  603. // Processes a function definition after a signature for which we have already
  604. // built a function ID. This logic is shared between processing regular function
  605. // definitions and delayed parsing of inline method definitions.
  606. static auto HandleFunctionDefinitionAfterSignature(
  607. Context& context, Parse::FunctionDefinitionStartId node_id,
  608. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  609. StartFunctionDefinition(context, decl_id, function_id);
  610. context.node_stack().Push(node_id, function_id);
  611. }
  612. auto HandleFunctionDefinitionSuspend(Context& context,
  613. Parse::FunctionDefinitionStartId node_id)
  614. -> DeferredDefinitionWorklist::SuspendedFunction {
  615. // Process the declaration portion of the function.
  616. auto [function_id, decl_id] =
  617. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  618. return {.function_id = function_id,
  619. .decl_id = decl_id,
  620. .saved_name_state = context.decl_name_stack().Suspend()};
  621. }
  622. auto HandleFunctionDefinitionResume(
  623. Context& context, Parse::FunctionDefinitionStartId node_id,
  624. DeferredDefinitionWorklist::SuspendedFunction&& suspended_fn) -> void {
  625. context.decl_name_stack().Restore(std::move(suspended_fn.saved_name_state));
  626. HandleFunctionDefinitionAfterSignature(
  627. context, node_id, suspended_fn.function_id, suspended_fn.decl_id);
  628. }
  629. auto HandleParseNode(Context& context, Parse::FunctionDefinitionStartId node_id)
  630. -> bool {
  631. // Process the declaration portion of the function.
  632. auto [function_id, decl_id] =
  633. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  634. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  635. decl_id);
  636. return true;
  637. }
  638. auto HandleParseNode(Context& context, Parse::FunctionDefinitionId node_id)
  639. -> bool {
  640. SemIR::FunctionId function_id =
  641. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  642. // If the `}` of the function is reachable, reject if we need a return value
  643. // and otherwise add an implicit `return;`.
  644. if (IsCurrentPositionReachable(context)) {
  645. if (context.functions().Get(function_id).return_form_inst_id.has_value()) {
  646. CARBON_DIAGNOSTIC(
  647. MissingReturnStatement, Error,
  648. "missing `return` at end of function with declared return type");
  649. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  650. MissingReturnStatement);
  651. } else {
  652. AddReturnCleanupBlock(context, node_id);
  653. }
  654. }
  655. FinishFunctionDefinition(context, function_id);
  656. context.decl_name_stack().PopScope(/*check_unused=*/true);
  657. return true;
  658. }
  659. auto HandleParseNode(Context& context,
  660. Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  661. // Process the declaration portion of the function.
  662. auto [function_id, _] =
  663. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  664. context.node_stack().Push(node_id, function_id);
  665. return true;
  666. }
  667. auto HandleParseNode(Context& context, Parse::BuiltinNameId node_id) -> bool {
  668. context.node_stack().Push(node_id);
  669. return true;
  670. }
  671. // Looks up a builtin function kind given its name as a string.
  672. // TODO: Move this out to another file.
  673. static auto LookupBuiltinFunctionKind(Context& context,
  674. Parse::BuiltinNameId name_id)
  675. -> SemIR::BuiltinFunctionKind {
  676. auto builtin_name = context.string_literal_values().Get(
  677. context.tokens().GetStringLiteralValue(
  678. context.parse_tree().node_token(name_id)));
  679. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  680. if (kind == SemIR::BuiltinFunctionKind::None) {
  681. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  682. "unknown builtin function name \"{0}\"", std::string);
  683. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  684. builtin_name.str());
  685. }
  686. return kind;
  687. }
  688. auto HandleParseNode(Context& context,
  689. Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  690. auto name_id =
  691. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  692. auto [fn_node_id, function_id] =
  693. context.node_stack()
  694. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  695. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  696. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  697. CheckFunctionDefinitionSignature(context, function_id);
  698. auto& function = context.functions().Get(function_id);
  699. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  700. function.SetBuiltinFunction(builtin_kind);
  701. // Build an empty generic definition if this is a generic builtin.
  702. StartGenericDefinition(context, function.generic_id);
  703. FinishGenericDefinition(context, function.generic_id);
  704. } else {
  705. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  706. "invalid signature for builtin function \"{0}\"",
  707. std::string);
  708. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  709. builtin_kind.name().str());
  710. }
  711. }
  712. context.decl_name_stack().PopScope();
  713. return true;
  714. }
  715. auto HandleParseNode(Context& context, Parse::FunctionTerseDefinitionId node_id)
  716. -> bool {
  717. return context.TODO(node_id, "HandleFunctionTerseDefinition");
  718. }
  719. } // namespace Carbon::Check