function.cpp 20 KB

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