handle_binding_pattern.cpp 16 KB

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