handle_function.cpp 23 KB

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