LCOV - code coverage report
Current view: top level - gcc/rust/expand - rust-derive-hash.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 97.9 % 142 139
Test Date: 2026-12-05 16:10:02 Functions: 92.3 % 13 12
Legend: Lines:     hit not hit

            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          428 : DeriveHash::DeriveHash (location_t loc, Builder::Source item_source)
      32          428 :   : DeriveVisitor (loc, item_source)
      33          428 : {}
      34              : 
      35              : std::unique_ptr<AST::Item>
      36          428 : DeriveHash::go (Item &item)
      37              : {
      38          428 :   item.accept_vis (*this);
      39              : 
      40          428 :   return std::move (expanded);
      41              : }
      42              : 
      43              : std::unique_ptr<Expr>
      44          561 : DeriveHash::hash_call (std::unique_ptr<Expr> &&value)
      45              : {
      46         3366 :   auto hash = builder.path_in_expression ({builder.get_path_start (), "hash",
      47          561 :                                            "Hash", "hash"},
      48         1122 :                                           builder.has_opening_scope ());
      49              : 
      50         1122 :   return builder.call (ptrify (hash),
      51         1122 :                        vec (std::move (value),
      52         1683 :                             builder.identifier (DeriveHash::state)));
      53          561 : }
      54              : 
      55              : std::unique_ptr<AssociatedItem>
      56          428 : DeriveHash::hash_fn (std::unique_ptr<BlockExpr> &&block)
      57              : {
      58          428 :   auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
      59              : 
      60          428 :   auto state_type = std::unique_ptr<TypeNoBounds> (
      61          428 :     new TypePath (builder.type_path (DeriveHash::state_type)));
      62          428 :   auto state_param =
      63              : 
      64          856 :     builder.function_param (builder.identifier_pattern (DeriveHash::state),
      65          856 :                             builder.reference_type (std::move (state_type),
      66          428 :                                                     true));
      67              : 
      68          428 :   auto params = vec (builder.self_ref_param (), std::move (state_param));
      69          856 :   auto bounds = vec (builder.trait_bound (
      70         2140 :     builder.type_path ({builder.get_path_start (), "hash", "Hasher"},
      71          428 :                        builder.has_opening_scope ())));
      72          428 :   auto generics = vec (
      73          428 :     builder.generic_type_param (DeriveHash::state_type, std::move (bounds)));
      74              : 
      75          856 :   return builder.function ("hash", std::move (params), nullptr,
      76          428 :                            std::move (block), std::move (generics));
      77          428 : }
      78              : 
      79              : std::unique_ptr<Item>
      80          428 : 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         1050 :   auto hash_path = [this] () {
      85         3110 :     return builder.type_path ({builder.get_path_start (), "hash", "Hash"},
      86         1244 :                               builder.has_opening_scope ());
      87          428 :   };
      88              : 
      89          428 :   auto trait_items = vec (std::move (hash_fn));
      90              : 
      91         1050 :   auto generics = setup_impl_generics (name, type_generics, [&, this] () {
      92          194 :     return builder.trait_bound (hash_path ());
      93          428 :   });
      94              : 
      95          856 :   return builder.trait_impl (hash_path (), std::move (generics.self_type),
      96              :                              std::move (trait_items),
      97          856 :                              std::move (generics.impl));
      98          428 : }
      99              : 
     100              : void
     101          167 : DeriveHash::visit_struct (StructStruct &item)
     102              : {
     103          167 :   auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
     104              : 
     105          360 :   for (auto &field : item.get_fields ())
     106              :     {
     107          193 :       auto value = builder.ref (
     108          386 :         builder.field_access (builder.identifier ("self"),
     109          386 :                               field.get_field_name ().as_string ()));
     110              : 
     111          193 :       auto stmt = builder.statementify (hash_call (std::move (value)));
     112              : 
     113          193 :       hash_calls.emplace_back (std::move (stmt));
     114          193 :     }
     115              : 
     116          167 :   auto block = builder.block (std::move (hash_calls));
     117              : 
     118          334 :   expanded = hash_impl (hash_fn (std::move (block)),
     119          167 :                         item.get_identifier ().as_string (),
     120          334 :                         item.get_generic_params ());
     121          167 : }
     122              : 
     123              : void
     124          169 : DeriveHash::visit_tuple (TupleStruct &item)
     125              : {
     126          169 :   auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
     127              : 
     128          339 :   for (size_t idx = 0; idx < item.get_fields ().size (); idx++)
     129              :     {
     130          170 :       auto value = builder.ref (builder.tuple_idx ("self", idx));
     131              : 
     132          170 :       auto stmt = builder.statementify (hash_call (std::move (value)));
     133              : 
     134          170 :       hash_calls.emplace_back (std::move (stmt));
     135          170 :     }
     136              : 
     137          169 :   auto block = builder.block (std::move (hash_calls));
     138              : 
     139          338 :   expanded = hash_impl (hash_fn (std::move (block)),
     140          169 :                         item.get_identifier ().as_string (),
     141          338 :                         item.get_generic_params ());
     142          169 : }
     143              : 
     144              : MatchCase
     145          105 : DeriveHash::match_enum_tuple (PathInExpression variant_path,
     146              :                               const EnumItemTuple &variant)
     147              : {
     148          105 :   auto self_patterns = std::vector<std::unique_ptr<Pattern>> ();
     149          105 :   auto hash_calls = std::vector<std::unique_ptr<Stmt>> ();
     150              : 
     151          210 :   for (size_t i = 0; i < variant.get_tuple_fields ().size (); i++)
     152              :     {
     153          105 :       auto pattern = "__self_" + std::to_string (i);
     154              : 
     155          210 :       auto call = hash_call (builder.ref (builder.identifier (pattern)));
     156              : 
     157          210 :       self_patterns.emplace_back (builder.identifier_pattern (pattern));
     158          105 :       hash_calls.emplace_back (builder.statementify (std::move (call)));
     159          105 :     }
     160              : 
     161          105 :   auto patterns_elts = std::unique_ptr<TupleStructItems> (
     162          105 :     new TupleStructItemsNoRest (std::move (self_patterns)));
     163          105 :   auto pattern = std::unique_ptr<Pattern> (
     164          105 :     new ReferencePattern (std::unique_ptr<Pattern> (new TupleStructPattern (
     165          210 :                             variant_path, std::move (patterns_elts))),
     166          210 :                           false, false, loc));
     167              : 
     168          105 :   auto block = builder.block (std::move (hash_calls));
     169              : 
     170          105 :   return builder.match_case (std::move (pattern), std::move (block));
     171          105 : }
     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           92 : 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           92 :   auto cases = std::vector<MatchCase> ();
     240          184 :   auto type_name = item.get_identifier ().as_string ();
     241              : 
     242           92 :   auto let_discr = builder.discriminant_value (DeriveHash::discr);
     243              : 
     244           92 :   auto discr_hash = builder.statementify (
     245           92 :     hash_call (builder.ref (builder.identifier (DeriveHash::discr))));
     246              : 
     247          342 :   for (auto &variant : item.get_variants ())
     248              :     {
     249          250 :       auto variant_path
     250              :         = builder.variant_path (type_name,
     251          250 :                                 variant->get_identifier ().as_string ());
     252              : 
     253          250 :       switch (variant->get_enum_item_kind ())
     254              :         {
     255          144 :         case EnumItem::Kind::Identifier:
     256          144 :         case EnumItem::Kind::Discriminant:
     257              :           // nothing to do in these cases, as we just need to hash the
     258              :           // discriminant value
     259          144 :           continue;
     260          105 :         case EnumItem::Kind::Tuple:
     261          210 :           cases.emplace_back (
     262          210 :             match_enum_tuple (variant_path,
     263          105 :                               static_cast<EnumItemTuple &> (*variant)));
     264          105 :           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          250 :     }
     272              : 
     273              :   // The extra empty wildcard case
     274           92 :   cases.emplace_back (
     275          184 :     builder.match_case (builder.wildcard (), builder.block ()));
     276              : 
     277           92 :   auto match = builder.match (builder.identifier ("self"), std::move (cases));
     278              : 
     279           92 :   auto block
     280          184 :     = builder.block (vec (std::move (let_discr), std::move (discr_hash)),
     281           92 :                      std::move (match));
     282              : 
     283          276 :   expanded = hash_impl (hash_fn (std::move (block)), type_name,
     284          184 :                         item.get_generic_params ());
     285           92 : }
     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
        

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.