handle_binding_pattern.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. // A `self` binding can only appear in an implicit parameter list.
  144. if (name_id == SemIR::NameId::SelfValue &&
  145. !context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
  146. CARBON_DIAGNOSTIC(
  147. SelfOutsideImplicitParamList, Error,
  148. "`self` can only be declared in an implicit parameter list");
  149. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  150. }
  151. if (node_kind == Parse::NodeKind::CompileTimeBindingPattern &&
  152. introducer.kind == Lex::TokenKind::Let) {
  153. // TODO: We should re-evaluate the contents of the eval block in a
  154. // synthesized specific to form these values, in order to propagate the
  155. // values.
  156. return context.TODO(node_id,
  157. "local `let :!` bindings are currently unsupported");
  158. }
  159. // Allocate an instruction of the appropriate kind, linked to the name for
  160. // error locations.
  161. switch (context.full_pattern_stack().CurrentKind()) {
  162. case FullPatternStack::Kind::ImplicitParamList:
  163. case FullPatternStack::Kind::ExplicitParamList: {
  164. if (!IsValidParamForIntroducer(context, node_id, name_id, introducer.kind,
  165. is_generic)) {
  166. if (name_id != SemIR::NameId::Underscore) {
  167. AddNameToLookup(context, name_id, SemIR::ErrorInst::InstId);
  168. }
  169. // Replace the parameter with `ErrorInst` so that we don't try
  170. // constructing a generic based on it.
  171. context.node_stack().Push(node_id, SemIR::ErrorInst::InstId);
  172. break;
  173. }
  174. auto result_inst_id = make_binding_pattern();
  175. // A binding pattern in a function signature is a `Call` parameter
  176. // unless it's nested inside a `var` pattern (because then the
  177. // enclosing `var` pattern is), or it's a compile-time binding pattern
  178. // (because then it's not passed to the `Call` inst).
  179. if (node_kind == Parse::NodeKind::LetBindingPattern) {
  180. auto type_id = context.insts().GetAttachedType(result_inst_id);
  181. if (is_ref) {
  182. result_inst_id = AddPatternInst<SemIR::RefParamPattern>(
  183. context, node_id,
  184. {.type_id = type_id,
  185. .subpattern_id = result_inst_id,
  186. .index = SemIR::CallParamIndex::None});
  187. } else {
  188. result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
  189. context, node_id,
  190. {.type_id = type_id,
  191. .subpattern_id = result_inst_id,
  192. .index = SemIR::CallParamIndex::None});
  193. }
  194. }
  195. context.node_stack().Push(node_id, result_inst_id);
  196. break;
  197. }
  198. case FullPatternStack::Kind::NameBindingDecl: {
  199. auto incomplete_diagnoser = [&] {
  200. CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Error,
  201. "binding pattern has incomplete type {0} in name "
  202. "binding declaration",
  203. InstIdAsType);
  204. return context.emitter().Build(type_node, IncompleteTypeInBindingDecl,
  205. cast_type_inst_id);
  206. };
  207. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  208. cast_type_id = AsConcreteType(
  209. context, cast_type_id, type_node, incomplete_diagnoser, [&] {
  210. CARBON_DIAGNOSTIC(
  211. AbstractTypeInVarPattern, Error,
  212. "binding pattern has abstract type {0} in `var` "
  213. "pattern",
  214. SemIR::TypeId);
  215. return context.emitter().Build(
  216. type_node, AbstractTypeInVarPattern, cast_type_id);
  217. });
  218. } else {
  219. cast_type_id = AsCompleteType(context, cast_type_id, type_node,
  220. incomplete_diagnoser);
  221. }
  222. auto binding_pattern_id = make_binding_pattern();
  223. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  224. CARBON_CHECK(!is_generic);
  225. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  226. // TODO: Should we check this for the `var` as a whole, rather than
  227. // for the name binding?
  228. auto bind_id = context.bind_name_map()
  229. .Lookup(binding_pattern_id)
  230. .value()
  231. .bind_name_id;
  232. RegisterReturnedVar(context,
  233. introducer.modifier_node_id(ModifierOrder::Decl),
  234. type_node, cast_type_id, bind_id);
  235. }
  236. }
  237. context.node_stack().Push(node_id, binding_pattern_id);
  238. break;
  239. }
  240. }
  241. return true;
  242. }
  243. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  244. -> bool {
  245. return HandleAnyBindingPattern(context, node_id,
  246. Parse::NodeKind::LetBindingPattern);
  247. }
  248. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  249. -> bool {
  250. return HandleAnyBindingPattern(context, node_id,
  251. Parse::NodeKind::VarBindingPattern);
  252. }
  253. auto HandleParseNode(Context& context,
  254. Parse::CompileTimeBindingPatternStartId node_id) -> bool {
  255. // Make a scope to contain the `.Self` facet value for use in the type of the
  256. // compile time binding. This is popped when handling the
  257. // CompileTimeBindingPatternId.
  258. context.scope_stack().PushForSameRegion();
  259. // The `.Self` must have a type of `FacetType`, so that it gets wrapped in
  260. // `FacetAccessType` when used in a type position, such as in `U:! I(.Self)`.
  261. // This allows substitution with other facet values without requiring an
  262. // additional `FacetAccessType` to be inserted.
  263. SemIR::FacetTypeId facet_type_id =
  264. context.facet_types().Add(SemIR::FacetTypeInfo{});
  265. auto const_id = EvalOrAddInst<SemIR::FacetType>(
  266. context, node_id,
  267. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  268. auto type_id = context.types().GetTypeIdForTypeConstantId(const_id);
  269. MakePeriodSelfFacetValue(context, type_id);
  270. return true;
  271. }
  272. auto HandleParseNode(Context& context,
  273. Parse::CompileTimeBindingPatternId node_id) -> bool {
  274. // Pop the `.Self` facet value name introduced by the
  275. // CompileTimeBindingPatternStart.
  276. context.scope_stack().Pop();
  277. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  278. const DeclIntroducerState& introducer =
  279. context.decl_introducer_state_stack().innermost();
  280. if (introducer.kind == Lex::TokenKind::Let) {
  281. // Disallow `let` outside of function and interface definitions.
  282. // TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
  283. // can represent a block scope, but is also used for other kinds of scopes
  284. // that aren't necessarily part of a function decl.
  285. // We don't need to check if the scope is an interface here as this is
  286. // already caught in the parse phase by the separated associated constant
  287. // logic.
  288. auto scope_inst_id = context.scope_stack().PeekInstId();
  289. if (scope_inst_id.has_value()) {
  290. auto scope_inst = context.insts().Get(scope_inst_id);
  291. if (!scope_inst.Is<SemIR::FunctionDecl>()) {
  292. context.TODO(
  293. node_id,
  294. "`let` compile time binding outside function or interface");
  295. node_kind = Parse::NodeKind::LetBindingPattern;
  296. }
  297. }
  298. }
  299. return HandleAnyBindingPattern(context, node_id, node_kind);
  300. }
  301. auto HandleParseNode(Context& context,
  302. Parse::AssociatedConstantNameAndTypeId node_id) -> bool {
  303. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  304. auto [cast_type_inst_id, cast_type_id] =
  305. ExprAsType(context, type_node, parsed_type_id);
  306. EndSubpatternAsExpr(context, cast_type_inst_id);
  307. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  308. if (name_id == SemIR::NameId::Underscore) {
  309. // The action item here may be to document this as not allowed, and
  310. // add a proper diagnostic.
  311. context.TODO(node_id, "_ used as associated constant name");
  312. }
  313. cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
  314. CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedConstantDecl, Error,
  315. "associated constant has incomplete type {0}",
  316. SemIR::TypeId);
  317. return context.emitter().Build(
  318. type_node, IncompleteTypeInAssociatedConstantDecl, cast_type_id);
  319. });
  320. SemIR::AssociatedConstantDecl assoc_const_decl = {
  321. .type_id = cast_type_id,
  322. .assoc_const_id = SemIR::AssociatedConstantId::None,
  323. .decl_block_id = SemIR::InstBlockId::None};
  324. auto decl_id =
  325. AddPlaceholderInstInNoBlock(context, node_id, assoc_const_decl);
  326. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  327. {.name_id = name_id,
  328. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  329. .decl_id = decl_id,
  330. .generic_id = SemIR::GenericId::None,
  331. .default_value_id = SemIR::InstId::None});
  332. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  333. context.node_stack().Push(node_id, decl_id);
  334. return true;
  335. }
  336. auto HandleParseNode(Context& context, Parse::FieldNameAndTypeId node_id)
  337. -> bool {
  338. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  339. auto [cast_type_inst_id, cast_type_id] =
  340. ExprAsType(context, type_node, parsed_type_id);
  341. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  342. auto parent_class_decl =
  343. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  344. CARBON_CHECK(parent_class_decl);
  345. cast_type_id = AsConcreteType(
  346. context, cast_type_id, type_node,
  347. [&] {
  348. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  349. "field has incomplete type {0}", SemIR::TypeId);
  350. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  351. cast_type_id);
  352. },
  353. [&] {
  354. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  355. "field has abstract type {0}", SemIR::TypeId);
  356. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  357. cast_type_id);
  358. });
  359. if (cast_type_id == SemIR::ErrorInst::TypeId) {
  360. cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
  361. }
  362. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  363. auto field_type_id = GetUnboundElementType(
  364. context, context.types().GetInstId(class_info.self_type_id),
  365. cast_type_inst_id);
  366. auto field_id =
  367. AddInst<SemIR::FieldDecl>(context, node_id,
  368. {.type_id = field_type_id,
  369. .name_id = name_id,
  370. .index = SemIR::ElementIndex::None});
  371. context.field_decls_stack().AppendToTop(field_id);
  372. auto name_context =
  373. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  374. context.decl_name_stack().AddNameOrDiagnose(
  375. name_context, field_id,
  376. context.decl_introducer_state_stack()
  377. .innermost()
  378. .modifier_set.GetAccessKind());
  379. return true;
  380. }
  381. auto HandleParseNode(Context& context, Parse::RefBindingNameId node_id)
  382. -> bool {
  383. context.node_stack().Push(node_id);
  384. return true;
  385. }
  386. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  387. -> bool {
  388. context.node_stack().Push(node_id);
  389. return true;
  390. }
  391. } // namespace Carbon::Check