handle_function.cpp 21 KB

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