handle_name.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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.types().GetInstId(
  45. context.classes().Get(class_decl->class_id).self_type_id);
  46. }
  47. if (auto interface_decl = lookup_result.TryAs<SemIR::InterfaceDecl>()) {
  48. // TODO: unimplemented
  49. return SemIR::InstId::Invalid;
  50. }
  51. // Anything else should be a typed value already.
  52. CARBON_CHECK(lookup_result.kind().value_kind() == SemIR::InstValueKind::Typed)
  53. << "Unexpected kind for lookup result, " << lookup_result;
  54. return lookup_result_id;
  55. }
  56. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  57. -> SemIR::ElementIndex {
  58. auto element_inst = context.insts().Get(element_id);
  59. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  60. return field->index;
  61. }
  62. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  63. return base->index;
  64. }
  65. CARBON_FATAL() << "Unexpected value " << element_inst
  66. << " in class element name";
  67. }
  68. // Returns whether `function_id` is an instance method, that is, whether it has
  69. // an implicit `self` parameter.
  70. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  71. SemIR::FunctionId function_id) -> bool {
  72. auto& function = sem_ir.functions().Get(function_id);
  73. for (auto param_id :
  74. sem_ir.inst_blocks().Get(function.implicit_param_refs_id)) {
  75. auto inst = sem_ir.insts().Get(param_id);
  76. if (auto addr = inst.TryAs<SemIR::AddrPattern>()) {
  77. inst = sem_ir.insts().Get(addr->inner_id);
  78. }
  79. if (auto param = inst.TryAs<SemIR::Param>();
  80. param && param->name_id == SemIR::NameId::SelfValue) {
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86. auto HandleMemberAccessExpr(Context& context, Parse::NodeId parse_node)
  87. -> bool {
  88. SemIR::NameId name_id = context.node_stack().PopName();
  89. auto base_id = context.node_stack().PopExpr();
  90. // If the base is a name scope, such as a class or namespace, perform lookup
  91. // into that scope.
  92. if (auto name_scope_id = GetAsNameScope(context, base_id)) {
  93. auto inst_id =
  94. name_scope_id->is_valid()
  95. ? context.LookupQualifiedName(parse_node, name_id, *name_scope_id)
  96. : SemIR::InstId::BuiltinError;
  97. inst_id = GetExprValueForLookupResult(context, inst_id);
  98. if (!inst_id.is_valid()) {
  99. return context.TODO(parse_node, "Unimplemented use of interface");
  100. }
  101. auto inst = context.insts().Get(inst_id);
  102. // TODO: Track that this instruction was named within `base_id`.
  103. context.AddInstAndPush(
  104. parse_node,
  105. SemIR::NameRef{parse_node, inst.type_id(), name_id, inst_id});
  106. return true;
  107. }
  108. // If the base isn't a scope, it must have a complete type.
  109. auto base_type_id = context.insts().Get(base_id).type_id();
  110. if (!context.TryToCompleteType(base_type_id, [&] {
  111. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  112. "Member access into object of incomplete type `{0}`.",
  113. std::string);
  114. return context.emitter().Build(
  115. context.insts().Get(base_id).parse_node(),
  116. IncompleteTypeInMemberAccess,
  117. context.sem_ir().StringifyType(base_type_id));
  118. })) {
  119. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  120. return true;
  121. }
  122. // Materialize a temporary for the base expression if necessary.
  123. base_id = ConvertToValueOrRefExpr(context, base_id);
  124. base_type_id = context.insts().Get(base_id).type_id();
  125. switch (auto base_type = context.types().GetAsInst(base_type_id);
  126. base_type.kind()) {
  127. case SemIR::ClassType::Kind: {
  128. // Perform lookup for the name in the class scope.
  129. auto class_scope_id = context.classes()
  130. .Get(base_type.As<SemIR::ClassType>().class_id)
  131. .scope_id;
  132. auto member_id =
  133. context.LookupQualifiedName(parse_node, name_id, class_scope_id);
  134. member_id = GetExprValueForLookupResult(context, member_id);
  135. // Perform instance binding if we found an instance member.
  136. auto member_type_id = context.insts().Get(member_id).type_id();
  137. if (auto unbound_element_type =
  138. context.types().TryGetAs<SemIR::UnboundElementType>(
  139. member_type_id)) {
  140. // Convert the base to the type of the element if necessary.
  141. base_id = ConvertToValueOrRefOfType(
  142. context, parse_node, base_id, unbound_element_type->class_type_id);
  143. // Find the specified element, which could be either a field or a base
  144. // class, and build an element access expression.
  145. auto element_id = context.GetConstantValue(member_id);
  146. CARBON_CHECK(element_id.is_valid())
  147. << "Non-constant value " << context.insts().Get(member_id)
  148. << " of unbound element type";
  149. auto index = GetClassElementIndex(context, element_id);
  150. auto access_id = context.AddInst(SemIR::ClassElementAccess{
  151. parse_node, unbound_element_type->element_type_id, base_id, index});
  152. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  153. SemIR::ExprCategory::Value &&
  154. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  155. SemIR::ExprCategory::Value) {
  156. // Class element access on a value expression produces an
  157. // ephemeral reference if the class's value representation is a
  158. // pointer to the object representation. Add a value binding in
  159. // that case so that the expression category of the result
  160. // matches the expression category of the base.
  161. access_id = ConvertToValueExpr(context, access_id);
  162. }
  163. context.node_stack().Push(parse_node, access_id);
  164. return true;
  165. }
  166. if (member_type_id ==
  167. context.GetBuiltinType(SemIR::BuiltinKind::FunctionType)) {
  168. // Find the named function and check whether it's an instance method.
  169. auto function_name_id = context.GetConstantValue(member_id);
  170. CARBON_CHECK(function_name_id.is_valid())
  171. << "Non-constant value " << context.insts().Get(member_id)
  172. << " of function type";
  173. auto function_decl =
  174. context.insts().Get(function_name_id).TryAs<SemIR::FunctionDecl>();
  175. CARBON_CHECK(function_decl)
  176. << "Unexpected value " << context.insts().Get(function_name_id)
  177. << " of function type";
  178. if (IsInstanceMethod(context.sem_ir(), function_decl->function_id)) {
  179. context.AddInstAndPush(
  180. parse_node,
  181. SemIR::BoundMethod{
  182. parse_node,
  183. context.GetBuiltinType(SemIR::BuiltinKind::BoundMethodType),
  184. base_id, member_id});
  185. return true;
  186. }
  187. }
  188. // For a non-instance member, the result is that member.
  189. // TODO: Track that this was named within `base_id`.
  190. context.AddInstAndPush(
  191. parse_node,
  192. SemIR::NameRef{parse_node, member_type_id, name_id, member_id});
  193. return true;
  194. }
  195. case SemIR::StructType::Kind: {
  196. auto refs = context.inst_blocks().Get(
  197. base_type.As<SemIR::StructType>().fields_id);
  198. // TODO: Do we need to optimize this with a lookup table for O(1)?
  199. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  200. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  201. if (name_id == field.name_id) {
  202. context.AddInstAndPush(
  203. parse_node, SemIR::StructAccess{parse_node, field.field_type_id,
  204. base_id, SemIR::ElementIndex(i)});
  205. return true;
  206. }
  207. }
  208. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  209. "Type `{0}` does not have a member `{1}`.", std::string,
  210. std::string);
  211. context.emitter().Emit(parse_node, QualifiedExprNameNotFound,
  212. context.sem_ir().StringifyType(base_type_id),
  213. context.names().GetFormatted(name_id).str());
  214. break;
  215. }
  216. // TODO: `ConstType` should support member access just like the
  217. // corresponding non-const type, except that the result should have `const`
  218. // type if it creates a reference expression performing field access.
  219. default: {
  220. if (base_type_id != SemIR::TypeId::Error) {
  221. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  222. "Type `{0}` does not support qualified expressions.",
  223. std::string);
  224. context.emitter().Emit(parse_node, QualifiedExprUnsupported,
  225. context.sem_ir().StringifyType(base_type_id));
  226. }
  227. break;
  228. }
  229. }
  230. // Should only be reached on error.
  231. context.node_stack().Push(parse_node, SemIR::InstId::BuiltinError);
  232. return true;
  233. }
  234. auto HandlePointerMemberAccessExpr(Context& context, Parse::NodeId parse_node)
  235. -> bool {
  236. return context.TODO(parse_node, "HandlePointerMemberAccessExpr");
  237. }
  238. static auto GetIdentifierAsName(Context& context, Parse::NodeId parse_node)
  239. -> std::optional<SemIR::NameId> {
  240. auto token = context.parse_tree().node_token(parse_node);
  241. if (context.tokens().GetKind(token) != Lex::TokenKind::Identifier) {
  242. CARBON_CHECK(context.parse_tree().node_has_error(parse_node));
  243. return std::nullopt;
  244. }
  245. return SemIR::NameId::ForIdentifier(context.tokens().GetIdentifier(token));
  246. }
  247. // Handle a name that is used as an expression by performing unqualified name
  248. // lookup.
  249. static auto HandleNameAsExpr(Context& context, Parse::NodeId parse_node,
  250. SemIR::NameId name_id) -> bool {
  251. auto value_id = context.LookupUnqualifiedName(parse_node, name_id);
  252. value_id = GetExprValueForLookupResult(context, value_id);
  253. if (!value_id.is_valid()) {
  254. return context.TODO(parse_node, "Unimplemented use of interface");
  255. }
  256. auto value = context.insts().Get(value_id);
  257. context.AddInstAndPush(parse_node, SemIR::NameRef{parse_node, value.type_id(),
  258. name_id, value_id});
  259. return true;
  260. }
  261. auto HandleIdentifierName(Context& context, Parse::NodeId parse_node) -> bool {
  262. // The parent is responsible for binding the name.
  263. auto name_id = GetIdentifierAsName(context, parse_node);
  264. if (!name_id) {
  265. return context.TODO(parse_node, "Error recovery from keyword name.");
  266. }
  267. context.node_stack().Push(parse_node, *name_id);
  268. return true;
  269. }
  270. auto HandleIdentifierNameExpr(Context& context, Parse::NodeId parse_node)
  271. -> bool {
  272. auto name_id = GetIdentifierAsName(context, parse_node);
  273. if (!name_id) {
  274. return context.TODO(parse_node, "Error recovery from keyword name.");
  275. }
  276. return HandleNameAsExpr(context, parse_node, *name_id);
  277. }
  278. auto HandleBaseName(Context& context, Parse::NodeId parse_node) -> bool {
  279. context.node_stack().Push(parse_node, SemIR::NameId::Base);
  280. return true;
  281. }
  282. auto HandleSelfTypeNameExpr(Context& context, Parse::NodeId parse_node)
  283. -> bool {
  284. return HandleNameAsExpr(context, parse_node, SemIR::NameId::SelfType);
  285. }
  286. auto HandleSelfValueName(Context& context, Parse::NodeId parse_node) -> bool {
  287. context.node_stack().Push(parse_node, SemIR::NameId::SelfValue);
  288. return true;
  289. }
  290. auto HandleSelfValueNameExpr(Context& context, Parse::NodeId parse_node)
  291. -> bool {
  292. return HandleNameAsExpr(context, parse_node, SemIR::NameId::SelfValue);
  293. }
  294. auto HandleQualifiedDecl(Context& context, Parse::NodeId parse_node) -> bool {
  295. auto [parse_node2, name_id2] = context.node_stack().PopNameWithParseNode();
  296. Parse::NodeId parse_node1 = context.node_stack().PeekParseNode();
  297. switch (context.parse_tree().node_kind(parse_node1)) {
  298. case Parse::NodeKind::QualifiedDecl:
  299. // This is the second or subsequent QualifiedDecl in a chain.
  300. // Nothing to do: the first QualifiedDecl remains as a
  301. // bracketing node for later QualifiedDecls.
  302. break;
  303. case Parse::NodeKind::IdentifierName: {
  304. // This is the first QualifiedDecl in a chain, and starts with an
  305. // identifier name.
  306. auto name_id =
  307. context.node_stack().Pop<Parse::NodeKind::IdentifierName>();
  308. context.decl_name_stack().ApplyNameQualifier(parse_node1, name_id);
  309. // Add the QualifiedDecl so that it can be used for bracketing.
  310. context.node_stack().Push(parse_node);
  311. break;
  312. }
  313. default:
  314. CARBON_FATAL() << "Unexpected node kind on left side of qualified "
  315. "declaration name";
  316. }
  317. context.decl_name_stack().ApplyNameQualifier(parse_node2, name_id2);
  318. return true;
  319. }
  320. auto HandlePackageExpr(Context& context, Parse::NodeId parse_node) -> bool {
  321. context.AddInstAndPush(
  322. parse_node,
  323. SemIR::NameRef{
  324. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType),
  325. SemIR::NameId::PackageNamespace, SemIR::InstId::PackageNamespace});
  326. return true;
  327. }
  328. } // namespace Carbon::Check