handle_binding_pattern.cpp 16 KB

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