handle_binding_pattern.cpp 17 KB

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