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