handle_function.cpp 12 KB

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