handle_function.cpp 25 KB

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