handle_function.cpp 24 KB

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