handle_function.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 "toolchain/base/kind_switch.h"
  5. #include "toolchain/check/context.h"
  6. #include "toolchain/check/control_flow.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/decl_introducer_state.h"
  9. #include "toolchain/check/decl_name_stack.h"
  10. #include "toolchain/check/function.h"
  11. #include "toolchain/check/generic.h"
  12. #include "toolchain/check/handle.h"
  13. #include "toolchain/check/import.h"
  14. #include "toolchain/check/import_ref.h"
  15. #include "toolchain/check/inst.h"
  16. #include "toolchain/check/interface.h"
  17. #include "toolchain/check/literal.h"
  18. #include "toolchain/check/merge.h"
  19. #include "toolchain/check/modifiers.h"
  20. #include "toolchain/check/name_component.h"
  21. #include "toolchain/check/name_lookup.h"
  22. #include "toolchain/check/type.h"
  23. #include "toolchain/check/type_completion.h"
  24. #include "toolchain/sem_ir/builtin_function_kind.h"
  25. #include "toolchain/sem_ir/entry_point.h"
  26. #include "toolchain/sem_ir/function.h"
  27. #include "toolchain/sem_ir/ids.h"
  28. #include "toolchain/sem_ir/pattern.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Check {
  31. auto HandleParseNode(Context& context, Parse::FunctionIntroducerId node_id)
  32. -> bool {
  33. // Create an instruction block to hold the instructions created as part of the
  34. // function signature, such as parameter and return types.
  35. context.inst_block_stack().Push();
  36. // Push the bracketing node.
  37. context.node_stack().Push(node_id);
  38. // Optional modifiers and the name follow.
  39. context.decl_introducer_state_stack().Push<Lex::TokenKind::Fn>();
  40. context.decl_name_stack().PushScopeAndStartName();
  41. // The function is potentially generic.
  42. StartGenericDecl(context);
  43. return true;
  44. }
  45. auto HandleParseNode(Context& context, Parse::ReturnTypeId node_id) -> bool {
  46. // Propagate the type expression.
  47. auto [type_node_id, type_inst_id] = context.node_stack().PopExprWithNodeId();
  48. auto type_id = ExprAsType(context, type_node_id, type_inst_id).type_id;
  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. auto return_slot_pattern_id = AddPatternInst<SemIR::ReturnSlotPattern>(
  62. context, node_id, {.type_id = type_id, .type_inst_id = type_inst_id});
  63. auto param_pattern_id = AddPatternInst<SemIR::OutParamPattern>(
  64. context, node_id,
  65. {.type_id = type_id,
  66. .subpattern_id = return_slot_pattern_id,
  67. .index = SemIR::CallParamIndex::None});
  68. context.node_stack().Push(node_id, param_pattern_id);
  69. return true;
  70. }
  71. static auto DiagnoseModifiers(Context& context, DeclIntroducerState& introducer,
  72. bool is_definition,
  73. SemIR::InstId parent_scope_inst_id,
  74. std::optional<SemIR::Inst> parent_scope_inst)
  75. -> void {
  76. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  77. LimitModifiersOnDecl(context, introducer,
  78. KeywordModifierSet::Access | KeywordModifierSet::Extern |
  79. KeywordModifierSet::Method |
  80. KeywordModifierSet::Interface);
  81. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  82. is_definition);
  83. CheckMethodModifiersOnFunction(context, introducer, parent_scope_inst_id,
  84. parent_scope_inst);
  85. RequireDefaultFinalOnlyInInterfaces(context, introducer, parent_scope_inst);
  86. }
  87. // Tries to merge new_function into prev_function_id. Since new_function won't
  88. // have a definition even if one is upcoming, set is_definition to indicate the
  89. // planned result.
  90. //
  91. // If merging is successful, returns true and may update the previous function.
  92. // Otherwise, returns false. Prints a diagnostic when appropriate.
  93. static auto MergeFunctionRedecl(Context& context,
  94. Parse::AnyFunctionDeclId node_id,
  95. SemIR::Function& new_function,
  96. bool new_is_definition,
  97. SemIR::FunctionId prev_function_id,
  98. SemIR::ImportIRId prev_import_ir_id) -> bool {
  99. auto& prev_function = context.functions().Get(prev_function_id);
  100. if (!CheckFunctionTypeMatches(context, new_function, prev_function)) {
  101. return false;
  102. }
  103. DiagnoseIfInvalidRedecl(
  104. context, Lex::TokenKind::Fn, prev_function.name_id,
  105. RedeclInfo(new_function, node_id, new_is_definition),
  106. RedeclInfo(prev_function, prev_function.latest_decl_id(),
  107. prev_function.has_definition_started()),
  108. prev_import_ir_id);
  109. if (new_is_definition && prev_function.has_definition_started()) {
  110. return false;
  111. }
  112. if (!prev_function.first_owning_decl_id.has_value()) {
  113. prev_function.first_owning_decl_id = new_function.first_owning_decl_id;
  114. }
  115. if (new_is_definition) {
  116. // Track the signature from the definition, so that IDs in the body
  117. // match IDs in the signature.
  118. prev_function.MergeDefinition(new_function);
  119. prev_function.return_slot_pattern_id = new_function.return_slot_pattern_id;
  120. prev_function.self_param_id = new_function.self_param_id;
  121. }
  122. if (prev_import_ir_id.has_value()) {
  123. ReplacePrevInstForMerge(context, new_function.parent_scope_id,
  124. prev_function.name_id,
  125. new_function.first_owning_decl_id);
  126. }
  127. return true;
  128. }
  129. // Check whether this is a redeclaration, merging if needed.
  130. static auto TryMergeRedecl(Context& context, Parse::AnyFunctionDeclId node_id,
  131. SemIR::NameId name_id, SemIR::InstId prev_id,
  132. SemIR::LocId name_loc_id,
  133. SemIR::FunctionDecl& function_decl,
  134. SemIR::Function& function_info, bool is_definition)
  135. -> void {
  136. if (!prev_id.has_value()) {
  137. return;
  138. }
  139. auto prev_function_id = SemIR::FunctionId::None;
  140. auto prev_type_id = SemIR::TypeId::None;
  141. auto prev_import_ir_id = SemIR::ImportIRId::None;
  142. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  143. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  144. prev_function_id = function_decl.function_id;
  145. prev_type_id = function_decl.type_id;
  146. break;
  147. }
  148. case SemIR::ImportRefLoaded::Kind: {
  149. auto import_ir_inst = GetCanonicalImportIRInst(context, prev_id);
  150. // Verify the decl so that things like aliases are name conflicts.
  151. const auto* import_ir =
  152. context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  153. if (!import_ir->insts().Is<SemIR::FunctionDecl>(import_ir_inst.inst_id)) {
  154. break;
  155. }
  156. // Use the type to get the ID.
  157. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  158. context.constant_values().GetConstantInstId(prev_id))) {
  159. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  160. struct_value->type_id)) {
  161. prev_function_id = function_type->function_id;
  162. prev_type_id = struct_value->type_id;
  163. prev_import_ir_id = import_ir_inst.ir_id;
  164. }
  165. }
  166. break;
  167. }
  168. default:
  169. break;
  170. }
  171. if (!prev_function_id.has_value()) {
  172. DiagnoseDuplicateName(context, name_id, name_loc_id, prev_id);
  173. return;
  174. }
  175. if (MergeFunctionRedecl(context, node_id, function_info, is_definition,
  176. prev_function_id, prev_import_ir_id)) {
  177. // When merging, use the existing function rather than adding a new one.
  178. function_decl.function_id = prev_function_id;
  179. function_decl.type_id = prev_type_id;
  180. }
  181. }
  182. // Build a FunctionDecl describing the signature of a function. This
  183. // handles the common logic shared by function declaration syntax and function
  184. // definition syntax.
  185. static auto BuildFunctionDecl(Context& context,
  186. Parse::AnyFunctionDeclId node_id,
  187. bool is_definition)
  188. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  189. auto return_slot_pattern_id = SemIR::InstId::None;
  190. if (auto [return_node, maybe_return_slot_pattern_id] =
  191. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  192. maybe_return_slot_pattern_id) {
  193. return_slot_pattern_id = *maybe_return_slot_pattern_id;
  194. }
  195. auto name = PopNameComponent(context, return_slot_pattern_id);
  196. if (!name.param_patterns_id.has_value()) {
  197. context.TODO(node_id, "function with positional parameters");
  198. name.param_patterns_id = SemIR::InstBlockId::Empty;
  199. }
  200. auto name_context = context.decl_name_stack().FinishName(name);
  201. context.node_stack()
  202. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  203. // Process modifiers.
  204. auto [parent_scope_inst_id, parent_scope_inst] =
  205. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  206. auto introducer =
  207. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Fn>();
  208. DiagnoseModifiers(context, introducer, is_definition, parent_scope_inst_id,
  209. parent_scope_inst);
  210. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  211. auto virtual_modifier =
  212. introducer.modifier_set.ToEnum<SemIR::Function::VirtualModifier>()
  213. .Case(KeywordModifierSet::Virtual,
  214. SemIR::Function::VirtualModifier::Virtual)
  215. .Case(KeywordModifierSet::Abstract,
  216. SemIR::Function::VirtualModifier::Abstract)
  217. .Case(KeywordModifierSet::Impl,
  218. SemIR::Function::VirtualModifier::Impl)
  219. .Default(SemIR::Function::VirtualModifier::None);
  220. SemIR::Class* virtual_class_info = nullptr;
  221. if (virtual_modifier != SemIR::Function::VirtualModifier::None &&
  222. parent_scope_inst) {
  223. if (auto class_decl = parent_scope_inst->TryAs<SemIR::ClassDecl>()) {
  224. virtual_class_info = &context.classes().Get(class_decl->class_id);
  225. if (virtual_modifier == SemIR::Function::VirtualModifier::Impl &&
  226. !virtual_class_info->base_id.has_value()) {
  227. CARBON_DIAGNOSTIC(ImplWithoutBase, Error, "impl without base class");
  228. context.emitter().Build(node_id, ImplWithoutBase).Emit();
  229. }
  230. // TODO: If this is an `impl` function, check there's a matching base
  231. // function that's impl or virtual.
  232. virtual_class_info->is_dynamic = true;
  233. }
  234. }
  235. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Interface)) {
  236. // TODO: Once we are saving the modifiers for a function, add check that
  237. // the function may only be defined if it is marked `default` or `final`.
  238. context.TODO(introducer.modifier_node_id(ModifierOrder::Decl),
  239. "interface modifier");
  240. }
  241. // Add the function declaration.
  242. auto decl_block_id = context.inst_block_stack().Pop();
  243. auto function_decl = SemIR::FunctionDecl{
  244. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  245. auto decl_id =
  246. AddPlaceholderInst(context, SemIR::LocIdAndInst(node_id, function_decl));
  247. // Find self parameter pattern.
  248. // TODO: Do this during initial traversal of implicit params.
  249. auto self_param_id = SemIR::InstId::None;
  250. auto implicit_param_patterns =
  251. context.inst_blocks().GetOrEmpty(name.implicit_param_patterns_id);
  252. if (const auto* i = llvm::find_if(implicit_param_patterns,
  253. [&](auto implicit_param_id) {
  254. return SemIR::IsSelfPattern(
  255. context.sem_ir(), implicit_param_id);
  256. });
  257. i != implicit_param_patterns.end()) {
  258. self_param_id = *i;
  259. }
  260. if (virtual_modifier != SemIR::Function::VirtualModifier::None &&
  261. !self_param_id.has_value()) {
  262. CARBON_DIAGNOSTIC(VirtualWithoutSelf, Error, "virtual class function");
  263. context.emitter().Build(node_id, VirtualWithoutSelf).Emit();
  264. }
  265. // Build the function entity. This will be merged into an existing function if
  266. // there is one, or otherwise added to the function store.
  267. auto function_info =
  268. SemIR::Function{{name_context.MakeEntityWithParamsBase(
  269. name, decl_id, is_extern, introducer.extern_library)},
  270. {.return_slot_pattern_id = name.return_slot_pattern_id,
  271. .virtual_modifier = virtual_modifier,
  272. .self_param_id = self_param_id}};
  273. if (is_definition) {
  274. function_info.definition_id = decl_id;
  275. }
  276. if (virtual_class_info) {
  277. context.vtable_stack().AddInstId(decl_id);
  278. }
  279. if (name_context.state == DeclNameStack::NameContext::State::Poisoned) {
  280. DiagnosePoisonedName(context, name_context.name_id_for_new_inst(),
  281. name_context.poisoning_loc_id, name_context.loc_id);
  282. } else {
  283. TryMergeRedecl(context, node_id, name_context.name_id,
  284. name_context.prev_inst_id(), name_context.loc_id,
  285. function_decl, function_info, is_definition);
  286. }
  287. // Create a new function if this isn't a valid redeclaration.
  288. if (!function_decl.function_id.has_value()) {
  289. if (function_info.is_extern && context.sem_ir().is_impl()) {
  290. DiagnoseExternRequiresDeclInApiFile(context, node_id);
  291. }
  292. function_info.generic_id = BuildGenericDecl(context, decl_id);
  293. function_decl.function_id = context.functions().Add(function_info);
  294. function_decl.type_id =
  295. GetFunctionType(context, function_decl.function_id,
  296. context.scope_stack().PeekSpecificId());
  297. } else {
  298. FinishGenericRedecl(context, decl_id, function_info.generic_id);
  299. // TODO: Validate that the redeclaration doesn't set an access modifier.
  300. }
  301. // Write the function ID into the FunctionDecl.
  302. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  303. // Diagnose 'definition of `abstract` function' using the canonical Function's
  304. // modifiers.
  305. if (is_definition &&
  306. context.functions().Get(function_decl.function_id).virtual_modifier ==
  307. SemIR::Function::VirtualModifier::Abstract) {
  308. CARBON_DIAGNOSTIC(DefinedAbstractFunction, Error,
  309. "definition of `abstract` function");
  310. context.emitter().Emit(TokenOnly(node_id), DefinedAbstractFunction);
  311. }
  312. // Check if we need to add this to name lookup, now that the function decl is
  313. // done.
  314. if (name_context.state != DeclNameStack::NameContext::State::Poisoned &&
  315. !name_context.prev_inst_id().has_value()) {
  316. // At interface scope, a function declaration introduces an associated
  317. // function.
  318. auto lookup_result_id = decl_id;
  319. if (parent_scope_inst && !name_context.has_qualifiers) {
  320. if (auto interface_scope =
  321. parent_scope_inst->TryAs<SemIR::InterfaceDecl>()) {
  322. lookup_result_id = BuildAssociatedEntity(
  323. context, interface_scope->interface_id, decl_id);
  324. }
  325. }
  326. context.decl_name_stack().AddName(name_context, lookup_result_id,
  327. introducer.modifier_set.GetAccessKind());
  328. }
  329. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  330. auto return_type_id = function_info.GetDeclaredReturnType(context.sem_ir());
  331. // TODO: Update this once valid signatures for the entry point are decided.
  332. if (function_info.implicit_param_patterns_id.has_value() ||
  333. !function_info.param_patterns_id.has_value() ||
  334. !context.inst_blocks().Get(function_info.param_patterns_id).empty() ||
  335. (return_type_id.has_value() &&
  336. return_type_id != GetTupleType(context, {}) &&
  337. // TODO: Decide on valid return types for `Main.Run`. Perhaps we should
  338. // have an interface for this.
  339. return_type_id != MakeIntType(context, node_id, SemIR::IntKind::Signed,
  340. context.ints().Add(32)))) {
  341. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  342. "invalid signature for `Main.Run` function; expected "
  343. "`fn ()` or `fn () -> i32`");
  344. context.emitter().Emit(node_id, InvalidMainRunSignature);
  345. }
  346. }
  347. if (!is_definition && context.sem_ir().is_impl() && !is_extern) {
  348. context.definitions_required().push_back(decl_id);
  349. }
  350. return {function_decl.function_id, decl_id};
  351. }
  352. auto HandleParseNode(Context& context, Parse::FunctionDeclId node_id) -> bool {
  353. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  354. context.decl_name_stack().PopScope();
  355. return true;
  356. }
  357. static auto CheckFunctionDefinitionSignature(Context& context,
  358. SemIR::Function& function)
  359. -> void {
  360. auto params_to_complete =
  361. context.inst_blocks().GetOrEmpty(function.call_params_id);
  362. // Check the return type is complete.
  363. if (function.return_slot_pattern_id.has_value()) {
  364. CheckFunctionReturnType(
  365. context, context.insts().GetLocId(function.return_slot_pattern_id),
  366. function, SemIR::SpecificId::None);
  367. params_to_complete = params_to_complete.drop_back();
  368. }
  369. // Check the parameter types are complete.
  370. for (auto param_ref_id : params_to_complete) {
  371. if (param_ref_id == SemIR::ErrorInst::SingletonInstId) {
  372. continue;
  373. }
  374. // The parameter types need to be complete.
  375. RequireCompleteType(
  376. context, context.insts().GetAs<SemIR::AnyParam>(param_ref_id).type_id,
  377. context.insts().GetLocId(param_ref_id), [&] {
  378. CARBON_DIAGNOSTIC(
  379. IncompleteTypeInFunctionParam, Error,
  380. "parameter has incomplete type {0} in function definition",
  381. TypeOfInstId);
  382. return context.emitter().Build(
  383. param_ref_id, IncompleteTypeInFunctionParam, param_ref_id);
  384. });
  385. }
  386. }
  387. // Processes a function definition after a signature for which we have already
  388. // built a function ID. This logic is shared between processing regular function
  389. // definitions and delayed parsing of inline method definitions.
  390. static auto HandleFunctionDefinitionAfterSignature(
  391. Context& context, Parse::FunctionDefinitionStartId node_id,
  392. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  393. auto& function = context.functions().Get(function_id);
  394. // Create the function scope and the entry block.
  395. context.return_scope_stack().push_back({.decl_id = decl_id});
  396. context.inst_block_stack().Push();
  397. context.region_stack().PushRegion(context.inst_block_stack().PeekOrAdd());
  398. context.scope_stack().Push(decl_id);
  399. StartGenericDefinition(context);
  400. CheckFunctionDefinitionSignature(context, function);
  401. context.node_stack().Push(node_id, function_id);
  402. }
  403. auto HandleFunctionDefinitionSuspend(Context& context,
  404. Parse::FunctionDefinitionStartId node_id)
  405. -> SuspendedFunction {
  406. // Process the declaration portion of the function.
  407. auto [function_id, decl_id] =
  408. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  409. return {.function_id = function_id,
  410. .decl_id = decl_id,
  411. .saved_name_state = context.decl_name_stack().Suspend()};
  412. }
  413. auto HandleFunctionDefinitionResume(Context& context,
  414. Parse::FunctionDefinitionStartId node_id,
  415. SuspendedFunction suspended_fn) -> void {
  416. context.decl_name_stack().Restore(suspended_fn.saved_name_state);
  417. HandleFunctionDefinitionAfterSignature(
  418. context, node_id, suspended_fn.function_id, suspended_fn.decl_id);
  419. }
  420. auto HandleParseNode(Context& context, Parse::FunctionDefinitionStartId node_id)
  421. -> bool {
  422. // Process the declaration portion of the function.
  423. auto [function_id, decl_id] =
  424. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  425. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  426. decl_id);
  427. return true;
  428. }
  429. auto HandleParseNode(Context& context, Parse::FunctionDefinitionId node_id)
  430. -> bool {
  431. SemIR::FunctionId function_id =
  432. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  433. // If the `}` of the function is reachable, reject if we need a return value
  434. // and otherwise add an implicit `return;`.
  435. if (IsCurrentPositionReachable(context)) {
  436. if (context.functions()
  437. .Get(function_id)
  438. .return_slot_pattern_id.has_value()) {
  439. CARBON_DIAGNOSTIC(
  440. MissingReturnStatement, Error,
  441. "missing `return` at end of function with declared return type");
  442. context.emitter().Emit(TokenOnly(node_id), MissingReturnStatement);
  443. } else {
  444. AddInst<SemIR::Return>(context, node_id, {});
  445. }
  446. }
  447. context.scope_stack().Pop();
  448. context.inst_block_stack().Pop();
  449. context.return_scope_stack().pop_back();
  450. context.decl_name_stack().PopScope();
  451. auto& function = context.functions().Get(function_id);
  452. function.body_block_ids = context.region_stack().PopRegion();
  453. // If this is a generic function, collect information about the definition.
  454. FinishGenericDefinition(context, function.generic_id);
  455. return true;
  456. }
  457. auto HandleParseNode(Context& context,
  458. Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  459. // Process the declaration portion of the function.
  460. auto [function_id, _] =
  461. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  462. context.node_stack().Push(node_id, function_id);
  463. return true;
  464. }
  465. auto HandleParseNode(Context& context, Parse::BuiltinNameId node_id) -> bool {
  466. context.node_stack().Push(node_id);
  467. return true;
  468. }
  469. // Looks up a builtin function kind given its name as a string.
  470. // TODO: Move this out to another file.
  471. static auto LookupBuiltinFunctionKind(Context& context,
  472. Parse::BuiltinNameId name_id)
  473. -> SemIR::BuiltinFunctionKind {
  474. auto builtin_name = context.string_literal_values().Get(
  475. context.tokens().GetStringLiteralValue(
  476. context.parse_tree().node_token(name_id)));
  477. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  478. if (kind == SemIR::BuiltinFunctionKind::None) {
  479. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  480. "unknown builtin function name \"{0}\"", std::string);
  481. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  482. builtin_name.str());
  483. }
  484. return kind;
  485. }
  486. // Returns whether `function` is a valid declaration of `builtin_kind`.
  487. static auto IsValidBuiltinDeclaration(Context& context,
  488. const SemIR::Function& function,
  489. SemIR::BuiltinFunctionKind builtin_kind)
  490. -> bool {
  491. // Form the list of parameter types for the declaration.
  492. llvm::SmallVector<SemIR::TypeId> param_type_ids;
  493. auto implicit_param_patterns =
  494. context.inst_blocks().GetOrEmpty(function.implicit_param_patterns_id);
  495. auto param_patterns =
  496. context.inst_blocks().GetOrEmpty(function.param_patterns_id);
  497. param_type_ids.reserve(implicit_param_patterns.size() +
  498. param_patterns.size());
  499. for (auto param_id : llvm::concat<const SemIR::InstId>(
  500. implicit_param_patterns, param_patterns)) {
  501. // TODO: We also need to track whether the parameter is declared with
  502. // `var`.
  503. param_type_ids.push_back(context.insts().Get(param_id).type_id());
  504. }
  505. // Get the return type. This is `()` if none was specified.
  506. auto return_type_id = function.GetDeclaredReturnType(context.sem_ir());
  507. if (!return_type_id.has_value()) {
  508. return_type_id = GetTupleType(context, {});
  509. }
  510. return builtin_kind.IsValidType(context.sem_ir(), param_type_ids,
  511. return_type_id);
  512. }
  513. auto HandleParseNode(Context& context,
  514. Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  515. auto name_id =
  516. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  517. auto [fn_node_id, function_id] =
  518. context.node_stack()
  519. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  520. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  521. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  522. auto& function = context.functions().Get(function_id);
  523. CheckFunctionDefinitionSignature(context, function);
  524. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  525. function.builtin_function_kind = builtin_kind;
  526. // Build an empty generic definition if this is a generic builtin.
  527. StartGenericDefinition(context);
  528. FinishGenericDefinition(context, function.generic_id);
  529. } else {
  530. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  531. "invalid signature for builtin function \"{0}\"",
  532. std::string);
  533. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  534. builtin_kind.name().str());
  535. }
  536. }
  537. context.decl_name_stack().PopScope();
  538. return true;
  539. }
  540. } // namespace Carbon::Check