handle_name.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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(QualifiedExpressionInIncompleteClassScope, 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. QualifiedExpressionInIncompleteClassScope,
  27. context.sem_ir().StringifyTypeExpression(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 GetExpressionValueForLookupResult(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::ClassDeclaration>()) {
  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 HandleMemberAccessExpression(Context& context, Parse::Node parse_node)
  52. -> bool {
  53. IdentifierId name_id = context.node_stack().Pop<Parse::NodeKind::Name>();
  54. auto base_id = context.node_stack().PopExpression();
  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 = GetExpressionValueForLookupResult(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::NameReference{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 = ConvertToValueOrReferenceExpression(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 = GetExpressionValueForLookupResult(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::UnboundFieldType>()) {
  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::ClassFieldAccess{
  116. parse_node, unbound_field_type->field_type_id, base_id,
  117. field->index});
  118. if (SemIR::GetExpressionCategory(context.sem_ir(), base_id) ==
  119. SemIR::ExpressionCategory::Value &&
  120. SemIR::GetExpressionCategory(context.sem_ir(), access_id) !=
  121. SemIR::ExpressionCategory::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 = ConvertToValueExpression(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 = context.insts()
  140. .Get(function_name_id)
  141. .TryAs<SemIR::FunctionDeclaration>();
  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::SelfParameter>()) {
  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::NameReference{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::MemberIndex(i)});
  176. return true;
  177. }
  178. }
  179. CARBON_DIAGNOSTIC(QualifiedExpressionNameNotFound, Error,
  180. "Type `{0}` does not have a member `{1}`.", std::string,
  181. llvm::StringRef);
  182. context.emitter().Emit(parse_node, QualifiedExpressionNameNotFound,
  183. context.sem_ir().StringifyType(base_type_id),
  184. context.identifiers().Get(name_id));
  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(QualifiedExpressionUnsupported, Error,
  193. "Type `{0}` does not support qualified expressions.",
  194. std::string);
  195. context.emitter().Emit(parse_node, QualifiedExpressionUnsupported,
  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 HandlePointerMemberAccessExpression(Context& context,
  206. Parse::Node parse_node) -> bool {
  207. return context.TODO(parse_node, "HandlePointerMemberAccessExpression");
  208. }
  209. auto HandleName(Context& context, Parse::Node parse_node) -> bool {
  210. auto name_id = 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 HandleNameExpression(Context& context, Parse::Node parse_node) -> bool {
  217. auto name_id = context.tokens().GetIdentifier(
  218. context.parse_tree().node_token(parse_node));
  219. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  220. value_id = GetExpressionValueForLookupResult(context, value_id);
  221. auto value = context.insts().Get(value_id);
  222. context.AddInstAndPush(
  223. parse_node,
  224. SemIR::NameReference{parse_node, value.type_id(), name_id, value_id});
  225. return true;
  226. }
  227. auto HandleQualifiedDeclaration(Context& context, Parse::Node parse_node)
  228. -> bool {
  229. auto [parse_node2, name_id2] =
  230. context.node_stack().PopWithParseNode<Parse::NodeKind::Name>();
  231. Parse::Node parse_node1 = context.node_stack().PeekParseNode();
  232. switch (context.parse_tree().node_kind(parse_node1)) {
  233. case Parse::NodeKind::QualifiedDeclaration:
  234. // This is the second or subsequent QualifiedDeclaration in a chain.
  235. // Nothing to do: the first QualifiedDeclaration remains as a
  236. // bracketing node for later QualifiedDeclarations.
  237. break;
  238. case Parse::NodeKind::Name: {
  239. // This is the first QualifiedDeclaration in a chain, and starts with a
  240. // name.
  241. auto name_id = context.node_stack().Pop<Parse::NodeKind::Name>();
  242. context.declaration_name_stack().ApplyNameQualifier(parse_node1, name_id);
  243. // Add the QualifiedDeclaration so that it can be used for bracketing.
  244. context.node_stack().Push(parse_node);
  245. break;
  246. }
  247. default:
  248. CARBON_FATAL() << "Unexpected node kind on left side of qualified "
  249. "declaration name";
  250. }
  251. context.declaration_name_stack().ApplyNameQualifier(parse_node2, name_id2);
  252. return true;
  253. }
  254. auto HandleSelfTypeNameExpression(Context& context, Parse::Node parse_node)
  255. -> bool {
  256. // TODO: This will find a local variable declared with name `r#Self`, but
  257. // should not. See #2984 and the corresponding code in
  258. // HandleClassDefinitionStart.
  259. auto name_id = context.identifiers().Add(
  260. Lex::TokenKind::SelfTypeIdentifier.fixed_spelling());
  261. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  262. auto value = context.insts().Get(value_id);
  263. context.AddInstAndPush(
  264. parse_node,
  265. SemIR::NameReference{parse_node, value.type_id(), name_id, value_id});
  266. return true;
  267. }
  268. auto HandleSelfValueName(Context& context, Parse::Node parse_node) -> bool {
  269. context.node_stack().Push(parse_node);
  270. return true;
  271. }
  272. auto HandleSelfValueNameExpression(Context& context, Parse::Node parse_node)
  273. -> bool {
  274. // TODO: This will find a local variable declared with name `r#self`, but
  275. // should not. See #2984 and the corresponding code in
  276. // HandleFunctionDefinitionStart.
  277. auto name_id = context.identifiers().Add(SemIR::SelfParameter::Name);
  278. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  279. auto value = context.insts().Get(value_id);
  280. context.AddInstAndPush(
  281. parse_node,
  282. SemIR::NameReference{parse_node, value.type_id(), name_id, value_id});
  283. return true;
  284. }
  285. } // namespace Carbon::Check