handle_function.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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/handle.h"
  11. #include "toolchain/check/interface.h"
  12. #include "toolchain/check/merge.h"
  13. #include "toolchain/check/modifiers.h"
  14. #include "toolchain/check/name_component.h"
  15. #include "toolchain/sem_ir/builtin_function_kind.h"
  16. #include "toolchain/sem_ir/entry_point.h"
  17. #include "toolchain/sem_ir/function.h"
  18. #include "toolchain/sem_ir/generic.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::Check {
  22. auto HandleFunctionIntroducer(Context& context,
  23. Parse::FunctionIntroducerId node_id) -> bool {
  24. // Create an instruction block to hold the instructions created as part of the
  25. // function signature, such as parameter and return types.
  26. context.inst_block_stack().Push();
  27. // Push the bracketing node.
  28. context.node_stack().Push(node_id);
  29. // Optional modifiers and the name follow.
  30. context.decl_introducer_state_stack().Push<Lex::TokenKind::Fn>();
  31. context.decl_name_stack().PushScopeAndStartName();
  32. return true;
  33. }
  34. auto HandleReturnType(Context& context, Parse::ReturnTypeId node_id) -> bool {
  35. // Propagate the type expression.
  36. auto [type_node_id, type_inst_id] = context.node_stack().PopExprWithNodeId();
  37. auto type_id = ExprAsType(context, type_node_id, type_inst_id);
  38. // TODO: Use a dedicated instruction rather than VarStorage here.
  39. context.AddInstAndPush<SemIR::VarStorage>(
  40. node_id, {.type_id = type_id, .name_id = SemIR::NameId::ReturnSlot});
  41. return true;
  42. }
  43. static auto DiagnoseModifiers(Context& context, DeclIntroducerState& introducer,
  44. bool is_definition,
  45. SemIR::InstId parent_scope_inst_id,
  46. std::optional<SemIR::Inst> parent_scope_inst)
  47. -> void {
  48. CheckAccessModifiersOnDecl(context, introducer, parent_scope_inst);
  49. LimitModifiersOnDecl(context, introducer,
  50. KeywordModifierSet::Access | KeywordModifierSet::Extern |
  51. KeywordModifierSet::Method |
  52. KeywordModifierSet::Interface);
  53. RestrictExternModifierOnDecl(context, introducer, parent_scope_inst,
  54. is_definition);
  55. CheckMethodModifiersOnFunction(context, introducer, parent_scope_inst_id,
  56. parent_scope_inst);
  57. RequireDefaultFinalOnlyInInterfaces(context, introducer, parent_scope_inst);
  58. }
  59. // Returns the return slot usage for a function given the computed usage for two
  60. // different declarations of the function.
  61. static auto MergeReturnSlot(SemIR::Function::ReturnSlot a,
  62. SemIR::Function::ReturnSlot b)
  63. -> SemIR::Function::ReturnSlot {
  64. if (a == SemIR::Function::ReturnSlot::NotComputed) {
  65. return b;
  66. }
  67. if (b == SemIR::Function::ReturnSlot::NotComputed) {
  68. return a;
  69. }
  70. if (a == SemIR::Function::ReturnSlot::Error) {
  71. return b;
  72. }
  73. if (b == SemIR::Function::ReturnSlot::Error) {
  74. return a;
  75. }
  76. CARBON_CHECK(a == b)
  77. << "Different return slot usage computed for the same function.";
  78. return a;
  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, SemIRLoc new_loc,
  87. SemIR::Function& new_function,
  88. bool new_is_import, bool new_is_definition,
  89. SemIR::FunctionId prev_function_id,
  90. SemIR::ImportIRId prev_import_ir_id) -> bool {
  91. auto& prev_function = context.functions().Get(prev_function_id);
  92. if (!CheckFunctionTypeMatches(context, new_function, prev_function, {})) {
  93. return false;
  94. }
  95. CheckIsAllowedRedecl(context, Lex::TokenKind::Fn, prev_function.name_id,
  96. {.loc = new_loc,
  97. .is_definition = new_is_definition,
  98. .is_extern = new_function.is_extern},
  99. {.loc = prev_function.definition_id.is_valid()
  100. ? prev_function.definition_id
  101. : prev_function.decl_id,
  102. .is_definition = prev_function.definition_id.is_valid(),
  103. .is_extern = prev_function.is_extern},
  104. prev_import_ir_id);
  105. if (new_is_definition) {
  106. // Track the signature from the definition, so that IDs in the body
  107. // match IDs in the signature.
  108. prev_function.definition_id = new_function.definition_id;
  109. prev_function.implicit_param_refs_id = new_function.implicit_param_refs_id;
  110. prev_function.param_refs_id = new_function.param_refs_id;
  111. prev_function.return_storage_id = new_function.return_storage_id;
  112. }
  113. // The new function might have return slot information if it was imported.
  114. prev_function.return_slot =
  115. MergeReturnSlot(prev_function.return_slot, new_function.return_slot);
  116. if ((prev_import_ir_id.is_valid() && !new_is_import) ||
  117. (prev_function.is_extern && !new_function.is_extern)) {
  118. prev_function.is_extern = new_function.is_extern;
  119. prev_function.decl_id = new_function.decl_id;
  120. ReplacePrevInstForMerge(context, prev_function.parent_scope_id,
  121. prev_function.name_id, new_function.decl_id);
  122. }
  123. return true;
  124. }
  125. // Check whether this is a redeclaration, merging if needed.
  126. static auto TryMergeRedecl(Context& context, Parse::AnyFunctionDeclId node_id,
  127. SemIR::InstId prev_id,
  128. SemIR::FunctionDecl& function_decl,
  129. SemIR::Function& function_info, bool is_definition)
  130. -> void {
  131. if (!prev_id.is_valid()) {
  132. return;
  133. }
  134. auto prev_function_id = SemIR::FunctionId::Invalid;
  135. auto prev_import_ir_id = SemIR::ImportIRId::Invalid;
  136. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  137. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  138. prev_function_id = function_decl.function_id;
  139. break;
  140. }
  141. case CARBON_KIND(SemIR::ImportRefLoaded import_ref): {
  142. auto import_ir_inst =
  143. context.import_ir_insts().Get(import_ref.import_ir_inst_id);
  144. // Verify the decl so that things like aliases are name conflicts.
  145. const auto* import_ir =
  146. context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  147. if (!import_ir->insts().Is<SemIR::FunctionDecl>(import_ir_inst.inst_id)) {
  148. break;
  149. }
  150. // Use the type to get the ID.
  151. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  152. context.constant_values().GetConstantInstId(prev_id))) {
  153. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  154. struct_value->type_id)) {
  155. prev_function_id = function_type->function_id;
  156. prev_import_ir_id = import_ir_inst.ir_id;
  157. }
  158. }
  159. break;
  160. }
  161. default:
  162. break;
  163. }
  164. if (!prev_function_id.is_valid()) {
  165. context.DiagnoseDuplicateName(function_info.decl_id, prev_id);
  166. return;
  167. }
  168. if (MergeFunctionRedecl(context, node_id, function_info,
  169. /*new_is_import=*/false, 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 decl_block_id = context.inst_block_stack().Pop();
  183. auto return_storage_id = SemIR::InstId::Invalid;
  184. auto return_slot = SemIR::Function::ReturnSlot::NotComputed;
  185. if (auto [return_node, maybe_return_storage_id] =
  186. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  187. maybe_return_storage_id) {
  188. return_storage_id = *maybe_return_storage_id;
  189. } else {
  190. // If there's no return type, there's no return slot.
  191. return_slot = SemIR::Function::ReturnSlot::Absent;
  192. }
  193. auto name = PopNameComponent(context);
  194. if (!name.params_id.is_valid()) {
  195. context.TODO(node_id, "function with positional parameters");
  196. name.params_id = SemIR::InstBlockId::Empty;
  197. }
  198. auto name_context = context.decl_name_stack().FinishName(name);
  199. context.node_stack()
  200. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  201. // Process modifiers.
  202. auto [parent_scope_inst_id, parent_scope_inst] =
  203. context.name_scopes().GetInstIfValid(name_context.parent_scope_id);
  204. auto introducer =
  205. context.decl_introducer_state_stack().Pop<Lex::TokenKind::Fn>();
  206. DiagnoseModifiers(context, introducer, is_definition, parent_scope_inst_id,
  207. parent_scope_inst);
  208. bool is_extern = introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern);
  209. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Method)) {
  210. context.TODO(introducer.modifier_node_id(ModifierOrder::Decl),
  211. "method modifier");
  212. }
  213. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Interface)) {
  214. // TODO: Once we are saving the modifiers for a function, add check that
  215. // the function may only be defined if it is marked `default` or `final`.
  216. context.TODO(introducer.modifier_node_id(ModifierOrder::Decl),
  217. "interface modifier");
  218. }
  219. // Add the function declaration.
  220. auto function_decl = SemIR::FunctionDecl{
  221. SemIR::TypeId::Invalid, SemIR::FunctionId::Invalid, decl_block_id};
  222. auto decl_id =
  223. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, function_decl));
  224. // Build the function entity. This will be merged into an existing function if
  225. // there is one, or otherwise added to the function store.
  226. auto function_info = SemIR::Function{
  227. .name_id = name_context.name_id_for_new_inst(),
  228. .parent_scope_id = name_context.parent_scope_id_for_new_inst(),
  229. .decl_id = decl_id,
  230. .generic_id = SemIR::GenericId::Invalid,
  231. .implicit_param_refs_id = name.implicit_params_id,
  232. .param_refs_id = name.params_id,
  233. .return_storage_id = return_storage_id,
  234. .is_extern = is_extern,
  235. .return_slot = return_slot};
  236. if (is_definition) {
  237. function_info.definition_id = decl_id;
  238. }
  239. TryMergeRedecl(context, node_id, name_context.prev_inst_id(), function_decl,
  240. function_info, is_definition);
  241. // Create a new function if this isn't a valid redeclaration.
  242. if (!function_decl.function_id.is_valid()) {
  243. // For a generic function, build the corresponding Generic entity.
  244. if (!context.scope_stack().compile_time_binding_stack().empty()) {
  245. function_info.generic_id = context.generics().Add(SemIR::Generic{
  246. .decl_id = decl_id,
  247. .bindings_id = context.inst_blocks().Add(
  248. context.scope_stack().compile_time_binding_stack())});
  249. }
  250. function_decl.function_id = context.functions().Add(function_info);
  251. } else {
  252. // TODO: Validate that the redeclaration doesn't set an access modifier.
  253. }
  254. function_decl.type_id = context.GetFunctionType(function_decl.function_id);
  255. // Write the function ID into the FunctionDecl.
  256. context.ReplaceInstBeforeConstantUse(decl_id, function_decl);
  257. // Check if we need to add this to name lookup, now that the function decl is
  258. // done.
  259. if (!name_context.prev_inst_id().is_valid()) {
  260. // At interface scope, a function declaration introduces an associated
  261. // function.
  262. auto lookup_result_id = function_info.decl_id;
  263. if (parent_scope_inst && !name_context.has_qualifiers) {
  264. if (auto interface_scope =
  265. parent_scope_inst->TryAs<SemIR::InterfaceDecl>()) {
  266. lookup_result_id = BuildAssociatedEntity(
  267. context, interface_scope->interface_id, decl_id);
  268. }
  269. }
  270. context.decl_name_stack().AddName(name_context, lookup_result_id,
  271. introducer.modifier_set.GetAccessKind());
  272. }
  273. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  274. auto return_type_id = function_info.declared_return_type(context.sem_ir());
  275. // TODO: Update this once valid signatures for the entry point are decided.
  276. if (function_info.implicit_param_refs_id.is_valid() ||
  277. !function_info.param_refs_id.is_valid() ||
  278. !context.inst_blocks().Get(function_info.param_refs_id).empty() ||
  279. (return_type_id.is_valid() &&
  280. return_type_id !=
  281. context.GetBuiltinType(SemIR::BuiltinKind::IntType) &&
  282. return_type_id != context.GetTupleType({}))) {
  283. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  284. "Invalid signature for `Main.Run` function. Expected "
  285. "`fn ()` or `fn () -> i32`.");
  286. context.emitter().Emit(node_id, InvalidMainRunSignature);
  287. }
  288. }
  289. if (!is_definition && context.IsImplFile() && !is_extern) {
  290. context.definitions_required().push_back(decl_id);
  291. }
  292. return {function_decl.function_id, decl_id};
  293. }
  294. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId node_id)
  295. -> bool {
  296. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  297. context.decl_name_stack().PopScope();
  298. return true;
  299. }
  300. // Processes a function definition after a signature for which we have already
  301. // built a function ID. This logic is shared between processing regular function
  302. // definitions and delayed parsing of inline method definitions.
  303. static auto HandleFunctionDefinitionAfterSignature(
  304. Context& context, Parse::FunctionDefinitionStartId node_id,
  305. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  306. auto& function = context.functions().Get(function_id);
  307. // Create the function scope and the entry block.
  308. context.return_scope_stack().push_back({.decl_id = decl_id});
  309. context.inst_block_stack().Push();
  310. context.scope_stack().Push(decl_id);
  311. context.AddCurrentCodeBlockToFunction();
  312. // Check the return type is complete.
  313. CheckFunctionReturnType(context, function.return_storage_id, function);
  314. // Check the parameter types are complete.
  315. for (auto param_id : llvm::concat<const SemIR::InstId>(
  316. context.inst_blocks().GetOrEmpty(function.implicit_param_refs_id),
  317. context.inst_blocks().GetOrEmpty(function.param_refs_id))) {
  318. auto param = context.insts().Get(param_id);
  319. // Find the parameter in the pattern.
  320. // TODO: More general pattern handling?
  321. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  322. param_id = addr_pattern->inner_id;
  323. param = context.insts().Get(param_id);
  324. }
  325. // The parameter types need to be complete.
  326. context.TryToCompleteType(param.type_id(), [&] {
  327. CARBON_DIAGNOSTIC(
  328. IncompleteTypeInFunctionParam, Error,
  329. "Parameter has incomplete type `{0}` in function definition.",
  330. SemIR::TypeId);
  331. return context.emitter().Build(param_id, IncompleteTypeInFunctionParam,
  332. param.type_id());
  333. });
  334. }
  335. context.node_stack().Push(node_id, function_id);
  336. }
  337. auto HandleFunctionDefinitionSuspend(Context& context,
  338. Parse::FunctionDefinitionStartId node_id)
  339. -> SuspendedFunction {
  340. // Process the declaration portion of the function.
  341. auto [function_id, decl_id] =
  342. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  343. return {.function_id = function_id,
  344. .decl_id = decl_id,
  345. .saved_name_state = context.decl_name_stack().Suspend()};
  346. }
  347. auto HandleFunctionDefinitionResume(Context& context,
  348. Parse::FunctionDefinitionStartId node_id,
  349. SuspendedFunction suspended_fn) -> void {
  350. context.decl_name_stack().Restore(suspended_fn.saved_name_state);
  351. HandleFunctionDefinitionAfterSignature(
  352. context, node_id, suspended_fn.function_id, suspended_fn.decl_id);
  353. }
  354. auto HandleFunctionDefinitionStart(Context& context,
  355. Parse::FunctionDefinitionStartId node_id)
  356. -> bool {
  357. // Process the declaration portion of the function.
  358. auto [function_id, decl_id] =
  359. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  360. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  361. decl_id);
  362. return true;
  363. }
  364. auto HandleFunctionDefinition(Context& context,
  365. Parse::FunctionDefinitionId node_id) -> bool {
  366. SemIR::FunctionId function_id =
  367. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  368. // If the `}` of the function is reachable, reject if we need a return value
  369. // and otherwise add an implicit `return;`.
  370. if (context.is_current_position_reachable()) {
  371. if (context.functions().Get(function_id).return_storage_id.is_valid()) {
  372. CARBON_DIAGNOSTIC(
  373. MissingReturnStatement, Error,
  374. "Missing `return` at end of function with declared return type.");
  375. context.emitter().Emit(TokenOnly(node_id), MissingReturnStatement);
  376. } else {
  377. context.AddInst<SemIR::Return>(node_id, {});
  378. }
  379. }
  380. context.scope_stack().Pop();
  381. context.inst_block_stack().Pop();
  382. context.return_scope_stack().pop_back();
  383. context.decl_name_stack().PopScope();
  384. return true;
  385. }
  386. auto HandleBuiltinFunctionDefinitionStart(
  387. Context& context, Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  388. // Process the declaration portion of the function.
  389. auto [function_id, _] =
  390. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  391. context.node_stack().Push(node_id, function_id);
  392. return true;
  393. }
  394. auto HandleBuiltinName(Context& context, Parse::BuiltinNameId node_id) -> bool {
  395. context.node_stack().Push(node_id);
  396. return true;
  397. }
  398. // Looks up a builtin function kind given its name as a string.
  399. // TODO: Move this out to another file.
  400. static auto LookupBuiltinFunctionKind(Context& context,
  401. Parse::BuiltinNameId name_id)
  402. -> SemIR::BuiltinFunctionKind {
  403. auto builtin_name = context.string_literal_values().Get(
  404. context.tokens().GetStringLiteralValue(
  405. context.parse_tree().node_token(name_id)));
  406. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  407. if (kind == SemIR::BuiltinFunctionKind::None) {
  408. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  409. "Unknown builtin function name \"{0}\".", std::string);
  410. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  411. builtin_name.str());
  412. }
  413. return kind;
  414. }
  415. // Returns whether `function` is a valid declaration of the builtin
  416. // `builtin_kind`.
  417. static auto IsValidBuiltinDeclaration(Context& context,
  418. const SemIR::Function& function,
  419. SemIR::BuiltinFunctionKind builtin_kind)
  420. -> bool {
  421. // Form the list of parameter types for the declaration.
  422. llvm::SmallVector<SemIR::TypeId> param_type_ids;
  423. auto implicit_param_refs =
  424. context.inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  425. auto param_refs = context.inst_blocks().GetOrEmpty(function.param_refs_id);
  426. param_type_ids.reserve(implicit_param_refs.size() + param_refs.size());
  427. for (auto param_id :
  428. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  429. // TODO: We also need to track whether the parameter is declared with
  430. // `var`.
  431. param_type_ids.push_back(context.insts().Get(param_id).type_id());
  432. }
  433. // Get the return type. This is `()` if none was specified.
  434. auto return_type_id = function.declared_return_type(context.sem_ir());
  435. if (!return_type_id.is_valid()) {
  436. return_type_id = context.GetTupleType({});
  437. }
  438. return builtin_kind.IsValidType(context.sem_ir(), param_type_ids,
  439. return_type_id);
  440. }
  441. auto HandleBuiltinFunctionDefinition(
  442. Context& context, Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  443. auto name_id =
  444. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  445. auto [fn_node_id, function_id] =
  446. context.node_stack()
  447. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  448. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  449. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  450. auto& function = context.functions().Get(function_id);
  451. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  452. function.builtin_kind = builtin_kind;
  453. } else {
  454. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  455. "Invalid signature for builtin function \"{0}\".",
  456. std::string);
  457. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  458. builtin_kind.name().str());
  459. }
  460. }
  461. context.decl_name_stack().PopScope();
  462. return true;
  463. }
  464. } // namespace Carbon::Check