handle_binding_pattern.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. // TODO: The node stack is a fragile way of getting context information.
  97. // Get this information from somewhere else.
  98. auto context_node_kind = context.node_stack().PeekNodeKind();
  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 = context.GetCurrentScopeAs<SemIR::ClassDecl>();
  102. parent_class_decl.has_value() &&
  103. context_node_kind == Parse::NodeKind::VariableIntroducer) {
  104. cast_type_id = context.AsConcreteType(
  105. 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.GetCurrentScopeAs<SemIR::InterfaceDecl>();
  141. parent_interface_decl.has_value() && is_generic) {
  142. cast_type_id = context.AsCompleteType(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. context.entity_names().Add(
  150. {.name_id = name_id,
  151. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  152. .bind_index = SemIR::CompileTimeBindIndex::None});
  153. SemIR::InstId decl_id = context.AddInst<SemIR::AssociatedConstantDecl>(
  154. context.parse_tree().As<Parse::CompileTimeBindingPatternId>(node_id),
  155. {cast_type_id, name_id});
  156. context.node_stack().Push(node_id, decl_id);
  157. // Add an associated entity name to the interface scope.
  158. auto assoc_id = BuildAssociatedEntity(
  159. context, parent_interface_decl->interface_id, decl_id);
  160. auto name_context =
  161. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  162. context.decl_name_stack().AddNameOrDiagnose(
  163. name_context, assoc_id, introducer.modifier_set.GetAccessKind());
  164. return true;
  165. }
  166. // Allocate an instruction of the appropriate kind, linked to the name for
  167. // error locations.
  168. switch (context_node_kind) {
  169. case Parse::NodeKind::VariableIntroducer: {
  170. CARBON_CHECK(!is_generic);
  171. cast_type_id = context.AsConcreteType(
  172. cast_type_id, type_node,
  173. [&] {
  174. CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
  175. "variable has incomplete type {0}",
  176. SemIR::TypeId);
  177. return context.emitter().Build(type_node, IncompleteTypeInVarDecl,
  178. cast_type_id);
  179. },
  180. [&] {
  181. CARBON_DIAGNOSTIC(AbstractTypeInVarDecl, Error,
  182. "variable has abstract type {0}", SemIR::TypeId);
  183. return context.emitter().Build(type_node, AbstractTypeInVarDecl,
  184. cast_type_id);
  185. });
  186. auto binding_pattern_id = make_binding_pattern();
  187. if (introducer.modifier_set.HasAnyOf(KeywordModifierSet::Returned)) {
  188. // TODO: Should we check this for the `var` as a whole, rather than for
  189. // the name binding?
  190. auto bind_id = context.bind_name_map()
  191. .Lookup(binding_pattern_id)
  192. .value()
  193. .bind_name_id;
  194. RegisterReturnedVar(context,
  195. introducer.modifier_node_id(ModifierOrder::Decl),
  196. type_node, cast_type_id, bind_id);
  197. }
  198. context.node_stack().Push(node_id, binding_pattern_id);
  199. break;
  200. }
  201. case Parse::NodeKind::ImplicitParamListStart:
  202. case Parse::NodeKind::TuplePatternStart: {
  203. // Parameters can have incomplete types in a function declaration, but not
  204. // in a function definition. We don't know which kind we have here.
  205. // TODO: A tuple pattern can appear in other places than function
  206. // parameters.
  207. auto param_pattern_id = SemIR::InstId::None;
  208. bool had_error = false;
  209. switch (introducer.kind) {
  210. case Lex::TokenKind::Fn: {
  211. if (context_node_kind == Parse::NodeKind::ImplicitParamListStart &&
  212. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  213. CARBON_DIAGNOSTIC(
  214. ImplictParamMustBeConstant, Error,
  215. "implicit parameters of functions must be constant or `self`");
  216. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  217. had_error = true;
  218. }
  219. break;
  220. }
  221. case Lex::TokenKind::Class:
  222. case Lex::TokenKind::Impl:
  223. case Lex::TokenKind::Interface: {
  224. if (name_id == SemIR::NameId::SelfValue) {
  225. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  226. "`self` parameter only allowed on functions");
  227. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  228. had_error = true;
  229. } else if (!is_generic) {
  230. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  231. "parameters of generic types must be constant");
  232. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  233. had_error = true;
  234. }
  235. break;
  236. }
  237. default:
  238. break;
  239. }
  240. if (had_error) {
  241. context.AddNameToLookup(name_id, SemIR::ErrorInst::SingletonInstId);
  242. // Replace the parameter with an invalid instruction so that we don't
  243. // try constructing a generic based on it.
  244. param_pattern_id = SemIR::ErrorInst::SingletonInstId;
  245. } else {
  246. auto pattern_inst_id = make_binding_pattern();
  247. param_pattern_id = context.AddPatternInst<SemIR::ValueParamPattern>(
  248. node_id,
  249. {
  250. .type_id = context.insts().Get(pattern_inst_id).type_id(),
  251. .subpattern_id = pattern_inst_id,
  252. .runtime_index = is_generic ? SemIR::RuntimeParamIndex::None
  253. : SemIR::RuntimeParamIndex::Unknown,
  254. });
  255. }
  256. context.node_stack().Push(node_id, param_pattern_id);
  257. // TODO: Use the pattern insts to generate the pattern-match insts
  258. // at the end of the full pattern, instead of eagerly generating them
  259. // here.
  260. break;
  261. }
  262. case Parse::NodeKind::LetIntroducer: {
  263. cast_type_id = context.AsCompleteType(cast_type_id, type_node, [&] {
  264. CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
  265. "`let` binding has incomplete type {0}",
  266. InstIdAsType);
  267. return context.emitter().Build(type_node, IncompleteTypeInLetDecl,
  268. cast_type_inst_id);
  269. });
  270. context.node_stack().Push(node_id, make_binding_pattern());
  271. break;
  272. }
  273. default:
  274. CARBON_FATAL("Found a pattern binding in unexpected context {0}",
  275. context_node_kind);
  276. }
  277. return true;
  278. }
  279. auto HandleParseNode(Context& context, Parse::LetBindingPatternId node_id)
  280. -> bool {
  281. return HandleAnyBindingPattern(context, node_id,
  282. Parse::NodeKind::LetBindingPattern);
  283. }
  284. auto HandleParseNode(Context& context, Parse::VarBindingPatternId node_id)
  285. -> bool {
  286. return HandleAnyBindingPattern(context, node_id,
  287. Parse::NodeKind::VarBindingPattern);
  288. }
  289. auto HandleParseNode(Context& context,
  290. Parse::CompileTimeBindingPatternId node_id) -> bool {
  291. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  292. if (context.decl_introducer_state_stack().innermost().kind ==
  293. Lex::TokenKind::Let) {
  294. // Disallow `let` outside of function and interface definitions.
  295. // TODO: Find a less brittle way of doing this. An invalid scope_inst_id
  296. // can represent a block scope, but is also used for other kinds of scopes
  297. // that aren't necessarily part of an interface or function decl.
  298. auto scope_inst_id = context.scope_stack().PeekInstId();
  299. if (scope_inst_id.has_value()) {
  300. auto scope_inst = context.insts().Get(scope_inst_id);
  301. if (!scope_inst.Is<SemIR::InterfaceDecl>() &&
  302. !scope_inst.Is<SemIR::FunctionDecl>()) {
  303. context.TODO(
  304. node_id,
  305. "`let` compile time binding outside function or interface");
  306. node_kind = Parse::NodeKind::LetBindingPattern;
  307. }
  308. }
  309. }
  310. return HandleAnyBindingPattern(context, node_id, node_kind);
  311. }
  312. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  313. auto param_pattern_id = context.node_stack().PopPattern();
  314. if (SemIR::Function::GetNameFromPatternId(
  315. context.sem_ir(), param_pattern_id) == SemIR::NameId::SelfValue) {
  316. auto pointer_type = context.types().TryGetAs<SemIR::PointerType>(
  317. context.insts().Get(param_pattern_id).type_id());
  318. if (pointer_type) {
  319. auto addr_pattern_id = context.AddPatternInst<SemIR::AddrPattern>(
  320. node_id, {.type_id = SemIR::AutoType::SingletonTypeId,
  321. .inner_id = param_pattern_id});
  322. context.node_stack().Push(node_id, addr_pattern_id);
  323. } else {
  324. CARBON_DIAGNOSTIC(
  325. AddrOnNonPointerType, Error,
  326. "`addr` can only be applied to a binding with a pointer type");
  327. context.emitter().Emit(node_id, AddrOnNonPointerType);
  328. context.node_stack().Push(node_id, param_pattern_id);
  329. }
  330. } else {
  331. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  332. "`addr` can only be applied to a `self` parameter");
  333. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  334. context.node_stack().Push(node_id, param_pattern_id);
  335. }
  336. return true;
  337. }
  338. auto HandleParseNode(Context& context, Parse::TemplateId node_id) -> bool {
  339. return context.TODO(node_id, "HandleTemplate");
  340. }
  341. } // namespace Carbon::Check