Debian Codegraph @

debian/rust-vendor/linktime-proc-macro/src/hash/mod.rs

raw
1 use proc_macro::{Delimiter, TokenStream, TokenTree};
2 use std::path::Path;
3
4 pub(crate) mod xx3;
5
6 struct TokenTreeDeepIterator {
7 stack: Vec<proc_macro::token_stream::IntoIter>,
8 }
9
10 impl Iterator for TokenTreeDeepIterator {
11 type Item = TokenTree;
12
13 fn next(&mut self) -> Option<Self::Item> {
14 loop {
15 let mut iter = self.stack.pop()?;
16 let Some(token) = iter.next() else {
17 continue;
18 };
19 self.stack.push(iter);
20 if let TokenTree::Group(group) = &token {
21 self.stack.push(group.stream().into_iter());
22 }
23 return Some(token);
24 }
25 }
26 }
27
28 /// Content (position-independent) identity for an ignored token. Groups
29 /// contribute only their delimiter and the deep iterator visits children
30 /// separately.
31 fn token_content(token: &TokenTree) -> String {
32 match token {
33 TokenTree::Group(group) => match group.delimiter() {
34 Delimiter::Parenthesis => "(".to_string(),
35 Delimiter::Brace => "{".to_string(),
36 Delimiter::Bracket => "[".to_string(),
37 Delimiter::None => String::new(),
38 },
39 TokenTree::Ident(ident) => ident.to_string(),
40 TokenTree::Punct(punct) => punct.as_char().to_string(),
41 TokenTree::Literal(literal) => literal.to_string(),
42 }
43 }
44
45 /// Hash location of every token in `tokens`. Tokens under `ignore_base` contribute
46 /// content instead, so def-site spans from that crate don't shift the hash.
47 #[allow(clippy::unnecessary_map_or)]
48 pub(crate) fn location_hash(tokens: TokenStream, ignore_base: Option<&Path>) -> u64 {
49 let iterator = TokenTreeDeepIterator {
50 stack: vec![tokens.into_iter()],
51 };
52
53 // TODO: Can we avoid doing multiple hashes?
54 let mut buffer: Vec<u8> = Vec::with_capacity(1024);
55 let mut last_hash = 0_u64;
56 for token in iterator {
57 let span = token.span();
58 buffer.clear();
59 buffer.extend_from_slice(&last_hash.to_be_bytes());
60
61 let ignored = ignore_base.map_or(false, |base| {
62 crate::fallback::local_file(&span).map_or(false, |file| file.starts_with(base))
63 });
64
65 if ignored {
66 buffer.extend_from_slice(token_content(&token).as_bytes());
67 } else {
68 let line = crate::fallback::line(&span);
69 let column = crate::fallback::column(&span);
70 let file = crate::fallback::file(&span);
71 buffer.extend_from_slice(&(line as u64).to_be_bytes());
72 buffer.extend_from_slice(&(column as u64).to_be_bytes());
73 buffer.extend_from_slice(file.as_bytes());
74 }
75
76 last_hash = crate::hash::xx3::xx3hash_bytes(&buffer);
77 }
78
79 last_hash
80 }