handle_function.cpp 17 KB

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