handle_binding_pattern.cpp 16 KB

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