handle_function.cpp 21 KB

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