handle_name.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 "llvm/ADT/STLExtras.h"
  5. #include "toolchain/check/context.h"
  6. #include "toolchain/check/convert.h"
  7. #include "toolchain/check/eval.h"
  8. #include "toolchain/lex/token_kind.h"
  9. #include "toolchain/sem_ir/inst.h"
  10. #include "toolchain/sem_ir/typed_insts.h"
  11. namespace Carbon::Check {
  12. // Returns the name scope corresponding to base_id, or nullopt if not a scope.
  13. // On invalid scopes, prints a diagnostic and still returns the scope.
  14. static auto GetAsNameScope(Context& context, SemIR::InstId base_id)
  15. -> std::optional<SemIR::NameScopeId> {
  16. auto base_const_id = context.constant_values().Get(base_id);
  17. if (!base_const_id.is_constant()) {
  18. // A name scope must be a constant.
  19. return std::nullopt;
  20. }
  21. auto base = context.insts().Get(base_const_id.inst_id());
  22. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  23. return base_as_namespace->name_scope_id;
  24. }
  25. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  26. auto& class_info = context.classes().Get(base_as_class->class_id);
  27. if (!class_info.is_defined()) {
  28. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  29. "Member access into incomplete class `{0}`.",
  30. std::string);
  31. auto builder =
  32. context.emitter().Build(base_id, QualifiedExprInIncompleteClassScope,
  33. context.sem_ir().StringifyTypeExpr(base_id));
  34. context.NoteIncompleteClass(base_as_class->class_id, builder);
  35. builder.Emit();
  36. }
  37. return class_info.scope_id;
  38. }
  39. return std::nullopt;
  40. }
  41. // Given an instruction produced by a name lookup, get the value to use for that
  42. // result in an expression.
  43. static auto GetExprValueForLookupResult(Context& context,
  44. SemIR::InstId lookup_result_id)
  45. -> SemIR::InstId {
  46. // If lookup finds a class declaration, the value is its `Self` type.
  47. auto lookup_result = context.insts().Get(lookup_result_id);
  48. if (auto class_decl = lookup_result.TryAs<SemIR::ClassDecl>()) {
  49. return context.types().GetInstId(
  50. context.classes().Get(class_decl->class_id).self_type_id);
  51. }
  52. if (auto interface_decl = lookup_result.TryAs<SemIR::InterfaceDecl>()) {
  53. return TryEvalInst(context, SemIR::InstId::Invalid,
  54. SemIR::InterfaceType{SemIR::TypeId::TypeType,
  55. interface_decl->interface_id})
  56. .inst_id();
  57. }
  58. // Anything else should be a typed value already.
  59. CARBON_CHECK(lookup_result.kind().value_kind() == SemIR::InstValueKind::Typed)
  60. << "Unexpected kind for lookup result, " << lookup_result;
  61. return lookup_result_id;
  62. }
  63. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  64. -> SemIR::ElementIndex {
  65. auto element_inst = context.insts().Get(element_id);
  66. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  67. return field->index;
  68. }
  69. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  70. return base->index;
  71. }
  72. CARBON_FATAL() << "Unexpected value " << element_inst
  73. << " in class element name";
  74. }
  75. // Returns whether `function_id` is an instance method, that is, whether it has
  76. // an implicit `self` parameter.
  77. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  78. SemIR::FunctionId function_id) -> bool {
  79. const auto& function = sem_ir.functions().Get(function_id);
  80. for (auto param_id :
  81. sem_ir.inst_blocks().Get(function.implicit_param_refs_id)) {
  82. auto param =
  83. SemIR::Function::GetParamFromParamRefId(sem_ir, param_id).second;
  84. if (param.name_id == SemIR::NameId::SelfValue) {
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. auto HandleMemberAccessExpr(Context& context,
  91. Parse::MemberAccessExprId parse_node) -> bool {
  92. SemIR::NameId name_id = context.node_stack().PopName();
  93. auto base_id = context.node_stack().PopExpr();
  94. // If the base is a name scope, such as a class or namespace, perform lookup
  95. // into that scope.
  96. if (auto name_scope_id = GetAsNameScope(context, base_id)) {
  97. auto inst_id =
  98. name_scope_id->is_valid()
  99. ? context.LookupQualifiedName(parse_node, name_id, *name_scope_id)
  100. : SemIR::InstId::BuiltinError;
  101. inst_id = GetExprValueForLookupResult(context, inst_id);
  102. auto inst = context.insts().Get(inst_id);
  103. // TODO: Track that this instruction was named within `base_id`.
  104. context.AddInstAndPush(
  105. {parse_node, SemIR::NameRef{inst.type_id(), name_id, inst_id}});
  106. return true;
  107. }
  108. // If the base isn't a scope, it must have a complete type.
  109. auto base_type_id = context.insts().Get(base_id).type_id();
  110. if (!context.TryToCompleteType(base_type_id, [&] {
  111. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  112. "Member access into object of incomplete type `{0}`.",
  113. SemIR::TypeId);
  114. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  115. base_type_id);
  116. })) {
  117. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  118. return true;
  119. }
  120. // Materialize a temporary for the base expression if necessary.
  121. base_id = ConvertToValueOrRefExpr(context, base_id);
  122. base_type_id = context.insts().Get(base_id).type_id();
  123. switch (auto base_type = context.types().GetAsInst(base_type_id);
  124. base_type.kind()) {
  125. case SemIR::ClassType::Kind: {
  126. // Perform lookup for the name in the class scope.
  127. auto class_scope_id = context.classes()
  128. .Get(base_type.As<SemIR::ClassType>().class_id)
  129. .scope_id;
  130. auto member_id =
  131. context.LookupQualifiedName(parse_node, name_id, class_scope_id);
  132. member_id = GetExprValueForLookupResult(context, member_id);
  133. // Perform instance binding if we found an instance member.
  134. auto member_type_id = context.insts().Get(member_id).type_id();
  135. if (auto unbound_element_type =
  136. context.types().TryGetAs<SemIR::UnboundElementType>(
  137. member_type_id)) {
  138. // Convert the base to the type of the element if necessary.
  139. base_id = ConvertToValueOrRefOfType(
  140. context, parse_node, base_id, unbound_element_type->class_type_id);
  141. // Find the specified element, which could be either a field or a base
  142. // class, and build an element access expression.
  143. auto element_id = context.constant_values().Get(member_id);
  144. CARBON_CHECK(element_id.is_constant())
  145. << "Non-constant value " << context.insts().Get(member_id)
  146. << " of unbound element type";
  147. auto index = GetClassElementIndex(context, element_id.inst_id());
  148. auto access_id = context.AddInst(
  149. {parse_node,
  150. SemIR::ClassElementAccess{unbound_element_type->element_type_id,
  151. base_id, index}});
  152. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  153. SemIR::ExprCategory::Value &&
  154. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  155. SemIR::ExprCategory::Value) {
  156. // Class element access on a value expression produces an
  157. // ephemeral reference if the class's value representation is a
  158. // pointer to the object representation. Add a value binding in
  159. // that case so that the expression category of the result
  160. // matches the expression category of the base.
  161. access_id = ConvertToValueExpr(context, access_id);
  162. }
  163. context.node_stack().Push(parse_node, access_id);
  164. return true;
  165. }
  166. if (member_type_id ==
  167. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType)) {
  168. // Find the named function and check whether it's an instance method.
  169. auto function_name_id = context.constant_values().Get(member_id);
  170. CARBON_CHECK(function_name_id.is_constant())
  171. << "Non-constant value " << context.insts().Get(member_id)
  172. << " of function type";
  173. auto function_decl = context.insts()
  174. .Get(function_name_id.inst_id())
  175. .TryAs<SemIR::FunctionDecl>();
  176. CARBON_CHECK(function_decl)
  177. << "Unexpected value "
  178. << context.insts().Get(function_name_id.inst_id())
  179. << " of function type";
  180. if (IsInstanceMethod(context.sem_ir(), function_decl->function_id)) {
  181. context.AddInstAndPush(
  182. {parse_node,
  183. SemIR::BoundMethod{
  184. context.GetBuiltinType(SemIR::BuiltinKind::BoundMethodType),
  185. base_id, member_id}});
  186. return true;
  187. }
  188. }
  189. // For a non-instance member, the result is that member.
  190. // TODO: Track that this was named within `base_id`.
  191. context.AddInstAndPush(
  192. {parse_node, SemIR::NameRef{member_type_id, name_id, member_id}});
  193. return true;
  194. }
  195. case SemIR::StructType::Kind: {
  196. auto refs = context.inst_blocks().Get(
  197. base_type.As<SemIR::StructType>().fields_id);
  198. // TODO: Do we need to optimize this with a lookup table for O(1)?
  199. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  200. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  201. if (name_id == field.name_id) {
  202. context.AddInstAndPush(
  203. {parse_node, SemIR::StructAccess{field.field_type_id, base_id,
  204. SemIR::ElementIndex(i)}});
  205. return true;
  206. }
  207. }
  208. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  209. "Type `{0}` does not have a member `{1}`.",
  210. SemIR::TypeId, std::string);
  211. context.emitter().Emit(parse_node, QualifiedExprNameNotFound,
  212. base_type_id,
  213. context.names().GetFormatted(name_id).str());
  214. break;
  215. }
  216. // TODO: `ConstType` should support member access just like the
  217. // corresponding non-const type, except that the result should have `const`
  218. // type if it creates a reference expression performing field access.
  219. default: {
  220. if (base_type_id != SemIR::TypeId::Error) {
  221. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  222. "Type `{0}` does not support qualified expressions.",
  223. SemIR::TypeId);
  224. context.emitter().Emit(parse_node, QualifiedExprUnsupported,
  225. base_type_id);
  226. }
  227. break;
  228. }
  229. }
  230. // Should only be reached on error.
  231. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  232. return true;
  233. }
  234. auto HandlePointerMemberAccessExpr(Context& context,
  235. Parse::PointerMemberAccessExprId parse_node)
  236. -> bool {
  237. return context.TODO(parse_node, "HandlePointerMemberAccessExpr");
  238. }
  239. static auto GetIdentifierAsName(Context& context, Parse::NodeId parse_node)
  240. -> std::optional<SemIR::NameId> {
  241. auto token = context.parse_tree().node_token(parse_node);
  242. if (context.tokens().GetKind(token) != Lex::TokenKind::Identifier) {
  243. CARBON_CHECK(context.parse_tree().node_has_error(parse_node));
  244. return std::nullopt;
  245. }
  246. return SemIR::NameId::ForIdentifier(context.tokens().GetIdentifier(token));
  247. }
  248. // Handle a name that is used as an expression by performing unqualified name
  249. // lookup.
  250. static auto HandleNameAsExpr(Context& context, Parse::NodeId parse_node,
  251. SemIR::NameId name_id) -> bool {
  252. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  253. value_id = GetExprValueForLookupResult(context, value_id);
  254. auto value = context.insts().Get(value_id);
  255. context.AddInstAndPush(
  256. {parse_node, SemIR::NameRef{value.type_id(), name_id, value_id}});
  257. return true;
  258. }
  259. auto HandleIdentifierName(Context& context, Parse::IdentifierNameId parse_node)
  260. -> bool {
  261. // The parent is responsible for binding the name.
  262. auto name_id = GetIdentifierAsName(context, parse_node);
  263. if (!name_id) {
  264. return context.TODO(parse_node, "Error recovery from keyword name.");
  265. }
  266. context.node_stack().Push(parse_node, *name_id);
  267. return true;
  268. }
  269. auto HandleIdentifierNameExpr(Context& context,
  270. Parse::IdentifierNameExprId parse_node) -> bool {
  271. auto name_id = GetIdentifierAsName(context, parse_node);
  272. if (!name_id) {
  273. return context.TODO(parse_node, "Error recovery from keyword name.");
  274. }
  275. return HandleNameAsExpr(context, parse_node, *name_id);
  276. }
  277. auto HandleBaseName(Context& context, Parse::BaseNameId parse_node) -> bool {
  278. context.node_stack().Push(parse_node, SemIR::NameId::Base);
  279. return true;
  280. }
  281. auto HandleSelfTypeNameExpr(Context& context,
  282. Parse::SelfTypeNameExprId parse_node) -> bool {
  283. return HandleNameAsExpr(context, parse_node, SemIR::NameId::SelfType);
  284. }
  285. auto HandleSelfValueName(Context& context, Parse::SelfValueNameId parse_node)
  286. -> bool {
  287. context.node_stack().Push(parse_node, SemIR::NameId::SelfValue);
  288. return true;
  289. }
  290. auto HandleSelfValueNameExpr(Context& context,
  291. Parse::SelfValueNameExprId parse_node) -> bool {
  292. return HandleNameAsExpr(context, parse_node, SemIR::NameId::SelfValue);
  293. }
  294. auto HandleQualifiedName(Context& context, Parse::QualifiedNameId parse_node)
  295. -> bool {
  296. auto [parse_node2, name_id2] = context.node_stack().PopNameWithParseNode();
  297. Parse::NodeId parse_node1 = context.node_stack().PeekParseNode();
  298. switch (context.parse_tree().node_kind(parse_node1)) {
  299. case Parse::NodeKind::QualifiedName:
  300. // This is the second or subsequent QualifiedName in a chain.
  301. // Nothing to do: the first QualifiedName remains as a
  302. // bracketing node for later QualifiedNames.
  303. break;
  304. case Parse::NodeKind::IdentifierName: {
  305. // This is the first QualifiedName in a chain, and starts with an
  306. // identifier name.
  307. auto name_id =
  308. context.node_stack().Pop<Parse::NodeKind::IdentifierName>();
  309. context.decl_name_stack().ApplyNameQualifier(parse_node1, name_id);
  310. // Add the QualifiedName so that it can be used for bracketing.
  311. context.node_stack().Push(parse_node);
  312. break;
  313. }
  314. default:
  315. CARBON_FATAL() << "Unexpected node kind on left side of qualified "
  316. "declaration name";
  317. }
  318. context.decl_name_stack().ApplyNameQualifier(parse_node2, name_id2);
  319. return true;
  320. }
  321. auto HandlePackageExpr(Context& context, Parse::PackageExprId parse_node)
  322. -> bool {
  323. context.AddInstAndPush(
  324. {parse_node,
  325. SemIR::NameRef{context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType),
  326. SemIR::NameId::PackageNamespace,
  327. SemIR::InstId::PackageNamespace}});
  328. return true;
  329. }
  330. } // namespace Carbon::Check