Debian Codegraph @

debian/rust-vendor/phf_codegen/src/lib.rs

raw
1 //! A set of builders to generate Rust source for PHF data structures at
2 //! compile time.
3 //!
4 //! The provided builders are intended to be used in a Cargo build script to
5 //! generate a Rust source file that will be included in a library at build
6 //! time.
7 //!
8 //! For more information about `rust-phf` crates, see [the `phf` crate's documentation][phf].
9 //!
10 //! [phf]: https://docs.rs/phf
11 //!
12 //! ## Examples
13 //!
14 //! To use `phf_codegen` on build.rs, you have to add dependencies under `[build-dependencies]`:
15 //!
16 //! ```toml
17 //! [build-dependencies]
18 //! phf = { version = "0.14.0", default-features = false }
19 //! phf_codegen = "0.14.0"
20 //! ```
21 //!
22 //! When using the experimental `ptrhash` feature, enable it on both
23 //! `phf_codegen` and the runtime `phf` dependency so the generated constants
24 //! and runtime layout stay in sync.
25 //!
26 //! Then put code on build.rs:
27 //!
28 //! ```ignore
29 //! use std::env;
30 //! use std::fs::File;
31 //! use std::io::{BufWriter, Write};
32 //! use std::path::Path;
33 //!
34 //! fn main() {
35 //! let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
36 //! let mut file = BufWriter::new(File::create(&path).unwrap());
37 //!
38 //! write!(
39 //! &mut file,
40 //! "static KEYWORDS: phf::Map<&'static str, Keyword> = {}",
41 //! phf_codegen::Map::new()
42 //! .entry("loop", "Keyword::Loop")
43 //! .entry("continue", "Keyword::Continue")
44 //! .entry("break", "Keyword::Break")
45 //! .entry("fn", "Keyword::Fn")
46 //! .entry("extern", "Keyword::Extern")
47 //! .build()
48 //! )
49 //! .unwrap();
50 //! write!(&mut file, ";\n").unwrap();
51 //! }
52 //! ```
53 //!
54 //! and lib.rs:
55 //!
56 //! ```ignore
57 //! #[derive(Clone)]
58 //! enum Keyword {
59 //! Loop,
60 //! Continue,
61 //! Break,
62 //! Fn,
63 //! Extern,
64 //! }
65 //!
66 //! include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
67 //!
68 //! pub fn parse_keyword(keyword: &str) -> Option<Keyword> {
69 //! KEYWORDS.get(keyword).cloned()
70 //! }
71 //! ```
72 //!
73 //! ### Byte-String Keys
74 //! Byte strings by default produce references to fixed-size arrays; the compiler needs a hint
75 //! to coerce them to slices:
76 //!
77 //! build.rs:
78 //!
79 //! ```no_run
80 //! use std::env;
81 //! use std::fs::File;
82 //! use std::io::{BufWriter, Write};
83 //! use std::path::Path;
84 //!
85 //! let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
86 //! let mut file = BufWriter::new(File::create(&path).unwrap());
87 //!
88 //! writeln!(
89 //! &mut file,
90 //! "static KEYWORDS: phf::Map<&'static [u8], Keyword> = \n{};\n",
91 //! phf_codegen::Map::<&[u8]>::new()
92 //! .entry(b"loop", "Keyword::Loop")
93 //! .entry(b"continue", "Keyword::Continue")
94 //! .entry(b"break", "Keyword::Break")
95 //! .entry(b"fn", "Keyword::Fn")
96 //! .entry(b"extern", "Keyword::Extern")
97 //! .build()
98 //! ).unwrap();
99 //! ```
100 //!
101 //! lib.rs:
102 //!
103 //! ```ignore
104 //! #[derive(Clone)]
105 //! enum Keyword {
106 //! Loop,
107 //! Continue,
108 //! Break,
109 //! Fn,
110 //! Extern,
111 //! }
112 //!
113 //! include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
114 //!
115 //! pub fn parse_keyword(keyword: &[u8]) -> Option<Keyword> {
116 //! KEYWORDS.get(keyword).cloned()
117 //! }
118 //! ```
119 //!
120 //! ## Note
121 //!
122 //! The compiler's stack will overflow when processing extremely long method
123 //! chains (500+ calls). When generating large PHF data structures, consider
124 //! looping over the entries or making each call a separate statement:
125 //!
126 //! ```rust
127 //! let entries = [("hello", "1"), ("world", "2")];
128 //!
129 //! let mut builder = phf_codegen::Map::new();
130 //! for &(key, value) in &entries {
131 //! builder.entry(key, value);
132 //! }
133 //! // ...
134 //! ```
135 //!
136 //! ```rust
137 //! let mut builder = phf_codegen::Map::new();
138 //! builder.entry("hello", "1");
139 //! builder.entry("world", "2");
140 //! // ...
141 //! ```
142
143 #![doc(html_root_url = "https://docs.rs/phf_codegen/0.14.0")]
144 #![allow(clippy::new_without_default)]
145
146 use phf_shared::{FmtConst, PhfHash};
147 use std::borrow::Cow;
148 use std::collections::HashSet;
149 use std::fmt;
150 use std::hash::Hash;
151
152 #[cfg(not(feature = "ptrhash"))]
153 use phf_generator::HashState;
154 #[cfg(feature = "ptrhash")]
155 use phf_generator::ptrhash::HashState;
156
157 struct Delegate<T>(T);
158
159 impl<T: FmtConst> fmt::Display for Delegate<T> {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 self.0.fmt_const(f)
162 }
163 }
164
165 #[cfg(feature = "quote")]
166 fn write_tokens(tokens: &mut proc_macro2::TokenStream, value: impl fmt::Display) {
167 tokens.extend(
168 value
169 .to_string()
170 .parse::<proc_macro2::TokenStream>()
171 .expect("phf_codegen generated invalid Rust tokens"),
172 );
173 }
174
175 fn generate_hash_state<H: PhfHash>(keys: &[H]) -> HashState {
176 #[cfg(not(feature = "ptrhash"))]
177 {
178 phf_generator::generate_hash(keys)
179 }
180
181 #[cfg(feature = "ptrhash")]
182 {
183 phf_generator::ptrhash::generate_hash(keys)
184 }
185 }
186
187 /// A builder for the `phf::Map` type.
188 pub struct Map<'a, K> {
189 keys: Vec<K>,
190 values: Vec<Cow<'a, str>>,
191 path: Cow<'a, str>,
192 }
193
194 impl<'a, K: Hash + PhfHash + Eq + FmtConst> Map<'a, K> {
195 /// Creates a new `phf::Map` builder.
196 pub fn new() -> Self {
197 // FIXME rust#27438
198 //
199 // On Windows/MSVC there are major problems with the handling of dllimport.
200 // Here, because downstream build scripts only invoke generics from phf_codegen,
201 // the linker ends up throwing a way a bunch of static symbols we actually need.
202 // This works around the problem, assuming that all clients call `Map::new` by
203 // calling a non-generic function.
204 fn noop_fix_for_27438() {}
205 noop_fix_for_27438();
206
207 Map {
208 keys: vec![],
209 values: vec![],
210 path: Cow::Borrowed("::phf"),
211 }
212 }
213
214 /// Set the path to the `phf` crate from the global namespace
215 pub fn phf_path(&mut self, path: impl Into<Cow<'a, str>>) -> &mut Self {
216 self.path = path.into();
217 self
218 }
219
220 /// Adds an entry to the builder.
221 ///
222 /// `value` will be written exactly as provided in the constructed source.
223 pub fn entry(&mut self, key: K, value: impl Into<Cow<'a, str>>) -> &mut Self {
224 self.keys.push(key);
225 self.values.push(value.into());
226 self
227 }
228
229 /// Calculate the hash parameters and return a struct implementing
230 /// [`Display`](::std::fmt::Display) for the constructed `phf::Map`.
231 ///
232 /// With the `quote` feature enabled, the returned value also implements
233 /// `quote::ToTokens`.
234 ///
235 /// # Panics
236 ///
237 /// Panics if there are any duplicate keys.
238 pub fn build(&self) -> DisplayMap<'_, K> {
239 let mut set = HashSet::new();
240 for key in &self.keys {
241 if !set.insert(key) {
242 panic!("duplicate key `{}`", Delegate(key));
243 }
244 }
245
246 let state = generate_hash_state(&self.keys);
247
248 DisplayMap {
249 state,
250 path: &self.path,
251 keys: &self.keys,
252 values: &self.values,
253 }
254 }
255 }
256
257 /// An adapter for printing a [`Map`](Map).
258 pub struct DisplayMap<'a, K> {
259 path: &'a str,
260 state: HashState,
261 keys: &'a [K],
262 values: &'a [Cow<'a, str>],
263 }
264
265 impl<'a, K: FmtConst + 'a> fmt::Display for DisplayMap<'a, K> {
266 #[cfg(not(feature = "ptrhash"))]
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 // funky formatting here for nice output
269 write!(
270 f,
271 "{}::Map {{
272 key: {:?},
273 disps: &[",
274 self.path, self.state.key
275 )?;
276
277 // write map displacements
278 for &(d1, d2) in &self.state.disps {
279 write!(
280 f,
281 "
282 ({}, {}),",
283 d1, d2
284 )?;
285 }
286
287 write!(
288 f,
289 "
290 ],
291 entries: &[",
292 )?;
293
294 // write map entries
295 for &idx in &self.state.map {
296 write!(
297 f,
298 "
299 ({}, {}),",
300 Delegate(&self.keys[idx]),
301 &self.values[idx]
302 )?;
303 }
304
305 write!(
306 f,
307 "
308 ],
309 }}"
310 )
311 }
312
313 #[cfg(feature = "ptrhash")]
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(
316 f,
317 "{}::Map {{
318 key: {:?},
319 pilots: &[",
320 self.path, self.state.seed
321 )?;
322
323 for &pilot in &self.state.pilots {
324 write!(
325 f,
326 "
327 {},",
328 pilot
329 )?;
330 }
331
332 write!(
333 f,
334 "
335 ],
336 remap: &[",
337 )?;
338
339 for &index in &self.state.remap {
340 write!(
341 f,
342 "
343 {},",
344 index
345 )?;
346 }
347
348 write!(
349 f,
350 "
351 ],
352 entries: &[",
353 )?;
354
355 for &idx in &self.state.map {
356 write!(
357 f,
358 "
359 ({}, {}),",
360 Delegate(&self.keys[idx]),
361 &self.values[idx]
362 )?;
363 }
364
365 write!(
366 f,
367 "
368 ],
369 }}"
370 )
371 }
372 }
373
374 #[cfg(feature = "quote")]
375 impl<'a, K: FmtConst + 'a> quote::ToTokens for DisplayMap<'a, K> {
376 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
377 write_tokens(tokens, self);
378 }
379 }
380
381 impl<'a, K, V> FromIterator<(K, V)> for Map<'a, K>
382 where
383 K: Hash + PhfHash + Eq + FmtConst,
384 V: Into<Cow<'a, str>>,
385 {
386 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
387 let mut map = Map::new();
388 for (key, value) in iter {
389 map.entry(key, value);
390 }
391 map
392 }
393 }
394
395 /// A builder for the `phf::Set` type.
396 pub struct Set<'a, T> {
397 map: Map<'a, T>,
398 }
399
400 impl<'a, T: Hash + PhfHash + Eq + FmtConst> Set<'a, T> {
401 /// Constructs a new `phf::Set` builder.
402 pub fn new() -> Self {
403 Set { map: Map::new() }
404 }
405
406 /// Set the path to the `phf` crate from the global namespace
407 pub fn phf_path(&mut self, path: impl Into<Cow<'a, str>>) -> &mut Self {
408 self.map.phf_path(path);
409 self
410 }
411
412 /// Adds an entry to the builder.
413 pub fn entry(&mut self, entry: T) -> &mut Self {
414 self.map.entry(entry, "()");
415 self
416 }
417
418 /// Calculate the hash parameters and return a struct implementing
419 /// [`Display`](::std::fmt::Display) for the constructed `phf::Set`.
420 ///
421 /// With the `quote` feature enabled, the returned value also implements
422 /// `quote::ToTokens`.
423 ///
424 /// # Panics
425 ///
426 /// Panics if there are any duplicate keys.
427 pub fn build(&self) -> DisplaySet<'_, T> {
428 DisplaySet {
429 inner: self.map.build(),
430 }
431 }
432 }
433
434 /// An adapter for printing a [`Set`](Set).
435 pub struct DisplaySet<'a, T> {
436 inner: DisplayMap<'a, T>,
437 }
438
439 impl<'a, T: FmtConst + 'a> fmt::Display for DisplaySet<'a, T> {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 write!(f, "{}::Set {{ map: {} }}", self.inner.path, self.inner)
442 }
443 }
444
445 #[cfg(feature = "quote")]
446 impl<'a, T: FmtConst + 'a> quote::ToTokens for DisplaySet<'a, T> {
447 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
448 write_tokens(tokens, self);
449 }
450 }
451
452 /// A builder for the `phf::OrderedMap` type.
453 pub struct OrderedMap<'a, K> {
454 keys: Vec<K>,
455 values: Vec<Cow<'a, str>>,
456 path: Cow<'a, str>,
457 }
458
459 impl<'a, K: Hash + PhfHash + Eq + FmtConst> OrderedMap<'a, K> {
460 /// Constructs a enw `phf::OrderedMap` builder.
461 pub fn new() -> Self {
462 OrderedMap {
463 keys: vec![],
464 values: vec![],
465 path: Cow::Borrowed("::phf"),
466 }
467 }
468
469 /// Set the path to the `phf` crate from the global namespace
470 pub fn phf_path(&mut self, path: impl Into<Cow<'a, str>>) -> &mut Self {
471 self.path = path.into();
472 self
473 }
474
475 /// Adds an entry to the builder.
476 ///
477 /// `value` will be written exactly as provided in the constructed source.
478 pub fn entry(&mut self, key: K, value: impl Into<Cow<'a, str>>) -> &mut Self {
479 self.keys.push(key);
480 self.values.push(value.into());
481 self
482 }
483
484 /// Calculate the hash parameters and return a struct implementing
485 /// [`Display`](::std::fmt::Display) for the constructed `phf::OrderedMap`.
486 ///
487 /// With the `quote` feature enabled, the returned value also implements
488 /// `quote::ToTokens`.
489 ///
490 /// # Panics
491 ///
492 /// Panics if there are any duplicate keys.
493 pub fn build(&self) -> DisplayOrderedMap<'_, K> {
494 let mut set = HashSet::new();
495 for key in &self.keys {
496 if !set.insert(key) {
497 panic!("duplicate key `{}`", Delegate(key));
498 }
499 }
500
501 let state = generate_hash_state(&self.keys);
502
503 DisplayOrderedMap {
504 state,
505 path: &self.path,
506 keys: &self.keys,
507 values: &self.values,
508 }
509 }
510 }
511
512 /// An adapter for printing a [`OrderedMap`](OrderedMap).
513 pub struct DisplayOrderedMap<'a, K> {
514 path: &'a str,
515 state: HashState,
516 keys: &'a [K],
517 values: &'a [Cow<'a, str>],
518 }
519
520 impl<'a, K: FmtConst + 'a> fmt::Display for DisplayOrderedMap<'a, K> {
521 #[cfg(not(feature = "ptrhash"))]
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 write!(
524 f,
525 "{}::OrderedMap {{
526 key: {:?},
527 disps: &[",
528 self.path, self.state.key
529 )?;
530 for &(d1, d2) in &self.state.disps {
531 write!(
532 f,
533 "
534 ({}, {}),",
535 d1, d2
536 )?;
537 }
538 write!(
539 f,
540 "
541 ],
542 idxs: &[",
543 )?;
544 for &idx in &self.state.map {
545 write!(
546 f,
547 "
548 {},",
549 idx
550 )?;
551 }
552 write!(
553 f,
554 "
555 ],
556 entries: &[",
557 )?;
558 for (key, value) in self.keys.iter().zip(self.values.iter()) {
559 write!(
560 f,
561 "
562 ({}, {}),",
563 Delegate(key),
564 value
565 )?;
566 }
567 write!(
568 f,
569 "
570 ],
571 }}"
572 )
573 }
574
575 #[cfg(feature = "ptrhash")]
576 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577 write!(
578 f,
579 "{}::OrderedMap {{
580 key: {:?},
581 pilots: &[",
582 self.path, self.state.seed
583 )?;
584
585 for &pilot in &self.state.pilots {
586 write!(
587 f,
588 "
589 {},",
590 pilot
591 )?;
592 }
593
594 write!(
595 f,
596 "
597 ],
598 remap: &[",
599 )?;
600
601 for &index in &self.state.remap {
602 write!(
603 f,
604 "
605 {},",
606 index
607 )?;
608 }
609
610 write!(
611 f,
612 "
613 ],
614 idxs: &[",
615 )?;
616
617 for &idx in &self.state.map {
618 write!(
619 f,
620 "
621 {},",
622 idx
623 )?;
624 }
625
626 write!(
627 f,
628 "
629 ],
630 entries: &[",
631 )?;
632
633 for (key, value) in self.keys.iter().zip(self.values.iter()) {
634 write!(
635 f,
636 "
637 ({}, {}),",
638 Delegate(key),
639 value
640 )?;
641 }
642
643 write!(
644 f,
645 "
646 ],
647 }}"
648 )
649 }
650 }
651
652 #[cfg(feature = "quote")]
653 impl<'a, K: FmtConst + 'a> quote::ToTokens for DisplayOrderedMap<'a, K> {
654 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
655 write_tokens(tokens, self);
656 }
657 }
658
659 /// A builder for the `phf::OrderedSet` type.
660 pub struct OrderedSet<'a, T> {
661 map: OrderedMap<'a, T>,
662 }
663
664 impl<'a, T: Hash + PhfHash + Eq + FmtConst> OrderedSet<'a, T> {
665 /// Constructs a new `phf::OrderedSet` builder.
666 pub fn new() -> Self {
667 OrderedSet {
668 map: OrderedMap::new(),
669 }
670 }
671
672 /// Set the path to the `phf` crate from the global namespace
673 pub fn phf_path(&mut self, path: impl Into<Cow<'a, str>>) -> &mut Self {
674 self.map.phf_path(path);
675 self
676 }
677
678 /// Adds an entry to the builder.
679 pub fn entry(&mut self, entry: T) -> &mut Self {
680 self.map.entry(entry, "()");
681 self
682 }
683
684 /// Calculate the hash parameters and return a struct implementing
685 /// [`Display`](::std::fmt::Display) for the constructed `phf::OrderedSet`.
686 ///
687 /// With the `quote` feature enabled, the returned value also implements
688 /// `quote::ToTokens`.
689 ///
690 /// # Panics
691 ///
692 /// Panics if there are any duplicate keys.
693 pub fn build(&self) -> DisplayOrderedSet<'_, T> {
694 DisplayOrderedSet {
695 inner: self.map.build(),
696 }
697 }
698 }
699
700 /// An adapter for printing a [`OrderedSet`](OrderedSet).
701 pub struct DisplayOrderedSet<'a, T> {
702 inner: DisplayOrderedMap<'a, T>,
703 }
704
705 impl<'a, T: FmtConst + 'a> fmt::Display for DisplayOrderedSet<'a, T> {
706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707 write!(
708 f,
709 "{}::OrderedSet {{ map: {} }}",
710 self.inner.path, self.inner
711 )
712 }
713 }
714
715 #[cfg(feature = "quote")]
716 impl<'a, T: FmtConst + 'a> quote::ToTokens for DisplayOrderedSet<'a, T> {
717 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
718 write_tokens(tokens, self);
719 }
720 }