handle_binding_pattern.cpp 17 KB

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