function.cpp 20 KB

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