handle_function.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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/modifiers.h"
  8. #include "toolchain/parse/tree_node_location_translator.h"
  9. #include "toolchain/sem_ir/entry_point.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. namespace Carbon::Check {
  12. auto HandleFunctionIntroducer(Context& context,
  13. Parse::FunctionIntroducerId parse_node) -> bool {
  14. // Create an instruction block to hold the instructions created as part of the
  15. // function signature, such as parameter and return types.
  16. context.inst_block_stack().Push();
  17. // Push the bracketing node.
  18. context.node_stack().Push(parse_node);
  19. // Optional modifiers and the name follow.
  20. context.decl_state_stack().Push(DeclState::Fn);
  21. context.decl_name_stack().PushScopeAndStartName();
  22. return true;
  23. }
  24. auto HandleReturnType(Context& context, Parse::ReturnTypeId parse_node)
  25. -> bool {
  26. // Propagate the type expression.
  27. auto [type_parse_node, type_inst_id] =
  28. context.node_stack().PopExprWithParseNode();
  29. auto type_id = ExprAsType(context, type_parse_node, type_inst_id);
  30. // TODO: Use a dedicated instruction rather than VarStorage here.
  31. context.AddInstAndPush(
  32. {parse_node, SemIR::VarStorage{type_id, SemIR::NameId::ReturnSlot}});
  33. return true;
  34. }
  35. static auto DiagnoseModifiers(Context& context) -> KeywordModifierSet {
  36. Lex::TokenKind decl_kind = Lex::TokenKind::Fn;
  37. CheckAccessModifiersOnDecl(context, decl_kind);
  38. LimitModifiersOnDecl(context,
  39. KeywordModifierSet::Access | KeywordModifierSet::Method |
  40. KeywordModifierSet::Interface,
  41. decl_kind);
  42. // Rules for abstract, virtual, and impl, which are only allowed in classes.
  43. if (auto class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>()) {
  44. auto inheritance_kind =
  45. context.classes().Get(class_decl->class_id).inheritance_kind;
  46. if (inheritance_kind == SemIR::Class::Final) {
  47. ForbidModifiersOnDecl(context, KeywordModifierSet::Virtual, decl_kind,
  48. " in a non-abstract non-base `class` definition",
  49. context.GetCurrentScopeParseNode());
  50. }
  51. if (inheritance_kind != SemIR::Class::Abstract) {
  52. ForbidModifiersOnDecl(context, KeywordModifierSet::Abstract, decl_kind,
  53. " in a non-abstract `class` definition",
  54. context.GetCurrentScopeParseNode());
  55. }
  56. } else {
  57. ForbidModifiersOnDecl(context, KeywordModifierSet::Method, decl_kind,
  58. " outside of a class");
  59. }
  60. RequireDefaultFinalOnlyInInterfaces(context, decl_kind);
  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 parse_node,
  68. bool is_definition)
  69. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  70. // TODO: This contains the IR block for the parameters and return type. At
  71. // present, it's just loose, but it's not strictly required for parameter
  72. // refs; we should either stop constructing it completely or, if it turns out
  73. // to be needed, store it. Note, the underlying issue is that the LLVM IR has
  74. // nowhere clear to emit, so changing storage would require addressing that
  75. // problem. For comparison with function calls, the IR needs to be emitted
  76. // prior to the call.
  77. context.inst_block_stack().Pop();
  78. auto return_type_id = SemIR::TypeId::Invalid;
  79. auto return_slot_id = SemIR::InstId::Invalid;
  80. if (auto return_node_and_id =
  81. context.node_stack()
  82. .PopWithParseNodeIf<Parse::NodeKind::ReturnType>()) {
  83. auto return_storage_id = return_node_and_id->second;
  84. return_type_id = context.insts().Get(return_storage_id).type_id();
  85. return_type_id = context.AsCompleteType(return_type_id, [&] {
  86. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  87. "Function returns incomplete type `{0}`.", std::string);
  88. return context.emitter().Build(
  89. return_node_and_id->first, IncompleteTypeInFunctionReturnType,
  90. context.sem_ir().StringifyType(return_type_id));
  91. });
  92. if (!SemIR::GetInitRepr(context.sem_ir(), return_type_id)
  93. .has_return_slot()) {
  94. // The function only has a return slot if it uses in-place initialization.
  95. } else {
  96. return_slot_id = return_storage_id;
  97. }
  98. }
  99. SemIR::InstBlockId param_refs_id =
  100. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  101. SemIR::InstBlockId implicit_param_refs_id =
  102. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  103. SemIR::InstBlockId::Empty);
  104. auto name_context = context.decl_name_stack().FinishName();
  105. context.node_stack()
  106. .PopAndDiscardSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  107. // Process modifiers.
  108. auto modifiers = DiagnoseModifiers(context);
  109. if (!!(modifiers & KeywordModifierSet::Access)) {
  110. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  111. "access modifier");
  112. }
  113. if (!!(modifiers & KeywordModifierSet::Method)) {
  114. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  115. "method modifier");
  116. }
  117. if (!!(modifiers & KeywordModifierSet::Interface)) {
  118. // TODO: Once we are saving the modifiers for a function, add check that
  119. // the function may only be defined if it is marked `default` or `final`.
  120. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  121. "interface modifier");
  122. }
  123. context.decl_state_stack().Pop(DeclState::Fn);
  124. // Add the function declaration.
  125. auto function_decl = SemIR::FunctionDecl{
  126. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  127. SemIR::FunctionId::Invalid};
  128. auto function_decl_id = context.AddInst({parse_node, function_decl});
  129. // Check whether this is a redeclaration.
  130. auto existing_id =
  131. context.decl_name_stack().LookupOrAddName(name_context, function_decl_id);
  132. if (existing_id.is_valid()) {
  133. if (auto existing_function_decl =
  134. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  135. // This is a redeclaration of an existing function.
  136. function_decl.function_id = existing_function_decl->function_id;
  137. // TODO: Check that the signature matches!
  138. // Track the signature from the definition, so that IDs in the body match
  139. // IDs in the signature.
  140. if (is_definition) {
  141. auto& function_info =
  142. context.functions().Get(function_decl.function_id);
  143. function_info.implicit_param_refs_id = implicit_param_refs_id;
  144. function_info.param_refs_id = param_refs_id;
  145. function_info.return_type_id = return_type_id;
  146. function_info.return_slot_id = return_slot_id;
  147. }
  148. } else {
  149. // This is a redeclaration of something other than a function.
  150. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  151. }
  152. }
  153. // Create a new function if this isn't a valid redeclaration.
  154. if (!function_decl.function_id.is_valid()) {
  155. function_decl.function_id = context.functions().Add(
  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 = function_decl_id,
  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_slot_id = return_slot_id});
  163. }
  164. // Write the function ID into the FunctionDecl.
  165. context.insts().Set(function_decl_id, function_decl);
  166. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  167. // TODO: Update this once valid signatures for the entry point are decided.
  168. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  169. !context.inst_blocks().Get(param_refs_id).empty() ||
  170. (return_slot_id.is_valid() &&
  171. return_type_id !=
  172. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  173. return_type_id != context.CanonicalizeTupleType({}))) {
  174. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  175. "Invalid signature for `Main.Run` function. Expected "
  176. "`fn ()` or `fn () -> i32`.");
  177. context.emitter().Emit(parse_node, InvalidMainRunSignature);
  178. }
  179. }
  180. return {function_decl.function_id, function_decl_id};
  181. }
  182. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId parse_node)
  183. -> bool {
  184. BuildFunctionDecl(context, parse_node, /*is_definition=*/false);
  185. context.decl_name_stack().PopScope();
  186. return true;
  187. }
  188. auto HandleFunctionDefinitionStart(Context& context,
  189. Parse::FunctionDefinitionStartId parse_node)
  190. -> bool {
  191. // Process the declaration portion of the function.
  192. auto [function_id, decl_id] =
  193. BuildFunctionDecl(context, parse_node, /*is_definition=*/true);
  194. auto& function = context.functions().Get(function_id);
  195. // Track that this declaration is the definition.
  196. if (function.definition_id.is_valid()) {
  197. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  198. "Redefinition of function {0}.", std::string);
  199. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  200. "Previous definition was here.");
  201. context.emitter()
  202. .Build(parse_node, FunctionRedefinition,
  203. context.names().GetFormatted(function.name_id).str())
  204. .Note(function.definition_id, FunctionPreviousDefinition)
  205. .Emit();
  206. } else {
  207. function.definition_id = decl_id;
  208. }
  209. // Create the function scope and the entry block.
  210. context.return_scope_stack().push_back({.decl_id = decl_id});
  211. context.inst_block_stack().Push();
  212. context.PushScope(decl_id);
  213. context.AddCurrentCodeBlockToFunction();
  214. // Bring the implicit and explicit parameters into scope.
  215. for (auto param_id : llvm::concat<SemIR::InstId>(
  216. context.inst_blocks().Get(function.implicit_param_refs_id),
  217. context.inst_blocks().Get(function.param_refs_id))) {
  218. auto param = context.insts().Get(param_id);
  219. // Find the parameter in the pattern.
  220. // TODO: More general pattern handling?
  221. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  222. param_id = addr_pattern->inner_id;
  223. param = context.insts().Get(param_id);
  224. }
  225. // The parameter types need to be complete.
  226. context.TryToCompleteType(param.type_id(), [&] {
  227. CARBON_DIAGNOSTIC(
  228. IncompleteTypeInFunctionParam, Error,
  229. "Parameter has incomplete type `{0}` in function definition.",
  230. std::string);
  231. return context.emitter().Build(
  232. context.insts().GetParseNode(param_id), IncompleteTypeInFunctionParam,
  233. context.sem_ir().StringifyType(param.type_id()));
  234. });
  235. if (auto fn_param = param.TryAs<SemIR::AnyBindName>()) {
  236. context.AddNameToLookup(
  237. context.insts().GetParseNode(param_id),
  238. context.bind_names().Get(fn_param->bind_name_id).name_id, param_id);
  239. } else {
  240. CARBON_FATAL() << "Unexpected kind of parameter in function definition "
  241. << param;
  242. }
  243. }
  244. context.node_stack().Push(parse_node, function_id);
  245. return true;
  246. }
  247. auto HandleFunctionDefinition(Context& context,
  248. Parse::FunctionDefinitionId parse_node) -> bool {
  249. SemIR::FunctionId function_id =
  250. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  251. // If the `}` of the function is reachable, reject if we need a return value
  252. // and otherwise add an implicit `return;`.
  253. if (context.is_current_position_reachable()) {
  254. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  255. CARBON_DIAGNOSTIC(
  256. MissingReturnStatement, Error,
  257. "Missing `return` at end of function with declared return type.");
  258. context.emitter().Emit(TokenOnly(parse_node), MissingReturnStatement);
  259. } else {
  260. context.AddInst({parse_node, SemIR::Return{}});
  261. }
  262. }
  263. context.PopScope();
  264. context.inst_block_stack().Pop();
  265. context.return_scope_stack().pop_back();
  266. context.decl_name_stack().PopScope();
  267. return true;
  268. }
  269. } // namespace Carbon::Check