handle_function.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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(
  42. Context& context,
  43. Parse::NodeIdOneOf<Parse::FunctionDeclId, Parse::FunctionDefinitionStartId>
  44. parse_node,
  45. bool is_definition) -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  46. // TODO: This contains the IR block for the parameters and return type. At
  47. // present, it's just loose, but it's not strictly required for parameter
  48. // refs; we should either stop constructing it completely or, if it turns out
  49. // to be needed, store it. Note, the underlying issue is that the LLVM IR has
  50. // nowhere clear to emit, so changing storage would require addressing that
  51. // problem. For comparison with function calls, the IR needs to be emitted
  52. // prior to the call.
  53. context.inst_block_stack().Pop();
  54. auto return_type_id = SemIR::TypeId::Invalid;
  55. auto return_slot_id = SemIR::InstId::Invalid;
  56. if (auto return_node_and_id =
  57. context.node_stack()
  58. .PopWithParseNodeIf<Parse::NodeKind::ReturnType>()) {
  59. auto return_storage_id = return_node_and_id->second;
  60. return_type_id = context.insts().Get(return_storage_id).type_id();
  61. return_type_id = context.AsCompleteType(return_type_id, [&] {
  62. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  63. "Function returns incomplete type `{0}`.", std::string);
  64. return context.emitter().Build(
  65. return_node_and_id->first, IncompleteTypeInFunctionReturnType,
  66. context.sem_ir().StringifyType(return_type_id));
  67. });
  68. if (!SemIR::GetInitRepr(context.sem_ir(), return_type_id)
  69. .has_return_slot()) {
  70. // The function only has a return slot if it uses in-place initialization.
  71. } else {
  72. return_slot_id = return_storage_id;
  73. }
  74. }
  75. SemIR::InstBlockId param_refs_id =
  76. context.node_stack().Pop<Parse::NodeKind::TuplePattern>();
  77. SemIR::InstBlockId implicit_param_refs_id =
  78. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  79. SemIR::InstBlockId::Empty);
  80. auto name_context = context.decl_name_stack().FinishName();
  81. context.node_stack()
  82. .PopAndDiscardSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  83. // Process modifiers.
  84. auto modifiers = DiagnoseModifiers(context);
  85. if (!!(modifiers & KeywordModifierSet::Access)) {
  86. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  87. "access modifier");
  88. }
  89. if (!!(modifiers & KeywordModifierSet::Method)) {
  90. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  91. "method modifier");
  92. }
  93. if (!!(modifiers & KeywordModifierSet::Interface)) {
  94. // TODO: Once we are saving the modifiers for a function, add check that
  95. // the function may only be defined if it is marked `default` or `final`.
  96. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  97. "interface modifier");
  98. }
  99. context.decl_state_stack().Pop(DeclState::Fn);
  100. // Add the function declaration.
  101. auto function_decl = SemIR::FunctionDecl{
  102. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  103. SemIR::FunctionId::Invalid};
  104. auto function_decl_id = context.AddInst(function_decl);
  105. // Check whether this is a redeclaration.
  106. auto existing_id =
  107. context.decl_name_stack().LookupOrAddName(name_context, function_decl_id);
  108. if (existing_id.is_valid()) {
  109. if (auto existing_function_decl =
  110. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  111. // This is a redeclaration of an existing function.
  112. function_decl.function_id = existing_function_decl->function_id;
  113. // TODO: Check that the signature matches!
  114. // Track the signature from the definition, so that IDs in the body match
  115. // IDs in the signature.
  116. if (is_definition) {
  117. auto& function_info =
  118. context.functions().Get(function_decl.function_id);
  119. function_info.implicit_param_refs_id = implicit_param_refs_id;
  120. function_info.param_refs_id = param_refs_id;
  121. function_info.return_type_id = return_type_id;
  122. function_info.return_slot_id = return_slot_id;
  123. }
  124. } else {
  125. // This is a redeclaration of something other than a function.
  126. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  127. }
  128. }
  129. // Create a new function if this isn't a valid redeclaration.
  130. if (!function_decl.function_id.is_valid()) {
  131. function_decl.function_id = context.functions().Add(
  132. {.name_id =
  133. name_context.state == DeclNameStack::NameContext::State::Unresolved
  134. ? name_context.unresolved_name_id
  135. : SemIR::NameId::Invalid,
  136. .decl_id = function_decl_id,
  137. .implicit_param_refs_id = implicit_param_refs_id,
  138. .param_refs_id = param_refs_id,
  139. .return_type_id = return_type_id,
  140. .return_slot_id = return_slot_id});
  141. }
  142. // Write the function ID into the FunctionDecl.
  143. context.insts().Set(function_decl_id, function_decl);
  144. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  145. // TODO: Update this once valid signatures for the entry point are decided.
  146. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  147. !context.inst_blocks().Get(param_refs_id).empty() ||
  148. (return_slot_id.is_valid() &&
  149. return_type_id !=
  150. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  151. return_type_id != context.CanonicalizeTupleType(parse_node, {}))) {
  152. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  153. "Invalid signature for `Main.Run` function. Expected "
  154. "`fn ()` or `fn () -> i32`.");
  155. context.emitter().Emit(parse_node, InvalidMainRunSignature);
  156. }
  157. }
  158. return {function_decl.function_id, function_decl_id};
  159. }
  160. auto HandleFunctionDecl(Context& context, Parse::FunctionDeclId parse_node)
  161. -> bool {
  162. BuildFunctionDecl(context, parse_node, /*is_definition=*/false);
  163. context.decl_name_stack().PopScope();
  164. return true;
  165. }
  166. auto HandleFunctionDefinition(Context& context,
  167. Parse::FunctionDefinitionId parse_node) -> bool {
  168. SemIR::FunctionId function_id =
  169. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  170. // If the `}` of the function is reachable, reject if we need a return value
  171. // and otherwise add an implicit `return;`.
  172. if (context.is_current_position_reachable()) {
  173. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  174. CARBON_DIAGNOSTIC(
  175. MissingReturnStatement, Error,
  176. "Missing `return` at end of function with declared return type.");
  177. context.emitter().Emit(TokenOnly(parse_node), MissingReturnStatement);
  178. } else {
  179. context.AddInst(SemIR::Return{parse_node});
  180. }
  181. }
  182. context.PopScope();
  183. context.inst_block_stack().Pop();
  184. context.return_scope_stack().pop_back();
  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(context.insts().Get(function.definition_id).parse_node(),
  205. FunctionPreviousDefinition)
  206. .Emit();
  207. } else {
  208. function.definition_id = decl_id;
  209. }
  210. // Create the function scope and the entry block.
  211. context.return_scope_stack().push_back({.decl_id = decl_id});
  212. context.inst_block_stack().Push();
  213. context.PushScope(decl_id);
  214. context.AddCurrentCodeBlockToFunction();
  215. // Bring the implicit and explicit parameters into scope.
  216. for (auto param_id : llvm::concat<SemIR::InstId>(
  217. context.inst_blocks().Get(function.implicit_param_refs_id),
  218. context.inst_blocks().Get(function.param_refs_id))) {
  219. auto param = context.insts().Get(param_id);
  220. // Find the parameter in the pattern.
  221. // TODO: More general pattern handling?
  222. if (auto addr_pattern = param.TryAs<SemIR::AddrPattern>()) {
  223. param_id = addr_pattern->inner_id;
  224. param = context.insts().Get(param_id);
  225. }
  226. // The parameter types need to be complete.
  227. context.TryToCompleteType(param.type_id(), [&] {
  228. CARBON_DIAGNOSTIC(
  229. IncompleteTypeInFunctionParam, Error,
  230. "Parameter has incomplete type `{0}` in function definition.",
  231. std::string);
  232. return context.emitter().Build(
  233. param.parse_node(), IncompleteTypeInFunctionParam,
  234. context.sem_ir().StringifyType(param.type_id()));
  235. });
  236. if (auto fn_param = param.TryAs<SemIR::BindName>()) {
  237. context.AddNameToLookup(fn_param->parse_node, fn_param->name_id,
  238. 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 HandleFunctionIntroducer(Context& context,
  248. Parse::FunctionIntroducerId parse_node) -> bool {
  249. // Create an instruction block to hold the instructions created as part of the
  250. // function signature, such as parameter and return types.
  251. context.inst_block_stack().Push();
  252. // Push the bracketing node.
  253. context.node_stack().Push(parse_node);
  254. // Optional modifiers and the name follow.
  255. context.decl_state_stack().Push(DeclState::Fn);
  256. context.decl_name_stack().PushScopeAndStartName();
  257. return true;
  258. }
  259. auto HandleReturnType(Context& context, Parse::ReturnTypeId parse_node)
  260. -> bool {
  261. // Propagate the type expression.
  262. auto [type_parse_node, type_inst_id] =
  263. context.node_stack().PopExprWithParseNode();
  264. auto type_id = ExprAsType(context, type_parse_node, type_inst_id);
  265. // TODO: Use a dedicated instruction rather than VarStorage here.
  266. context.AddInstAndPush(
  267. parse_node,
  268. SemIR::VarStorage{parse_node, type_id, SemIR::NameId::ReturnSlot});
  269. return true;
  270. }
  271. } // namespace Carbon::Check