function.cpp 20 KB

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