handle_name.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. std::string);
  114. return context.emitter().Build(
  115. base_id, IncompleteTypeInMemberAccess,
  116. context.sem_ir().StringifyType(base_type_id));
  117. })) {
  118. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  119. return true;
  120. }
  121. // Materialize a temporary for the base expression if necessary.
  122. base_id = ConvertToValueOrRefExpr(context, base_id);
  123. base_type_id = context.insts().Get(base_id).type_id();
  124. switch (auto base_type = context.types().GetAsInst(base_type_id);
  125. base_type.kind()) {
  126. case SemIR::ClassType::Kind: {
  127. // Perform lookup for the name in the class scope.
  128. auto class_scope_id = context.classes()
  129. .Get(base_type.As<SemIR::ClassType>().class_id)
  130. .scope_id;
  131. auto member_id =
  132. context.LookupQualifiedName(parse_node, name_id, class_scope_id);
  133. member_id = GetExprValueForLookupResult(context, member_id);
  134. // Perform instance binding if we found an instance member.
  135. auto member_type_id = context.insts().Get(member_id).type_id();
  136. if (auto unbound_element_type =
  137. context.types().TryGetAs<SemIR::UnboundElementType>(
  138. member_type_id)) {
  139. // Convert the base to the type of the element if necessary.
  140. base_id = ConvertToValueOrRefOfType(
  141. context, parse_node, base_id, unbound_element_type->class_type_id);
  142. // Find the specified element, which could be either a field or a base
  143. // class, and build an element access expression.
  144. auto element_id = context.constant_values().Get(member_id);
  145. CARBON_CHECK(element_id.is_constant())
  146. << "Non-constant value " << context.insts().Get(member_id)
  147. << " of unbound element type";
  148. auto index = GetClassElementIndex(context, element_id.inst_id());
  149. auto access_id = context.AddInst(
  150. {parse_node,
  151. SemIR::ClassElementAccess{unbound_element_type->element_type_id,
  152. base_id, index}});
  153. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  154. SemIR::ExprCategory::Value &&
  155. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  156. SemIR::ExprCategory::Value) {
  157. // Class element access on a value expression produces an
  158. // ephemeral reference if the class's value representation is a
  159. // pointer to the object representation. Add a value binding in
  160. // that case so that the expression category of the result
  161. // matches the expression category of the base.
  162. access_id = ConvertToValueExpr(context, access_id);
  163. }
  164. context.node_stack().Push(parse_node, access_id);
  165. return true;
  166. }
  167. if (member_type_id ==
  168. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType)) {
  169. // Find the named function and check whether it's an instance method.
  170. auto function_name_id = context.constant_values().Get(member_id);
  171. CARBON_CHECK(function_name_id.is_constant())
  172. << "Non-constant value " << context.insts().Get(member_id)
  173. << " of function type";
  174. auto function_decl = context.insts()
  175. .Get(function_name_id.inst_id())
  176. .TryAs<SemIR::FunctionDecl>();
  177. CARBON_CHECK(function_decl)
  178. << "Unexpected value "
  179. << context.insts().Get(function_name_id.inst_id())
  180. << " of function type";
  181. if (IsInstanceMethod(context.sem_ir(), function_decl->function_id)) {
  182. context.AddInstAndPush(
  183. {parse_node,
  184. SemIR::BoundMethod{
  185. context.GetBuiltinType(SemIR::BuiltinKind::BoundMethodType),
  186. base_id, member_id}});
  187. return true;
  188. }
  189. }
  190. // For a non-instance member, the result is that member.
  191. // TODO: Track that this was named within `base_id`.
  192. context.AddInstAndPush(
  193. {parse_node, SemIR::NameRef{member_type_id, name_id, member_id}});
  194. return true;
  195. }
  196. case SemIR::StructType::Kind: {
  197. auto refs = context.inst_blocks().Get(
  198. base_type.As<SemIR::StructType>().fields_id);
  199. // TODO: Do we need to optimize this with a lookup table for O(1)?
  200. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  201. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  202. if (name_id == field.name_id) {
  203. context.AddInstAndPush(
  204. {parse_node, SemIR::StructAccess{field.field_type_id, base_id,
  205. SemIR::ElementIndex(i)}});
  206. return true;
  207. }
  208. }
  209. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  210. "Type `{0}` does not have a member `{1}`.", std::string,
  211. std::string);
  212. context.emitter().Emit(parse_node, QualifiedExprNameNotFound,
  213. context.sem_ir().StringifyType(base_type_id),
  214. context.names().GetFormatted(name_id).str());
  215. break;
  216. }
  217. // TODO: `ConstType` should support member access just like the
  218. // corresponding non-const type, except that the result should have `const`
  219. // type if it creates a reference expression performing field access.
  220. default: {
  221. if (base_type_id != SemIR::TypeId::Error) {
  222. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  223. "Type `{0}` does not support qualified expressions.",
  224. std::string);
  225. context.emitter().Emit(parse_node, QualifiedExprUnsupported,
  226. context.sem_ir().StringifyType(base_type_id));
  227. }
  228. break;
  229. }
  230. }
  231. // Should only be reached on error.
  232. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  233. return true;
  234. }
  235. auto HandlePointerMemberAccessExpr(Context& context,
  236. Parse::PointerMemberAccessExprId parse_node)
  237. -> bool {
  238. return context.TODO(parse_node, "HandlePointerMemberAccessExpr");
  239. }
  240. static auto GetIdentifierAsName(Context& context, Parse::NodeId parse_node)
  241. -> std::optional<SemIR::NameId> {
  242. auto token = context.parse_tree().node_token(parse_node);
  243. if (context.tokens().GetKind(token) != Lex::TokenKind::Identifier) {
  244. CARBON_CHECK(context.parse_tree().node_has_error(parse_node));
  245. return std::nullopt;
  246. }
  247. return SemIR::NameId::ForIdentifier(context.tokens().GetIdentifier(token));
  248. }
  249. // Handle a name that is used as an expression by performing unqualified name
  250. // lookup.
  251. static auto HandleNameAsExpr(Context& context, Parse::NodeId parse_node,
  252. SemIR::NameId name_id) -> bool {
  253. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  254. value_id = GetExprValueForLookupResult(context, value_id);
  255. auto value = context.insts().Get(value_id);
  256. context.AddInstAndPush(
  257. {parse_node, SemIR::NameRef{value.type_id(), name_id, value_id}});
  258. return true;
  259. }
  260. auto HandleIdentifierName(Context& context, Parse::IdentifierNameId parse_node)
  261. -> bool {
  262. // The parent is responsible for binding the name.
  263. auto name_id = GetIdentifierAsName(context, parse_node);
  264. if (!name_id) {
  265. return context.TODO(parse_node, "Error recovery from keyword name.");
  266. }
  267. context.node_stack().Push(parse_node, *name_id);
  268. return true;
  269. }
  270. auto HandleIdentifierNameExpr(Context& context,
  271. Parse::IdentifierNameExprId parse_node) -> bool {
  272. auto name_id = GetIdentifierAsName(context, parse_node);
  273. if (!name_id) {
  274. return context.TODO(parse_node, "Error recovery from keyword name.");
  275. }
  276. return HandleNameAsExpr(context, parse_node, *name_id);
  277. }
  278. auto HandleBaseName(Context& context, Parse::BaseNameId parse_node) -> bool {
  279. context.node_stack().Push(parse_node, SemIR::NameId::Base);
  280. return true;
  281. }
  282. auto HandleSelfTypeNameExpr(Context& context,
  283. Parse::SelfTypeNameExprId parse_node) -> bool {
  284. return HandleNameAsExpr(context, parse_node, SemIR::NameId::SelfType);
  285. }
  286. auto HandleSelfValueName(Context& context, Parse::SelfValueNameId parse_node)
  287. -> bool {
  288. context.node_stack().Push(parse_node, SemIR::NameId::SelfValue);
  289. return true;
  290. }
  291. auto HandleSelfValueNameExpr(Context& context,
  292. Parse::SelfValueNameExprId parse_node) -> bool {
  293. return HandleNameAsExpr(context, parse_node, SemIR::NameId::SelfValue);
  294. }
  295. auto HandleQualifiedName(Context& context, Parse::QualifiedNameId parse_node)
  296. -> bool {
  297. auto [parse_node2, name_id2] = context.node_stack().PopNameWithParseNode();
  298. Parse::NodeId parse_node1 = context.node_stack().PeekParseNode();
  299. switch (context.parse_tree().node_kind(parse_node1)) {
  300. case Parse::NodeKind::QualifiedName:
  301. // This is the second or subsequent QualifiedName in a chain.
  302. // Nothing to do: the first QualifiedName remains as a
  303. // bracketing node for later QualifiedNames.
  304. break;
  305. case Parse::NodeKind::IdentifierName: {
  306. // This is the first QualifiedName in a chain, and starts with an
  307. // identifier name.
  308. auto name_id =
  309. context.node_stack().Pop<Parse::NodeKind::IdentifierName>();
  310. context.decl_name_stack().ApplyNameQualifier(parse_node1, name_id);
  311. // Add the QualifiedName so that it can be used for bracketing.
  312. context.node_stack().Push(parse_node);
  313. break;
  314. }
  315. default:
  316. CARBON_FATAL() << "Unexpected node kind on left side of qualified "
  317. "declaration name";
  318. }
  319. context.decl_name_stack().ApplyNameQualifier(parse_node2, name_id2);
  320. return true;
  321. }
  322. auto HandlePackageExpr(Context& context, Parse::PackageExprId parse_node)
  323. -> bool {
  324. context.AddInstAndPush(
  325. {parse_node,
  326. SemIR::NameRef{context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType),
  327. SemIR::NameId::PackageNamespace,
  328. SemIR::InstId::PackageNamespace}});
  329. return true;
  330. }
  331. } // namespace Carbon::Check