handle_function.cpp 24 KB

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