handle_name.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 = context.emitter().Build(
  26. context.insts().Get(base_id).parse_node(),
  27. QualifiedExprInIncompleteClassScope,
  28. context.sem_ir().StringifyTypeExpr(base_id, true));
  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. auto HandleMemberAccessExpr(Context& context, Parse::NodeId parse_node)
  53. -> bool {
  54. SemIR::NameId name_id = context.node_stack().Pop<Parse::NodeKind::Name>();
  55. auto base_id = context.node_stack().PopExpr();
  56. // If the base is a name scope, such as a class or namespace, perform lookup
  57. // into that scope.
  58. if (auto name_scope_id = GetAsNameScope(context, base_id)) {
  59. auto inst_id =
  60. name_scope_id->is_valid()
  61. ? context.LookupQualifiedName(parse_node, name_id, *name_scope_id)
  62. : SemIR::InstId::BuiltinError;
  63. inst_id = GetExprValueForLookupResult(context, inst_id);
  64. auto inst = context.insts().Get(inst_id);
  65. // TODO: Track that this instruction was named within `base_id`.
  66. context.AddInstAndPush(
  67. parse_node,
  68. SemIR::NameRef{parse_node, inst.type_id(), name_id, inst_id});
  69. return true;
  70. }
  71. // If the base isn't a scope, it must have a complete type.
  72. auto base_type_id = context.insts().Get(base_id).type_id();
  73. if (!context.TryToCompleteType(base_type_id, [&] {
  74. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  75. "Member access into object of incomplete type `{0}`.",
  76. std::string);
  77. return context.emitter().Build(
  78. context.insts().Get(base_id).parse_node(),
  79. IncompleteTypeInMemberAccess,
  80. context.sem_ir().StringifyType(base_type_id, true));
  81. })) {
  82. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  83. return true;
  84. }
  85. // Materialize a temporary for the base expression if necessary.
  86. base_id = ConvertToValueOrRefExpr(context, base_id);
  87. base_type_id = context.insts().Get(base_id).type_id();
  88. auto base_type = context.insts().Get(
  89. context.sem_ir().GetTypeAllowBuiltinTypes(base_type_id));
  90. switch (base_type.kind()) {
  91. case SemIR::ClassType::Kind: {
  92. // Perform lookup for the name in the class scope.
  93. auto class_scope_id = context.classes()
  94. .Get(base_type.As<SemIR::ClassType>().class_id)
  95. .scope_id;
  96. auto member_id =
  97. context.LookupQualifiedName(parse_node, name_id, class_scope_id);
  98. member_id = GetExprValueForLookupResult(context, member_id);
  99. // Perform instance binding if we found an instance member.
  100. auto member_type_id = context.insts().Get(member_id).type_id();
  101. auto member_type_inst = context.insts().Get(
  102. context.sem_ir().GetTypeAllowBuiltinTypes(member_type_id));
  103. if (auto unbound_field_type =
  104. member_type_inst.TryAs<SemIR::UnboundElementType>()) {
  105. // TODO: Check that the unbound field type describes a member of this
  106. // class. Perform a conversion of the base if necessary.
  107. // Find the named field and build a field access expression.
  108. auto field_id = context.GetConstantValue(member_id);
  109. CARBON_CHECK(field_id.is_valid())
  110. << "Non-constant value " << context.insts().Get(member_id)
  111. << " of unbound field type";
  112. auto field = context.insts().Get(field_id).TryAs<SemIR::Field>();
  113. CARBON_CHECK(field)
  114. << "Unexpected value " << context.insts().Get(field_id)
  115. << " for field name expression";
  116. auto access_id = context.AddInst(SemIR::ClassElementAccess{
  117. parse_node, unbound_field_type->element_type_id, base_id,
  118. field->index});
  119. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  120. SemIR::ExprCategory::Value &&
  121. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  122. SemIR::ExprCategory::Value) {
  123. // Class field access on a value expression produces an ephemeral
  124. // reference if the class's value representation is a pointer to the
  125. // object representation. Add a value binding in that case so that the
  126. // expression category of the result matches the expression category
  127. // of the base.
  128. access_id = ConvertToValueExpr(context, access_id);
  129. }
  130. context.node_stack().Push(parse_node, access_id);
  131. return true;
  132. }
  133. if (member_type_id ==
  134. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType)) {
  135. // Find the named function and check whether it's an instance method.
  136. auto function_name_id = context.GetConstantValue(member_id);
  137. CARBON_CHECK(function_name_id.is_valid())
  138. << "Non-constant value " << context.insts().Get(member_id)
  139. << " of function type";
  140. auto function_decl =
  141. context.insts().Get(function_name_id).TryAs<SemIR::FunctionDecl>();
  142. CARBON_CHECK(function_decl)
  143. << "Unexpected value " << context.insts().Get(function_name_id)
  144. << " of function type";
  145. auto& function = context.functions().Get(function_decl->function_id);
  146. for (auto param_id :
  147. context.inst_blocks().Get(function.implicit_param_refs_id)) {
  148. if (context.insts().Get(param_id).Is<SemIR::SelfParam>()) {
  149. context.AddInstAndPush(
  150. parse_node,
  151. SemIR::BoundMethod{
  152. parse_node,
  153. context.GetBuiltinType(SemIR::BuiltinKind::BoundMethodType),
  154. base_id, member_id});
  155. return true;
  156. }
  157. }
  158. }
  159. // For a non-instance member, the result is that member.
  160. // TODO: Track that this was named within `base_id`.
  161. context.AddInstAndPush(
  162. parse_node,
  163. SemIR::NameRef{parse_node, member_type_id, name_id, member_id});
  164. return true;
  165. }
  166. case SemIR::StructType::Kind: {
  167. auto refs = context.inst_blocks().Get(
  168. base_type.As<SemIR::StructType>().fields_id);
  169. // TODO: Do we need to optimize this with a lookup table for O(1)?
  170. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  171. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  172. if (name_id == field.name_id) {
  173. context.AddInstAndPush(
  174. parse_node, SemIR::StructAccess{parse_node, field.field_type_id,
  175. base_id, SemIR::ElementIndex(i)});
  176. return true;
  177. }
  178. }
  179. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  180. "Type `{0}` does not have a member `{1}`.", std::string,
  181. std::string);
  182. context.emitter().Emit(parse_node, QualifiedExprNameNotFound,
  183. context.sem_ir().StringifyType(base_type_id),
  184. context.names().GetFormatted(name_id).str());
  185. break;
  186. }
  187. // TODO: `ConstType` should support member access just like the
  188. // corresponding non-const type, except that the result should have `const`
  189. // type if it creates a reference expression performing field access.
  190. default: {
  191. if (base_type_id != SemIR::TypeId::Error) {
  192. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  193. "Type `{0}` does not support qualified expressions.",
  194. std::string);
  195. context.emitter().Emit(parse_node, QualifiedExprUnsupported,
  196. context.sem_ir().StringifyType(base_type_id));
  197. }
  198. break;
  199. }
  200. }
  201. // Should only be reached on error.
  202. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  203. return true;
  204. }
  205. auto HandlePointerMemberAccessExpr(Context& context, Parse::NodeId parse_node)
  206. -> bool {
  207. return context.TODO(parse_node, "HandlePointerMemberAccessExpr");
  208. }
  209. auto HandleName(Context& context, Parse::NodeId parse_node) -> bool {
  210. auto name_id = SemIR::NameId::ForIdentifier(context.tokens().GetIdentifier(
  211. context.parse_tree().node_token(parse_node)));
  212. // The parent is responsible for binding the name.
  213. context.node_stack().Push(parse_node, name_id);
  214. return true;
  215. }
  216. auto HandleNameExpr(Context& context, Parse::NodeId parse_node) -> bool {
  217. auto name_id = SemIR::NameId::ForIdentifier(context.tokens().GetIdentifier(
  218. context.parse_tree().node_token(parse_node)));
  219. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  220. value_id = GetExprValueForLookupResult(context, value_id);
  221. auto value = context.insts().Get(value_id);
  222. context.AddInstAndPush(parse_node, SemIR::NameRef{parse_node, value.type_id(),
  223. name_id, value_id});
  224. return true;
  225. }
  226. auto HandleQualifiedDecl(Context& context, Parse::NodeId parse_node) -> bool {
  227. auto [parse_node2, name_id2] =
  228. context.node_stack().PopWithParseNode<Parse::NodeKind::Name>();
  229. Parse::NodeId parse_node1 = context.node_stack().PeekParseNode();
  230. switch (context.parse_tree().node_kind(parse_node1)) {
  231. case Parse::NodeKind::QualifiedDecl:
  232. // This is the second or subsequent QualifiedDecl in a chain.
  233. // Nothing to do: the first QualifiedDecl remains as a
  234. // bracketing node for later QualifiedDecls.
  235. break;
  236. case Parse::NodeKind::Name: {
  237. // This is the first QualifiedDecl in a chain, and starts with a
  238. // name.
  239. auto name_id = context.node_stack().Pop<Parse::NodeKind::Name>();
  240. context.decl_name_stack().ApplyNameQualifier(parse_node1, name_id);
  241. // Add the QualifiedDecl so that it can be used for bracketing.
  242. context.node_stack().Push(parse_node);
  243. break;
  244. }
  245. default:
  246. CARBON_FATAL() << "Unexpected node kind on left side of qualified "
  247. "declaration name";
  248. }
  249. context.decl_name_stack().ApplyNameQualifier(parse_node2, name_id2);
  250. return true;
  251. }
  252. auto HandlePackageExpr(Context& context, Parse::NodeId parse_node) -> bool {
  253. context.AddInstAndPush(
  254. parse_node,
  255. SemIR::NameRef{
  256. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType),
  257. SemIR::NameId::PackageNamespace, SemIR::InstId::PackageNamespace});
  258. return true;
  259. }
  260. auto HandleSelfTypeNameExpr(Context& context, Parse::NodeId parse_node)
  261. -> bool {
  262. auto name_id = SemIR::NameId::SelfType;
  263. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  264. auto value = context.insts().Get(value_id);
  265. context.AddInstAndPush(parse_node, SemIR::NameRef{parse_node, value.type_id(),
  266. name_id, value_id});
  267. return true;
  268. }
  269. auto HandleSelfValueName(Context& context, Parse::NodeId parse_node) -> bool {
  270. context.node_stack().Push(parse_node);
  271. return true;
  272. }
  273. auto HandleSelfValueNameExpr(Context& context, Parse::NodeId parse_node)
  274. -> bool {
  275. auto name_id = SemIR::NameId::SelfValue;
  276. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  277. auto value = context.insts().Get(value_id);
  278. context.AddInstAndPush(parse_node, SemIR::NameRef{parse_node, value.type_id(),
  279. name_id, value_id});
  280. return true;
  281. }
  282. } // namespace Carbon::Check