function.cpp 20 KB

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