Line data Source code
1 : // Copyright (C) 2025-2026 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-ord.h"
20 : #include "rust-ast.h"
21 : #include "rust-derive-cmp-common.h"
22 : #include "rust-derive.h"
23 : #include "rust-item.h"
24 : #include "rust-system.h"
25 :
26 : namespace Rust {
27 : namespace AST {
28 :
29 695 : DeriveOrd::DeriveOrd (Ordering ordering, location_t loc,
30 : Builder::Source item_source)
31 695 : : DeriveVisitor (loc, item_source), ordering (ordering)
32 695 : {}
33 :
34 : std::unique_ptr<Item>
35 695 : DeriveOrd::go (Item &item)
36 : {
37 695 : item.accept_vis (*this);
38 :
39 695 : return std::move (expanded);
40 : }
41 :
42 : std::unique_ptr<Expr>
43 1037 : DeriveOrd::cmp_call (std::unique_ptr<Expr> &&self_expr,
44 : std::unique_ptr<Expr> &&other_expr)
45 : {
46 1037 : auto cmp_fn_path
47 6222 : = builder.path_in_expression ({builder.get_path_start (), "cmp",
48 : trait (ordering), fn (ordering)},
49 2074 : builder.has_opening_scope ());
50 :
51 2074 : return builder.call (ptrify (cmp_fn_path),
52 2074 : vec (builder.ref (std::move (self_expr)),
53 3111 : builder.ref (std::move (other_expr))));
54 1037 : }
55 :
56 : std::unique_ptr<Item>
57 695 : DeriveOrd::cmp_impl (
58 : std::unique_ptr<BlockExpr> &&fn_block, Identifier type_name,
59 : const std::vector<std::unique_ptr<GenericParam>> &type_generics)
60 : {
61 695 : auto fn = cmp_fn (std::move (fn_block), type_name);
62 :
63 695 : auto trait = ordering == Ordering::Partial ? "PartialOrd" : "Ord";
64 1600 : auto trait_path = [&, this] () {
65 4525 : return builder.type_path ({builder.get_path_start (), "cmp", trait},
66 1810 : builder.has_opening_scope ());
67 695 : };
68 :
69 695 : auto trait_bound
70 210 : = [&, this] () { return builder.trait_bound (trait_path ()); };
71 :
72 695 : auto trait_items = vec (std::move (fn));
73 :
74 695 : auto cmp_generics
75 695 : = setup_impl_generics (type_name.as_string (), type_generics, trait_bound);
76 :
77 1390 : return builder.trait_impl (trait_path (), std::move (cmp_generics.self_type),
78 : std::move (trait_items),
79 1390 : std::move (cmp_generics.impl));
80 695 : }
81 :
82 : std::unique_ptr<AssociatedItem>
83 695 : DeriveOrd::cmp_fn (std::unique_ptr<BlockExpr> &&block, Identifier type_name)
84 : {
85 : // Ordering
86 695 : auto return_type
87 3475 : = builder.type_path ({builder.get_path_start (), "cmp", "Ordering"},
88 1390 : builder.has_opening_scope ());
89 :
90 : // In the case of PartialOrd, we return an Option<Ordering>
91 695 : if (ordering == Ordering::Partial)
92 : {
93 348 : auto generic = GenericArg::create_type (ptrify (return_type));
94 :
95 348 : auto generic_seg = builder.type_path_segment_generic (
96 696 : "Option", GenericArgs ({}, {generic}, {}, loc));
97 348 : auto core = builder.type_path_segment (builder.get_path_start ());
98 348 : auto option = builder.type_path_segment ("option");
99 :
100 348 : return_type
101 696 : = builder.type_path (vec (std::move (core), std::move (option),
102 : std::move (generic_seg)),
103 348 : builder.has_opening_scope ());
104 348 : }
105 :
106 : // &self, other: &Self
107 : //
108 : // this must be Self for a generic type Wrapping<T> the bare struct name has
109 : // no type arguments
110 695 : auto params
111 1390 : = vec (builder.self_ref_param (),
112 1390 : builder.function_param (builder.identifier_pattern ("other"),
113 1390 : builder.reference_type (
114 2085 : ptrify (builder.type_path ("Self")))));
115 :
116 695 : auto function_name = fn (ordering);
117 :
118 3475 : return builder.function (function_name, std::move (params),
119 2085 : ptrify (return_type), std::move (block));
120 695 : }
121 :
122 : std::unique_ptr<Pattern>
123 230 : DeriveOrd::make_equal ()
124 : {
125 230 : std::unique_ptr<Pattern> equal
126 1150 : = ptrify (builder.path_in_expression ({builder.get_path_start (), "cmp",
127 230 : "Ordering", "Equal"},
128 230 : builder.has_opening_scope ()));
129 :
130 : // We need to wrap the pattern in Option::Some if we are doing partial
131 : // ordering
132 230 : if (ordering == Ordering::Partial)
133 : {
134 127 : auto pattern_items = std::unique_ptr<TupleStructItems> (
135 127 : new TupleStructItemsNoRest (vec (std::move (equal))));
136 :
137 127 : equal
138 254 : = std::make_unique<TupleStructPattern> (builder.path_in_expression (
139 : LangItem::Kind::OPTION_SOME),
140 127 : std::move (pattern_items));
141 127 : }
142 :
143 230 : return equal;
144 : }
145 :
146 : std::pair<MatchArm, MatchArm>
147 230 : DeriveOrd::make_cmp_arms ()
148 : {
149 : // All comparison results other than Ordering::Equal
150 230 : auto non_equal = builder.identifier_pattern (DeriveOrd::not_equal);
151 230 : auto equal = make_equal ();
152 :
153 230 : return {builder.match_arm (std::move (equal)),
154 230 : builder.match_arm (std::move (non_equal))};
155 230 : }
156 :
157 : std::unique_ptr<Expr>
158 755 : DeriveOrd::recursive_match (std::vector<SelfOther> &&members)
159 : {
160 755 : if (members.empty ())
161 : {
162 74 : std::unique_ptr<Expr> value
163 444 : = ptrify (builder.path_in_expression ({builder.get_path_start (), "cmp",
164 74 : "Ordering", "Equal"},
165 74 : builder.has_opening_scope ()));
166 :
167 74 : if (ordering == Ordering::Partial)
168 111 : value = builder.call (ptrify (builder.path_in_expression (
169 : LangItem::Kind::OPTION_SOME)),
170 37 : std::move (value));
171 :
172 : return value;
173 : }
174 :
175 681 : std::unique_ptr<Expr> final_expr = nullptr;
176 :
177 1592 : for (auto it = members.rbegin (); it != members.rend (); it++)
178 : {
179 911 : auto &member = *it;
180 :
181 911 : auto call = cmp_call (std::move (member.self_expr),
182 911 : std::move (member.other_expr));
183 :
184 : // For the last member (so the first iterator), we just create a call
185 : // expression
186 911 : if (it == members.rbegin ())
187 : {
188 681 : final_expr = std::move (call);
189 681 : continue;
190 : }
191 :
192 : // If we aren't dealing with the last member, then we need to wrap all of
193 : // that in a big match expression and keep going
194 230 : auto match_arms = make_cmp_arms ();
195 :
196 230 : auto match_cases
197 : = {builder.match_case (std::move (match_arms.first),
198 : std::move (final_expr)),
199 : builder.match_case (std::move (match_arms.second),
200 1150 : builder.identifier (DeriveOrd::not_equal))};
201 :
202 230 : final_expr = builder.match (std::move (call), std::move (match_cases));
203 1601 : }
204 :
205 681 : return final_expr;
206 681 : }
207 :
208 : // we need to do a recursive match expression for all of the fields used in a
209 : // struct so for something like struct Foo { a: i32, b: i32, c: i32 } we must
210 : // first compare each `a` field, then `b`, then `c`, like this:
211 : //
212 : // match cmp_fn(self.<field>, other.<field>) {
213 : // Ordering::Equal => <recurse>,
214 : // cmp => cmp,
215 : // }
216 : //
217 : // and the recurse will be the exact same expression, on the next field. so that
218 : // our result looks like this:
219 : //
220 : // match cmp_fn(self.a, other.a) {
221 : // Ordering::Equal => match cmp_fn(self.b, other.b) {
222 : // Ordering::Equal =>cmp_fn(self.c, other.c),
223 : // cmp => cmp,
224 : // }
225 : // cmp => cmp,
226 : // }
227 : //
228 : // the last field comparison needs not to be a match but just the function call.
229 : // this is going to be annoying lol
230 : void
231 255 : DeriveOrd::visit_struct (StructStruct &item)
232 : {
233 255 : auto fields = SelfOther::fields (builder, item.get_fields ());
234 :
235 255 : auto match_expr = recursive_match (std::move (fields));
236 :
237 510 : expanded = cmp_impl (builder.block (std::move (match_expr)),
238 510 : item.get_identifier (), item.get_generic_params ());
239 255 : }
240 :
241 : // same as structs, but for each field index instead of each field name -
242 : // straightforward once we have `visit_struct` working
243 : void
244 314 : DeriveOrd::visit_tuple (TupleStruct &item)
245 : {
246 314 : auto fields = SelfOther::indexes (builder, item.get_fields ());
247 :
248 314 : auto match_expr = recursive_match (std::move (fields));
249 :
250 628 : expanded = cmp_impl (builder.block (std::move (match_expr)),
251 628 : item.get_identifier (), item.get_generic_params ());
252 314 : }
253 :
254 : // for enums, we need to generate a match for each of the enum's variant that
255 : // contains data and then do the same thing as visit_struct or visit_enum. if
256 : // the two aren't the same variant, then compare the two discriminant values for
257 : // all the dataless enum variants and in the general case.
258 : //
259 : // so for enum Foo { A(i32, i32), B, C } we need to do the following
260 : //
261 : // match (self, other) {
262 : // (A(self_0, self_1), A(other_0, other_1)) => {
263 : // match cmp_fn(self_0, other_0) {
264 : // Ordering::Equal => cmp_fn(self_1, other_1),
265 : // cmp => cmp,
266 : // },
267 : // _ => cmp_fn(discr_value(self), discr_value(other))
268 : // }
269 : void
270 126 : DeriveOrd::visit_enum (Enum &item)
271 : {
272 : // NOTE: We can factor this even further with DerivePartialEq, but this is
273 : // getting out of scope for this PR surely
274 :
275 126 : auto cases = std::vector<MatchCase> ();
276 252 : auto type_name = item.get_identifier ().as_string ();
277 :
278 126 : auto let_sd = builder.discriminant_value (DeriveOrd::self_discr, "self");
279 126 : auto let_od = builder.discriminant_value (DeriveOrd::other_discr, "other");
280 :
281 252 : auto discr_cmp = cmp_call (builder.identifier (DeriveOrd::self_discr),
282 378 : builder.identifier (DeriveOrd::other_discr));
283 :
284 312 : auto recursive_match_fn = [this] (std::vector<SelfOther> &&fields) {
285 186 : return recursive_match (std::move (fields));
286 126 : };
287 :
288 386 : for (auto &variant : item.get_variants ())
289 : {
290 260 : auto enum_builder
291 520 : = EnumMatchBuilder (type_name, variant->get_identifier ().as_string (),
292 260 : recursive_match_fn, builder);
293 :
294 260 : switch (variant->get_enum_item_kind ())
295 : {
296 8 : case EnumItem::Kind::Struct:
297 8 : cases.emplace_back (enum_builder.strukt (*variant));
298 8 : break;
299 178 : case EnumItem::Kind::Tuple:
300 178 : cases.emplace_back (enum_builder.tuple (*variant));
301 178 : break;
302 : case EnumItem::Kind::Identifier:
303 : case EnumItem::Kind::Discriminant:
304 : // We don't need to do anything for these, as they are handled by the
305 : // discriminant value comparison
306 : break;
307 : }
308 260 : }
309 :
310 : // Add the last case which compares the discriminant values in case `self` and
311 : // `other` are actually different variants of the enum
312 126 : cases.emplace_back (
313 252 : builder.match_case (builder.wildcard (), std::move (discr_cmp)));
314 :
315 126 : auto match
316 252 : = builder.match (builder.tuple (vec (builder.identifier ("self"),
317 252 : builder.identifier ("other"))),
318 126 : std::move (cases));
319 :
320 126 : expanded
321 252 : = cmp_impl (builder.block (vec (std::move (let_sd), std::move (let_od)),
322 : std::move (match)),
323 630 : type_name, item.get_generic_params ());
324 126 : }
325 :
326 : void
327 0 : DeriveOrd::visit_union (Union &item)
328 : {
329 0 : auto trait_name = trait (ordering);
330 :
331 0 : rust_error_at (item.get_locus (), "derive(%s) cannot be used on unions",
332 : trait_name.c_str ());
333 0 : }
334 :
335 : } // namespace AST
336 : } // namespace Rust
|