function.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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/function.h"
  5. #include "common/find.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/inst.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/check/pattern.h"
  12. #include "toolchain/check/pattern_match.h"
  13. #include "toolchain/check/scope_stack.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/check/type_completion.h"
  16. #include "toolchain/sem_ir/builtin_function_kind.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/pattern.h"
  19. namespace Carbon::Check {
  20. auto FindSelfPattern(Context& context,
  21. SemIR::InstBlockId implicit_param_patterns_id)
  22. -> SemIR::InstId {
  23. auto implicit_param_patterns =
  24. context.inst_blocks().GetOrEmpty(implicit_param_patterns_id);
  25. return FindIfOrNone(implicit_param_patterns, [&](auto implicit_param_id) {
  26. return SemIR::IsSelfPattern(context.sem_ir(), implicit_param_id);
  27. });
  28. }
  29. auto AddReturnPatterns(Context& context, SemIR::LocId loc_id,
  30. Context::FormExpr form_expr) -> SemIR::InstBlockId {
  31. llvm::SmallVector<SemIR::InstId, 1> return_patterns;
  32. auto form_inst = context.insts().Get(form_expr.form_inst_id);
  33. CARBON_KIND_SWITCH(form_inst) {
  34. case SemIR::RefForm::Kind: {
  35. break;
  36. }
  37. case CARBON_KIND(SemIR::InitForm init_form): {
  38. auto pattern_type_id = GetPatternType(context, form_expr.type_id);
  39. auto return_slot_pattern_id = AddPatternInst<SemIR::ReturnSlotPattern>(
  40. context, loc_id,
  41. {.type_id = pattern_type_id,
  42. .type_inst_id = form_expr.type_component_id});
  43. return_patterns.push_back(AddPatternInst<SemIR::OutParamPattern>(
  44. context, SemIR::LocId(form_expr.form_inst_id),
  45. {.type_id = pattern_type_id,
  46. .subpattern_id = return_slot_pattern_id,
  47. .index = init_form.index}));
  48. break;
  49. }
  50. case SemIR::ErrorInst::Kind: {
  51. break;
  52. }
  53. default:
  54. CARBON_FATAL("unexpected inst kind: {0}", form_inst);
  55. }
  56. return context.inst_blocks().AddCanonical(return_patterns);
  57. }
  58. auto IsValidBuiltinDeclaration(Context& context,
  59. const SemIR::Function& function,
  60. SemIR::BuiltinFunctionKind builtin_kind)
  61. -> bool {
  62. if (!function.call_params_id.has_value()) {
  63. // For now, we have no builtins that support positional parameters.
  64. return false;
  65. }
  66. // Find the list of call parameters other than the implicit return slots.
  67. auto call_params = context.inst_blocks()
  68. .Get(function.call_params_id)
  69. .drop_back(context.inst_blocks()
  70. .GetOrEmpty(function.return_patterns_id)
  71. .size());
  72. // Get the return type. This is `()` if none was specified.
  73. auto return_type_id = function.GetDeclaredReturnType(context.sem_ir());
  74. if (!return_type_id.has_value()) {
  75. return_type_id = GetTupleType(context, {});
  76. }
  77. return builtin_kind.IsValidType(context.sem_ir(), call_params,
  78. return_type_id);
  79. }
  80. auto MakeBuiltinFunction(Context& context, SemIR::LocId loc_id,
  81. SemIR::BuiltinFunctionKind builtin_kind,
  82. SemIR::NameScopeId name_scope_id,
  83. SemIR::NameId name_id,
  84. BuiltinFunctionSignature signature) -> SemIR::InstId {
  85. StartFunctionSignature(context);
  86. // Build and add a `[ref self: Self]` parameter if needed.
  87. auto implicit_param_patterns_id = SemIR::InstBlockId::None;
  88. auto self_param_id = SemIR::InstId::None;
  89. if (signature.self_type_id.has_value()) {
  90. context.full_pattern_stack().PushFullPattern(
  91. FullPatternStack::Kind::ImplicitParamList);
  92. BeginSubpattern(context);
  93. auto self_type_region_id = EndSubpatternAsExpr(
  94. context, context.types().GetInstId(signature.self_type_id));
  95. self_param_id = AddParamPattern(context, loc_id, SemIR::NameId::SelfValue,
  96. self_type_region_id, signature.self_type_id,
  97. signature.self_is_ref);
  98. implicit_param_patterns_id = context.inst_blocks().Add({self_param_id});
  99. context.full_pattern_stack().EndImplicitParamList();
  100. } else {
  101. context.full_pattern_stack().PushFullPattern(
  102. FullPatternStack::Kind::ExplicitParamList);
  103. }
  104. // Build and add any explicit parameters. We always use value parameters for
  105. // now.
  106. auto param_patterns_id = SemIR::InstBlockId::Empty;
  107. if (!signature.param_type_ids.empty()) {
  108. context.inst_block_stack().Push();
  109. for (auto param_type_id : signature.param_type_ids) {
  110. BeginSubpattern(context);
  111. auto param_type_region_id = EndSubpatternAsExpr(
  112. context, context.types().GetInstId(param_type_id));
  113. context.inst_block_stack().AddInstId(AddParamPattern(
  114. context, loc_id, SemIR::NameId::Underscore, param_type_region_id,
  115. param_type_id, /*is_ref=*/false));
  116. }
  117. param_patterns_id = context.inst_block_stack().Pop();
  118. }
  119. // Build and add the return type. We always use an initializing form for now.
  120. auto return_patterns_id = SemIR::InstBlockId::None;
  121. Context::FormExpr return_form = {.form_inst_id = SemIR::InstId::None,
  122. .type_component_id = SemIR::TypeInstId::None,
  123. .type_id = SemIR::TypeId::None};
  124. if (signature.return_type_id.has_value()) {
  125. return_form = ExprAsReturnForm(
  126. context, loc_id, context.types().GetInstId(signature.return_type_id));
  127. return_patterns_id = AddReturnPatterns(context, loc_id, return_form);
  128. }
  129. auto [call_param_patterns_id, call_params_id] =
  130. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  131. return_patterns_id);
  132. context.full_pattern_stack().PopFullPattern();
  133. auto [pattern_block_id, decl_block_id] = FinishFunctionSignature(context);
  134. // Add the function declaration.
  135. // TODO: This should probably handle generics.
  136. auto [decl_id, function_id] = MakeFunctionDecl(
  137. context, loc_id, decl_block_id, /*build_generic=*/false,
  138. /*is_definition=*/true,
  139. SemIR::Function{
  140. {
  141. .name_id = name_id,
  142. .parent_scope_id = name_scope_id,
  143. .generic_id = SemIR::GenericId::None,
  144. .first_param_node_id = Parse::NodeId::None,
  145. .last_param_node_id = Parse::NodeId::None,
  146. .pattern_block_id = pattern_block_id,
  147. .implicit_param_patterns_id = implicit_param_patterns_id,
  148. .param_patterns_id = param_patterns_id,
  149. .is_extern = false,
  150. .extern_library_id = SemIR::LibraryNameId::None,
  151. .non_owning_decl_id = SemIR::InstId::None,
  152. // Set by `MakeFunctionDecl`.
  153. .first_owning_decl_id = SemIR::InstId::None,
  154. },
  155. {
  156. .call_param_patterns_id = call_param_patterns_id,
  157. .call_params_id = call_params_id,
  158. .return_type_inst_id = return_form.type_component_id,
  159. .return_form_inst_id = return_form.form_inst_id,
  160. .return_patterns_id = return_patterns_id,
  161. .self_param_id = self_param_id,
  162. }});
  163. // Add the builtin to the imports block so that it appears in the formatted
  164. // IR.
  165. // TODO: Find a better way to handle this. Ideally we should stop using this
  166. // function entirely and declare builtins in the prelude.
  167. context.imports().push_back(decl_id);
  168. auto& function = context.functions().Get(function_id);
  169. CARBON_CHECK(IsValidBuiltinDeclaration(context, function, builtin_kind));
  170. function.SetBuiltinFunction(builtin_kind);
  171. return decl_id;
  172. }
  173. auto CheckFunctionReturnTypeMatches(Context& context,
  174. const SemIR::Function& new_function,
  175. const SemIR::Function& prev_function,
  176. SemIR::SpecificId prev_specific_id,
  177. bool diagnose) -> bool {
  178. // TODO: Pass a specific ID for `prev_function` instead of substitutions and
  179. // use it here.
  180. auto new_return_type_id =
  181. new_function.GetDeclaredReturnType(context.sem_ir());
  182. auto prev_return_type_id =
  183. prev_function.GetDeclaredReturnType(context.sem_ir(), prev_specific_id);
  184. if (new_return_type_id == SemIR::ErrorInst::TypeId ||
  185. prev_return_type_id == SemIR::ErrorInst::TypeId) {
  186. return false;
  187. }
  188. if (!context.types().AreEqualAcrossDeclarations(new_return_type_id,
  189. prev_return_type_id)) {
  190. if (!diagnose) {
  191. return false;
  192. }
  193. CARBON_DIAGNOSTIC(
  194. FunctionRedeclReturnTypeDiffers, Error,
  195. "function redeclaration differs because return type is {0}",
  196. SemIR::TypeId);
  197. CARBON_DIAGNOSTIC(
  198. FunctionRedeclReturnTypeDiffersNoReturn, Error,
  199. "function redeclaration differs because no return type is provided");
  200. auto diag =
  201. new_return_type_id.has_value()
  202. ? context.emitter().Build(new_function.latest_decl_id(),
  203. FunctionRedeclReturnTypeDiffers,
  204. new_return_type_id)
  205. : context.emitter().Build(new_function.latest_decl_id(),
  206. FunctionRedeclReturnTypeDiffersNoReturn);
  207. if (prev_return_type_id.has_value()) {
  208. CARBON_DIAGNOSTIC(FunctionRedeclReturnTypePrevious, Note,
  209. "previously declared with return type {0}",
  210. SemIR::TypeId);
  211. diag.Note(prev_function.latest_decl_id(),
  212. FunctionRedeclReturnTypePrevious, prev_return_type_id);
  213. } else {
  214. CARBON_DIAGNOSTIC(FunctionRedeclReturnTypePreviousNoReturn, Note,
  215. "previously declared with no return type");
  216. diag.Note(prev_function.latest_decl_id(),
  217. FunctionRedeclReturnTypePreviousNoReturn);
  218. }
  219. diag.Emit();
  220. return false;
  221. }
  222. return true;
  223. }
  224. auto CheckFunctionTypeMatches(Context& context,
  225. const SemIR::Function& new_function,
  226. const SemIR::Function& prev_function,
  227. SemIR::SpecificId prev_specific_id,
  228. bool check_syntax, bool check_self, bool diagnose)
  229. -> bool {
  230. if (!CheckRedeclParamsMatch(context, DeclParams(new_function),
  231. DeclParams(prev_function), prev_specific_id,
  232. diagnose, check_syntax, check_self)) {
  233. return false;
  234. }
  235. return CheckFunctionReturnTypeMatches(context, new_function, prev_function,
  236. prev_specific_id, diagnose);
  237. }
  238. auto CheckFunctionReturnPatternType(Context& context, SemIR::LocId loc_id,
  239. SemIR::InstId return_pattern_id,
  240. SemIR::SpecificId specific_id)
  241. -> SemIR::TypeId {
  242. auto arg_type_id = SemIR::ExtractScrutineeType(
  243. context.sem_ir(), SemIR::GetTypeOfInstInSpecific(
  244. context.sem_ir(), specific_id, return_pattern_id));
  245. auto init_repr = SemIR::InitRepr::ForType(context.sem_ir(), arg_type_id);
  246. if (!init_repr.is_valid()) {
  247. auto diagnose_incomplete_return_type = [&] {
  248. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  249. "function returns incomplete type {0}", SemIR::TypeId);
  250. return context.emitter().Build(loc_id, IncompleteTypeInFunctionReturnType,
  251. arg_type_id);
  252. };
  253. auto diagnose_abstract_return_type = [&] {
  254. CARBON_DIAGNOSTIC(AbstractTypeInFunctionReturnType, Error,
  255. "function returns abstract type {0}", SemIR::TypeId);
  256. return context.emitter().Build(loc_id, AbstractTypeInFunctionReturnType,
  257. arg_type_id);
  258. };
  259. // TODO: Consider suppressing the diagnostic if we've already diagnosed a
  260. // definition or call to this function.
  261. if (!RequireConcreteType(
  262. context, arg_type_id, SemIR::LocId(return_pattern_id),
  263. diagnose_incomplete_return_type, diagnose_abstract_return_type)) {
  264. return SemIR::ErrorInst::TypeId;
  265. }
  266. }
  267. return arg_type_id;
  268. }
  269. auto CheckFunctionDefinitionSignature(Context& context,
  270. SemIR::FunctionId function_id) -> void {
  271. auto& function = context.functions().Get(function_id);
  272. auto params_to_complete =
  273. context.inst_blocks().GetOrEmpty(function.call_params_id);
  274. // The return parameter will be diagnosed after and differently from other
  275. // parameters.
  276. auto return_call_param = SemIR::InstId::None;
  277. if (!params_to_complete.empty() && function.return_patterns_id.has_value()) {
  278. return_call_param = params_to_complete.consume_back();
  279. }
  280. // Check the parameter types are complete.
  281. for (auto param_ref_id : params_to_complete) {
  282. if (param_ref_id == SemIR::ErrorInst::InstId) {
  283. continue;
  284. }
  285. // The parameter types need to be complete.
  286. RequireCompleteType(
  287. context, context.insts().GetAs<SemIR::AnyParam>(param_ref_id).type_id,
  288. SemIR::LocId(param_ref_id), [&] {
  289. CARBON_DIAGNOSTIC(
  290. IncompleteTypeInFunctionParam, Error,
  291. "parameter has incomplete type {0} in function definition",
  292. TypeOfInstId);
  293. return context.emitter().Build(
  294. param_ref_id, IncompleteTypeInFunctionParam, param_ref_id);
  295. });
  296. }
  297. // Check the return type is complete.
  298. if (function.return_patterns_id.has_value()) {
  299. for (auto return_pattern_id :
  300. context.inst_blocks().Get(function.return_patterns_id)) {
  301. CheckFunctionReturnPatternType(context, SemIR::LocId(return_pattern_id),
  302. return_pattern_id,
  303. SemIR::SpecificId::None);
  304. }
  305. // `CheckFunctionReturnPatternType` should have diagnosed incomplete types,
  306. // so don't `RequireCompleteType` on the return type.
  307. if (return_call_param.has_value()) {
  308. TryToCompleteType(
  309. context,
  310. context.insts().GetAs<SemIR::AnyParam>(return_call_param).type_id,
  311. SemIR::LocId(return_call_param));
  312. }
  313. }
  314. }
  315. auto StartFunctionSignature(Context& context) -> void {
  316. context.scope_stack().PushForDeclName();
  317. context.inst_block_stack().Push();
  318. context.pattern_block_stack().Push();
  319. }
  320. auto FinishFunctionSignature(Context& context)
  321. -> FinishFunctionSignatureResult {
  322. auto pattern_block_id = context.pattern_block_stack().Pop();
  323. auto decl_block_id = context.inst_block_stack().Pop();
  324. context.scope_stack().Pop();
  325. return {.pattern_block_id = pattern_block_id, .decl_block_id = decl_block_id};
  326. }
  327. auto MakeFunctionDecl(Context& context, SemIR::LocId loc_id,
  328. SemIR::InstBlockId decl_block_id, bool build_generic,
  329. bool is_definition, SemIR::Function function)
  330. -> std::pair<SemIR::InstId, SemIR::FunctionId> {
  331. CARBON_CHECK(!function.first_owning_decl_id.has_value());
  332. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  333. SemIR::FunctionId::None, decl_block_id};
  334. auto decl_id = AddPlaceholderInstInNoBlock(
  335. context, SemIR::LocIdAndInst::UncheckedLoc(loc_id, function_decl));
  336. function.first_owning_decl_id = decl_id;
  337. if (is_definition) {
  338. function.definition_id = decl_id;
  339. }
  340. if (build_generic) {
  341. function.generic_id = BuildGenericDecl(context, decl_id);
  342. }
  343. // Create the `Function` object.
  344. function_decl.function_id = context.functions().Add(std::move(function));
  345. function_decl.type_id =
  346. GetFunctionType(context, function_decl.function_id,
  347. build_generic ? context.scope_stack().PeekSpecificId()
  348. : SemIR::SpecificId::None);
  349. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  350. return {decl_id, function_decl.function_id};
  351. }
  352. auto StartFunctionDefinition(Context& context, SemIR::InstId decl_id,
  353. SemIR::FunctionId function_id) -> void {
  354. // Create the function scope and the entry block.
  355. context.scope_stack().PushForFunctionBody(decl_id);
  356. context.inst_block_stack().Push();
  357. context.region_stack().PushRegion(context.inst_block_stack().PeekOrAdd());
  358. StartGenericDefinition(context,
  359. context.functions().Get(function_id).generic_id);
  360. CheckFunctionDefinitionSignature(context, function_id);
  361. }
  362. auto FinishFunctionDefinition(Context& context, SemIR::FunctionId function_id)
  363. -> void {
  364. context.inst_block_stack().Pop();
  365. context.scope_stack().Pop();
  366. auto& function = context.functions().Get(function_id);
  367. function.body_block_ids = context.region_stack().PopRegion();
  368. // If this is a generic function, collect information about the definition.
  369. FinishGenericDefinition(context, function.generic_id);
  370. }
  371. } // namespace Carbon::Check