handle_binding_pattern.cpp 16 KB

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