handle_function.cpp 12 KB

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