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/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. auto containing_kind = context.decl_state_stack().containing().kind;
  18. if (containing_kind != DeclState::Class) {
  19. ForbidModifiersOnDecl(context, KeywordModifierSet::Method, decl_kind,
  20. " outside of a class");
  21. } else {
  22. auto containing_decl_modifiers =
  23. context.decl_state_stack().containing().modifier_set;
  24. if (!(containing_decl_modifiers & KeywordModifierSet::Class)) {
  25. ForbidModifiersOnDecl(context, KeywordModifierSet::Virtual, decl_kind,
  26. " in a non-abstract non-base `class` definition",
  27. context.decl_state_stack().containing().first_node);
  28. }
  29. if (!(containing_decl_modifiers & KeywordModifierSet::Abstract)) {
  30. ForbidModifiersOnDecl(context, KeywordModifierSet::Abstract, decl_kind,
  31. " in a non-abstract `class` definition",
  32. context.decl_state_stack().containing().first_node);
  33. }
  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, bool is_definition)
  42. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  43. // TODO: This contains the IR block for the parameters and return type. At
  44. // present, it's just loose, but it's not strictly required for parameter
  45. // refs; we should either stop constructing it completely or, if it turns out
  46. // to be needed, store it. Note, the underlying issue is that the LLVM IR has
  47. // nowhere clear to emit, so changing storage would require addressing that
  48. // problem. For comparison with function calls, the IR needs to be emitted
  49. // prior to the call.
  50. context.inst_block_stack().Pop();
  51. auto return_type_id = SemIR::TypeId::Invalid;
  52. auto return_slot_id = SemIR::InstId::Invalid;
  53. if (context.parse_tree().node_kind(context.node_stack().PeekParseNode()) ==
  54. Parse::NodeKind::ReturnType) {
  55. auto [return_node, return_storage_id] =
  56. context.node_stack().PopWithParseNode<Parse::NodeKind::ReturnType>();
  57. auto return_node_copy = return_node;
  58. return_type_id = context.insts().Get(return_storage_id).type_id();
  59. if (!context.TryToCompleteType(return_type_id, [&] {
  60. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  61. "Function returns incomplete type `{0}`.",
  62. std::string);
  63. return context.emitter().Build(
  64. return_node_copy, IncompleteTypeInFunctionReturnType,
  65. context.sem_ir().StringifyType(return_type_id));
  66. })) {
  67. return_type_id = SemIR::TypeId::Error;
  68. } else if (!SemIR::GetInitializingRepresentation(context.sem_ir(),
  69. return_type_id)
  70. .has_return_slot()) {
  71. // The function only has a return slot if it uses in-place initialization.
  72. } else {
  73. return_slot_id = return_storage_id;
  74. }
  75. }
  76. SemIR::InstBlockId param_refs_id =
  77. context.node_stack().Pop<Parse::NodeKind::ParamList>();
  78. SemIR::InstBlockId implicit_param_refs_id =
  79. context.node_stack().PopIf<Parse::NodeKind::ImplicitParamList>().value_or(
  80. SemIR::InstBlockId::Empty);
  81. auto name_context = context.decl_name_stack().FinishName();
  82. context.node_stack()
  83. .PopAndDiscardSoloParseNode<Parse::NodeKind::FunctionIntroducer>();
  84. auto first_node = context.decl_state_stack().innermost().first_node;
  85. // Process modifiers.
  86. auto modifiers = DiagnoseModifiers(context);
  87. if (!!(modifiers & KeywordModifierSet::Access)) {
  88. context.TODO(context.decl_state_stack().innermost().saw_access_modifier,
  89. "access modifier");
  90. }
  91. if (!!(modifiers & KeywordModifierSet::Method)) {
  92. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  93. "method modifier");
  94. }
  95. if (!!(modifiers & KeywordModifierSet::Interface)) {
  96. context.TODO(context.decl_state_stack().innermost().saw_decl_modifier,
  97. "interface modifier");
  98. }
  99. // Add the function declaration.
  100. auto function_decl = SemIR::FunctionDecl{
  101. first_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(first_node, {}))) {
  151. CARBON_DIAGNOSTIC(InvalidMainRunSignature, Error,
  152. "Invalid signature for `Main.Run` function. Expected "
  153. "`fn ()` or `fn () -> i32`.");
  154. context.emitter().Emit(first_node, InvalidMainRunSignature);
  155. }
  156. }
  157. return {function_decl.function_id, function_decl_id};
  158. }
  159. auto HandleFunctionDecl(Context& context, Parse::NodeId /*parse_node*/)
  160. -> bool {
  161. BuildFunctionDecl(context, /*is_definition=*/false);
  162. context.decl_name_stack().PopScope();
  163. context.decl_state_stack().Pop(DeclState::Fn);
  164. return true;
  165. }
  166. auto HandleFunctionDefinition(Context& context, Parse::NodeId parse_node)
  167. -> 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(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. context.decl_state_stack().Pop(DeclState::Fn);
  187. return true;
  188. }
  189. auto HandleFunctionDefinitionStart(Context& context, Parse::NodeId parse_node)
  190. -> bool {
  191. // Process the declaration portion of the function.
  192. auto [function_id, decl_id] =
  193. BuildFunctionDecl(context, /*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. // The parameter types need to be complete.
  221. context.TryToCompleteType(param.type_id(), [&] {
  222. CARBON_DIAGNOSTIC(
  223. IncompleteTypeInFunctionParam, Error,
  224. "Parameter has incomplete type `{0}` in function definition.",
  225. std::string);
  226. return context.emitter().Build(
  227. param.parse_node(), IncompleteTypeInFunctionParam,
  228. context.sem_ir().StringifyType(param.type_id()));
  229. });
  230. if (auto fn_param = param.TryAs<SemIR::Param>()) {
  231. context.AddNameToLookup(fn_param->parse_node, fn_param->name_id,
  232. param_id);
  233. } else if (auto self_param = param.TryAs<SemIR::SelfParam>()) {
  234. context.AddNameToLookup(self_param->parse_node, SemIR::NameId::SelfValue,
  235. param_id);
  236. } else {
  237. CARBON_FATAL() << "Unexpected kind of parameter in function definition "
  238. << param;
  239. }
  240. }
  241. context.node_stack().Push(parse_node, function_id);
  242. return true;
  243. }
  244. auto HandleFunctionIntroducer(Context& context, Parse::NodeId parse_node)
  245. -> bool {
  246. // Create an instruction block to hold the instructions created as part of the
  247. // function signature, such as parameter and return types.
  248. context.inst_block_stack().Push();
  249. // Push the bracketing node.
  250. context.node_stack().Push(parse_node);
  251. // Optional modifiers and the name follow.
  252. context.decl_state_stack().Push(DeclState::Fn, parse_node);
  253. context.decl_name_stack().PushScopeAndStartName();
  254. return true;
  255. }
  256. auto HandleReturnType(Context& context, Parse::NodeId parse_node) -> bool {
  257. // Propagate the type expression.
  258. auto [type_parse_node, type_inst_id] =
  259. context.node_stack().PopExprWithParseNode();
  260. auto type_id = ExprAsType(context, type_parse_node, type_inst_id);
  261. // TODO: Use a dedicated instruction rather than VarStorage here.
  262. context.AddInstAndPush(
  263. parse_node,
  264. SemIR::VarStorage{parse_node, type_id, SemIR::NameId::ReturnSlot});
  265. return true;
  266. }
  267. } // namespace Carbon::Check