handle_binding_pattern.cpp 16 KB

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