handle_binding_pattern.cpp 16 KB

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