handle_function.cpp 14 KB

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