function.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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/sem_ir/builtin_function_kind.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/pattern.h"
  19. namespace Carbon::Check {
  20. auto FindSelfPattern(Context& context,
  21. SemIR::InstBlockId implicit_param_patterns_id)
  22. -> SemIR::InstId {
  23. auto implicit_param_patterns =
  24. context.inst_blocks().GetOrEmpty(implicit_param_patterns_id);
  25. return FindIfOrNone(implicit_param_patterns, [&](auto implicit_param_id) {
  26. return SemIR::IsSelfPattern(context.sem_ir(), implicit_param_id);
  27. });
  28. }
  29. auto AddReturnPatterns(Context& context, SemIR::LocId loc_id,
  30. Context::FormExpr form_expr) -> SemIR::InstBlockId {
  31. llvm::SmallVector<SemIR::InstId, 1> return_patterns;
  32. auto form_inst = context.insts().Get(form_expr.form_inst_id);
  33. CARBON_KIND_SWITCH(form_inst) {
  34. case SemIR::RefForm::Kind: {
  35. break;
  36. }
  37. case CARBON_KIND(SemIR::InitForm init_form): {
  38. auto pattern_type_id = GetPatternType(context, form_expr.type_id);
  39. auto return_slot_pattern_id = AddPatternInst<SemIR::ReturnSlotPattern>(
  40. context, loc_id,
  41. {.type_id = pattern_type_id,
  42. .type_inst_id = form_expr.type_component_id});
  43. return_patterns.push_back(AddPatternInst<SemIR::OutParamPattern>(
  44. context, SemIR::LocId(form_expr.form_inst_id),
  45. {.type_id = pattern_type_id,
  46. .subpattern_id = return_slot_pattern_id,
  47. .index = init_form.index}));
  48. break;
  49. }
  50. case SemIR::ErrorInst::Kind: {
  51. break;
  52. }
  53. default:
  54. CARBON_FATAL("unexpected inst kind: {0}", form_inst);
  55. }
  56. return context.inst_blocks().AddCanonical(return_patterns);
  57. }
  58. auto IsValidBuiltinDeclaration(Context& context,
  59. const SemIR::Function& function,
  60. SemIR::BuiltinFunctionKind builtin_kind)
  61. -> bool {
  62. if (!function.call_params_id.has_value()) {
  63. // For now, we have no builtins that support positional parameters.
  64. return false;
  65. }
  66. // Find the list of call parameters other than the implicit return slots.
  67. auto call_params = context.inst_blocks()
  68. .Get(function.call_params_id)
  69. .drop_back(context.inst_blocks()
  70. .GetOrEmpty(function.return_patterns_id)
  71. .size());
  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. auto MakeBuiltinFunction(Context& context, SemIR::LocId loc_id,
  81. SemIR::BuiltinFunctionKind builtin_kind,
  82. SemIR::NameScopeId name_scope_id,
  83. SemIR::NameId name_id,
  84. BuiltinFunctionSignature signature) -> SemIR::InstId {
  85. StartFunctionSignature(context);
  86. // Build and add a `[ref self: Self]` parameter if needed.
  87. auto implicit_param_patterns_id = SemIR::InstBlockId::None;
  88. auto self_param_id = SemIR::InstId::None;
  89. if (signature.self_type_id.has_value()) {
  90. context.full_pattern_stack().PushFullPattern(
  91. FullPatternStack::Kind::ImplicitParamList);
  92. BeginSubpattern(context);
  93. auto self_type_region_id = EndSubpatternAsExpr(
  94. context, context.types().GetTypeInstId(signature.self_type_id));
  95. self_param_id = AddParamPattern(context, loc_id, SemIR::NameId::SelfValue,
  96. self_type_region_id, signature.self_type_id,
  97. signature.self_is_ref);
  98. implicit_param_patterns_id = context.inst_blocks().Add({self_param_id});
  99. context.full_pattern_stack().EndImplicitParamList();
  100. } else {
  101. context.full_pattern_stack().PushFullPattern(
  102. FullPatternStack::Kind::ExplicitParamList);
  103. }
  104. // Build and add any explicit parameters. We always use value parameters for
  105. // now.
  106. auto param_patterns_id = SemIR::InstBlockId::Empty;
  107. if (!signature.param_type_ids.empty()) {
  108. context.inst_block_stack().Push();
  109. for (auto param_type_id : signature.param_type_ids) {
  110. BeginSubpattern(context);
  111. auto param_type_region_id = EndSubpatternAsExpr(
  112. context, context.types().GetTypeInstId(param_type_id));
  113. context.inst_block_stack().AddInstId(AddParamPattern(
  114. context, loc_id, SemIR::NameId::Underscore, param_type_region_id,
  115. param_type_id, /*is_ref=*/false));
  116. }
  117. param_patterns_id = context.inst_block_stack().Pop();
  118. }
  119. // Build and add the return type. We always use an initializing form for now.
  120. auto return_patterns_id = SemIR::InstBlockId::None;
  121. Context::FormExpr return_form = {.form_inst_id = SemIR::InstId::None,
  122. .type_component_id = SemIR::TypeInstId::None,
  123. .type_id = SemIR::TypeId::None};
  124. if (signature.return_type_id.has_value()) {
  125. return_form = ExprAsReturnForm(
  126. context, loc_id,
  127. context.types().GetTypeInstId(signature.return_type_id));
  128. return_patterns_id = AddReturnPatterns(context, loc_id, return_form);
  129. }
  130. auto [call_param_patterns_id, call_params_id] =
  131. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  132. return_patterns_id);
  133. context.full_pattern_stack().PopFullPattern();
  134. auto [pattern_block_id, decl_block_id] = FinishFunctionSignature(context);
  135. // Add the function declaration.
  136. // TODO: This should probably handle generics.
  137. auto [decl_id, function_id] = MakeFunctionDecl(
  138. context, loc_id, decl_block_id, /*build_generic=*/false,
  139. /*is_definition=*/true,
  140. SemIR::Function{
  141. {
  142. .name_id = name_id,
  143. .parent_scope_id = name_scope_id,
  144. .generic_id = SemIR::GenericId::None,
  145. .first_param_node_id = Parse::NodeId::None,
  146. .last_param_node_id = Parse::NodeId::None,
  147. .pattern_block_id = pattern_block_id,
  148. .implicit_param_patterns_id = implicit_param_patterns_id,
  149. .param_patterns_id = param_patterns_id,
  150. .is_extern = false,
  151. .extern_library_id = SemIR::LibraryNameId::None,
  152. .non_owning_decl_id = SemIR::InstId::None,
  153. // Set by `MakeFunctionDecl`.
  154. .first_owning_decl_id = SemIR::InstId::None,
  155. },
  156. {
  157. .call_param_patterns_id = call_param_patterns_id,
  158. .call_params_id = call_params_id,
  159. .return_type_inst_id = return_form.type_component_id,
  160. .return_form_inst_id = return_form.form_inst_id,
  161. .return_patterns_id = return_patterns_id,
  162. .self_param_id = self_param_id,
  163. }});
  164. // Add the builtin to the imports block so that it appears in the formatted
  165. // IR.
  166. // TODO: Find a better way to handle this. Ideally we should stop using this
  167. // function entirely and declare builtins in the prelude.
  168. context.imports().push_back(decl_id);
  169. auto& function = context.functions().Get(function_id);
  170. CARBON_CHECK(IsValidBuiltinDeclaration(context, function, builtin_kind));
  171. function.SetBuiltinFunction(builtin_kind);
  172. return decl_id;
  173. }
  174. auto CheckFunctionReturnTypeMatches(Context& context,
  175. const SemIR::Function& new_function,
  176. const SemIR::Function& prev_function,
  177. SemIR::SpecificId prev_specific_id,
  178. bool diagnose) -> bool {
  179. // TODO: Pass a specific ID for `prev_function` instead of substitutions and
  180. // use it here.
  181. auto new_return_type_id =
  182. new_function.GetDeclaredReturnType(context.sem_ir());
  183. auto prev_return_type_id =
  184. prev_function.GetDeclaredReturnType(context.sem_ir(), prev_specific_id);
  185. if (new_return_type_id == SemIR::ErrorInst::TypeId ||
  186. prev_return_type_id == SemIR::ErrorInst::TypeId) {
  187. return false;
  188. }
  189. if (!context.types().AreEqualAcrossDeclarations(new_return_type_id,
  190. prev_return_type_id)) {
  191. if (!diagnose) {
  192. return false;
  193. }
  194. CARBON_DIAGNOSTIC(
  195. FunctionRedeclReturnTypeDiffers, Error,
  196. "function redeclaration differs because return type is {0}",
  197. SemIR::TypeId);
  198. CARBON_DIAGNOSTIC(
  199. FunctionRedeclReturnTypeDiffersNoReturn, Error,
  200. "function redeclaration differs because no return type is provided");
  201. auto diag =
  202. new_return_type_id.has_value()
  203. ? context.emitter().Build(new_function.latest_decl_id(),
  204. FunctionRedeclReturnTypeDiffers,
  205. new_return_type_id)
  206. : context.emitter().Build(new_function.latest_decl_id(),
  207. FunctionRedeclReturnTypeDiffersNoReturn);
  208. if (prev_return_type_id.has_value()) {
  209. CARBON_DIAGNOSTIC(FunctionRedeclReturnTypePrevious, Note,
  210. "previously declared with return type {0}",
  211. SemIR::TypeId);
  212. diag.Note(prev_function.latest_decl_id(),
  213. FunctionRedeclReturnTypePrevious, prev_return_type_id);
  214. } else {
  215. CARBON_DIAGNOSTIC(FunctionRedeclReturnTypePreviousNoReturn, Note,
  216. "previously declared with no return type");
  217. diag.Note(prev_function.latest_decl_id(),
  218. FunctionRedeclReturnTypePreviousNoReturn);
  219. }
  220. diag.Emit();
  221. return false;
  222. }
  223. return true;
  224. }
  225. auto CheckFunctionTypeMatches(Context& context,
  226. const SemIR::Function& new_function,
  227. const SemIR::Function& prev_function,
  228. SemIR::SpecificId prev_specific_id,
  229. bool check_syntax, bool check_self, bool diagnose)
  230. -> bool {
  231. if (!CheckRedeclParamsMatch(context, DeclParams(new_function),
  232. DeclParams(prev_function), prev_specific_id,
  233. diagnose, check_syntax, check_self)) {
  234. return false;
  235. }
  236. return CheckFunctionReturnTypeMatches(context, new_function, prev_function,
  237. prev_specific_id, diagnose);
  238. }
  239. auto CheckFunctionReturnPatternType(Context& context, SemIR::LocId loc_id,
  240. SemIR::InstId return_pattern_id,
  241. SemIR::SpecificId specific_id)
  242. -> SemIR::TypeId {
  243. auto arg_type_id = SemIR::ExtractScrutineeType(
  244. context.sem_ir(), SemIR::GetTypeOfInstInSpecific(
  245. context.sem_ir(), specific_id, return_pattern_id));
  246. auto init_repr = SemIR::InitRepr::ForType(context.sem_ir(), arg_type_id);
  247. if (!init_repr.is_valid()) {
  248. auto diagnose_incomplete_return_type = [&] {
  249. CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error,
  250. "function returns incomplete type {0}", SemIR::TypeId);
  251. return context.emitter().Build(loc_id, IncompleteTypeInFunctionReturnType,
  252. arg_type_id);
  253. };
  254. auto diagnose_abstract_return_type = [&] {
  255. CARBON_DIAGNOSTIC(AbstractTypeInFunctionReturnType, Error,
  256. "function returns abstract type {0}", SemIR::TypeId);
  257. return context.emitter().Build(loc_id, AbstractTypeInFunctionReturnType,
  258. arg_type_id);
  259. };
  260. // TODO: Consider suppressing the diagnostic if we've already diagnosed a
  261. // definition or call to this function.
  262. if (!RequireConcreteType(
  263. context, arg_type_id, SemIR::LocId(return_pattern_id),
  264. diagnose_incomplete_return_type, diagnose_abstract_return_type)) {
  265. return SemIR::ErrorInst::TypeId;
  266. }
  267. }
  268. return arg_type_id;
  269. }
  270. auto CheckFunctionDefinitionSignature(Context& context,
  271. SemIR::FunctionId function_id) -> void {
  272. auto& function = context.functions().Get(function_id);
  273. auto params_to_complete =
  274. context.inst_blocks().GetOrEmpty(function.call_params_id);
  275. // The return parameter will be diagnosed after and differently from other
  276. // parameters.
  277. auto return_call_param = SemIR::InstId::None;
  278. if (!params_to_complete.empty() && function.return_patterns_id.has_value()) {
  279. return_call_param = params_to_complete.consume_back();
  280. }
  281. // Check the parameter types are complete.
  282. for (auto param_ref_id : params_to_complete) {
  283. if (param_ref_id == SemIR::ErrorInst::InstId) {
  284. continue;
  285. }
  286. // The parameter types need to be complete.
  287. RequireCompleteType(
  288. context, context.insts().GetAs<SemIR::AnyParam>(param_ref_id).type_id,
  289. SemIR::LocId(param_ref_id), [&] {
  290. CARBON_DIAGNOSTIC(
  291. IncompleteTypeInFunctionParam, Error,
  292. "parameter has incomplete type {0} in function definition",
  293. TypeOfInstId);
  294. return context.emitter().Build(
  295. param_ref_id, IncompleteTypeInFunctionParam, param_ref_id);
  296. });
  297. }
  298. // Check the return type is complete.
  299. if (function.return_patterns_id.has_value()) {
  300. for (auto return_pattern_id :
  301. context.inst_blocks().Get(function.return_patterns_id)) {
  302. CheckFunctionReturnPatternType(context, SemIR::LocId(return_pattern_id),
  303. return_pattern_id,
  304. SemIR::SpecificId::None);
  305. }
  306. // `CheckFunctionReturnPatternType` should have diagnosed incomplete types,
  307. // so don't `RequireCompleteType` on the return type.
  308. if (return_call_param.has_value()) {
  309. TryToCompleteType(
  310. context,
  311. context.insts().GetAs<SemIR::AnyParam>(return_call_param).type_id,
  312. SemIR::LocId(return_call_param));
  313. }
  314. }
  315. }
  316. auto StartFunctionSignature(Context& context) -> void {
  317. context.scope_stack().PushForDeclName();
  318. context.inst_block_stack().Push();
  319. context.pattern_block_stack().Push();
  320. }
  321. auto FinishFunctionSignature(Context& context)
  322. -> FinishFunctionSignatureResult {
  323. auto pattern_block_id = context.pattern_block_stack().Pop();
  324. auto decl_block_id = context.inst_block_stack().Pop();
  325. context.scope_stack().Pop();
  326. return {.pattern_block_id = pattern_block_id, .decl_block_id = decl_block_id};
  327. }
  328. auto MakeFunctionDecl(Context& context, SemIR::LocId loc_id,
  329. SemIR::InstBlockId decl_block_id, bool build_generic,
  330. bool is_definition, SemIR::Function function)
  331. -> std::pair<SemIR::InstId, SemIR::FunctionId> {
  332. CARBON_CHECK(!function.first_owning_decl_id.has_value());
  333. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  334. SemIR::FunctionId::None, decl_block_id};
  335. auto decl_id = AddPlaceholderInstInNoBlock(
  336. context, SemIR::LocIdAndInst::UncheckedLoc(loc_id, function_decl));
  337. function.first_owning_decl_id = decl_id;
  338. if (is_definition) {
  339. function.definition_id = decl_id;
  340. }
  341. if (build_generic) {
  342. function.generic_id = BuildGenericDecl(context, decl_id);
  343. }
  344. // Create the `Function` object.
  345. function_decl.function_id = context.functions().Add(std::move(function));
  346. function_decl.type_id =
  347. GetFunctionType(context, function_decl.function_id,
  348. build_generic ? context.scope_stack().PeekSpecificId()
  349. : SemIR::SpecificId::None);
  350. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  351. return {decl_id, function_decl.function_id};
  352. }
  353. auto StartFunctionDefinition(Context& context, SemIR::InstId decl_id,
  354. SemIR::FunctionId function_id) -> void {
  355. // Create the function scope and the entry block.
  356. context.scope_stack().PushForFunctionBody(decl_id);
  357. context.inst_block_stack().Push();
  358. context.region_stack().PushRegion(context.inst_block_stack().PeekOrAdd());
  359. StartGenericDefinition(context,
  360. context.functions().Get(function_id).generic_id);
  361. CheckFunctionDefinitionSignature(context, function_id);
  362. }
  363. auto FinishFunctionDefinition(Context& context, SemIR::FunctionId function_id)
  364. -> void {
  365. context.inst_block_stack().Pop();
  366. context.scope_stack().Pop();
  367. auto& function = context.functions().Get(function_id);
  368. function.body_block_ids = context.region_stack().PopRegion();
  369. // If this is a generic function, collect information about the definition.
  370. FinishGenericDefinition(context, function.generic_id);
  371. }
  372. } // namespace Carbon::Check