handle_function.cpp 25 KB

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