handle_binding_pattern.cpp 18 KB

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