handle_function.cpp 15 KB

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