handle_binding_pattern.cpp 17 KB

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