handle_binding_pattern.cpp 15 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/name_lookup.h"
  9. #include "toolchain/check/return.h"
  10. #include "toolchain/check/subpattern.h"
  11. #include "toolchain/check/type.h"
  12. #include "toolchain/check/type_completion.h"
  13. #include "toolchain/diagnostics/format_providers.h"
  14. #include "toolchain/sem_ir/ids.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. namespace Carbon::Check {
  17. static auto HandleAnyBindingPattern(Context& context, Parse::NodeId node_id,
  18. Parse::NodeKind node_kind) -> bool {
  19. // TODO: split this into smaller, more focused functions.
  20. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  21. auto [cast_type_inst_id, cast_type_id] =
  22. ExprAsType(context, type_node, parsed_type_id);
  23. // TODO: Handle `_` bindings.
  24. SemIR::ExprRegionId type_expr_region_id =
  25. EndSubpatternAsExpr(context, cast_type_inst_id);
  26. // The name in a template binding may be wrapped in `template`.
  27. bool is_generic = node_kind == Parse::NodeKind::CompileTimeBindingPattern;
  28. auto is_template =
  29. context.node_stack()
  30. .PopAndDiscardSoloNodeIdIf<Parse::NodeKind::TemplateBindingName>();
  31. // A non-generic template binding is diagnosed by the parser.
  32. is_template &= is_generic;
  33. // Every other kind of pattern binding has a name.
  34. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  35. const DeclIntroducerState& introducer =
  36. context.decl_introducer_state_stack().innermost();
  37. auto make_binding_pattern = [&]() -> SemIR::InstId {
  38. auto bind_id = SemIR::InstId::None;
  39. auto binding_pattern_id = SemIR::InstId::None;
  40. // TODO: Eventually the name will need to support associations with other
  41. // scopes, but right now we don't support qualified names here.
  42. auto entity_name_id = context.entity_names().AddSymbolicBindingName(
  43. name_id, context.scope_stack().PeekNameScopeId(),
  44. is_generic ? context.scope_stack().AddCompileTimeBinding()
  45. : SemIR::CompileTimeBindIndex::None,
  46. is_template);
  47. if (is_generic) {
  48. bind_id = context.AddInstInNoBlock(SemIR::LocIdAndInst(
  49. name_node, SemIR::BindSymbolicName{.type_id = cast_type_id,
  50. .entity_name_id = entity_name_id,
  51. .value_id = SemIR::InstId::None}));
  52. binding_pattern_id =
  53. context.AddPatternInst<SemIR::SymbolicBindingPattern>(
  54. name_node,
  55. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  56. } else {
  57. bind_id = context.AddInstInNoBlock(SemIR::LocIdAndInst(
  58. name_node, SemIR::BindName{.type_id = cast_type_id,
  59. .entity_name_id = entity_name_id,
  60. .value_id = SemIR::InstId::None}));
  61. binding_pattern_id = context.AddPatternInst<SemIR::BindingPattern>(
  62. name_node,
  63. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  64. }
  65. // Add name to lookup immediately, so it can be used in the rest of the
  66. // enclosing pattern.
  67. if (is_generic) {
  68. context.scope_stack().PushCompileTimeBinding(bind_id);
  69. }
  70. auto name_context =
  71. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  72. context.decl_name_stack().AddNameOrDiagnose(
  73. name_context, bind_id, introducer.modifier_set.GetAccessKind());
  74. context.full_pattern_stack().AddBindName(name_id);
  75. bool inserted = context.bind_name_map()
  76. .Insert(binding_pattern_id,
  77. {.bind_name_id = bind_id,
  78. .type_expr_region_id = type_expr_region_id})
  79. .is_inserted();
  80. CARBON_CHECK(inserted);
  81. return binding_pattern_id;
  82. };
  83. // A `self` binding can only appear in an implicit parameter list.
  84. if (name_id == SemIR::NameId::SelfValue &&
  85. !context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
  86. CARBON_DIAGNOSTIC(
  87. SelfOutsideImplicitParamList, Error,
  88. "`self` can only be declared in an implicit parameter list");
  89. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  90. }
  91. // A `var` binding in a class scope declares a field, not a true binding,
  92. // so we handle it separately.
  93. if (auto parent_class_decl =
  94. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  95. parent_class_decl.has_value() && !is_generic &&
  96. node_kind == Parse::NodeKind::VarBindingPattern) {
  97. cast_type_id = AsConcreteType(
  98. context, cast_type_id, type_node,
  99. [&] {
  100. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  101. "field has incomplete type {0}", SemIR::TypeId);
  102. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  103. cast_type_id);
  104. },
  105. [&] {
  106. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  107. "field has abstract type {0}", SemIR::TypeId);
  108. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  109. cast_type_id);
  110. });
  111. auto binding_id =
  112. context.parse_tree().As<Parse::VarBindingPatternId>(node_id);
  113. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  114. auto field_type_id =
  115. GetUnboundElementType(context, class_info.self_type_id, cast_type_id);
  116. auto field_id = context.AddInst<SemIR::FieldDecl>(
  117. binding_id, {.type_id = field_type_id,
  118. .name_id = name_id,
  119. .index = SemIR::ElementIndex::None});
  120. context.field_decls_stack().AppendToTop(field_id);
  121. context.node_stack().Push(node_id, field_id);
  122. auto name_context =
  123. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  124. context.decl_name_stack().AddNameOrDiagnose(
  125. name_context, field_id, introducer.modifier_set.GetAccessKind());
  126. return true;
  127. }
  128. // A binding in an interface scope declares an associated constant, not a
  129. // true binding, so we handle it separately.
  130. if (auto parent_interface_decl =
  131. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  132. parent_interface_decl.has_value() && is_generic) {
  133. cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
  134. CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedConstantDecl, Error,
  135. "associated constant has incomplete type {0}",
  136. SemIR::TypeId);
  137. return context.emitter().Build(
  138. type_node, IncompleteTypeInAssociatedConstantDecl, cast_type_id);
  139. });
  140. if (is_template) {
  141. CARBON_DIAGNOSTIC(TemplateBindingInAssociatedConstantDecl, Error,
  142. "associated constant has `template` binding");
  143. context.emitter().Emit(type_node,
  144. TemplateBindingInAssociatedConstantDecl);
  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. AddNameToLookup(context, 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 = AsConcreteType(
  236. context, 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 = AsCompleteType(context, 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::TemplateBindingNameId node_id)
  330. -> bool {
  331. context.node_stack().Push(node_id);
  332. return true;
  333. }
  334. } // namespace Carbon::Check