handle_name.cpp 13 KB

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