handle_class.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 "toolchain/check/context.h"
  5. #include "toolchain/lex/token_kind.h"
  6. namespace Carbon::Check {
  7. auto HandleClassIntroducer(Context& context, Parse::Node parse_node) -> bool {
  8. // Create an instruction block to hold the instructions created as part of the
  9. // class signature, such as generic parameters.
  10. context.inst_block_stack().Push();
  11. // Push the bracketing node.
  12. context.node_stack().Push(parse_node);
  13. // A name should always follow.
  14. context.decl_name_stack().PushScopeAndStartName();
  15. return true;
  16. }
  17. auto HandleAbstractModifier(Context& context, Parse::Node parse_node) -> bool {
  18. context.node_stack().Push(parse_node);
  19. return true;
  20. }
  21. auto HandleBaseModifier(Context& context, Parse::Node parse_node) -> bool {
  22. context.node_stack().Push(parse_node);
  23. return true;
  24. }
  25. static auto BuildClassDecl(Context& context)
  26. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  27. auto name_context = context.decl_name_stack().FinishName();
  28. auto introducer = context.node_stack().PeekParseNode();
  29. bool abstract =
  30. context.node_stack()
  31. .PopAndDiscardSoloParseNodeIf<Parse::NodeKind::AbstractModifier>();
  32. bool base =
  33. context.node_stack()
  34. .PopAndDiscardSoloParseNodeIf<Parse::NodeKind::BaseModifier>();
  35. context.node_stack()
  36. .PopAndDiscardSoloParseNode<Parse::NodeKind::ClassIntroducer>();
  37. auto decl_block_id = context.inst_block_stack().Pop();
  38. CARBON_CHECK(!(abstract && base)) << "Cannot be both `abstract` and `base`";
  39. auto inheritance_kind = abstract ? SemIR::Class::Abstract
  40. : base ? SemIR::Class::Base
  41. : SemIR::Class::Final;
  42. // Add the class declaration.
  43. auto class_decl =
  44. SemIR::ClassDecl{introducer, SemIR::ClassId::Invalid, decl_block_id};
  45. auto class_decl_id = context.AddInst(class_decl);
  46. // Check whether this is a redeclaration.
  47. auto existing_id =
  48. context.decl_name_stack().LookupOrAddName(name_context, class_decl_id);
  49. if (existing_id.is_valid()) {
  50. if (auto existing_class_decl =
  51. context.insts().Get(existing_id).TryAs<SemIR::ClassDecl>()) {
  52. // This is a redeclaration of an existing class.
  53. class_decl.class_id = existing_class_decl->class_id;
  54. auto& class_info = context.classes().Get(class_decl.class_id);
  55. // The introducer kind must match the previous declaration.
  56. // TODO: The rule here is not yet decided. See #3384.
  57. if (class_info.inheritance_kind != inheritance_kind) {
  58. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducer, Error,
  59. "Class redeclared with different inheritance kind.");
  60. CARBON_DIAGNOSTIC(ClassRedeclarationDifferentIntroducerPrevious, Note,
  61. "Previously declared here.");
  62. context.emitter()
  63. .Build(introducer, ClassRedeclarationDifferentIntroducer)
  64. .Note(existing_class_decl->parse_node,
  65. ClassRedeclarationDifferentIntroducerPrevious)
  66. .Emit();
  67. }
  68. // TODO: Check that the generic parameter list agrees with the prior
  69. // declaration.
  70. } else {
  71. // This is a redeclaration of something other than a class.
  72. context.DiagnoseDuplicateName(name_context.parse_node, existing_id);
  73. }
  74. }
  75. // Create a new class if this isn't a valid redeclaration.
  76. if (!class_decl.class_id.is_valid()) {
  77. // TODO: If this is an invalid redeclaration of a non-class entity or there
  78. // was an error in the qualifier, we will have lost track of the class name
  79. // here. We should keep track of it even if the name is invalid.
  80. class_decl.class_id = context.classes().Add(
  81. {.name_id =
  82. name_context.state == DeclNameStack::NameContext::State::Unresolved
  83. ? name_context.unresolved_name_id
  84. : SemIR::NameId::Invalid,
  85. // `.self_type_id` depends on `class_id`, so is set below.
  86. .self_type_id = SemIR::TypeId::Invalid,
  87. .decl_id = class_decl_id,
  88. .inheritance_kind = inheritance_kind});
  89. // Build the `Self` type.
  90. auto& class_info = context.classes().Get(class_decl.class_id);
  91. class_info.self_type_id =
  92. context.CanonicalizeType(context.AddInst(SemIR::ClassType{
  93. introducer, context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  94. class_decl.class_id}));
  95. }
  96. // Write the class ID into the ClassDecl.
  97. context.insts().Set(class_decl_id, class_decl);
  98. return {class_decl.class_id, class_decl_id};
  99. }
  100. auto HandleClassDecl(Context& context, Parse::Node /*parse_node*/) -> bool {
  101. BuildClassDecl(context);
  102. context.decl_name_stack().PopScope();
  103. return true;
  104. }
  105. auto HandleClassDefinitionStart(Context& context, Parse::Node parse_node)
  106. -> bool {
  107. auto [class_id, class_decl_id] = BuildClassDecl(context);
  108. auto& class_info = context.classes().Get(class_id);
  109. // Track that this declaration is the definition.
  110. if (class_info.definition_id.is_valid()) {
  111. CARBON_DIAGNOSTIC(ClassRedefinition, Error, "Redefinition of class {0}.",
  112. llvm::StringRef);
  113. CARBON_DIAGNOSTIC(ClassPreviousDefinition, Note,
  114. "Previous definition was here.");
  115. context.emitter()
  116. .Build(parse_node, ClassRedefinition,
  117. context.names().GetFormatted(class_info.name_id))
  118. .Note(context.insts().Get(class_info.definition_id).parse_node(),
  119. ClassPreviousDefinition)
  120. .Emit();
  121. } else {
  122. class_info.definition_id = class_decl_id;
  123. class_info.scope_id = context.name_scopes().Add();
  124. }
  125. // Enter the class scope.
  126. context.PushScope(class_decl_id, class_info.scope_id);
  127. // Introduce `Self`.
  128. context.AddNameToLookup(
  129. parse_node, SemIR::NameId::SelfType,
  130. context.sem_ir().GetTypeAllowBuiltinTypes(class_info.self_type_id));
  131. context.inst_block_stack().Push();
  132. context.node_stack().Push(parse_node, class_id);
  133. context.args_type_info_stack().Push();
  134. // TODO: Handle the case where there's control flow in the class body. For
  135. // example:
  136. //
  137. // class C {
  138. // var v: if true then i32 else f64;
  139. // }
  140. //
  141. // We may need to track a list of instruction blocks here, as we do for a
  142. // function.
  143. class_info.body_block_id = context.inst_block_stack().PeekOrAdd();
  144. return true;
  145. }
  146. auto HandleClassDefinition(Context& context, Parse::Node parse_node) -> bool {
  147. auto fields_id = context.args_type_info_stack().Pop();
  148. auto class_id =
  149. context.node_stack().Pop<Parse::NodeKind::ClassDefinitionStart>();
  150. context.inst_block_stack().Pop();
  151. context.PopScope();
  152. context.decl_name_stack().PopScope();
  153. // The class type is now fully defined.
  154. auto& class_info = context.classes().Get(class_id);
  155. class_info.object_representation_id =
  156. context.CanonicalizeStructType(parse_node, fields_id);
  157. return true;
  158. }
  159. } // namespace Carbon::Check