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-hash.h"
20 : #include "rust-ast.h"
21 : #include "rust-expr.h"
22 : #include "rust-item.h"
23 : #include "rust-path.h"
24 : #include "rust-pattern.h"
25 : #include "rust-stmt.h"
26 : #include "rust-system.h"
27 :
28 : namespace Rust {
29 : namespace AST {
30 :
31 292 : DeriveHash::DeriveHash (location_t loc, Builder::Source item_source)
32 292 : : DeriveVisitor (loc, item_source)
33 292 : {}
34 :
35 : std::unique_ptr<AST::Item>
36 292 : DeriveHash::go (Item &item)
37 : {
38 292 : item.accept_vis (*this);
39 :
40 292 : return std::move (expanded);
41 : }
42 :
43 : std::unique_ptr<Expr>
44 385 : DeriveHash::hash_call (std::unique_ptr<Expr> &&value)
45 : {
46 2310 : auto hash = builder.path_in_expression ({builder.get_path_start (), "hash",
47 385 : "Hash", "hash"},
48 770 : builder.has_opening_scope ());
49 :
50 770 : return builder.call (ptrify (hash),
51 770 : vec (std::move (value),
52 1155 : builder.identifier (DeriveHash::state)));
53 385 : }
54 :
55 : std::unique_ptr<AssociatedItem>
56 292 : DeriveHash::hash_fn (std::unique_ptr<BlockExpr> &&block)
57 : {
58 292 : auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
59 :
60 292 : auto state_type = std::unique_ptr<TypeNoBounds> (
61 292 : new TypePath (builder.type_path (DeriveHash::state_type)));
62 292 : auto state_param =
63 :
64 584 : builder.function_param (builder.identifier_pattern (DeriveHash::state),
65 584 : builder.reference_type (std::move (state_type),
66 292 : true));
67 :
68 292 : auto params = vec (builder.self_ref_param (), std::move (state_param));
69 584 : auto bounds = vec (builder.trait_bound (
70 1460 : builder.type_path ({builder.get_path_start (), "hash", "Hasher"},
71 292 : builder.has_opening_scope ())));
72 292 : auto generics = vec (
73 292 : builder.generic_type_param (DeriveHash::state_type, std::move (bounds)));
74 :
75 584 : return builder.function ("hash", std::move (params), nullptr,
76 292 : std::move (block), std::move (generics));
77 292 : }
78 :
79 : std::unique_ptr<Item>
80 292 : DeriveHash::hash_impl (
81 : std::unique_ptr<AssociatedItem> &&hash_fn, std::string name,
82 : const std::vector<std::unique_ptr<GenericParam>> &type_generics)
83 : {
84 718 : auto hash_path = [this] () {
85 2130 : return builder.type_path ({builder.get_path_start (), "hash", "Hash"},
86 852 : builder.has_opening_scope ());
87 292 : };
88 :
89 292 : auto trait_items = vec (std::move (hash_fn));
90 :
91 718 : auto generics = setup_impl_generics (name, type_generics, [&, this] () {
92 134 : return builder.trait_bound (hash_path ());
93 292 : });
94 :
95 584 : return builder.trait_impl (hash_path (), std::move (generics.self_type),
96 : std::move (trait_items),
97 584 : std::move (generics.impl));
98 292 : }
99 :
100 : void
101 115 : DeriveHash::visit_struct (StructStruct &item)
102 : {
103 115 : auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
104 :
105 248 : for (auto &field : item.get_fields ())
106 : {
107 133 : auto value = builder.ref (
108 266 : builder.field_access (builder.identifier ("self"),
109 266 : field.get_field_name ().as_string ()));
110 :
111 133 : auto stmt = builder.statementify (hash_call (std::move (value)));
112 :
113 133 : hash_calls.emplace_back (std::move (stmt));
114 133 : }
115 :
116 115 : auto block = builder.block (std::move (hash_calls));
117 :
118 230 : expanded = hash_impl (hash_fn (std::move (block)),
119 115 : item.get_identifier ().as_string (),
120 230 : item.get_generic_params ());
121 115 : }
122 :
123 : void
124 113 : DeriveHash::visit_tuple (TupleStruct &item)
125 : {
126 113 : auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
127 :
128 227 : for (size_t idx = 0; idx < item.get_fields ().size (); idx++)
129 : {
130 114 : auto value = builder.ref (builder.tuple_idx ("self", idx));
131 :
132 114 : auto stmt = builder.statementify (hash_call (std::move (value)));
133 :
134 114 : hash_calls.emplace_back (std::move (stmt));
135 114 : }
136 :
137 113 : auto block = builder.block (std::move (hash_calls));
138 :
139 226 : expanded = hash_impl (hash_fn (std::move (block)),
140 113 : item.get_identifier ().as_string (),
141 226 : item.get_generic_params ());
142 113 : }
143 :
144 : MatchCase
145 73 : DeriveHash::match_enum_tuple (PathInExpression variant_path,
146 : const EnumItemTuple &variant)
147 : {
148 73 : auto self_patterns = std::vector<std::unique_ptr<Pattern>> ();
149 73 : auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
150 :
151 146 : for (size_t i = 0; i < variant.get_tuple_fields ().size (); i++)
152 : {
153 73 : auto pattern = "__self_" + std::to_string (i);
154 :
155 146 : auto call = hash_call (builder.ref (builder.identifier (pattern)));
156 :
157 146 : self_patterns.emplace_back (builder.identifier_pattern (pattern));
158 73 : hash_calls.emplace_back (builder.statementify (std::move (call)));
159 73 : }
160 :
161 73 : auto patterns_elts = std::unique_ptr<TupleStructItems> (
162 73 : new TupleStructItemsNoRest (std::move (self_patterns)));
163 73 : auto pattern = std::unique_ptr<Pattern> (
164 73 : new ReferencePattern (std::unique_ptr<Pattern> (new TupleStructPattern (
165 146 : variant_path, std::move (patterns_elts))),
166 146 : false, false, loc));
167 :
168 73 : auto block = builder.block (std::move (hash_calls));
169 :
170 73 : return builder.match_case (std::move (pattern), std::move (block));
171 73 : }
172 :
173 : MatchCase
174 1 : DeriveHash::match_enum_struct (PathInExpression variant_path,
175 : const EnumItemStruct &variant)
176 : {
177 1 : auto field_patterns = std::vector<std::unique_ptr<StructPatternField>> ();
178 1 : auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
179 :
180 2 : for (const auto &field : variant.get_struct_fields ())
181 : {
182 2 : auto call = hash_call (builder.ref (
183 4 : builder.identifier (field.get_field_name ().as_string ())));
184 :
185 1 : field_patterns.emplace_back (
186 1 : std::unique_ptr<StructPatternField> (new StructPatternFieldIdent (
187 2 : field.get_field_name (), false /* is_ref? true? */, false, {}, loc)));
188 :
189 1 : hash_calls.emplace_back (builder.statementify (std::move (call)));
190 1 : }
191 :
192 1 : auto pattern_elts = StructPatternElements (std::move (field_patterns));
193 1 : auto pattern = std::unique_ptr<Pattern> (
194 1 : new ReferencePattern (std::unique_ptr<Pattern> (new StructPattern (
195 2 : variant_path, loc, pattern_elts)),
196 2 : false, false, loc));
197 :
198 1 : auto block = builder.block (std::move (hash_calls));
199 1 : return builder.match_case (std::move (pattern), std::move (block));
200 2 : }
201 :
202 : void
203 64 : DeriveHash::visit_enum (Enum &item)
204 : {
205 : // Enums are a bit different: We start by hashing the discriminant value of
206 : // the enum instance, and then hash all of the data contained in each of the
207 : // enum's variants. For data-less variants, we don't have any data to hash, so
208 : // hashing the discriminant value is enough. To access the rest of the
209 : // variants' data, we create a match and destructure each internal field and
210 : // hash it.
211 : //
212 : // So for example with the following enum:
213 : //
214 : // ```rust
215 : // enum Foo {
216 : // A,
217 : // B(i32),
218 : // C { a: i32 },
219 : // }
220 : // ```
221 : //
222 : // we create the following implementation:
223 : //
224 : // ```rust
225 : // fn hash<H: Hasher>(&self, state: &mut H) {
226 : // let discriminant = intrinsics::discriminant_value(&self);
227 : // Hash::hash(&discriminant, state);
228 : //
229 : // match self {
230 : // B(self_0) => { Hash::hash(self_0, state); },
231 : // C { a } => { Hash::hash(a, state); },
232 : // _ => {},
233 : // }
234 : // }
235 : // ```
236 : //
237 : // Note the extra wildcard pattern to satisfy the exhaust checker.
238 :
239 64 : auto cases = std::vector<MatchCase> ();
240 128 : auto type_name = item.get_identifier ().as_string ();
241 :
242 64 : auto let_discr = builder.discriminant_value (DeriveHash::discr);
243 :
244 64 : auto discr_hash = builder.statementify (
245 64 : hash_call (builder.ref (builder.identifier (DeriveHash::discr))));
246 :
247 238 : for (auto &variant : item.get_variants ())
248 : {
249 174 : auto variant_path
250 : = builder.variant_path (type_name,
251 174 : variant->get_identifier ().as_string ());
252 :
253 174 : switch (variant->get_enum_item_kind ())
254 : {
255 100 : case EnumItem::Kind::Identifier:
256 100 : case EnumItem::Kind::Discriminant:
257 : // nothing to do in these cases, as we just need to hash the
258 : // discriminant value
259 100 : continue;
260 73 : case EnumItem::Kind::Tuple:
261 146 : cases.emplace_back (
262 146 : match_enum_tuple (variant_path,
263 73 : static_cast<EnumItemTuple &> (*variant)));
264 73 : break;
265 1 : case EnumItem::Kind::Struct:
266 2 : cases.emplace_back (
267 2 : match_enum_struct (variant_path,
268 1 : static_cast<EnumItemStruct &> (*variant)));
269 1 : break;
270 : }
271 174 : }
272 :
273 : // The extra empty wildcard case
274 64 : cases.emplace_back (
275 128 : builder.match_case (builder.wildcard (), builder.block ()));
276 :
277 64 : auto match = builder.match (builder.identifier ("self"), std::move (cases));
278 :
279 64 : auto block
280 128 : = builder.block (vec (std::move (let_discr), std::move (discr_hash)),
281 64 : std::move (match));
282 :
283 192 : expanded = hash_impl (hash_fn (std::move (block)), type_name,
284 128 : item.get_generic_params ());
285 64 : }
286 :
287 : void
288 0 : DeriveHash::visit_union (Union &item)
289 : {
290 0 : rust_error_at (item.get_locus (), "derive(Hash) cannot be used on unions");
291 0 : }
292 :
293 : } // namespace AST
294 : } // namespace Rust
|