Debian Codegraph @

gcc/rust/expand/rust-derive-partial-eq.cc

raw
1 // Copyright (C) 2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "rust-derive-partial-eq.h"
20 #include "rust-ast.h"
21 #include "rust-expr.h"
22 #include "rust-item.h"
23 #include "rust-operators.h"
24 #include "rust-path.h"
25 #include "rust-pattern.h"
26 #include "rust-system.h"
27
28 namespace Rust {
29 namespace AST {
30 DerivePartialEq::DerivePartialEq (location_t loc) : DeriveVisitor (loc) {}
31
32 std::vector<std::unique_ptr<AST::Item>>
33 DerivePartialEq::go (Item &item)
34 {
35 item.accept_vis (*this);
36
37 return std::move (expanded);
38 }
39
40 std::vector<std::unique_ptr<Item>>
41 DerivePartialEq::partialeq_impls (
42 std::unique_ptr<AssociatedItem> &&eq_fn, std::string name,
43 const std::vector<std::unique_ptr<GenericParam>> &type_generics)
44 {
45 auto eq = builder.type_path (LangItem::Kind::EQ);
46 auto speq = builder.type_path (LangItem::Kind::STRUCTURAL_PEQ);
47
48 auto trait_items = vec (std::move (eq_fn));
49
50 // no extra bound on StructuralPeq
51 auto peq_generics
52 = setup_impl_generics (name, type_generics, builder.trait_bound (eq));
53 auto speq_generics = setup_impl_generics (name, type_generics);
54
55 auto peq = builder.trait_impl (eq, std::move (peq_generics.self_type),
56 std::move (trait_items),
57 std::move (peq_generics.impl));
58
59 auto structural_peq
60 = builder.trait_impl (speq, std::move (speq_generics.self_type), {},
61 std::move (speq_generics.impl));
62
63 return vec (std::move (peq), std::move (structural_peq));
64 }
65
66 std::unique_ptr<AssociatedItem>
67 DerivePartialEq::eq_fn (std::unique_ptr<Expr> &&cmp_expression,
68 std::string type_name)
69 {
70 auto block = builder.block (tl::nullopt, std::move (cmp_expression));
71
72 auto self_type
73 = std::unique_ptr<TypeNoBounds> (new TypePath (builder.type_path ("Self")));
74
75 auto params
76 = vec (builder.self_ref_param (),
77 builder.function_param (builder.identifier_pattern ("other"),
78 builder.reference_type (
79 std::move (self_type))));
80
81 return builder.function ("eq", std::move (params),
82 builder.single_type_path ("bool"),
83 std::move (block));
84 }
85
86 DerivePartialEq::SelfOther
87 DerivePartialEq::tuple_indexes (int idx)
88 {
89 return SelfOther{
90 builder.tuple_idx ("self", idx),
91 builder.tuple_idx ("other", idx),
92 };
93 }
94
95 DerivePartialEq::SelfOther
96 DerivePartialEq::field_acccesses (const std::string &field_name)
97 {
98 return SelfOther{
99 builder.field_access (builder.identifier ("self"), field_name),
100 builder.field_access (builder.identifier ("other"), field_name),
101 };
102 }
103
104 std::unique_ptr<Expr>
105 DerivePartialEq::build_eq_expression (
106 std::vector<SelfOther> &&field_expressions)
107 {
108 // for unit structs or empty tuples, this is always true
109 if (field_expressions.empty ())
110 return builder.literal_bool (true);
111
112 auto cmp_expression
113 = builder.comparison_expr (std::move (field_expressions.at (0).self_expr),
114 std::move (field_expressions.at (0).other_expr),
115 ComparisonOperator::EQUAL);
116
117 for (size_t i = 1; i < field_expressions.size (); i++)
118 {
119 auto tmp = builder.comparison_expr (
120 std::move (field_expressions.at (i).self_expr),
121 std::move (field_expressions.at (i).other_expr),
122 ComparisonOperator::EQUAL);
123
124 cmp_expression
125 = builder.boolean_operation (std::move (cmp_expression),
126 std::move (tmp),
127 LazyBooleanOperator::LOGICAL_AND);
128 }
129
130 return cmp_expression;
131 }
132
133 void
134 DerivePartialEq::visit_tuple (TupleStruct &item)
135 {
136 auto type_name = item.get_struct_name ().as_string ();
137 auto fields = std::vector<SelfOther> ();
138
139 for (size_t idx = 0; idx < item.get_fields ().size (); idx++)
140 fields.emplace_back (tuple_indexes (idx));
141
142 auto fn = eq_fn (build_eq_expression (std::move (fields)), type_name);
143
144 expanded
145 = partialeq_impls (std::move (fn), type_name, item.get_generic_params ());
146 }
147
148 void
149 DerivePartialEq::visit_struct (StructStruct &item)
150 {
151 auto type_name = item.get_struct_name ().as_string ();
152 auto fields = std::vector<SelfOther> ();
153
154 for (auto &field : item.get_fields ())
155 fields.emplace_back (
156 field_acccesses (field.get_field_name ().as_string ()));
157
158 auto fn = eq_fn (build_eq_expression (std::move (fields)), type_name);
159
160 expanded
161 = partialeq_impls (std::move (fn), type_name, item.get_generic_params ());
162 }
163
164 MatchCase
165 DerivePartialEq::match_enum_identifier (
166 PathInExpression variant_path, const std::unique_ptr<EnumItem> &variant)
167 {
168 auto inner_ref_patterns
169 = vec (builder.ref_pattern (
170 std::unique_ptr<Pattern> (new PathInExpression (variant_path))),
171 builder.ref_pattern (
172 std::unique_ptr<Pattern> (new PathInExpression (variant_path))));
173
174 auto tuple_items = std::make_unique<TuplePatternItemsMultiple> (
175 std::move (inner_ref_patterns));
176
177 auto pattern = std::make_unique<TuplePattern> (std::move (tuple_items), loc);
178
179 return builder.match_case (std::move (pattern), builder.literal_bool (true));
180 }
181
182 MatchCase
183 DerivePartialEq::match_enum_tuple (PathInExpression variant_path,
184 const EnumItemTuple &variant)
185 {
186 auto self_patterns = std::vector<std::unique_ptr<Pattern>> ();
187 auto other_patterns = std::vector<std::unique_ptr<Pattern>> ();
188
189 auto self_other_exprs = std::vector<SelfOther> ();
190
191 for (size_t i = 0; i < variant.get_tuple_fields ().size (); i++)
192 {
193 // The patterns we're creating for each field are `self_<i>` and
194 // `other_<i>` where `i` is the index of the field. It doesn't actually
195 // matter what we use, as long as it's ordered, unique, and that we can
196 // reuse it in the match case's return expression to check that they are
197 // equal.
198
199 auto self_pattern_str = "__self_" + std::to_string (i);
200 auto other_pattern_str = "__other_" + std::to_string (i);
201
202 rust_debug ("]ARTHUR[ %s", self_pattern_str.c_str ());
203
204 self_patterns.emplace_back (
205 builder.identifier_pattern (self_pattern_str));
206 other_patterns.emplace_back (
207 builder.identifier_pattern (other_pattern_str));
208
209 self_other_exprs.emplace_back (SelfOther{
210 builder.identifier (self_pattern_str),
211 builder.identifier (other_pattern_str),
212 });
213 }
214
215 auto self_pattern_items = std::unique_ptr<TupleStructItems> (
216 new TupleStructItemsNoRange (std::move (self_patterns)));
217 auto other_pattern_items = std::unique_ptr<TupleStructItems> (
218 new TupleStructItemsNoRange (std::move (other_patterns)));
219
220 auto self_pattern = std::unique_ptr<Pattern> (
221 new ReferencePattern (std::unique_ptr<Pattern> (new TupleStructPattern (
222 variant_path, std::move (self_pattern_items))),
223 false, false, loc));
224 auto other_pattern = std::unique_ptr<Pattern> (
225 new ReferencePattern (std::unique_ptr<Pattern> (new TupleStructPattern (
226 variant_path, std::move (other_pattern_items))),
227 false, false, loc));
228
229 auto tuple_items = std::make_unique<TuplePatternItemsMultiple> (
230 vec (std::move (self_pattern), std::move (other_pattern)));
231
232 auto pattern = std::make_unique<TuplePattern> (std::move (tuple_items), loc);
233
234 auto expr = build_eq_expression (std::move (self_other_exprs));
235
236 return builder.match_case (std::move (pattern), std::move (expr));
237 }
238
239 MatchCase
240 DerivePartialEq::match_enum_struct (PathInExpression variant_path,
241 const EnumItemStruct &variant)
242 {
243 // NOTE: We currently do not support compiling struct patterns where an
244 // identifier is assigned a new pattern, e.g. Bloop { f0: x }
245 // This is what we should be using to compile PartialEq for enum struct
246 // variants, as we need to be comparing the field of each instance meaning we
247 // need to give two different names to two different instances of the same
248 // field. We cannot just use the field's name like we do when deriving
249 // `Clone`.
250
251 rust_unreachable ();
252 }
253
254 void
255 DerivePartialEq::visit_enum (Enum &item)
256 {
257 auto cases = std::vector<MatchCase> ();
258 auto type_name = item.get_identifier ().as_string ();
259
260 for (auto &variant : item.get_variants ())
261 {
262 auto variant_path
263 = builder.variant_path (type_name,
264 variant->get_identifier ().as_string ());
265
266 switch (variant->get_enum_item_kind ())
267 {
268 case EnumItem::Kind::Identifier:
269 case EnumItem::Kind::Discriminant:
270 cases.emplace_back (match_enum_identifier (variant_path, variant));
271 break;
272 case EnumItem::Kind::Tuple:
273 cases.emplace_back (
274 match_enum_tuple (variant_path,
275 static_cast<EnumItemTuple &> (*variant)));
276 break;
277 case EnumItem::Kind::Struct:
278 rust_sorry_at (
279 item.get_locus (),
280 "cannot derive(PartialEq) for enum struct variants yet");
281 break;
282 }
283 }
284
285 // NOTE: Mention using discriminant_value and skipping that last case, and
286 // instead skipping all identifiers/discriminant enum items and returning
287 // `true` in the wildcard case
288
289 // In case the two instances of `Self` don't have the same discriminant,
290 // automatically return false.
291 cases.emplace_back (
292 builder.match_case (builder.wildcard (), builder.literal_bool (false)));
293
294 auto match
295 = builder.match (builder.tuple (vec (builder.identifier ("self"),
296 builder.identifier ("other"))),
297 std::move (cases));
298
299 auto fn = eq_fn (std::move (match), type_name);
300
301 expanded
302 = partialeq_impls (std::move (fn), type_name, item.get_generic_params ());
303 }
304
305 void
306 DerivePartialEq::visit_union (Union &item)
307 {
308 rust_error_at (item.get_locus (),
309 "derive(PartialEq) cannot be used on unions");
310 }
311
312 } // namespace AST
313 } // namespace Rust