Debian Codegraph @

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

raw
1 mod args;
2
3 use std::borrow::Cow;
4 use std::collections::HashMap;
5 use std::path::{Path, PathBuf};
6
7 use proc_macro::{Group, Ident, Literal, Span, TokenStream, TokenTree};
8
9 use self::args::{
10 parse_arguments, pop_argument, pop_optional_argument, Argument, OutputType, PatternString,
11 TranslateString,
12 };
13
14 pub(crate) fn combine(item: TokenStream) -> TokenStream {
15 let mut args = parse_arguments(item, "combine!");
16 let output = pop_argument::<OutputType>(&mut args, "combine!", "output");
17 let input = pop_argument::<TokenStream>(&mut args, "combine!", "input");
18 let prefix = pop_optional_argument::<TokenStream>(&mut args, "combine!", "prefix");
19 let suffix = pop_optional_argument::<TokenStream>(&mut args, "combine!", "suffix");
20 let paren = pop_optional_argument::<TokenTree>(&mut args, "combine!", "paren");
21 let paren_prefix = pop_optional_argument::<TokenStream>(&mut args, "combine!", "paren_prefix");
22 let paren_suffix = pop_optional_argument::<TokenStream>(&mut args, "combine!", "paren_suffix");
23 let span = pop_optional_argument::<Span>(&mut args, "combine!", "span");
24
25 let mut s = String::with_capacity(32);
26
27 parse_stream(&mut s, "input", output, input);
28
29 let span = span.unwrap_or_else(Span::call_site);
30
31 let output_token = match output {
32 OutputType::Ident => TokenTree::Ident(Ident::new(to_ident(&s).as_ref(), span)),
33 OutputType::String => TokenTree::Literal(Literal::string(s.as_str())),
34 OutputType::ISize => {
35 let s = s.replace(|c: char| c != '+' && c != '-' && !c.is_ascii_digit(), "");
36 TokenTree::Literal(Literal::isize_suffixed(
37 s.parse::<isize>().expect("input: Expected a valid isize"),
38 ))
39 }
40 OutputType::RawString => unreachable!(),
41 };
42
43 let mut stream = TokenStream::new();
44 if let Some(prefix) = prefix {
45 stream.extend(prefix);
46 }
47 if let Some(paren) = paren {
48 let TokenTree::Group(group) = paren else {
49 panic!("combine!: Expected an empty group in paren");
50 };
51 let mut paren_stream = TokenStream::new();
52 if let Some(paren_prefix) = paren_prefix {
53 paren_stream.extend(paren_prefix);
54 }
55 paren_stream.extend([output_token]);
56 if let Some(paren_suffix) = paren_suffix {
57 paren_stream.extend(paren_suffix);
58 }
59 let group = Group::new(group.delimiter(), paren_stream);
60 stream.extend([TokenTree::Group(group)]);
61 } else {
62 stream.extend([output_token]);
63 }
64 if let Some(suffix) = suffix {
65 stream.extend(suffix);
66 }
67 stream
68 }
69
70 #[allow(unknown_lints, tail_expr_drop_order)]
71 fn parse_stream(s: &mut String, arg: &str, output: OutputType, input: TokenStream) {
72 let mut input = input.into_iter();
73 while let Some(token) = input.next() {
74 match token {
75 TokenTree::Literal(literal) => {
76 let literal = literal.to_string();
77 if literal.starts_with('"') && literal.ends_with('"') {
78 decode_literal_string(
79 s,
80 arg,
81 literal
82 .strip_prefix('"')
83 .unwrap()
84 .strip_suffix('"')
85 .unwrap(),
86 );
87 } else if literal.starts_with('\'') && literal.ends_with('\'') {
88 decode_literal_string(
89 s,
90 arg,
91 literal
92 .strip_prefix('\'')
93 .unwrap()
94 .strip_suffix('\'')
95 .unwrap(),
96 );
97 } else if literal.starts_with(|c: char| c.is_ascii_digit()) {
98 s.push_str(&literal);
99 } else {
100 panic!(
101 "{arg}: Expected a literal string or numeric literal, got `{literal:?}`"
102 );
103 }
104 }
105 TokenTree::Ident(ident) => {
106 let ident = ident.to_string();
107 if output != OutputType::RawString
108 && ident.len() > 2
109 && ident.starts_with("__")
110 && ident.ends_with("__")
111 {
112 parse_function(s, arg, &mut input, &ident);
113 } else {
114 s.push_str(&ident);
115 }
116 }
117 TokenTree::Group(group) => parse_stream(s, arg, output, group.stream()),
118 TokenTree::Punct(punct) => s.push(punct.as_char()),
119 }
120 }
121 }
122
123 /// Resolve `__LOCATIONHASH__`'s optional `ignore_base` into a crate-root
124 /// directory.
125 ///
126 /// The marker token's span locates the crate and its string value is a path
127 /// suffix stripped to reach that crate's root. Returns `None` (ignore nothing)
128 /// when `local_file` is unavailable, the suffix does not match, or the base
129 /// would be empty/filesystem-root (would match every token).
130 fn pop_ignore_base(args: &mut HashMap<String, TokenTree>, ident: &str) -> Option<PathBuf> {
131 let token = args.remove("ignore_base")?;
132 let span = <Span as Argument>::from_token_tree(token.clone())
133 .unwrap_or_else(|e| panic!("{ident}: Invalid argument 'ignore_base': {e}"));
134 let suffix = <String as Argument>::from_token_tree(token)
135 .unwrap_or_else(|e| panic!("{ident}: Invalid argument 'ignore_base': {e}"));
136
137 let file = crate::fallback::local_file(&span)?;
138 if !file.ends_with(&suffix) {
139 return None;
140 }
141 let components = Path::new(&suffix).components().count();
142 let base = file.ancestors().nth(components)?;
143 if base.as_os_str().is_empty() || base.parent().is_none() {
144 return None;
145 }
146 Some(base.to_path_buf())
147 }
148
149 fn parse_function(
150 s: &mut String,
151 arg: &str,
152 input: &mut proc_macro::token_stream::IntoIter,
153 ident: &String,
154 ) {
155 let func = &ident[2..ident.len() - 2];
156 let Some(TokenTree::Group(group)) = input.next() else {
157 panic!("Expected arguments after {ident:?}");
158 };
159 let mut args = parse_arguments(group.stream(), ident);
160 match func {
161 "FILE" => {
162 let of = pop_optional_argument::<Span>(&mut args, ident, "of")
163 .unwrap_or_else(Span::call_site);
164 let file = crate::fallback::file(&of);
165 s.push_str(&file);
166 }
167 "LINE" => {
168 let of = pop_optional_argument::<Span>(&mut args, ident, "of")
169 .unwrap_or_else(Span::call_site);
170 let line = crate::fallback::line(&of);
171 s.push_str(&line.to_string());
172 }
173 "COLUMN" => {
174 let of = pop_optional_argument::<Span>(&mut args, ident, "of")
175 .unwrap_or_else(Span::call_site);
176 let column = crate::fallback::column(&of);
177 s.push_str(&column.to_string());
178 }
179 "SOURCE" => {
180 let of = pop_argument::<TokenStream>(&mut args, ident, "of");
181 for (i, token) in of.into_iter().enumerate() {
182 if i > 0 {
183 s.push(' ');
184 }
185 s.push_str(
186 crate::fallback::source_text(&token.span())
187 .unwrap_or_default()
188 .as_ref(),
189 );
190 }
191 }
192 "DEBUG" => {
193 let of = pop_argument::<TokenTree>(&mut args, ident, "of");
194 s.push_str(&format!("{:?}", of));
195 }
196 "HASH" => {
197 let input = pop_argument::<String>(&mut args, ident, "string");
198 let alphabet = pop_optional_argument::<TranslateString>(&mut args, ident, "alphabet");
199 let mut hash = crate::hash::xx3::xx3hash(&input);
200 if let Some(alphabet) = alphabet {
201 if hash == 0 {
202 s.push(alphabet.char(0));
203 } else {
204 let mut hash_str = String::with_capacity(32);
205 while hash > 0 {
206 hash_str.push(alphabet.char((hash % alphabet.len() as u64) as usize));
207 hash /= alphabet.len() as u64;
208 }
209 s.extend(hash_str.chars().rev());
210 }
211 } else {
212 s.push_str(&format!("{:016x}", hash));
213 }
214 }
215 "LOCATIONHASH" => {
216 let input = pop_argument::<TokenStream>(&mut args, ident, "of");
217 let alphabet = pop_optional_argument::<TranslateString>(&mut args, ident, "alphabet");
218 let ignore_base = pop_ignore_base(&mut args, ident);
219 let mut hash = crate::hash::location_hash(input, ignore_base.as_deref());
220 if let Some(alphabet) = alphabet {
221 if hash == 0 {
222 s.push(alphabet.char(0));
223 } else {
224 let mut hash_str = String::with_capacity(32);
225 while hash > 0 {
226 hash_str.push(alphabet.char((hash % alphabet.len() as u64) as usize));
227 hash /= alphabet.len() as u64;
228 }
229 s.extend(hash_str.chars().rev());
230 }
231 } else {
232 s.push_str(&format!("{:016x}", hash));
233 }
234 }
235 "LENGTH" => {
236 let input = pop_argument::<String>(&mut args, ident, "string");
237 s.push_str(&input.len().to_string());
238 }
239 "REPLACE" => {
240 let input = pop_argument::<String>(&mut args, ident, "input");
241 let pattern = pop_argument::<PatternString>(&mut args, ident, "pattern");
242 let replacement = pop_argument::<String>(&mut args, ident, "replacement");
243
244 match pattern {
245 PatternString::Range(range) => {
246 s.push_str(&input.replace(|c: char| range.is_match(c), &replacement));
247 }
248 PatternString::String(string) => {
249 s.push_str(&input.replace(&string, &replacement));
250 }
251 }
252 }
253 "TRANSLATE" => {
254 let input = pop_argument::<String>(&mut args, ident, "input");
255 let pattern = pop_argument::<TranslateString>(&mut args, ident, "pattern");
256 let replacement =
257 pop_optional_argument::<TranslateString>(&mut args, ident, "replacement")
258 .unwrap_or_default();
259 for c in input.chars() {
260 if let Some(index) = pattern.find(c) {
261 if !replacement.is_empty() {
262 s.push(replacement.char(index));
263 }
264 } else {
265 s.push(c);
266 }
267 }
268 }
269 "TRIM" => {
270 let input = pop_argument::<String>(&mut args, ident, "input");
271 let left = pop_argument::<PatternString>(&mut args, ident, "left");
272 let right = pop_argument::<PatternString>(&mut args, ident, "right");
273 let input = match left {
274 PatternString::Range(range) => {
275 input.trim_start_matches(|c: char| range.is_match(c))
276 }
277 PatternString::String(string) => input.trim_start_matches(&string),
278 };
279 let input = match right {
280 PatternString::Range(range) => input.trim_end_matches(|c: char| range.is_match(c)),
281 PatternString::String(string) => input.trim_end_matches(&string),
282 };
283 s.push_str(input);
284 }
285 "CONTAINS" => {
286 let input = pop_argument::<String>(&mut args, ident, "input");
287 let pattern = pop_argument::<PatternString>(&mut args, ident, "pattern");
288 let sucesss = match pattern {
289 PatternString::Range(range) => input.contains(|c: char| range.is_match(c)),
290 PatternString::String(string) => input.contains(&string),
291 };
292 s.push_str(if sucesss { "1" } else { "0" });
293 }
294 "STREQ" => {
295 let a = pop_argument::<String>(&mut args, ident, "a");
296 let b = pop_argument::<String>(&mut args, ident, "b");
297 s.push_str(if a == b { "1" } else { "0" });
298 }
299 "SUBSTRING" => {
300 let input = pop_argument::<String>(&mut args, ident, "input");
301 let start = pop_optional_argument::<usize>(&mut args, ident, "start").unwrap_or(0);
302 let end = pop_optional_argument::<usize>(&mut args, ident, "end");
303 let length = pop_optional_argument::<usize>(&mut args, ident, "length");
304
305 let end = end.or(length.map(|l| start + l)).unwrap_or(usize::MAX);
306 let end = end.min(input.len());
307
308 s.push_str(&input[start..end]);
309 }
310 "PAD" => {
311 let input = pop_argument::<String>(&mut args, ident, "input");
312 let length = pop_argument::<usize>(&mut args, ident, "length");
313 let left =
314 pop_optional_argument::<String>(&mut args, ident, "left").unwrap_or_default();
315 let right =
316 pop_optional_argument::<String>(&mut args, ident, "right").unwrap_or_default();
317 if !left.is_empty() && !right.is_empty() {
318 panic!("{arg}: Expected a left xor right padding, got both");
319 }
320
321 let mut len = input.len();
322 if !left.is_empty() {
323 while len < length {
324 s.push_str(&left);
325 len += left.len();
326 }
327 }
328 s.push_str(&input);
329 if !right.is_empty() {
330 while len < length {
331 s.push_str(&right);
332 len += right.len();
333 }
334 }
335 }
336 "IF" => {
337 let a = pop_argument::<isize>(&mut args, ident, "test");
338 let then_tree = pop_argument::<String>(&mut args, ident, "then");
339 let else_tree =
340 pop_optional_argument::<String>(&mut args, ident, "else").unwrap_or_default();
341
342 if a != 0 {
343 s.push_str(&then_tree);
344 } else {
345 s.push_str(&else_tree);
346 }
347 }
348 "ADD" => {
349 let a = pop_argument::<isize>(&mut args, ident, "a");
350 let b = pop_argument::<isize>(&mut args, ident, "b");
351 s.push_str(&(a + b).to_string());
352 }
353 "SUB" => {
354 let a = pop_argument::<isize>(&mut args, ident, "a");
355 let b = pop_argument::<isize>(&mut args, ident, "b");
356 s.push_str(&(a - b).to_string());
357 }
358 "MUL" => {
359 let a = pop_argument::<isize>(&mut args, ident, "a");
360 let b = pop_argument::<isize>(&mut args, ident, "b");
361 s.push_str(&(a * b).to_string());
362 }
363 "DIV" => {
364 let a = pop_argument::<isize>(&mut args, ident, "a");
365 let b = pop_argument::<isize>(&mut args, ident, "b");
366 s.push_str(&(a / b).to_string());
367 }
368 "AND" => {
369 let a = pop_argument::<isize>(&mut args, ident, "a");
370 let b = pop_argument::<isize>(&mut args, ident, "b");
371 s.push_str(&(a & b).to_string());
372 }
373 "OR" => {
374 let a = pop_argument::<isize>(&mut args, ident, "a");
375 let b = pop_argument::<isize>(&mut args, ident, "b");
376 s.push_str(&(a | b).to_string());
377 }
378 "NE" => {
379 let a = pop_argument::<isize>(&mut args, ident, "a");
380 let b = pop_argument::<isize>(&mut args, ident, "b");
381 s.push_str(&((a != b) as u8).to_string());
382 }
383 "EQ" => {
384 let a = pop_argument::<isize>(&mut args, ident, "a");
385 let b = pop_argument::<isize>(&mut args, ident, "b");
386 s.push_str(&((a == b) as u8).to_string());
387 }
388 "GE" => {
389 let a = pop_argument::<isize>(&mut args, ident, "a");
390 let b = pop_argument::<isize>(&mut args, ident, "b");
391 s.push_str(&((a >= b) as u8).to_string());
392 }
393 "GT" => {
394 let a = pop_argument::<isize>(&mut args, ident, "a");
395 let b = pop_argument::<isize>(&mut args, ident, "b");
396 s.push_str(&((a > b) as u8).to_string());
397 }
398 "LE" => {
399 let a = pop_argument::<isize>(&mut args, ident, "a");
400 let b = pop_argument::<isize>(&mut args, ident, "b");
401 s.push_str(&((a <= b) as u8).to_string());
402 }
403 "LT" => {
404 let a = pop_argument::<isize>(&mut args, ident, "a");
405 let b = pop_argument::<isize>(&mut args, ident, "b");
406 s.push_str(&((a < b) as u8).to_string());
407 }
408 "RAW" => {
409 let input = pop_argument::<TokenStream>(&mut args, ident, "input");
410 let mut raw = String::with_capacity(32);
411 parse_stream(&mut raw, ident, OutputType::RawString, input);
412 s.push_str(&raw);
413 }
414 "TOSTRING" => {
415 let input = pop_argument::<String>(&mut args, ident, "input");
416 s.push_str(&input);
417 }
418 "TOIDENT" => {
419 let input = pop_argument::<String>(&mut args, ident, "input");
420 s.push_str(to_ident(&input).as_ref());
421 }
422 "TONUMBER" => {
423 let input = pop_argument::<isize>(&mut args, ident, "input");
424 s.push_str(&input.to_string());
425 }
426 _ => {
427 panic!("Unknown function: {func}");
428 }
429 }
430 }
431
432 pub(crate) fn decode_literal_string(s: &mut String, name: &str, literal: &str) {
433 if !literal.contains('\\') {
434 s.push_str(literal);
435 } else {
436 let mut iter = literal.chars();
437 while let Some(c) = iter.next() {
438 if c == '\\' {
439 match iter.next() {
440 Some('n') => s.push('\n'),
441 Some('r') => s.push('\r'),
442 Some('t') => s.push('\t'),
443 Some('\\') => s.push('\\'),
444 Some('"') => s.push('"'),
445 Some('\'') => s.push('\''),
446 Some('0') => s.push('\0'),
447 Some('x') => {
448 let Some(c) = iter.next() else {
449 panic!("{}: Expected a hexadecimal character", name);
450 };
451 let Some(c2) = iter.next() else {
452 panic!("{}: Expected a hexadecimal character", name);
453 };
454 let Ok(c) = format!("{}{}", c, c2).parse::<u8>() else {
455 panic!("{}: Expected a hexadecimal character", name);
456 };
457 s.push(char::from(c));
458 }
459 Some(_) => panic!("{name}: Expected a valid escape sequence (got {c:?})"),
460 None => break,
461 }
462 } else {
463 s.push(c);
464 }
465 }
466 }
467 }
468
469 fn to_ident(input: &str) -> Cow<'_, str> {
470 // Idents must be XID_Start + XID_Continue*, but we just use
471 // is_alphabetic and is_alphanumeric as an approximation.
472 let mut s = input;
473 while !s.starts_with(|c: char| c.is_alphabetic() || c == '_') {
474 if s.is_empty() {
475 panic!("No valid ident characters found in `{input}`");
476 }
477 s = &s[1..];
478 }
479
480 // If we detect any invalid chars, filter them one-by-one.
481 if s[1..].contains(|c: char| !c.is_alphanumeric() && c != '_') {
482 let mut output = String::with_capacity(s.len());
483 let mut chars = s.chars();
484 // We know there's always at least one
485 output.push(chars.next().unwrap());
486 for c in chars {
487 if c.is_alphanumeric() || c == '_' {
488 output.push(c);
489 }
490 }
491 Cow::Owned(output)
492 } else {
493 // Fast path: all valid chars are alphanumeric or underscore.
494 Cow::Borrowed(s)
495 }
496 }