handle_binding_pattern.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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*/)
  211. -> bool {
  212. // Make a scope to contain the `.Self` facet value for use in the type of the
  213. // compile time binding. This is popped when handling the
  214. // CompileTimeBindingPatternId.
  215. context.scope_stack().PushForSameRegion();
  216. MakePeriodSelfFacetValue(context, SemIR::TypeType::TypeId);
  217. return true;
  218. }
  219. auto HandleParseNode(Context& context,
  220. Parse::CompileTimeBindingPatternId node_id) -> bool {
  221. // Pop the `.Self` facet value name introduced by the
  222. // CompileTimeBindingPatternStart.
  223. context.scope_stack().Pop();
  224. auto node_kind = Parse::NodeKind::CompileTimeBindingPattern;
  225. const DeclIntroducerState& introducer =
  226. context.decl_introducer_state_stack().innermost();
  227. if (introducer.kind == Lex::TokenKind::Let) {
  228. // Disallow `let` outside of function and interface definitions.
  229. // TODO: Find a less brittle way of doing this. A `scope_inst_id` of `None`
  230. // can represent a block scope, but is also used for other kinds of scopes
  231. // that aren't necessarily part of a function decl.
  232. // We don't need to check if the scope is an interface here as this is
  233. // already caught in the parse phase by the separated associated constant
  234. // logic.
  235. auto scope_inst_id = context.scope_stack().PeekInstId();
  236. if (scope_inst_id.has_value()) {
  237. auto scope_inst = context.insts().Get(scope_inst_id);
  238. if (!scope_inst.Is<SemIR::FunctionDecl>()) {
  239. context.TODO(
  240. node_id,
  241. "`let` compile time binding outside function or interface");
  242. node_kind = Parse::NodeKind::LetBindingPattern;
  243. }
  244. }
  245. }
  246. return HandleAnyBindingPattern(context, node_id, node_kind);
  247. }
  248. auto HandleParseNode(Context& context,
  249. Parse::AssociatedConstantNameAndTypeId node_id) -> bool {
  250. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  251. auto [cast_type_inst_id, cast_type_id] =
  252. ExprAsType(context, type_node, parsed_type_id);
  253. EndSubpatternAsExpr(context, cast_type_inst_id);
  254. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  255. if (name_id == SemIR::NameId::Underscore) {
  256. // The action item here may be to document this as not allowed, and
  257. // add a proper diagnostic.
  258. context.TODO(node_id, "_ used as associated constant name");
  259. }
  260. cast_type_id = AsCompleteType(context, cast_type_id, type_node, [&] {
  261. CARBON_DIAGNOSTIC(IncompleteTypeInAssociatedConstantDecl, Error,
  262. "associated constant has incomplete type {0}",
  263. SemIR::TypeId);
  264. return context.emitter().Build(
  265. type_node, IncompleteTypeInAssociatedConstantDecl, cast_type_id);
  266. });
  267. SemIR::AssociatedConstantDecl assoc_const_decl = {
  268. .type_id = cast_type_id,
  269. .assoc_const_id = SemIR::AssociatedConstantId::None,
  270. .decl_block_id = SemIR::InstBlockId::None};
  271. auto decl_id =
  272. AddPlaceholderInstInNoBlock(context, node_id, assoc_const_decl);
  273. assoc_const_decl.assoc_const_id = context.associated_constants().Add(
  274. {.name_id = name_id,
  275. .parent_scope_id = context.scope_stack().PeekNameScopeId(),
  276. .decl_id = decl_id,
  277. .generic_id = SemIR::GenericId::None,
  278. .default_value_id = SemIR::InstId::None});
  279. ReplaceInstBeforeConstantUse(context, decl_id, assoc_const_decl);
  280. context.node_stack().Push(node_id, decl_id);
  281. return true;
  282. }
  283. auto HandleParseNode(Context& context, Parse::FieldNameAndTypeId node_id)
  284. -> bool {
  285. auto [type_node, parsed_type_id] = context.node_stack().PopExprWithNodeId();
  286. auto [cast_type_inst_id, cast_type_id] =
  287. ExprAsType(context, type_node, parsed_type_id);
  288. auto [name_node, name_id] = context.node_stack().PopNameWithNodeId();
  289. auto parent_class_decl =
  290. context.scope_stack().GetCurrentScopeAs<SemIR::ClassDecl>();
  291. CARBON_CHECK(parent_class_decl);
  292. cast_type_id = AsConcreteType(
  293. context, cast_type_id, type_node,
  294. [&] {
  295. CARBON_DIAGNOSTIC(IncompleteTypeInFieldDecl, Error,
  296. "field has incomplete type {0}", SemIR::TypeId);
  297. return context.emitter().Build(type_node, IncompleteTypeInFieldDecl,
  298. cast_type_id);
  299. },
  300. [&] {
  301. CARBON_DIAGNOSTIC(AbstractTypeInFieldDecl, Error,
  302. "field has abstract type {0}", SemIR::TypeId);
  303. return context.emitter().Build(type_node, AbstractTypeInFieldDecl,
  304. cast_type_id);
  305. });
  306. if (cast_type_id == SemIR::ErrorInst::TypeId) {
  307. cast_type_inst_id = SemIR::ErrorInst::TypeInstId;
  308. }
  309. auto& class_info = context.classes().Get(parent_class_decl->class_id);
  310. auto field_type_id = GetUnboundElementType(
  311. context, context.types().GetInstId(class_info.self_type_id),
  312. cast_type_inst_id);
  313. auto field_id =
  314. AddInst<SemIR::FieldDecl>(context, node_id,
  315. {.type_id = field_type_id,
  316. .name_id = name_id,
  317. .index = SemIR::ElementIndex::None});
  318. context.field_decls_stack().AppendToTop(field_id);
  319. auto name_context =
  320. context.decl_name_stack().MakeUnqualifiedName(node_id, name_id);
  321. context.decl_name_stack().AddNameOrDiagnose(
  322. name_context, field_id,
  323. context.decl_introducer_state_stack()
  324. .innermost()
  325. .modifier_set.GetAccessKind());
  326. return true;
  327. }
  328. auto HandleParseNode(Context& context, Parse::AddrId node_id) -> bool {
  329. auto param_pattern_id = context.node_stack().PopPattern();
  330. if (SemIR::IsSelfPattern(context.sem_ir(), param_pattern_id)) {
  331. auto param_type_id = ExtractScrutineeType(
  332. context.sem_ir(), context.insts().Get(param_pattern_id).type_id());
  333. auto pointer_type =
  334. context.types().TryGetAs<SemIR::PointerType>(param_type_id);
  335. if (pointer_type) {
  336. auto addr_pattern_id = AddPatternInst<SemIR::AddrPattern>(
  337. context, node_id,
  338. {.type_id = GetPatternType(context, SemIR::AutoType::TypeId),
  339. .inner_id = param_pattern_id});
  340. context.node_stack().Push(node_id, addr_pattern_id);
  341. } else {
  342. CARBON_DIAGNOSTIC(
  343. AddrOnNonPointerType, Error,
  344. "`addr` can only be applied to a binding with a pointer type");
  345. context.emitter().Emit(node_id, AddrOnNonPointerType);
  346. context.node_stack().Push(node_id, param_pattern_id);
  347. }
  348. } else {
  349. CARBON_DIAGNOSTIC(AddrOnNonSelfParam, Error,
  350. "`addr` can only be applied to a `self` parameter");
  351. context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
  352. AddrOnNonSelfParam);
  353. context.node_stack().Push(node_id, param_pattern_id);
  354. }
  355. return true;
  356. }
  357. auto HandleParseNode(Context& context, Parse::TemplateBindingNameId node_id)
  358. -> bool {
  359. context.node_stack().Push(node_id);
  360. return true;
  361. }
  362. } // namespace Carbon::Check