handle_function.cpp 32 KB

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