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