handle_function.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 target_scope_id)
  43. -> KeywordModifierSet {
  44. const Lex::TokenKind decl_kind = Lex::TokenKind::Fn;
  45. CheckAccessModifiersOnDecl(context, decl_kind, target_scope_id);
  46. LimitModifiersOnDecl(context,
  47. KeywordModifierSet::Access | KeywordModifierSet::Extern |
  48. KeywordModifierSet::Method |
  49. KeywordModifierSet::Interface,
  50. decl_kind);
  51. RestrictExternModifierOnDecl(context, decl_kind, target_scope_id,
  52. is_definition);
  53. CheckMethodModifiersOnFunction(context, target_scope_id);
  54. RequireDefaultFinalOnlyInInterfaces(context, decl_kind, target_scope_id);
  55. return context.decl_state_stack().innermost().modifier_set;
  56. }
  57. // Check whether this is a redeclaration, merging if needed.
  58. static auto TryMergeRedecl(Context& context, Parse::AnyFunctionDeclId node_id,
  59. SemIR::InstId prev_id,
  60. SemIR::FunctionDecl& function_decl,
  61. SemIR::Function& function_info, bool is_definition)
  62. -> void {
  63. if (!prev_id.is_valid()) {
  64. return;
  65. }
  66. auto prev_function_id = SemIR::FunctionId::Invalid;
  67. auto prev_import_ir_id = SemIR::ImportIRId::Invalid;
  68. CARBON_KIND_SWITCH(context.insts().Get(prev_id)) {
  69. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  70. prev_function_id = function_decl.function_id;
  71. break;
  72. }
  73. case CARBON_KIND(SemIR::ImportRefLoaded import_ref): {
  74. auto import_ir_inst =
  75. context.import_ir_insts().Get(import_ref.import_ir_inst_id);
  76. // Verify the decl so that things like aliases are name conflicts.
  77. const auto* import_ir =
  78. context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  79. if (!import_ir->insts().Is<SemIR::FunctionDecl>(import_ir_inst.inst_id)) {
  80. break;
  81. }
  82. // Use the type to get the ID.
  83. if (auto struct_value = context.insts().TryGetAs<SemIR::StructValue>(
  84. context.constant_values().Get(prev_id).inst_id())) {
  85. if (auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  86. struct_value->type_id)) {
  87. prev_function_id = function_type->function_id;
  88. prev_import_ir_id = import_ir_inst.ir_id;
  89. }
  90. }
  91. break;
  92. }
  93. default:
  94. break;
  95. }
  96. if (!prev_function_id.is_valid()) {
  97. context.DiagnoseDuplicateName(function_info.decl_id, prev_id);
  98. return;
  99. }
  100. if (MergeFunctionRedecl(context, node_id, function_info,
  101. /*new_is_import=*/false, is_definition,
  102. prev_function_id, prev_import_ir_id)) {
  103. // When merging, use the existing function rather than adding a new one.
  104. function_decl.function_id = prev_function_id;
  105. }
  106. }
  107. // Build a FunctionDecl describing the signature of a function. This
  108. // handles the common logic shared by function declaration syntax and function
  109. // definition syntax.
  110. static auto BuildFunctionDecl(Context& context,
  111. Parse::AnyFunctionDeclId node_id,
  112. bool is_definition)
  113. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  114. auto decl_block_id = context.inst_block_stack().Pop();
  115. auto return_type_id = SemIR::TypeId::Invalid;
  116. auto return_storage_id = SemIR::InstId::Invalid;
  117. auto return_slot = SemIR::Function::ReturnSlot::NotComputed;
  118. if (auto [return_node, maybe_return_storage_id] =
  119. context.node_stack().PopWithNodeIdIf<Parse::NodeKind::ReturnType>();
  120. maybe_return_storage_id) {
  121. return_type_id = context.insts().Get(*maybe_return_storage_id).type_id();
  122. return_storage_id = *maybe_return_storage_id;
  123. } else {
  124. // If there's no return type, there's no return slot.
  125. return_slot = SemIR::Function::ReturnSlot::Absent;
  126. }
  127. SemIR::InstBlockId param_refs_id =
  128. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  129. // TODO: Use Invalid rather than Empty if there was no implicit parameter
  130. // list.
  131. SemIR::InstBlockId implicit_param_refs_id =
  132. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  133. SemIR::InstBlockId::Empty);
  134. auto name_context = context.decl_name_stack().FinishName();
  135. context.node_stack()
  136. .PopAndDiscardSoloNodeId<Parse::NodeKind::FunctionIntroducer>();
  137. // Process modifiers.
  138. auto modifiers =
  139. DiagnoseModifiers(context, is_definition, name_context.target_scope_id);
  140. if (!!(modifiers & KeywordModifierSet::Access)) {
  141. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  142. ModifierOrder::Access),
  143. "access modifier");
  144. }
  145. bool is_extern = !!(modifiers & KeywordModifierSet::Extern);
  146. if (!!(modifiers & KeywordModifierSet::Method)) {
  147. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  148. ModifierOrder::Decl),
  149. "method modifier");
  150. }
  151. if (!!(modifiers & KeywordModifierSet::Interface)) {
  152. // TODO: Once we are saving the modifiers for a function, add check that
  153. // the function may only be defined if it is marked `default` or `final`.
  154. context.TODO(context.decl_state_stack().innermost().modifier_node_id(
  155. ModifierOrder::Decl),
  156. "interface modifier");
  157. }
  158. context.decl_state_stack().Pop(DeclState::Fn);
  159. // Add the function declaration.
  160. auto function_decl = SemIR::FunctionDecl{
  161. SemIR::TypeId::Invalid, SemIR::FunctionId::Invalid, decl_block_id};
  162. auto function_info = SemIR::Function{
  163. .name_id = name_context.name_id_for_new_inst(),
  164. .enclosing_scope_id = name_context.enclosing_scope_id_for_new_inst(),
  165. .decl_id = context.AddPlaceholderInst({node_id, function_decl}),
  166. .implicit_param_refs_id = implicit_param_refs_id,
  167. .param_refs_id = param_refs_id,
  168. .return_type_id = return_type_id,
  169. .return_storage_id = return_storage_id,
  170. .is_extern = is_extern,
  171. .return_slot = return_slot};
  172. if (is_definition) {
  173. function_info.definition_id = function_info.decl_id;
  174. }
  175. TryMergeRedecl(context, node_id, name_context.prev_inst_id(), function_decl,
  176. function_info, is_definition);
  177. // Create a new function if this isn't a valid redeclaration.
  178. if (!function_decl.function_id.is_valid()) {
  179. function_decl.function_id = context.functions().Add(function_info);
  180. }
  181. function_decl.type_id = context.GetFunctionType(function_decl.function_id);
  182. // Write the function ID into the FunctionDecl.
  183. context.ReplaceInstBeforeConstantUse(function_info.decl_id, function_decl);
  184. // Check if we need to add this to name lookup, now that the function decl is
  185. // done.
  186. if (!name_context.prev_inst_id().is_valid()) {
  187. // At interface scope, a function declaration introduces an associated
  188. // function.
  189. auto lookup_result_id = function_info.decl_id;
  190. if (name_context.enclosing_scope_id_for_new_inst().is_valid() &&
  191. !name_context.has_qualifiers) {
  192. auto scope_inst_id = context.name_scopes().GetInstIdIfValid(
  193. name_context.enclosing_scope_id_for_new_inst());
  194. if (auto interface_scope =
  195. context.insts().TryGetAsIfValid<SemIR::InterfaceDecl>(
  196. scope_inst_id)) {
  197. lookup_result_id = BuildAssociatedEntity(
  198. context, interface_scope->interface_id, function_info.decl_id);
  199. }
  200. }
  201. context.decl_name_stack().AddName(name_context, lookup_result_id);
  202. }
  203. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  204. // TODO: Update this once valid signatures for the entry point are decided.
  205. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  206. !context.inst_blocks().Get(param_refs_id).empty() ||
  207. (return_type_id.is_valid() &&
  208. return_type_id !=
  209. context.GetBuiltinType(SemIR::BuiltinKind::IntType) &&
  210. return_type_id != context.GetTupleType({}))) {
  211. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  212. "Invalid signature for `Main.Run` function. Expected "
  213. "`fn ()` or `fn () -> i32`.");
  214. context.emitter().Emit(node_id, InvalidMainRunSignature);
  215. }
  216. }
  217. return {function_decl.function_id, function_info.decl_id};
  218. }
  219. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId node_id)
  220. -> bool {
  221. BuildFunctionDecl(context, node_id, /*is_definition=*/false);
  222. context.decl_name_stack().PopScope();
  223. return true;
  224. }
  225. // Processes a function definition after a signature for which we have already
  226. // built a function ID. This logic is shared between processing regular function
  227. // definitions and delayed parsing of inline method definitions.
  228. static auto HandleFunctionDefinitionAfterSignature(
  229. Context& context, Parse::FunctionDefinitionStartId node_id,
  230. SemIR::FunctionId function_id, SemIR::InstId decl_id) -> void {
  231. auto& function = context.functions().Get(function_id);
  232. // Create the function scope and the entry block.
  233. context.return_scope_stack().push_back({.decl_id = decl_id});
  234. context.inst_block_stack().Push();
  235. context.scope_stack().Push(decl_id);
  236. context.AddCurrentCodeBlockToFunction();
  237. // Check the return type is complete.
  238. CheckFunctionReturnType(context, function.return_storage_id, function);
  239. // Check the parameter types are complete.
  240. for (auto param_id : llvm::concat<SemIR::InstId>(
  241. context.inst_blocks().Get(function.implicit_param_refs_id),
  242. context.inst_blocks().Get(function.param_refs_id))) {
  243. auto param = context.insts().Get(param_id);
  244. // Find the parameter in the pattern.
  245. // TODO: More general pattern handling?
  246. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  247. param_id = addr_pattern->inner_id;
  248. param = context.insts().Get(param_id);
  249. }
  250. // The parameter types need to be complete.
  251. context.TryToCompleteType(param.type_id(), [&] {
  252. CARBON_DIAGNOSTIC(
  253. IncompleteTypeInFunctionParam, Error,
  254. "Parameter has incomplete type `{0}` in function definition.",
  255. SemIR::TypeId);
  256. return context.emitter().Build(param_id, IncompleteTypeInFunctionParam,
  257. param.type_id());
  258. });
  259. }
  260. context.node_stack().Push(node_id, function_id);
  261. }
  262. auto HandleFunctionDefinitionSuspend(Context& context,
  263. Parse::FunctionDefinitionStartId node_id)
  264. -> SuspendedFunction {
  265. // Process the declaration portion of the function.
  266. auto [function_id, decl_id] =
  267. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  268. return {function_id, decl_id, context.decl_name_stack().Suspend()};
  269. }
  270. auto HandleFunctionDefinitionResume(Context& context,
  271. Parse::FunctionDefinitionStartId node_id,
  272. SuspendedFunction sus_fn) -> void {
  273. context.decl_name_stack().Restore(sus_fn.saved_name_state);
  274. HandleFunctionDefinitionAfterSignature(context, node_id, sus_fn.function_id,
  275. sus_fn.decl_id);
  276. }
  277. auto HandleFunctionDefinitionStart(Context& context,
  278. Parse::FunctionDefinitionStartId node_id)
  279. -> bool {
  280. // Process the declaration portion of the function.
  281. auto [function_id, decl_id] =
  282. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  283. HandleFunctionDefinitionAfterSignature(context, node_id, function_id,
  284. decl_id);
  285. return true;
  286. }
  287. auto HandleFunctionDefinition(Context& context,
  288. Parse::FunctionDefinitionId node_id) -> bool {
  289. SemIR::FunctionId function_id =
  290. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  291. // If the `}` of the function is reachable, reject if we need a return value
  292. // and otherwise add an implicit `return;`.
  293. if (context.is_current_position_reachable()) {
  294. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  295. CARBON_DIAGNOSTIC(
  296. MissingReturnStatement, Error,
  297. "Missing `return` at end of function with declared return type.");
  298. context.emitter().Emit(TokenOnly(node_id), MissingReturnStatement);
  299. } else {
  300. context.AddInst({node_id, SemIR::Return{}});
  301. }
  302. }
  303. context.scope_stack().Pop();
  304. context.inst_block_stack().Pop();
  305. context.return_scope_stack().pop_back();
  306. context.decl_name_stack().PopScope();
  307. return true;
  308. }
  309. auto HandleBuiltinFunctionDefinitionStart(
  310. Context& context, Parse::BuiltinFunctionDefinitionStartId node_id) -> bool {
  311. // Process the declaration portion of the function.
  312. auto [function_id, _] =
  313. BuildFunctionDecl(context, node_id, /*is_definition=*/true);
  314. context.node_stack().Push(node_id, function_id);
  315. return true;
  316. }
  317. auto HandleBuiltinName(Context& context, Parse::BuiltinNameId node_id) -> bool {
  318. context.node_stack().Push(node_id);
  319. return true;
  320. }
  321. // Looks up a builtin function kind given its name as a string.
  322. // TODO: Move this out to another file.
  323. static auto LookupBuiltinFunctionKind(Context& context,
  324. Parse::BuiltinNameId name_id)
  325. -> SemIR::BuiltinFunctionKind {
  326. auto builtin_name = context.string_literal_values().Get(
  327. context.tokens().GetStringLiteralValue(
  328. context.parse_tree().node_token(name_id)));
  329. auto kind = SemIR::BuiltinFunctionKind::ForBuiltinName(builtin_name);
  330. if (kind == SemIR::BuiltinFunctionKind::None) {
  331. CARBON_DIAGNOSTIC(UnknownBuiltinFunctionName, Error,
  332. "Unknown builtin function name \"{0}\".", std::string);
  333. context.emitter().Emit(name_id, UnknownBuiltinFunctionName,
  334. builtin_name.str());
  335. }
  336. return kind;
  337. }
  338. // Returns whether `function` is a valid declaration of the builtin
  339. // `builtin_kind`.
  340. static auto IsValidBuiltinDeclaration(Context& context,
  341. const SemIR::Function& function,
  342. SemIR::BuiltinFunctionKind builtin_kind)
  343. -> bool {
  344. // Form the list of parameter types for the declaration.
  345. llvm::SmallVector<SemIR::TypeId> param_type_ids;
  346. auto implicit_param_refs =
  347. context.inst_blocks().Get(function.implicit_param_refs_id);
  348. auto param_refs = context.inst_blocks().Get(function.param_refs_id);
  349. param_type_ids.reserve(implicit_param_refs.size() + param_refs.size());
  350. for (auto param_id :
  351. llvm::concat<SemIR::InstId>(implicit_param_refs, param_refs)) {
  352. // TODO: We also need to track whether the parameter is declared with
  353. // `var`.
  354. param_type_ids.push_back(context.insts().Get(param_id).type_id());
  355. }
  356. // Get the return type. This is `()` if none was specified.
  357. auto return_type_id = function.return_type_id;
  358. if (!return_type_id.is_valid()) {
  359. return_type_id = context.GetTupleType({});
  360. }
  361. return builtin_kind.IsValidType(context.sem_ir(), param_type_ids,
  362. return_type_id);
  363. }
  364. auto HandleBuiltinFunctionDefinition(
  365. Context& context, Parse::BuiltinFunctionDefinitionId /*node_id*/) -> bool {
  366. auto name_id =
  367. context.node_stack().PopForSoloNodeId<Parse::NodeKind::BuiltinName>();
  368. auto [fn_node_id, function_id] =
  369. context.node_stack()
  370. .PopWithNodeId<Parse::NodeKind::BuiltinFunctionDefinitionStart>();
  371. auto builtin_kind = LookupBuiltinFunctionKind(context, name_id);
  372. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  373. auto& function = context.functions().Get(function_id);
  374. if (IsValidBuiltinDeclaration(context, function, builtin_kind)) {
  375. function.builtin_kind = builtin_kind;
  376. } else {
  377. CARBON_DIAGNOSTIC(InvalidBuiltinSignature, Error,
  378. "Invalid signature for builtin function \"{0}\".",
  379. std::string);
  380. context.emitter().Emit(fn_node_id, InvalidBuiltinSignature,
  381. builtin_kind.name().str());
  382. }
  383. }
  384. context.decl_name_stack().PopScope();
  385. return true;
  386. }
  387. } // namespace Carbon::Check