handle_name.cpp 13 KB

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