handle_function.cpp 21 KB

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