11use rustc_middle:: ty:: TyCtxt ;
22use rustc_span:: source_map:: SourceMap ;
3+ use rustc_stable_hash:: { FromStableHash , SipHasher128Hash , StableHasher , hashers:: SipHasher128 } ;
34use serde:: Serialize ;
45use stable_mir:: { CrateDef , DefId , mir:: mono:: Instance } ;
6+ use std:: hash:: Hasher ;
57
68/// A Rust funtion with its file source, attributes, and raw function content.
79#[ derive( Debug , Serialize ) ]
810pub struct SerFunction {
11+ hash : String ,
912 /// DefId in stable_mir.
1013 def_id : String ,
1114 /// Every funtion must be declared in a specific file, even for those
@@ -22,15 +25,40 @@ pub struct SerFunction {
2225
2326impl SerFunction {
2427 pub fn new ( fun : super :: Function , tcx : TyCtxt , src_map : & SourceMap ) -> Self {
25- SerFunction {
26- def_id : format_def_id ( & fun. def_id ) ,
27- file : fun. file ,
28- attrs : fun. attrs . iter ( ) . map ( |a| a. as_str ( ) . to_owned ( ) ) . collect ( ) ,
29- func : fun. func ,
30- callees : fun. callees . iter ( ) . map ( |x| Callee :: new ( x, tcx, src_map) ) . collect ( ) ,
31- }
28+ let def_id = format_def_id ( & fun. def_id ) ;
29+ let file = fun. file ;
30+ let attrs: Vec < _ > = fun. attrs . iter ( ) . map ( |a| a. as_str ( ) . to_owned ( ) ) . collect ( ) ;
31+ let func = fun. func ;
32+ let callees: Vec < _ > = fun. callees . iter ( ) . map ( |x| Callee :: new ( x, tcx, src_map) ) . collect ( ) ;
33+
34+ // Hash
35+ let mut hasher = StableHasher :: < SipHasher128 > :: new ( ) ;
36+ hasher. write_str ( & file) ;
37+ hasher. write_str ( & func) ;
38+ hasher. write_length_prefix ( attrs. len ( ) ) ;
39+ attrs. iter ( ) . for_each ( |a| hasher. write_str ( a) ) ;
40+ hasher. write_length_prefix ( callees. len ( ) ) ;
41+ callees. iter ( ) . for_each ( |c| {
42+ hasher. write_str ( & c. file ) ;
43+ hasher. write_str ( & c. func ) ;
44+ } ) ;
45+ let Hash128 ( hash) = hasher. finish ( ) ;
46+
47+ SerFunction { hash, def_id, file, attrs, func, callees }
48+ }
49+ }
50+
51+ // ************* hash *************
52+ struct Hash128 ( String ) ;
53+
54+ impl FromStableHash for Hash128 {
55+ type Hash = SipHasher128Hash ;
56+
57+ fn from ( SipHasher128Hash ( [ a, b] ) : SipHasher128Hash ) -> Hash128 {
58+ Hash128 ( format ! ( "{a}{b}" ) )
3259 }
3360}
61+ // ************* hash *************
3462
3563fn format_def_id ( def_id : & DefId ) -> String {
3664 format ! ( "{def_id:?}" )
0 commit comments