handle_function.cpp 17 KB

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