handle_name.cpp 14 KB

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