function.cpp 20 KB

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