function.cpp 19 KB

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