handle_binding_pattern.cpp 17 KB

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