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