handle_function.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. if (!context.TryToCompleteType(return_type_id, [&] {
  59. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  60. "Function returns incomplete type `{0}`.",
  61. std::string);
  62. return context.emitter().Build(
  63. return_node_copy, IncompleteTypeInFunctionReturnType,
  64. context.sem_ir().StringifyType(return_type_id));
  65. })) {
  66. return_type_id = SemIR::TypeId::Error;
  67. } else 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::ParamList>();
  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. auto first_node = context.decl_state_stack().innermost().first_node;
  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. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  95. "interface modifier");
  96. }
  97. // Add the function declaration.
  98. auto function_decl = SemIR::FunctionDecl{
  99. first_node, context.GetBuiltinType(SemIR::BuiltinKind::FunctionType),
  100. SemIR::FunctionId::Invalid};
  101. auto function_decl_id = context.AddInst(function_decl);
  102. // Check whether this is a redeclaration.
  103. auto existing_id =
  104. context.decl_name_stack().LookupOrAddName(name_context, function_decl_id);
  105. if (existing_id.is_valid()) {
  106. if (auto existing_function_decl =
  107. context.insts().Get(existing_id).TryAs<SemIR::FunctionDecl>()) {
  108. // This is a redeclaration of an existing function.
  109. function_decl.function_id = existing_function_decl->function_id;
  110. // TODO: Check that the signature matches!
  111. // Track the signature from the definition, so that IDs in the body match
  112. // IDs in the signature.
  113. if (is_definition) {
  114. auto& function_info =
  115. context.functions().Get(function_decl.function_id);
  116. function_info.implicit_param_refs_id = implicit_param_refs_id;
  117. function_info.param_refs_id = param_refs_id;
  118. function_info.return_type_id = return_type_id;
  119. function_info.return_slot_id = return_slot_id;
  120. }
  121. } else {
  122. // This is a redeclaration of something other than a function.
  123. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  124. }
  125. }
  126. // Create a new function if this isn't a valid redeclaration.
  127. if (!function_decl.function_id.is_valid()) {
  128. function_decl.function_id = context.functions().Add(
  129. {.name_id =
  130. name_context.state == DeclNameStack::NameContext::State::Unresolved
  131. ? name_context.unresolved_name_id
  132. : SemIR::NameId::Invalid,
  133. .decl_id = function_decl_id,
  134. .implicit_param_refs_id = implicit_param_refs_id,
  135. .param_refs_id = param_refs_id,
  136. .return_type_id = return_type_id,
  137. .return_slot_id = return_slot_id});
  138. }
  139. // Write the function ID into the FunctionDecl.
  140. context.insts().Set(function_decl_id, function_decl);
  141. if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) {
  142. // TODO: Update this once valid signatures for the entry point are decided.
  143. if (!context.inst_blocks().Get(implicit_param_refs_id).empty() ||
  144. !context.inst_blocks().Get(param_refs_id).empty() ||
  145. (return_slot_id.is_valid() &&
  146. return_type_id !=
  147. context.GetBuiltinType(SemIR::BuiltinKind::BoolType) &&
  148. return_type_id != context.CanonicalizeTupleType(first_node, {}))) {
  149. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  150. "Invalid signature for `Main.Run` function. Expected "
  151. "`fn ()` or `fn () -> i32`.");
  152. context.emitter().Emit(first_node, InvalidMainRunSignature);
  153. }
  154. }
  155. return {function_decl.function_id, function_decl_id};
  156. }
  157. auto HandleFunctionDecl(Context& context, Parse::NodeId /*parse_node*/)
  158. -> bool {
  159. BuildFunctionDecl(context, /*is_definition=*/false);
  160. context.decl_name_stack().PopScope();
  161. context.decl_state_stack().Pop(DeclState::Fn);
  162. return true;
  163. }
  164. auto HandleFunctionDefinition(Context& context, Parse::NodeId parse_node)
  165. -> bool {
  166. SemIR::FunctionId function_id =
  167. context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
  168. // If the `}` of the function is reachable, reject if we need a return value
  169. // and otherwise add an implicit `return;`.
  170. if (context.is_current_position_reachable()) {
  171. if (context.functions().Get(function_id).return_type_id.is_valid()) {
  172. CARBON_DIAGNOSTIC(
  173. MissingReturnStatement, Error,
  174. "Missing `return` at end of function with declared return type.");
  175. context.emitter().Emit(parse_node, MissingReturnStatement);
  176. } else {
  177. context.AddInst(SemIR::Return{parse_node});
  178. }
  179. }
  180. context.PopScope();
  181. context.inst_block_stack().Pop();
  182. context.return_scope_stack().pop_back();
  183. context.decl_name_stack().PopScope();
  184. context.decl_state_stack().Pop(DeclState::Fn);
  185. return true;
  186. }
  187. auto HandleFunctionDefinitionStart(Context& context, Parse::NodeId parse_node)
  188. -> bool {
  189. // Process the declaration portion of the function.
  190. auto [function_id, decl_id] =
  191. BuildFunctionDecl(context, /*is_definition=*/true);
  192. auto& function = context.functions().Get(function_id);
  193. // Track that this declaration is the definition.
  194. if (function.definition_id.is_valid()) {
  195. CARBON_DIAGNOSTIC(FunctionRedefinition, Error,
  196. "Redefinition of function {0}.", std::string);
  197. CARBON_DIAGNOSTIC(FunctionPreviousDefinition, Note,
  198. "Previous definition was here.");
  199. context.emitter()
  200. .Build(parse_node, FunctionRedefinition,
  201. context.names().GetFormatted(function.name_id).str())
  202. .Note(context.insts().Get(function.definition_id).parse_node(),
  203. FunctionPreviousDefinition)
  204. .Emit();
  205. } else {
  206. function.definition_id = decl_id;
  207. }
  208. // Create the function scope and the entry block.
  209. context.return_scope_stack().push_back({.decl_id = decl_id});
  210. context.inst_block_stack().Push();
  211. context.PushScope(decl_id);
  212. context.AddCurrentCodeBlockToFunction();
  213. // Bring the implicit and explicit parameters into scope.
  214. for (auto param_id : llvm::concat<SemIR::InstId>(
  215. context.inst_blocks().Get(function.implicit_param_refs_id),
  216. context.inst_blocks().Get(function.param_refs_id))) {
  217. auto param = context.insts().Get(param_id);
  218. // The parameter types need to be complete.
  219. context.TryToCompleteType(param.type_id(), [&] {
  220. CARBON_DIAGNOSTIC(
  221. IncompleteTypeInFunctionParam, Error,
  222. "Parameter has incomplete type `{0}` in function definition.",
  223. std::string);
  224. return context.emitter().Build(
  225. param.parse_node(), IncompleteTypeInFunctionParam,
  226. context.sem_ir().StringifyType(param.type_id()));
  227. });
  228. if (auto fn_param = param.TryAs<SemIR::Param>()) {
  229. context.AddNameToLookup(fn_param->parse_node, fn_param->name_id,
  230. param_id);
  231. } else if (auto self_param = param.TryAs<SemIR::SelfParam>()) {
  232. context.AddNameToLookup(self_param->parse_node, SemIR::NameId::SelfValue,
  233. param_id);
  234. } else {
  235. CARBON_FATAL() << "Unexpected kind of parameter in function definition "
  236. << param;
  237. }
  238. }
  239. context.node_stack().Push(parse_node, function_id);
  240. return true;
  241. }
  242. auto HandleFunctionIntroducer(Context& context, Parse::NodeId parse_node)
  243. -> bool {
  244. // Create an instruction block to hold the instructions created as part of the
  245. // function signature, such as parameter and return types.
  246. context.inst_block_stack().Push();
  247. // Push the bracketing node.
  248. context.node_stack().Push(parse_node);
  249. // Optional modifiers and the name follow.
  250. context.decl_state_stack().Push(DeclState::Fn, parse_node);
  251. context.decl_name_stack().PushScopeAndStartName();
  252. return true;
  253. }
  254. auto HandleReturnType(Context& context, Parse::NodeId parse_node) -> bool {
  255. // Propagate the type expression.
  256. auto [type_parse_node, type_inst_id] =
  257. context.node_stack().PopExprWithParseNode();
  258. auto type_id = ExprAsType(context, type_parse_node, type_inst_id);
  259. // TODO: Use a dedicated instruction rather than VarStorage here.
  260. context.AddInstAndPush(
  261. parse_node,
  262. SemIR::VarStorage{parse_node, type_id, SemIR::NameId::ReturnSlot});
  263. return true;
  264. }
  265. } // namespace Carbon::Check