handle_function.cpp 16 KB

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