handle_binding_pattern.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  101. parent_class_decl.has_value() &&
  102. node_kind == Parse::NodeKind::VarBindingPattern) {
  103. cast_type_id = AsConcreteType(
  104. context, cast_type_id, type_node,
  105. [&] {
  106. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  107. "field has incomplete type {0}", SemIR::TypeId);
  108. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  109. cast_type_id);
  110. },
  111. [&] {
  112. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  113. "field has abstract type {0}", SemIR::TypeId);
  114. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  115. cast_type_id);
  116. });
  117. auto binding_id =
  118. is_generic
  119. ? Parse::NodeId::None
  120. : context.parse_tree().As<Parse::VarBindingPatternId>(node_id);
  121. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  122. auto field_type_id =
  123. context.GetUnboundElementType(class_info.self_type_id, cast_type_id);
  124. auto field_id = context.AddInst<SemIR::FieldDecl>(
  125. binding_id, {.type_id = field_type_id,
  126. .name_id = name_id,
  127. .index = SemIR::ElementIndex::None});
  128. context.field_decls_stack().AppendToTop(field_id);
  129. context.node_stack().Push(node_id, field_id);
  130. auto name_context =
  131. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  132. context.decl_name_stack().AddNameOrDiagnose(
  133. name_context, field_id, introducer.modifier_set.GetAccessKind());
  134. return true;
  135. }
  136. // A binding in an interface scope declares an associated constant, not a
  137. // true binding, so we handle it separately.
  138. if (auto parent_interface_decl =
  139. context.GetCurrentScopeAs<SemIR::InterfaceDecl>();
  140. parent_interface_decl.has_value() && is_generic) {
  141. cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
  142. CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedDecl, Error,
  143. "associated constant has incomplete type {0}",
  144. SemIR::TypeId);
  145. return context.emitter().Build(type_node, IncompleteTypeInAssociatedDecl,
  146. cast_type_id);
  147. });
  148. SemIR::AssociatedConstantDecl assoc_const_decl = {
  149. .type_id = cast_type_id,
  150. .assoc_const_id = SemIR::AssociatedConstantId::None,
  151. .decl_block_id = SemIR::InstBlockId::None};
  152. auto decl_id = context.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  153. context.parse_tree().As<Parse::CompileTimeBindingPatternId>(node_id),
  154. assoc_const_decl));
  155. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  156. {.name_id = name_id,
  157. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  158. .decl_id = decl_id,
  159. .generic_id = SemIR::GenericId::None,
  160. .default_value_id = SemIR::InstId::None});
  161. context.ReplaceInstBeforeConstantUse(decl_id, assoc_const_decl);
  162. context.node_stack().Push(node_id, decl_id);
  163. return true;
  164. }
  165. // Allocate an instruction of the appropriate kind, linked to the name for
  166. // error locations.
  167. switch (context.full_pattern_stack().CurrentKind()) {
  168. case FullPatternStack::Kind::ImplicitParamList:
  169. case FullPatternStack::Kind::ExplicitParamList: {
  170. // Parameters can have incomplete types in a function declaration, but not
  171. // in a function definition. We don't know which kind we have here.
  172. // TODO: A tuple pattern can appear in other places than function
  173. // parameters.
  174. auto param_pattern_id = SemIR::InstId::None;
  175. bool had_error = false;
  176. switch (introducer.kind) {
  177. case Lex::TokenKind::Fn: {
  178. if (context.full_pattern_stack().CurrentKind() ==
  179. FullPatternStack::Kind::ImplicitParamList &&
  180. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  181. CARBON_DIAGNOSTIC(
  182. ImplictParamMustBeConstant, Error,
  183. "implicit parameters of functions must be constant or `self`");
  184. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  185. had_error = true;
  186. }
  187. break;
  188. }
  189. case Lex::TokenKind::Class:
  190. case Lex::TokenKind::Impl:
  191. case Lex::TokenKind::Interface: {
  192. if (name_id == SemIR::NameId::SelfValue) {
  193. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  194. "`self` parameter only allowed on functions");
  195. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  196. had_error = true;
  197. } else if (!is_generic) {
  198. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  199. "parameters of generic types must be constant");
  200. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  201. had_error = true;
  202. }
  203. break;
  204. }
  205. default:
  206. break;
  207. }
  208. if (had_error) {
  209. context.AddNameToLookup(name_id, SemIR::ErrorInst::SingletonInstId);
  210. // Replace the parameter with `ErrorInst` so that we don't try
  211. // constructing a generic based on it.
  212. param_pattern_id = SemIR::ErrorInst::SingletonInstId;
  213. } else {
  214. auto pattern_inst_id = make_binding_pattern();
  215. param_pattern_id = context.AddPatternInst<SemIR::ValueParamPattern>(
  216. node_id,
  217. {
  218. .type_id = context.insts().Get(pattern_inst_id).type_id(),
  219. .subpattern_id = pattern_inst_id,
  220. .runtime_index = is_generic ? SemIR::RuntimeParamIndex::None
  221. : SemIR::RuntimeParamIndex::Unknown,
  222. });
  223. }
  224. context.node_stack().Push(node_id, param_pattern_id);
  225. break;
  226. }
  227. case FullPatternStack::Kind::NameBindingDecl: {
  228. auto incomplete_diagnoser = [&] {
  229. CARBON_DIAGNOSTIC(IncompleteTypeInBindingDecl, Error,
  230. "binding pattern has incomplete type {0} in name "
  231. "binding declaration",
  232. InstIdAsType);
  233. return context.emitter().Build(type_node, IncompleteTypeInBindingDecl,
  234. cast_type_inst_id);
  235. };
  236. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  237. cast_type_id = AsConcreteType(
  238. context, cast_type_id, type_node, incomplete_diagnoser, [&] {
  239. CARBON_DIAGNOSTIC(
  240. AbstractTypeInVarPattern, Error,
  241. "binding pattern has abstract type {0} in `var` "
  242. "pattern",
  243. SemIR::TypeId);
  244. return context.emitter().Build(
  245. type_node, AbstractTypeInVarPattern, cast_type_id);
  246. });
  247. } else {
  248. cast_type_id = AsCompleteType(context, cast_type_id, type_node,
  249. incomplete_diagnoser);
  250. }
  251. auto binding_pattern_id = make_binding_pattern();
  252. if (node_kind == Parse::NodeKind::VarBindingPattern) {
  253. CARBON_CHECK(!is_generic);
  254. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  255. // TODO: Should we check this for the `var` as a whole, rather than
  256. // for the name binding?
  257. auto bind_id = context.bind_name_map()
  258. .Lookup(binding_pattern_id)
  259. .value()
  260. .bind_name_id;
  261. RegisterReturnedVar(context,
  262. introducer.modifier_node_id(ModifierOrder::Decl),
  263. type_node, cast_type_id, bind_id);
  264. }
  265. }
  266. context.node_stack().Push(node_id, binding_pattern_id);
  267. break;
  268. }
  269. }
  270. return true;
  271. }
  272. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  273. -> bool {
  274. return HandleAnyBindingPattern(context, node_id,
  275. Parse::NodeKind::LetBindingPattern);
  276. }
  277. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  278. -> bool {
  279. return HandleAnyBindingPattern(context, node_id,
  280. Parse::NodeKind::VarBindingPattern);
  281. }
  282. auto HandleParseNode(Context& context,
  283. Parse::CompileTimeBindingPatternId node_id) -> bool {
  284. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  285. if (context.decl_introducer_state_stack().innermost().kind ==
  286. Lex::TokenKind::Let) {
  287. // Disallow `let` outside of function and interface definitions.
  288. // TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
  289. // can represent a block scope, but is also used for other kinds of scopes
  290. // that aren't necessarily part of an interface or function decl.
  291. auto scope_inst_id = context.scope_stack().PeekInstId();
  292. if (scope_inst_id.has_value()) {
  293. auto scope_inst = context.insts().Get(scope_inst_id);
  294. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  295. !scope_inst.Is<SemIR::FunctionDecl>()) {
  296. context.TODO(
  297. node_id,
  298. "`let` compile time binding outside function or interface");
  299. node_kind = Parse::NodeKind::LetBindingPattern;
  300. }
  301. }
  302. }
  303. return HandleAnyBindingPattern(context, node_id, node_kind);
  304. }
  305. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  306. auto param_pattern_id = context.node_stack().PopPattern();
  307. if (SemIR::Function::GetNameFromPatternId(
  308. context.sem_ir(), param_pattern_id) == SemIR::NameId::SelfValue) {
  309. auto pointer_type = context.types().TryGetAs<SemIR::PointerType>(
  310. context.insts().Get(param_pattern_id).type_id());
  311. if (pointer_type) {
  312. auto addr_pattern_id = context.AddPatternInst<SemIR::AddrPattern>(
  313. node_id, {.type_id = SemIR::AutoType::SingletonTypeId,
  314. .inner_id = param_pattern_id});
  315. context.node_stack().Push(node_id, addr_pattern_id);
  316. } else {
  317. CARBON_DIAGNOSTIC(
  318. AddrOnNonPointerType, Error,
  319. "`addr` can only be applied to a binding with a pointer type");
  320. context.emitter().Emit(node_id, AddrOnNonPointerType);
  321. context.node_stack().Push(node_id, param_pattern_id);
  322. }
  323. } else {
  324. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  325. "`addr` can only be applied to a `self` parameter");
  326. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  327. context.node_stack().Push(node_id, param_pattern_id);
  328. }
  329. return true;
  330. }
  331. auto HandleParseNode(Context& context, Parse::TemplateId node_id) -> bool {
  332. return context.TODO(node_id, "HandleTemplate");
  333. }
  334. } // namespace Carbon::Check