handle_binding_pattern.cpp 17 KB

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