type_structure.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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/type_structure.h"
  5. #include <concepts>
  6. #include <utility>
  7. #include <variant>
  8. #include "common/variant_helpers.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/type_iterator.h"
  12. namespace Carbon::Check {
  13. auto TypeStructure::IsCompatibleWith(const TypeStructure& other) const -> bool {
  14. const auto& lhs = structure_;
  15. const auto& rhs = other.structure_;
  16. const auto* lhs_cursor = lhs.begin();
  17. const auto* rhs_cursor = rhs.begin();
  18. const auto* lhs_concrete_cursor = concrete_types_.begin();
  19. const auto* rhs_concrete_cursor = other.concrete_types_.begin();
  20. while (true) {
  21. // If both structures end at the same time, they match.
  22. if (lhs_cursor == lhs.end() && rhs_cursor == rhs.end()) {
  23. return true;
  24. }
  25. // If one structure ends sooner than the other, they don't match.
  26. if (lhs_cursor == lhs.end() || rhs_cursor == rhs.end()) {
  27. return false;
  28. }
  29. // Same structural element on both sides. Compare concrete values if
  30. // possible to ensure they match. Both will be consumed.
  31. if (*lhs_cursor == *rhs_cursor) {
  32. // Each Concrete and ConcreteOpenParen shape entry has a paired concrete
  33. // value.
  34. if (*lhs_cursor == Structural::Concrete ||
  35. *lhs_cursor == Structural::ConcreteOpenParen) {
  36. if (*lhs_concrete_cursor != *rhs_concrete_cursor) {
  37. return false;
  38. }
  39. // Move past the shape and concrete value together.
  40. ++lhs_concrete_cursor;
  41. ++rhs_concrete_cursor;
  42. }
  43. ++lhs_cursor;
  44. ++rhs_cursor;
  45. continue;
  46. }
  47. // If the element on each side is concrete but they not the same structural
  48. // shape, then the structures don't match.
  49. if (*lhs_cursor != Structural::Symbolic &&
  50. *rhs_cursor != Structural::Symbolic) {
  51. return false;
  52. }
  53. // From here we know one side is a Symbolic and the other is not. We can
  54. // match the Symbolic against either a single Concrete or a larger bracketed
  55. // set of Concrete structural elements.
  56. //
  57. // We move the symbolic to the RHS to make only one case to handle in the
  58. // lambda.
  59. if (*lhs_cursor == Structural::Symbolic) {
  60. if (!ConsumeRhsSymbolic(rhs_cursor, rhs_concrete_cursor, lhs_cursor)) {
  61. return false;
  62. }
  63. } else {
  64. if (!ConsumeRhsSymbolic(lhs_cursor, lhs_concrete_cursor, rhs_cursor)) {
  65. return false;
  66. }
  67. }
  68. }
  69. return true;
  70. }
  71. // Returns false if the lhs and rhs can not match, true if we should
  72. // continue checking for compatibility.
  73. auto TypeStructure::ConsumeRhsSymbolic(
  74. llvm::SmallVector<Structural>::const_iterator& lhs_cursor,
  75. llvm::SmallVector<ConcreteType>::const_iterator& lhs_concrete_cursor,
  76. llvm::SmallVector<Structural>::const_iterator& rhs_cursor) -> bool {
  77. // Consume the symbolic on the RHS.
  78. ++rhs_cursor;
  79. // The symbolic on the RHS is in the same position as a close paren on the
  80. // LHS, which means the structures can not match.
  81. //
  82. // Example:
  83. // - ((c))
  84. // - ((c?))
  85. if (*lhs_cursor == TypeStructure::Structural::ConcreteCloseParen) {
  86. return false;
  87. }
  88. // There's either a Concrete element or an open paren on the LHS. If it's
  89. // the former, the Symbolic just matches with it. If it's the latter, the
  90. // Symbolic matches with everything on the LHS up to the matching closing
  91. // paren.
  92. CARBON_CHECK(*lhs_cursor == Structural::Concrete ||
  93. *lhs_cursor == Structural::ConcreteOpenParen);
  94. int depth = 0;
  95. do {
  96. switch (*lhs_cursor) {
  97. case Structural::ConcreteOpenParen:
  98. depth += 1;
  99. // Each Concrete and ConcreteOpenParen shape entry has a paired
  100. // concrete value. Skip the shape and concrete value together.
  101. ++lhs_concrete_cursor;
  102. break;
  103. case Structural::ConcreteCloseParen:
  104. depth -= 1;
  105. break;
  106. case Structural::Concrete:
  107. // Each Concrete and ConcreteOpenParen shape entry has a paired
  108. // concrete value. Skip the shape and concrete value together.
  109. ++lhs_concrete_cursor;
  110. break;
  111. case Structural::Symbolic:
  112. break;
  113. }
  114. ++lhs_cursor;
  115. } while (depth > 0);
  116. return true;
  117. }
  118. // A class that builds a `TypeStructure` for an `Impl`, or an impl lookup query,
  119. // that represents its self type and interface.
  120. class TypeStructureBuilder {
  121. public:
  122. // `context` must not be null.
  123. explicit TypeStructureBuilder(Context* context) : context_(context) {}
  124. auto Run(SemIR::InstId self_inst_id,
  125. SemIR::SpecificInterface interface_constraint) -> TypeStructure {
  126. structure_.clear();
  127. symbolic_type_indices_.clear();
  128. concrete_types_.clear();
  129. SemIR::TypeIterator type_iter(&context_->sem_ir());
  130. // The self type comes first in the type structure, so we push it last, as
  131. // the iterator starts with the last thing added.
  132. type_iter.Add(interface_constraint);
  133. if (self_inst_id.has_value()) {
  134. type_iter.Add(self_inst_id);
  135. }
  136. return Build(std::move(type_iter));
  137. }
  138. private:
  139. auto Build(SemIR::TypeIterator type_iter) -> TypeStructure;
  140. // Append a structural element to the TypeStructure being built.
  141. auto AppendStructuralConcrete(TypeStructure::ConcreteType type) -> void {
  142. concrete_types_.push_back(type);
  143. structure_.push_back(TypeStructure::Structural::Concrete);
  144. }
  145. auto AppendStructuralConcreteOpenParen(TypeStructure::ConcreteType type)
  146. -> void {
  147. concrete_types_.push_back(type);
  148. structure_.push_back(TypeStructure::Structural::ConcreteOpenParen);
  149. }
  150. auto AppendStructuralConcreteCloseParen() -> void {
  151. structure_.push_back(TypeStructure::Structural::ConcreteCloseParen);
  152. }
  153. auto AppendStructuralSymbolic() -> void {
  154. symbolic_type_indices_.push_back(structure_.size());
  155. structure_.push_back(TypeStructure::Structural::Symbolic);
  156. }
  157. Context* context_;
  158. // In-progress state for the equivalent `TypeStructure` fields.
  159. llvm::SmallVector<TypeStructure::Structural> structure_;
  160. llvm::SmallVector<int> symbolic_type_indices_;
  161. llvm::SmallVector<TypeStructure::ConcreteType> concrete_types_;
  162. };
  163. // Builds the type structure and returns it.
  164. auto TypeStructureBuilder::Build(SemIR::TypeIterator type_iter)
  165. -> TypeStructure {
  166. while (true) {
  167. auto step = type_iter.Next();
  168. if (step.Is<SemIR::TypeIterator::Step::Done>()) {
  169. break;
  170. }
  171. VariantMatch(
  172. step.any,
  173. [&](SemIR::TypeIterator::Step::Done) {
  174. CARBON_FATAL("already handled above");
  175. },
  176. [&](SemIR::TypeIterator::Step::End) {
  177. AppendStructuralConcreteCloseParen();
  178. },
  179. [&](SemIR::TypeIterator::Step::ConcreteType concrete) {
  180. AppendStructuralConcrete(concrete.type_id);
  181. },
  182. [&](SemIR::TypeIterator::Step::SymbolicType) {
  183. AppendStructuralSymbolic();
  184. },
  185. [&](SemIR::TypeIterator::Step::TemplateType) {
  186. AppendStructuralSymbolic();
  187. },
  188. [&](SemIR::TypeIterator::Step::ConcreteValue value) {
  189. AppendStructuralConcrete(
  190. context_->constant_values().Get(value.inst_id));
  191. },
  192. [&](SemIR::TypeIterator::Step::SymbolicValue) {
  193. AppendStructuralSymbolic();
  194. },
  195. [&](SemIR::TypeIterator::Step::StructFieldName field_name) {
  196. AppendStructuralConcrete(field_name.name_id);
  197. },
  198. [&](SemIR::TypeIterator::Step::StartOnly start) {
  199. VariantMatch(
  200. start.any,
  201. [&](SemIR::TypeIterator::Step::ClassStart class_start) {
  202. AppendStructuralConcrete(class_start.class_id);
  203. },
  204. [&](SemIR::TypeIterator::Step::StructStart) {
  205. AppendStructuralConcrete(TypeStructure::ConcreteStructType());
  206. },
  207. [&](SemIR::TypeIterator::Step::TupleStart) {
  208. AppendStructuralConcrete(TypeStructure::ConcreteTupleType());
  209. },
  210. [&](SemIR::TypeIterator::Step::InterfaceStart interface_start) {
  211. AppendStructuralConcrete(interface_start.interface_id);
  212. },
  213. [&](SemIR::TypeIterator::Step::IntStart int_start) {
  214. AppendStructuralConcrete(int_start.type_id);
  215. });
  216. },
  217. [&](SemIR::TypeIterator::Step::StartWithEnd start_with_end) {
  218. VariantMatch(
  219. start_with_end.any,
  220. [&](SemIR::TypeIterator::Step::ClassStart class_start) {
  221. AppendStructuralConcreteOpenParen(class_start.class_id);
  222. },
  223. [&](SemIR::TypeIterator::Step::StructStart) {
  224. AppendStructuralConcreteOpenParen(
  225. TypeStructure::ConcreteStructType());
  226. },
  227. [&](SemIR::TypeIterator::Step::TupleStart) {
  228. AppendStructuralConcreteOpenParen(
  229. TypeStructure::ConcreteTupleType());
  230. },
  231. [&](SemIR::TypeIterator::Step::InterfaceStart interface_start) {
  232. AppendStructuralConcreteOpenParen(interface_start.interface_id);
  233. },
  234. [&](SemIR::TypeIterator::Step::IntStart int_start) {
  235. AppendStructuralConcreteOpenParen(int_start.type_id);
  236. },
  237. [&](SemIR::TypeIterator::Step::ArrayStart) {
  238. AppendStructuralConcreteOpenParen(
  239. TypeStructure::ConcreteArrayType());
  240. },
  241. [&](SemIR::TypeIterator::Step::PointerStart) {
  242. AppendStructuralConcreteOpenParen(
  243. TypeStructure::ConcretePointerType());
  244. });
  245. });
  246. }
  247. // TODO: This requires 4 SmallVector moves (two here and two in the
  248. // constructor). Find a way to reduce that.
  249. return TypeStructure(std::exchange(structure_, {}),
  250. std::exchange(symbolic_type_indices_, {}),
  251. std::exchange(concrete_types_, {}));
  252. }
  253. auto BuildTypeStructure(Context& context, SemIR::InstId self_inst_id,
  254. SemIR::SpecificInterface interface) -> TypeStructure {
  255. TypeStructureBuilder builder(&context);
  256. return builder.Run(self_inst_id, interface);
  257. }
  258. } // namespace Carbon::Check