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 495 : DeriveOrd::DeriveOrd (Ordering ordering, location_t loc,
30 : Builder::Source item_source)
31 495 : : DeriveVisitor (loc, item_source), ordering (ordering)
32 495 : {}
33 :
34 : std::unique_ptr<Item>
35 495 : DeriveOrd::go (Item &item)
36 : {
37 495 : item.accept_vis (*this);
38 :
39 495 : return std::move (expanded);
40 : }
41 :
42 : std::unique_ptr<Expr>
43 765 : DeriveOrd::cmp_call (std::unique_ptr<Expr> &&self_expr,
44 : std::unique_ptr<Expr> &&other_expr)
45 : {
46 765 : auto cmp_fn_path
47 4590 : = builder.path_in_expression ({builder.get_path_start (), "cmp",
48 : trait (ordering), fn (ordering)},
49 1530 : builder.has_opening_scope ());
50 :
51 1530 : return builder.call (ptrify (cmp_fn_path),
52 1530 : vec (builder.ref (std::move (self_expr)),
53 2295 : builder.ref (std::move (other_expr))));
54 765 : }
55 :
56 : std::unique_ptr<Item>
57 495 : 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 495 : auto fn = cmp_fn (std::move (fn_block), type_name);
62 :
63 495 : auto trait = ordering == Ordering::Partial ? "PartialOrd" : "Ord";
64 1136 : auto trait_path = [&, this] () {
65 3205 : return builder.type_path ({builder.get_path_start (), "cmp", trait},
66 1282 : builder.has_opening_scope ());
67 495 : };
68 :
69 495 : auto trait_bound
70 146 : = [&, this] () { return builder.trait_bound (trait_path ()); };
71 :
72 495 : auto trait_items = vec (std::move (fn));
73 :
74 495 : auto cmp_generics
75 495 : = setup_impl_generics (type_name.as_string (), type_generics, trait_bound);
76 :
77 990 : return builder.trait_impl (trait_path (), std::move (cmp_generics.self_type),
78 : std::move (trait_items),
79 990 : std::move (cmp_generics.impl));
80 495 : }
81 :
82 : std::unique_ptr<AssociatedItem>
83 495 : DeriveOrd::cmp_fn (std::unique_ptr<BlockExpr> &&block, Identifier type_name)
84 : {
85 : // Ordering
86 495 : auto return_type
87 2475 : = builder.type_path ({builder.get_path_start (), "cmp", "Ordering"},
88 990 : builder.has_opening_scope ());
89 :
90 : // In the case of PartialOrd, we return an Option<Ordering>
91 495 : if (ordering == Ordering::Partial)
92 : {
93 248 : auto generic = GenericArg::create_type (ptrify (return_type));
94 :
95 248 : auto generic_seg = builder.type_path_segment_generic (
96 496 : "Option", GenericArgs ({}, {generic}, {}, loc));
97 248 : auto core = builder.type_path_segment (builder.get_path_start ());
98 248 : auto option = builder.type_path_segment ("option");
99 :
100 248 : return_type
101 496 : = builder.type_path (vec (std::move (core), std::move (option),
102 : std::move (generic_seg)),
103 248 : builder.has_opening_scope ());
104 248 : }
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 495 : auto params
111 990 : = vec (builder.self_ref_param (),
112 990 : builder.function_param (builder.identifier_pattern ("other"),
113 990 : builder.reference_type (
114 1485 : ptrify (builder.type_path ("Self")))));
115 :
116 495 : auto function_name = fn (ordering);
117 :
118 2475 : return builder.function (function_name, std::move (params),
119 1485 : ptrify (return_type), std::move (block));
120 495 : }
121 :
122 : std::unique_ptr<Pattern>
123 182 : DeriveOrd::make_equal ()
124 : {
125 182 : std::unique_ptr<Pattern> equal
126 910 : = ptrify (builder.path_in_expression ({builder.get_path_start (), "cmp",
127 182 : "Ordering", "Equal"},
128 182 : builder.has_opening_scope ()));
129 :
130 : // We need to wrap the pattern in Option::Some if we are doing partial
131 : // ordering
132 182 : if (ordering == Ordering::Partial)
133 : {
134 103 : auto pattern_items = std::unique_ptr<TupleStructItems> (
135 103 : new TupleStructItemsNoRest (vec (std::move (equal))));
136 :
137 103 : equal
138 206 : = std::make_unique<TupleStructPattern> (builder.path_in_expression (
139 : LangItem::Kind::OPTION_SOME),
140 103 : std::move (pattern_items));
141 103 : }
142 :
143 182 : return equal;
144 : }
145 :
146 : std::pair<MatchArm, MatchArm>
147 182 : DeriveOrd::make_cmp_arms ()
148 : {
149 : // All comparison results other than Ordering::Equal
150 182 : auto non_equal = builder.identifier_pattern (DeriveOrd::not_equal);
151 182 : auto equal = make_equal ();
152 :
153 182 : return {builder.match_arm (std::move (equal)),
154 182 : builder.match_arm (std::move (non_equal))};
155 182 : }
156 :
157 : std::unique_ptr<Expr>
158 539 : DeriveOrd::recursive_match (std::vector<SelfOther> &&members)
159 : {
160 539 : if (members.empty ())
161 : {
162 50 : std::unique_ptr<Expr> value
163 300 : = ptrify (builder.path_in_expression ({builder.get_path_start (), "cmp",
164 50 : "Ordering", "Equal"},
165 50 : builder.has_opening_scope ()));
166 :
167 50 : if (ordering == Ordering::Partial)
168 75 : value = builder.call (ptrify (builder.path_in_expression (
169 : LangItem::Kind::OPTION_SOME)),
170 25 : std::move (value));
171 :
172 : return value;
173 : }
174 :
175 489 : std::unique_ptr<Expr> final_expr = nullptr;
176 :
177 1160 : for (auto it = members.rbegin (); it != members.rend (); it++)
178 : {
179 671 : auto &member = *it;
180 :
181 671 : auto call = cmp_call (std::move (member.self_expr),
182 671 : std::move (member.other_expr));
183 :
184 : // For the last member (so the first iterator), we just create a call
185 : // expression
186 671 : if (it == members.rbegin ())
187 : {
188 489 : final_expr = std::move (call);
189 489 : 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 182 : auto match_arms = make_cmp_arms ();
195 :
196 182 : 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 910 : builder.identifier (DeriveOrd::not_equal))};
201 :
202 182 : final_expr = builder.match (std::move (call), std::move (match_cases));
203 1217 : }
204 :
205 489 : return final_expr;
206 489 : }
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 191 : DeriveOrd::visit_struct (StructStruct &item)
232 : {
233 191 : auto fields = SelfOther::fields (builder, item.get_fields ());
234 :
235 191 : auto match_expr = recursive_match (std::move (fields));
236 :
237 382 : expanded = cmp_impl (builder.block (std::move (match_expr)),
238 382 : item.get_identifier (), item.get_generic_params ());
239 191 : }
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 210 : DeriveOrd::visit_tuple (TupleStruct &item)
245 : {
246 210 : auto fields = SelfOther::indexes (builder, item.get_fields ());
247 :
248 210 : auto match_expr = recursive_match (std::move (fields));
249 :
250 420 : expanded = cmp_impl (builder.block (std::move (match_expr)),
251 420 : item.get_identifier (), item.get_generic_params ());
252 210 : }
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 94 : 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 94 : auto cases = std::vector<MatchCase> ();
276 188 : auto type_name = item.get_identifier ().as_string ();
277 :
278 94 : auto let_sd = builder.discriminant_value (DeriveOrd::self_discr, "self");
279 94 : auto let_od = builder.discriminant_value (DeriveOrd::other_discr, "other");
280 :
281 188 : auto discr_cmp = cmp_call (builder.identifier (DeriveOrd::self_discr),
282 282 : builder.identifier (DeriveOrd::other_discr));
283 :
284 232 : auto recursive_match_fn = [this] (std::vector<SelfOther> &&fields) {
285 138 : return recursive_match (std::move (fields));
286 94 : };
287 :
288 290 : for (auto &variant : item.get_variants ())
289 : {
290 196 : auto enum_builder
291 392 : = EnumMatchBuilder (type_name, variant->get_identifier ().as_string (),
292 196 : recursive_match_fn, builder);
293 :
294 196 : 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 130 : case EnumItem::Kind::Tuple:
300 130 : cases.emplace_back (enum_builder.tuple (*variant));
301 130 : 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 196 : }
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 94 : cases.emplace_back (
313 188 : builder.match_case (builder.wildcard (), std::move (discr_cmp)));
314 :
315 94 : auto match
316 188 : = builder.match (builder.tuple (vec (builder.identifier ("self"),
317 188 : builder.identifier ("other"))),
318 94 : std::move (cases));
319 :
320 94 : expanded
321 188 : = cmp_impl (builder.block (vec (std::move (let_sd), std::move (let_od)),
322 : std::move (match)),
323 470 : type_name, item.get_generic_params ());
324 94 : }
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
|