handle_binding_pattern.cpp 18 KB

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