handle_binding_pattern.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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/context.h"
  5. #include "toolchain/check/convert.h"
  6. #include "toolchain/check/facet_type.h"
  7. #include "toolchain/check/handle.h"
  8. #include "toolchain/check/inst.h"
  9. #include "toolchain/check/interface.h"
  10. #include "toolchain/check/name_lookup.h"
  11. #include "toolchain/check/pattern.h"
  12. #include "toolchain/check/return.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/check/type_completion.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. #include "toolchain/parse/node_ids.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/pattern.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::Check {
  22. auto HandleParseNode(Context& context, Parse::UnderscoreNameId node_id)
  23. -> bool {
  24. context.node_stack().Push(node_id, SemIR::NameId::Underscore);
  25. return true;
  26. }
  27. // Returns the `InstKind` corresponding to the pattern's `NodeKind`.
  28. static auto GetPatternInstKind(Parse::NodeKind node_kind, bool is_ref)
  29. -> SemIR::InstKind {
  30. switch (node_kind) {
  31. case Parse::NodeKind::CompileTimeBindingPattern:
  32. return SemIR::InstKind::SymbolicBindingPattern;
  33. case Parse::NodeKind::LetBindingPattern:
  34. return is_ref ? SemIR::InstKind::RefBindingPattern
  35. : SemIR::InstKind::ValueBindingPattern;
  36. case Parse::NodeKind::VarBindingPattern:
  37. return SemIR::InstKind::RefBindingPattern;
  38. default:
  39. CARBON_FATAL("Unexpected node kind: {0}", node_kind);
  40. }
  41. }
  42. // Returns true if a parameter is valid in the given `introducer_kind`.
  43. static auto IsValidParamForIntroducer(Context& context, Parse::NodeId node_id,
  44. SemIR::NameId name_id,
  45. Lex::TokenKind introducer_kind,
  46. bool is_generic) -> bool {
  47. switch (introducer_kind) {
  48. case Lex::TokenKind::Fn: {
  49. if (context.full_pattern_stack().CurrentKind() ==
  50. FullPatternStack::Kind::ImplicitParamList &&
  51. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  52. CARBON_DIAGNOSTIC(
  53. ImplictParamMustBeConstant, Error,
  54. "implicit parameters of functions must be constant or `self`");
  55. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  56. return false;
  57. }
  58. // Parameters can have incomplete types in a function declaration, but not
  59. // in a function definition. We don't know which kind we have here, so
  60. // don't validate it.
  61. return true;
  62. }
  63. case Lex::TokenKind::Choice:
  64. if (context.scope_stack().PeekInstId().has_value()) {
  65. // We are building a pattern for a choice alternative, not the
  66. // choice type itself.
  67. // Implicit param lists are prevented during parse.
  68. CARBON_CHECK(context.full_pattern_stack().CurrentKind() !=
  69. FullPatternStack::Kind::ImplicitParamList,
  70. "choice alternative with implicit parameters");
  71. // Don't fall through to the `Class` logic for choice alternatives.
  72. return true;
  73. }
  74. [[fallthrough]];
  75. case Lex::TokenKind::Class:
  76. case Lex::TokenKind::Impl:
  77. case Lex::TokenKind::Interface: {
  78. if (name_id == SemIR::NameId::SelfValue) {
  79. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  80. "`self` parameter only allowed on functions");
  81. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  82. return false;
  83. }
  84. if (!is_generic) {
  85. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  86. "parameters of generic types must be constant");
  87. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  88. return false;
  89. }
  90. return true;
  91. }
  92. default:
  93. return true;
  94. }
  95. }
  96. // TODO: make this function shorter by factoring pieces out.
  97. static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  98. Parse::NodeKind node_kind) -> bool {
  99. // TODO: split this into smaller, more focused functions.
  100. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  101. auto [cast_type_inst_id, cast_type_id] =
  102. ExprAsType(context, type_node, parsed_type_id);
  103. SemIR::ExprRegionId type_expr_region_id =
  104. EndSubpatternAsExpr(context, cast_type_inst_id);
  105. // The name in a generic binding may be wrapped in `template`.
  106. bool is_generic = node_kind == Parse::NodeKind::CompileTimeBindingPattern;
  107. bool is_template =
  108. context.node_stack()
  109. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::TemplateBindingName>();
  110. // A non-generic template binding is diagnosed by the parser.
  111. is_template &= is_generic;
  112. // The name in a runtime binding may be wrapped in `ref`.
  113. bool is_ref =
  114. context.node_stack()
  115. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::RefBindingName>();
  116. SemIR::InstKind pattern_inst_kind = GetPatternInstKind(node_kind, is_ref);
  117. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  118. const DeclIntroducerState& introducer =
  119. context.decl_introducer_state_stack().innermost();
  120. auto make_binding_pattern = [&]() -> SemIR::InstId {
  121. // TODO: Eventually the name will need to support associations with other
  122. // scopes, but right now we don't support qualified names here.
  123. auto binding =
  124. AddBindingPattern(context, name_node, name_id, cast_type_id,
  125. type_expr_region_id, pattern_inst_kind, is_template);
  126. // TODO: If `is_generic`, then `binding.bind_id is a SymbolicBinding. Subst
  127. // the `.Self` of type `type` in the `cast_type_id` type (a `FacetType`)
  128. // with the `binding.bind_id` itself, and build a new pattern with that.
  129. // This is kind of cyclical. So we need to reuse the EntityNameId, which
  130. // will also reuse the CompileTimeBinding for the new SymbolicBinding.
  131. if (name_id != SemIR::NameId::Underscore) {
  132. // Add name to lookup immediately, so it can be used in the rest of the
  133. // enclosing pattern.
  134. auto name_context =
  135. context.decl_name_stack().MakeUnqualifiedName(name_node, name_id);
  136. context.decl_name_stack().AddNameOrDiagnose(
  137. name_context, binding.bind_id,
  138. introducer.modifier_set.GetAccessKind());
  139. context.full_pattern_stack().AddBindName(name_id);
  140. }
  141. return binding.pattern_id;
  142. };
  143. auto abstract_diagnoser = [&] {
  144. CARBON_DIAGNOSTIC(AbstractTypeInVarPattern, Error,
  145. "binding pattern has abstract type {0} in `var` "
  146. "pattern",
  147. SemIR::TypeId);
  148. return context.emitter().Build(type_node, AbstractTypeInVarPattern,
  149. cast_type_id);
  150. };
  151. // A `self` binding can only appear in an implicit parameter list.
  152. if (name_id == SemIR::NameId::SelfValue &&
  153. !context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
  154. CARBON_DIAGNOSTIC(
  155. SelfOutsideImplicitParamList, Error,
  156. "`self` can only be declared in an implicit parameter list");
  157. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  158. }
  159. if (node_kind == Parse::NodeKind::CompileTimeBindingPattern &&
  160. introducer.kind == Lex::TokenKind::Let) {
  161. // TODO: We should re-evaluate the contents of the eval block in a
  162. // synthesized specific to form these values, in order to propagate the
  163. // values.
  164. return context.TODO(node_id,
  165. "local `let :!` bindings are currently unsupported");
  166. }
  167. // Allocate an instruction of the appropriate kind, linked to the name for
  168. // error locations.
  169. switch (context.full_pattern_stack().CurrentKind()) {
  170. case FullPatternStack::Kind::ImplicitParamList:
  171. case FullPatternStack::Kind::ExplicitParamList: {
  172. if (!IsValidParamForIntroducer(context, node_id, name_id, introducer.kind,
  173. is_generic)) {
  174. if (name_id != SemIR::NameId::Underscore) {
  175. AddNameToLookup(context, name_id, SemIR::ErrorInst::InstId);
  176. }
  177. // Replace the parameter with `ErrorInst` so that we don't try
  178. // constructing a generic based on it.
  179. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  180. break;
  181. }
  182. // Using `AsConcreteType` here causes `fn F[var self: Self]();`
  183. // to fail since `Self` is an incomplete type.
  184. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  185. auto [unqualified_type_id, qualifiers] =
  186. context.types().GetUnqualifiedTypeAndQualifiers(cast_type_id);
  187. if ((qualifiers & SemIR::TypeQualifiers::Partial) !=
  188. SemIR::TypeQualifiers::Partial &&
  189. context.types().Is<SemIR::ClassType>(unqualified_type_id)) {
  190. auto class_type =
  191. context.types().GetAs<SemIR::ClassType>(unqualified_type_id);
  192. auto& class_info = context.classes().Get(class_type.class_id);
  193. if (class_info.inheritance_kind ==
  194. SemIR::Class::InheritanceKind::Abstract) {
  195. auto builder = abstract_diagnoser();
  196. auto direct_use = true;
  197. NoteAbstractClass(context, class_type.class_id, direct_use,
  198. builder);
  199. builder.Emit();
  200. cast_type_id = SemIR::ErrorInst::TypeId;
  201. }
  202. }
  203. }
  204. auto result_inst_id = make_binding_pattern();
  205. // A binding pattern in a function signature is a `Call` parameter
  206. // unless it's nested inside a `var` pattern (because then the
  207. // enclosing `var` pattern is), or it's a compile-time binding pattern
  208. // (because then it's not passed to the `Call` inst).
  209. if (node_kind == Parse::NodeKind::LetBindingPattern) {
  210. auto type_id = context.insts().GetAttachedType(result_inst_id);
  211. if (is_ref) {
  212. result_inst_id = AddPatternInst<SemIR::RefParamPattern>(
  213. context, node_id,
  214. {.type_id = type_id,
  215. .subpattern_id = result_inst_id,
  216. .index = context.full_pattern_stack().NextCallParamIndex()});
  217. } else {
  218. result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
  219. context, node_id,
  220. {.type_id = type_id,
  221. .subpattern_id = result_inst_id,
  222. .index = context.full_pattern_stack().NextCallParamIndex()});
  223. }
  224. }
  225. context.node_stack().Push(node_id, result_inst_id);
  226. break;
  227. }
  228. case FullPatternStack::Kind::NameBindingDecl: {
  229. auto incomplete_diagnoser = [&] {
  230. CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Error,
  231. "binding pattern has incomplete type {0} in name "
  232. "binding declaration",
  233. InstIdAsType);
  234. return context.emitter().Build(type_node, IncompleteTypeInBindingDecl,
  235. cast_type_inst_id);
  236. };
  237. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  238. cast_type_id = AsConcreteType(context, cast_type_id, type_node,
  239. incomplete_diagnoser, abstract_diagnoser);
  240. } else {
  241. cast_type_id = AsCompleteType(context, cast_type_id, type_node,
  242. incomplete_diagnoser);
  243. }
  244. auto binding_pattern_id = make_binding_pattern();
  245. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  246. CARBON_CHECK(!is_generic);
  247. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  248. // TODO: Should we check this for the `var` as a whole, rather than
  249. // for the name binding?
  250. auto bind_id = context.bind_name_map()
  251. .Lookup(binding_pattern_id)
  252. .value()
  253. .bind_name_id;
  254. RegisterReturnedVar(context,
  255. introducer.modifier_node_id(ModifierOrder::Decl),
  256. type_node, cast_type_id, bind_id);
  257. }
  258. }
  259. context.node_stack().Push(node_id, binding_pattern_id);
  260. break;
  261. }
  262. }
  263. return true;
  264. }
  265. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  266. -> bool {
  267. return HandleAnyBindingPattern(context, node_id,
  268. Parse::NodeKind::LetBindingPattern);
  269. }
  270. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  271. -> bool {
  272. return HandleAnyBindingPattern(context, node_id,
  273. Parse::NodeKind::VarBindingPattern);
  274. }
  275. auto HandleParseNode(Context& context,
  276. Parse::CompileTimeBindingPatternStartId /*node_id*/)
  277. -> bool {
  278. // Make a scope to contain the `.Self` facet value for use in the type of the
  279. // compile time binding. This is popped when handling the
  280. // CompileTimeBindingPatternId.
  281. context.scope_stack().PushForSameRegion();
  282. // The `.Self` must have a type of `FacetType`, so that it gets wrapped in
  283. // `FacetAccessType` when used in a type position, such as in `U:! I(.Self)`.
  284. // This allows substitution with other facet values without requiring an
  285. // additional `FacetAccessType` to be inserted.
  286. auto type_id = GetEmptyFacetType(context);
  287. MakePeriodSelfFacetValue(context, type_id);
  288. return true;
  289. }
  290. auto HandleParseNode(Context& context,
  291. Parse::CompileTimeBindingPatternId node_id) -> bool {
  292. // Pop the `.Self` facet value name introduced by the
  293. // CompileTimeBindingPatternStart.
  294. context.scope_stack().Pop();
  295. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  296. const DeclIntroducerState& introducer =
  297. context.decl_introducer_state_stack().innermost();
  298. if (introducer.kind == Lex::TokenKind::Let) {
  299. // Disallow `let` outside of function and interface definitions.
  300. // TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
  301. // can represent a block scope, but is also used for other kinds of scopes
  302. // that aren't necessarily part of a function decl.
  303. // We don't need to check if the scope is an interface here as this is
  304. // already caught in the parse phase by the separated associated constant
  305. // logic.
  306. auto scope_inst_id = context.scope_stack().PeekInstId();
  307. if (scope_inst_id.has_value()) {
  308. auto scope_inst = context.insts().Get(scope_inst_id);
  309. if (!scope_inst.Is<SemIR::FunctionDecl>()) {
  310. context.TODO(
  311. node_id,
  312. "`let` compile time binding outside function or interface");
  313. node_kind = Parse::NodeKind::LetBindingPattern;
  314. }
  315. }
  316. }
  317. return HandleAnyBindingPattern(context, node_id, node_kind);
  318. }
  319. auto HandleParseNode(Context& context,
  320. Parse::AssociatedConstantNameAndTypeId node_id) -> bool {
  321. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  322. auto [cast_type_inst_id, cast_type_id] =
  323. ExprAsType(context, type_node, parsed_type_id);
  324. EndSubpatternAsExpr(context, cast_type_inst_id);
  325. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  326. if (name_id == SemIR::NameId::Underscore) {
  327. // The action item here may be to document this as not allowed, and
  328. // add a proper diagnostic.
  329. context.TODO(node_id, "_ used as associated constant name");
  330. }
  331. SemIR::AssociatedConstantDecl assoc_const_decl = {
  332. .type_id = cast_type_id,
  333. .assoc_const_id = SemIR::AssociatedConstantId::None,
  334. .decl_block_id = SemIR::InstBlockId::None};
  335. auto decl_id =
  336. AddPlaceholderInstInNoBlock(context, node_id, assoc_const_decl);
  337. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  338. {.name_id = name_id,
  339. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  340. .decl_id = decl_id,
  341. .generic_id = SemIR::GenericId::None,
  342. .default_value_id = SemIR::InstId::None});
  343. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  344. context.node_stack().Push(node_id, decl_id);
  345. return true;
  346. }
  347. auto HandleParseNode(Context& context, Parse::FieldNameAndTypeId node_id)
  348. -> bool {
  349. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  350. auto [cast_type_inst_id, cast_type_id] =
  351. ExprAsType(context, type_node, parsed_type_id);
  352. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  353. auto parent_class_decl =
  354. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  355. CARBON_CHECK(parent_class_decl);
  356. cast_type_id = AsConcreteType(
  357. context, cast_type_id, type_node,
  358. [&] {
  359. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  360. "field has incomplete type {0}", SemIR::TypeId);
  361. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  362. cast_type_id);
  363. },
  364. [&] {
  365. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  366. "field has abstract type {0}", SemIR::TypeId);
  367. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  368. cast_type_id);
  369. });
  370. if (cast_type_id == SemIR::ErrorInst::TypeId) {
  371. cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
  372. }
  373. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  374. auto field_type_id = GetUnboundElementType(
  375. context, context.types().GetInstId(class_info.self_type_id),
  376. cast_type_inst_id);
  377. auto field_id =
  378. AddInst<SemIR::FieldDecl>(context, node_id,
  379. {.type_id = field_type_id,
  380. .name_id = name_id,
  381. .index = SemIR::ElementIndex::None});
  382. context.field_decls_stack().AppendToTop(field_id);
  383. auto name_context =
  384. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  385. context.decl_name_stack().AddNameOrDiagnose(
  386. name_context, field_id,
  387. context.decl_introducer_state_stack()
  388. .innermost()
  389. .modifier_set.GetAccessKind());
  390. return true;
  391. }
  392. auto HandleParseNode(Context& context, Parse::RefBindingNameId node_id)
  393. -> bool {
  394. context.node_stack().Push(node_id);
  395. return true;
  396. }
  397. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  398. -> bool {
  399. context.node_stack().Push(node_id);
  400. return true;
  401. }
  402. auto HandleParseNode(Context& context, Parse::UnusedPatternId node_id) -> bool {
  403. return context.TODO(node_id, "unused");
  404. }
  405. } // namespace Carbon::Check