handle_binding_pattern.cpp 16 KB

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