handle_function.cpp 12 KB

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