handle_binding_pattern.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 binding_pattern_id = SemIR::InstId::None;
  69. if (is_generic) {
  70. binding_pattern_id = AddPatternInst<SemIR::SymbolicBindingPattern>(
  71. context, name_node,
  72. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  73. } else {
  74. binding_pattern_id = AddPatternInst<SemIR::BindingPattern>(
  75. context, name_node,
  76. {.type_id = cast_type_id, .entity_name_id = entity_name_id});
  77. }
  78. if (is_generic) {
  79. context.scope_stack().PushCompileTimeBinding(bind_id);
  80. }
  81. if (name_id != SemIR::NameId::Underscore) {
  82. // Add name to lookup immediately, so it can be used in the rest of the
  83. // enclosing pattern.
  84. auto name_context =
  85. context.decl_name_stack().MakeUnqualifiedName(name_node, name_id);
  86. context.decl_name_stack().AddNameOrDiagnose(
  87. name_context, bind_id, introducer.modifier_set.GetAccessKind());
  88. context.full_pattern_stack().AddBindName(name_id);
  89. }
  90. bool inserted = context.bind_name_map()
  91. .Insert(binding_pattern_id,
  92. {.bind_name_id = bind_id,
  93. .type_expr_region_id = type_expr_region_id})
  94. .is_inserted();
  95. CARBON_CHECK(inserted);
  96. return binding_pattern_id;
  97. };
  98. // A `self` binding can only appear in an implicit parameter list.
  99. if (name_id == SemIR::NameId::SelfValue &&
  100. !context.node_stack().PeekIs(Parse::NodeKind::ImplicitParamListStart)) {
  101. CARBON_DIAGNOSTIC(
  102. SelfOutsideImplicitParamList, Error,
  103. "`self` can only be declared in an implicit parameter list");
  104. context.emitter().Emit(node_id, SelfOutsideImplicitParamList);
  105. }
  106. // A binding in an interface scope declares an associated constant, not a
  107. // true binding, so we handle it separately.
  108. if (auto parent_interface_decl =
  109. context.scope_stack().GetCurrentScopeAs<SemIR::InterfaceDecl>();
  110. parent_interface_decl.has_value() && is_generic) {
  111. if (name_id == SemIR::NameId::Underscore) {
  112. // The action item here may be to document this as not allowed, and
  113. // add a proper diagnostic.
  114. context.TODO(node_id, "_ used as associated constant name");
  115. }
  116. cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
  117. CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedConstantDecl, Error,
  118. "associated constant has incomplete type {0}",
  119. SemIR::TypeId);
  120. return context.emitter().Build(
  121. type_node, IncompleteTypeInAssociatedConstantDecl, cast_type_id);
  122. });
  123. if (is_template) {
  124. CARBON_DIAGNOSTIC(TemplateBindingInAssociatedConstantDecl, Error,
  125. "associated constant has `template` binding");
  126. context.emitter().Emit(type_node,
  127. TemplateBindingInAssociatedConstantDecl);
  128. }
  129. SemIR::AssociatedConstantDecl assoc_const_decl = {
  130. .type_id = cast_type_id,
  131. .assoc_const_id = SemIR::AssociatedConstantId::None,
  132. .decl_block_id = SemIR::InstBlockId::None};
  133. auto decl_id = AddPlaceholderInstInNoBlock(
  134. context,
  135. context.parse_tree().As<Parse::CompileTimeBindingPatternId>(node_id),
  136. assoc_const_decl);
  137. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  138. {.name_id = name_id,
  139. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  140. .decl_id = decl_id,
  141. .generic_id = SemIR::GenericId::None,
  142. .default_value_id = SemIR::InstId::None});
  143. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  144. context.node_stack().Push(node_id, decl_id);
  145. return true;
  146. }
  147. // Allocate an instruction of the appropriate kind, linked to the name for
  148. // error locations.
  149. switch (context.full_pattern_stack().CurrentKind()) {
  150. case FullPatternStack::Kind::ImplicitParamList:
  151. case FullPatternStack::Kind::ExplicitParamList: {
  152. // Parameters can have incomplete types in a function declaration, but not
  153. // in a function definition. We don't know which kind we have here.
  154. bool had_error = false;
  155. switch (introducer.kind) {
  156. case Lex::TokenKind::Fn: {
  157. if (context.full_pattern_stack().CurrentKind() ==
  158. FullPatternStack::Kind::ImplicitParamList &&
  159. !(is_generic || name_id == SemIR::NameId::SelfValue)) {
  160. CARBON_DIAGNOSTIC(
  161. ImplictParamMustBeConstant, Error,
  162. "implicit parameters of functions must be constant or `self`");
  163. context.emitter().Emit(node_id, ImplictParamMustBeConstant);
  164. had_error = true;
  165. }
  166. break;
  167. }
  168. case Lex::TokenKind::Choice:
  169. if (context.scope_stack().PeekInstId().has_value()) {
  170. // We are building a pattern for a choice alternative, not the
  171. // choice type itself.
  172. // Implicit param lists are prevented during parse.
  173. CARBON_CHECK(context.full_pattern_stack().CurrentKind() !=
  174. FullPatternStack::Kind::ImplicitParamList,
  175. "choice alternative with implicit parameters");
  176. // Don't fall through to the `Class` logic for choice alternatives.
  177. break;
  178. }
  179. [[fallthrough]];
  180. case Lex::TokenKind::Class:
  181. case Lex::TokenKind::Impl:
  182. case Lex::TokenKind::Interface: {
  183. if (name_id == SemIR::NameId::SelfValue) {
  184. CARBON_DIAGNOSTIC(SelfParameterNotAllowed, Error,
  185. "`self` parameter only allowed on functions");
  186. context.emitter().Emit(node_id, SelfParameterNotAllowed);
  187. had_error = true;
  188. } else if (!is_generic) {
  189. CARBON_DIAGNOSTIC(GenericParamMustBeConstant, Error,
  190. "parameters of generic types must be constant");
  191. context.emitter().Emit(node_id, GenericParamMustBeConstant);
  192. had_error = true;
  193. }
  194. break;
  195. }
  196. default:
  197. break;
  198. }
  199. auto result_inst_id = SemIR::InstId::None;
  200. if (had_error) {
  201. if (name_id != SemIR::NameId::Underscore) {
  202. AddNameToLookup(context, name_id, SemIR::ErrorInst::InstId);
  203. }
  204. // Replace the parameter with `ErrorInst` so that we don't try
  205. // constructing a generic based on it.
  206. result_inst_id = SemIR::ErrorInst::InstId;
  207. } else {
  208. result_inst_id = make_binding_pattern();
  209. if (node_kind == Parse::NodeKind::LetBindingPattern) {
  210. // A value binding pattern in a function signature is a `Call`
  211. // parameter, but a variable binding pattern is not (instead the
  212. // enclosing `var` pattern is), and a symbolic binding pattern is not
  213. // (because it's not passed to the `Call` inst).
  214. result_inst_id = AddPatternInst<SemIR::ValueParamPattern>(
  215. context, node_id,
  216. {.type_id = context.insts().Get(result_inst_id).type_id(),
  217. .subpattern_id = result_inst_id,
  218. .index = SemIR::CallParamIndex::None});
  219. }
  220. }
  221. context.node_stack().Push(node_id, result_inst_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::FieldNameAndTypeId node_id)
  303. -> bool {
  304. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  305. auto [cast_type_inst_id, cast_type_id] =
  306. ExprAsType(context, type_node, parsed_type_id);
  307. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  308. auto parent_class_decl =
  309. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  310. CARBON_CHECK(parent_class_decl);
  311. cast_type_id = AsConcreteType(
  312. context, cast_type_id, type_node,
  313. [&] {
  314. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  315. "field has incomplete type {0}", SemIR::TypeId);
  316. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  317. cast_type_id);
  318. },
  319. [&] {
  320. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  321. "field has abstract type {0}", SemIR::TypeId);
  322. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  323. cast_type_id);
  324. });
  325. if (cast_type_id == SemIR::ErrorInst::TypeId) {
  326. cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
  327. }
  328. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  329. auto field_type_id = GetUnboundElementType(
  330. context, context.types().GetInstId(class_info.self_type_id),
  331. cast_type_inst_id);
  332. auto field_id =
  333. AddInst<SemIR::FieldDecl>(context, node_id,
  334. {.type_id = field_type_id,
  335. .name_id = name_id,
  336. .index = SemIR::ElementIndex::None});
  337. context.field_decls_stack().AppendToTop(field_id);
  338. auto name_context =
  339. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  340. context.decl_name_stack().AddNameOrDiagnose(
  341. name_context, field_id,
  342. context.decl_introducer_state_stack()
  343. .innermost()
  344. .modifier_set.GetAccessKind());
  345. return true;
  346. }
  347. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  348. auto param_pattern_id = context.node_stack().PopPattern();
  349. if (SemIR::IsSelfPattern(context.sem_ir(), param_pattern_id)) {
  350. auto pointer_type = context.types().TryGetAs<SemIR::PointerType>(
  351. context.insts().Get(param_pattern_id).type_id());
  352. if (pointer_type) {
  353. auto addr_pattern_id = AddPatternInst<SemIR::AddrPattern>(
  354. context, node_id,
  355. {.type_id = SemIR::AutoType::TypeId, .inner_id = param_pattern_id});
  356. context.node_stack().Push(node_id, addr_pattern_id);
  357. } else {
  358. CARBON_DIAGNOSTIC(
  359. AddrOnNonPointerType, Error,
  360. "`addr` can only be applied to a binding with a pointer type");
  361. context.emitter().Emit(node_id, AddrOnNonPointerType);
  362. context.node_stack().Push(node_id, param_pattern_id);
  363. }
  364. } else {
  365. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  366. "`addr` can only be applied to a `self` parameter");
  367. context.emitter().Emit(TokenOnly(node_id), AddrOnNonSelfParam);
  368. context.node_stack().Push(node_id, param_pattern_id);
  369. }
  370. return true;
  371. }
  372. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  373. -> bool {
  374. context.node_stack().Push(node_id);
  375. return true;
  376. }
  377. } // namespace Carbon::Check