-
Notifications
You must be signed in to change notification settings - Fork 20
/
writer.rs
1519 lines (1383 loc) · 46.8 KB
/
writer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::char;
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::fmt;
use std::fs::File;
use std::io::{self, Write};
use std::mem::size_of;
use std::path::{Path, PathBuf};
use std::str;
use byteorder::{BigEndian as BE, ByteOrder};
use fst::raw::Fst;
use fst::{MapBuilder, SetBuilder};
use regex_automata::{DenseDFA, Regex, SparseDFA, StateID};
use ucd_trie::TrieSetOwned;
use crate::error::Result;
use crate::util;
#[derive(Clone, Debug)]
pub struct WriterBuilder(WriterOptions);
#[derive(Clone, Debug)]
struct WriterOptions {
name: String,
columns: u64,
char_literals: bool,
fst_dir: Option<PathBuf>,
trie_set: bool,
dfa_dir: Option<PathBuf>,
ucd_version: Option<(u64, u64, u64)>,
}
impl WriterBuilder {
/// Create a new builder Unicode writers.
///
/// The name given corresponds to the Rust module name to use when
/// applicable.
pub fn new(name: &str) -> WriterBuilder {
WriterBuilder(WriterOptions {
name: name.to_string(),
columns: 79,
char_literals: false,
fst_dir: None,
trie_set: false,
dfa_dir: None,
ucd_version: None,
})
}
/// Create a new Unicode writer from this builder's configuration.
pub fn from_writer<W: io::Write + 'static>(&self, wtr: W) -> Writer {
Writer {
wtr: LineWriter::new(Box::new(wtr)),
wrote_header: false,
opts: self.0.clone(),
}
}
/// Create a new Unicode writer that writes to stdout.
pub fn from_stdout(&self) -> Writer {
self.from_writer(io::stdout())
}
/// Create a new Unicode writer that writes FSTs to a directory.
pub fn from_fst_dir<P: AsRef<Path>>(&self, fst_dir: P) -> Result<Writer> {
let mut opts = self.0.clone();
opts.fst_dir = Some(fst_dir.as_ref().to_path_buf());
let mut fpath = fst_dir.as_ref().join(rust_module_name(&opts.name));
fpath.set_extension("rs");
Ok(Writer {
wtr: LineWriter::new(Box::new(File::create(fpath)?)),
wrote_header: false,
opts,
})
}
/// Create a new writer that writes DFAs to a directory.
pub fn from_dfa_dir<P: AsRef<Path>>(&self, dfa_dir: P) -> Result<Writer> {
let mut opts = self.0.clone();
opts.dfa_dir = Some(dfa_dir.as_ref().to_path_buf());
let mut fpath = dfa_dir.as_ref().join(rust_module_name(&opts.name));
fpath.set_extension("rs");
Ok(Writer {
wtr: LineWriter::new(Box::new(File::create(fpath)?)),
wrote_header: false,
opts,
})
}
/// Set the column limit to use when writing Rust source code.
///
/// Note that this is adhered to on a "best effort" basis.
pub fn columns(&mut self, columns: u64) -> &mut WriterBuilder {
self.0.columns = columns;
self
}
/// When printing Rust source code, emit `char` literals instead of `u32`
/// literals. Any codepoints that aren't Unicode scalar values (i.e.,
/// surrogate codepoints) are silently dropped when writing.
pub fn char_literals(&mut self, yes: bool) -> &mut WriterBuilder {
self.0.char_literals = yes;
self
}
/// Emit a trie when writing sets of codepoints instead of a slice of
/// ranges.
pub fn trie_set(&mut self, yes: bool) -> &mut WriterBuilder {
self.0.trie_set = yes;
self
}
/// Set what version of the UCD we're generating data from.
pub fn ucd_version(
&mut self,
major: u64,
minor: u64,
patch: u64,
) -> &mut WriterBuilder {
self.0.ucd_version = Some((major, minor, patch));
self
}
}
/// A writer of various kinds of Unicode data.
///
/// A writer takes as input various forms of Unicode data and writes that data
/// in a number of different output formats.
pub struct Writer {
wtr: LineWriter<Box<dyn io::Write + 'static>>,
wrote_header: bool,
opts: WriterOptions,
}
impl Writer {
/// Write a sorted sequence of string names that map to Unicode set names.
pub fn names<I: IntoIterator<Item = T>, T: AsRef<str>>(
&mut self,
names: I,
) -> Result<()> {
self.header()?;
self.separator()?;
let ty = if self.opts.fst_dir.is_some() {
"::fst::Set<&'static [u8]>".to_string()
} else if self.opts.trie_set {
"&'static ::ucd_trie::TrieSet".to_string()
} else {
let charty = self.rust_codepoint_type();
format!("&'static [({}, {})]", charty, charty)
};
let mut names: Vec<String> =
names.into_iter().map(|name| name.as_ref().to_string()).collect();
names.sort();
writeln!(
self.wtr,
"pub const BY_NAME: &'static [(&'static str, {})] = &[",
ty,
)?;
for name in names {
let rustname = rust_const_name(&name);
self.wtr.write_str(&format!("({:?}, {}), ", name, rustname))?;
}
writeln!(self.wtr, "];")?;
Ok(())
}
/// Write a sorted sequence of codepoints.
///
/// Note that the specific representation of ranges may differ with the
/// output format. For example, if the output format is a slice, then a
/// straight-forward slice of sorted codepoint ranges is emitted. But if
/// the output format is an FST or similar, then all codepoints are
/// explicitly represented.
pub fn ranges(
&mut self,
name: &str,
codepoints: &BTreeSet<u32>,
) -> Result<()> {
self.header()?;
self.separator()?;
let name = rust_const_name(name);
if self.opts.fst_dir.is_some() {
let mut builder = SetBuilder::memory();
builder.extend_iter(codepoints.iter().cloned().map(u32_key))?;
let set = builder.into_set();
self.fst(&name, set.as_fst(), false)?;
} else if self.opts.trie_set {
let set: Vec<u32> = codepoints.iter().cloned().collect();
let trie = TrieSetOwned::from_codepoints(&set)?;
self.trie_set(&name, &trie)?;
} else {
let ranges = util::to_ranges(codepoints.iter().cloned());
self.ranges_slice(&name, &ranges)?;
}
self.wtr.flush()?;
Ok(())
}
fn ranges_slice(
&mut self,
name: &str,
table: &[(u32, u32)],
) -> Result<()> {
let ty = self.rust_codepoint_type();
writeln!(
self.wtr,
"pub const {}: &'static [({}, {})] = &[",
name, ty, ty
)?;
for &(start, end) in table {
let range = (self.rust_codepoint(start), self.rust_codepoint(end));
if let (Some(start), Some(end)) = range {
self.wtr.write_str(&format!("({}, {}), ", start, end))?;
}
}
writeln!(self.wtr, "];")?;
Ok(())
}
fn trie_set(&mut self, name: &str, trie: &TrieSetOwned) -> Result<()> {
let trie = trie.as_slice();
writeln!(
self.wtr,
"pub const {}: &'static ::ucd_trie::TrieSet = \
&::ucd_trie::TrieSet {{",
name
)?;
self.wtr.indent(" ");
writeln!(self.wtr, " tree1_level1: &[")?;
self.write_slice_u64(&trie.tree1_level1)?;
writeln!(self.wtr, " ],")?;
writeln!(self.wtr, " tree2_level1: &[")?;
self.write_slice_u8(&trie.tree2_level1)?;
writeln!(self.wtr, " ],")?;
writeln!(self.wtr, " tree2_level2: &[")?;
self.write_slice_u64(&trie.tree2_level2)?;
writeln!(self.wtr, " ],")?;
writeln!(self.wtr, " tree3_level1: &[")?;
self.write_slice_u8(&trie.tree3_level1)?;
writeln!(self.wtr, " ],")?;
writeln!(self.wtr, " tree3_level2: &[")?;
self.write_slice_u8(&trie.tree3_level2)?;
writeln!(self.wtr, " ],")?;
writeln!(self.wtr, " tree3_level3: &[")?;
self.write_slice_u64(&trie.tree3_level3)?;
writeln!(self.wtr, " ],")?;
writeln!(self.wtr, "}};")?;
Ok(())
}
/// Write a map that associates codepoint ranges to a single value in an
/// enumeration. This usually emits two items: a map from codepoint range
/// to index and a map from index to one of the enum variants.
///
/// The given map should be a map from the enum variant value to the set
/// of codepoints that have that value.
pub fn ranges_to_enum(
&mut self,
name: &str,
enum_map: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<()> {
self.header()?;
self.separator()?;
writeln!(
self.wtr,
"pub const {}_ENUM: &'static [&'static str] = &[",
rust_const_name(name)
)?;
for variant in enum_map.keys() {
self.wtr.write_str(&format!("{:?}, ", variant))?;
}
writeln!(self.wtr, "];")?;
let mut map = BTreeMap::new();
for (i, (_, ref set)) in enum_map.iter().enumerate() {
map.extend(set.iter().cloned().map(|cp| (cp, i as u64)));
}
self.ranges_to_unsigned_integer(name, &map)?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that associates codepoint ranges to a single value in a
/// Rust enum.
///
/// The given map should be a map from the enum variant value to the set
/// of codepoints that have that value.
pub fn ranges_to_rust_enum(
&mut self,
name: &str,
variants: &[&str],
enum_map: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<()> {
self.header()?;
self.separator()?;
writeln!(
self.wtr,
"#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]",
)?;
let enum_name = rust_type_name(name);
writeln!(self.wtr, "pub enum {} {{", enum_name)?;
for variant in variants {
self.wtr.write_str(&format!("{}, ", rust_type_name(variant)))?;
}
writeln!(self.wtr, "}}\n")?;
let mut map = BTreeMap::new();
for (variant, ref set) in enum_map.iter() {
map.extend(set.iter().cloned().map(|cp| (cp, variant)));
}
let ranges = util::to_range_values(
map.iter().map(|(&k, &v)| (k, rust_type_name(v))),
);
self.ranges_to_enum_slice(name, &enum_name, &ranges)?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that associates codepoint ranges to a single value in a
/// Rust enum with custom discriminants.
///
/// The given `variants_map` should be a map from the custom discriminant
/// to the enum variant value.
///
/// The given `enum_map` should be a map from the enum variant value to the
/// set of codepoints that have that value.
pub fn ranges_to_rust_enum_with_custom_discriminants(
&mut self,
name: &str,
variants_map: &BTreeMap<isize, String>,
enum_map: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<()> {
self.header()?;
self.separator()?;
writeln!(
self.wtr,
"#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]",
)?;
let enum_name = rust_type_name(name);
writeln!(self.wtr, "pub enum {} {{", enum_name)?;
for (discriminant, variant) in variants_map {
self.wtr.write_str(&format!(
"{} = {}, ",
rust_type_name(variant),
discriminant
))?;
}
writeln!(self.wtr, "}}\n")?;
let mut map = BTreeMap::new();
for (variant, ref set) in enum_map.iter() {
map.extend(set.iter().cloned().map(|cp| (cp, variant)));
}
let ranges = util::to_range_values(
map.iter().map(|(&k, &v)| (k, rust_type_name(v))),
);
self.ranges_to_enum_slice(name, &enum_name, &ranges)?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that combines codepoint ranges into a single table.
///
/// The given map should be a map from the variant value to the set of
/// codepoints that have that value.
pub fn ranges_to_combined(
&mut self,
name: &str,
enum_map: &BTreeMap<String, BTreeSet<u32>>,
) -> Result<()> {
let mut set = BTreeSet::new();
for other_set in enum_map.values() {
set.extend(other_set.iter().cloned());
}
self.ranges(name, &set)?;
self.wtr.flush()?;
Ok(())
}
fn ranges_to_enum_slice<S>(
&mut self,
name: &str,
enum_ty: &str,
table: &[(u32, u32, S)],
) -> Result<()>
where
S: fmt::Display,
{
let cp_ty = self.rust_codepoint_type();
writeln!(
self.wtr,
"pub const {}: &'static [({}, {}, {})] = &[",
name, cp_ty, cp_ty, enum_ty,
)?;
for (start, end, variant) in table {
let range =
(self.rust_codepoint(*start), self.rust_codepoint(*end));
if let (Some(start), Some(end)) = range {
let src = format!(
"({}, {}, {}::{}), ",
start, end, enum_ty, variant,
);
self.wtr.write_str(&src)?;
}
}
writeln!(self.wtr, "];")?;
Ok(())
}
/// Write a map that associates ranges of codepoints with an arbitrary
/// integer.
///
/// The smallest numeric type is used when applicable.
pub fn ranges_to_unsigned_integer(
&mut self,
name: &str,
map: &BTreeMap<u32, u64>,
) -> Result<()> {
self.header()?;
self.separator()?;
let name = rust_const_name(name);
if self.opts.fst_dir.is_some() {
let mut builder = MapBuilder::memory();
for (&k, &v) in map {
builder.insert(u32_key(k), v)?;
}
let map = builder.into_map();
self.fst(&name, map.as_fst(), true)?;
} else {
let ranges =
util::to_range_values(map.iter().map(|(&k, &v)| (k, v)));
self.ranges_to_unsigned_integer_slice(&name, &ranges)?;
}
self.wtr.flush()?;
Ok(())
}
fn ranges_to_unsigned_integer_slice(
&mut self,
name: &str,
table: &[(u32, u32, u64)],
) -> Result<()> {
let cp_ty = self.rust_codepoint_type();
let num_ty = match table.iter().map(|&(_, _, n)| n).max() {
None => "u8",
Some(max_num) => smallest_unsigned_type(max_num),
};
writeln!(
self.wtr,
"pub const {}: &'static [({}, {}, {})] = &[",
name, cp_ty, cp_ty, num_ty
)?;
for &(start, end, num) in table {
let range = (self.rust_codepoint(start), self.rust_codepoint(end));
if let (Some(start), Some(end)) = range {
let src = format!("({}, {}, {}), ", start, end, num);
self.wtr.write_str(&src)?;
}
}
writeln!(self.wtr, "];")?;
Ok(())
}
/// Write a map that associates strings to strings.
///
/// The only supported output format is a sorted slice, which can be
/// binary searched.
pub fn string_to_string(
&mut self,
name: &str,
map: &BTreeMap<String, String>,
) -> Result<()> {
if self.opts.fst_dir.is_some() {
return err!("cannot emit string->string map as an FST");
}
self.header()?;
self.separator()?;
let name = rust_const_name(name);
writeln!(
self.wtr,
"pub const {}: &'static [(&'static str, &'static str)] = &[",
name
)?;
for (k, v) in map {
self.wtr.write_str(&format!("({:?}, {:?}), ", k, v))?;
}
writeln!(self.wtr, "];")?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that associates strings to another map from strings to
/// strings.
///
/// The only supported output format is a sorted slice, which can be
/// binary searched.
pub fn string_to_string_to_string(
&mut self,
name: &str,
map: &BTreeMap<String, BTreeMap<String, String>>,
) -> Result<()> {
if self.opts.fst_dir.is_some() {
return err!("cannot emit string->string map as an FST");
}
self.header()?;
self.separator()?;
let name = rust_const_name(name);
writeln!(
self.wtr,
"pub const {}: &'static \
[(&'static str, \
&'static [(&'static str, &'static str)])] = &[",
name
)?;
let mut first = true;
for (k1, kv) in map {
if !first {
writeln!(self.wtr, "")?;
}
first = false;
self.wtr.write_str(&format!("({:?}, &[", k1))?;
for (k2, v) in kv {
self.wtr.write_str(&format!("({:?}, {:?}), ", k2, v))?;
}
self.wtr.write_str("]), ")?;
}
writeln!(self.wtr, "];")?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that associates codepoints with other codepoints.
///
/// This supports the FST format in addition to the standard sorted slice
/// format. When using an FST, the keys and values are 32-bit big endian
/// unsigned integers.
pub fn codepoint_to_codepoint(
&mut self,
name: &str,
map: &BTreeMap<u32, u32>,
) -> Result<()> {
self.header()?;
self.separator()?;
let name = rust_const_name(name);
if self.opts.fst_dir.is_some() {
let mut builder = MapBuilder::memory();
for (&k, &v) in map {
builder.insert(u32_key(k), v as u64)?;
}
let map = builder.into_map();
self.fst(&name, map.as_fst(), true)?;
} else {
let table: Vec<(u32, u32)> =
map.iter().map(|(&k, &v)| (k, v)).collect();
self.ranges_slice(&name, &table)?;
}
self.wtr.flush()?;
Ok(())
}
/// Write a function that associates codepoints with other codepoints.
///
/// The function will use a match expression to map between codepoints.
/// The fallback branch of the match returns 0.
pub fn codepoint_to_codepoint_fn(
&mut self,
name: &str,
map: &BTreeMap<u32, u32>,
) -> Result<()> {
self.header()?;
self.separator()?;
writeln!(self.wtr, "use std::num::NonZeroU32;")?;
self.separator()?;
let fn_name = rust_fn_name(name);
writeln!(
self.wtr,
"pub fn {}(cp: u32) -> Option<NonZeroU32> {{",
fn_name
)?;
self.wtr.indent(" ");
self.wtr.write_str(
"// new_unchecked is safe as ucd-generate checks \
that the destination",
)?;
self.wtr.flush_line()?;
self.wtr.write_str(
"// codepoint is non-zero at \
code generation time.",
)?;
self.wtr.flush_line()?;
self.wtr.write_str("unsafe {")?;
self.wtr.flush_line()?;
self.wtr.indent(" ");
self.wtr.write_str("match cp {")?;
self.wtr.flush_line()?;
self.wtr.indent(" ");
for (from, to) in map {
if *to == 0 {
return err!(
"destination codepoint must not be 0 (NUL) for \
rust-match output format"
);
}
self.wtr.write_str(&format!(
"{} => Some(NonZeroU32::new_unchecked({})),",
from, to
))?;
self.wtr.flush_line()?;
}
self.wtr.write_str("_ => None,")?;
self.wtr.flush_line()?;
self.wtr.indent(" ");
self.wtr.write_str("}")?;
self.wtr.flush_line()?;
self.wtr.indent(" ");
self.wtr.write_str("}")?;
self.wtr.flush_line()?;
writeln!(self.wtr, "}}")?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that associates codepoints with other codepoints, where
/// each codepoint can be associated with possibly many other codepoints.
///
/// This does not support the FST format.
pub fn multi_codepoint_to_codepoint(
&mut self,
name: &str,
map: &BTreeMap<u32, BTreeSet<u32>>,
emit_flat_table: bool,
) -> Result<()> {
if self.opts.fst_dir.is_some() {
return err!("cannot emit codepoint multimaps as an FST");
}
let mut map2: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
for (&k, vs) in map {
let vs2 = vs.iter().cloned().collect();
map2.insert(k, vs2);
}
self.codepoint_to_codepoints(name, &map2, emit_flat_table)
}
/// Write a map that associates codepoints with a sequence of other
/// codepoints.
///
/// This does not support the FST format.
pub fn codepoint_to_codepoints(
&mut self,
name: &str,
map: &BTreeMap<u32, Vec<u32>>,
emit_flat_table: bool,
) -> Result<()> {
if self.opts.fst_dir.is_some() {
return err!("cannot emit codepoint->codepoints map as an FST");
}
self.header()?;
self.separator()?;
let name = rust_const_name(name);
let ty = self.rust_codepoint_type();
if !emit_flat_table {
writeln!(
self.wtr,
"pub const {}: &'static [({}, &'static [{}])] = &[",
name, ty, ty
)?;
} else {
writeln!(
self.wtr,
"pub const {}: &'static [({}, [{}; 3])] = &[",
name, ty, ty
)?;
}
'LOOP: for (&k, vs) in map {
// Make sure both our keys and values can be represented in the
// user's chosen codepoint format.
let kstr = match self.rust_codepoint(k) {
None => continue 'LOOP,
Some(k) => k,
};
let (padded_vs, slice_prefix) = if emit_flat_table {
// These checks are for future-proofing and cannot be hit currently.
if vs.len() > 3 {
return err!(
"flat-table representation cannot be used when value \
arrays may contain more than 3 entries"
);
}
let flat_padding =
if self.opts.char_literals { 0 } else { !0 };
if vs.contains(&flat_padding) {
return err!(
"flat-table --chars representation cannot be used when \
the NUL character is present in the value array. (This \
error probably can be fixed by removing `--chars`)"
);
}
let res = vs
.iter()
.copied()
.chain(std::iter::repeat(flat_padding))
.take(3)
.collect::<Vec<_>>();
(res, "")
} else {
(vs.clone(), "&")
};
let mut vstrs = vec![];
for v in padded_vs {
match self.rust_codepoint(v) {
None => continue 'LOOP,
Some(v) => vstrs.push(v),
}
}
self.wtr.write_str(&format!("({}, {}[", kstr, slice_prefix))?;
if vstrs.len() == 1 {
self.wtr.write_str(&format!("{}", &vstrs[0]))?;
} else {
for v in vstrs {
self.wtr.write_str(&format!("{}, ", v))?;
}
}
self.wtr.write_str("]), ")?;
}
writeln!(self.wtr, "];")?;
self.wtr.flush()?;
Ok(())
}
/// Write a map that associates codepoints to strings.
///
/// When the output format is an FST, then the FST map emitted is from
/// codepoint to u64, where the string is encoded into the u64. The least
/// significant byte of the u64 corresponds to the first byte in the
/// string. The end of a string is delimited by the zero byte. If a string
/// is more than 8 bytes or contains a `NUL` byte, then an error is
/// returned.
pub fn codepoint_to_string(
&mut self,
name: &str,
map: &BTreeMap<u32, String>,
) -> Result<()> {
self.header()?;
self.separator()?;
let name = rust_const_name(name);
if self.opts.fst_dir.is_some() {
let mut builder = MapBuilder::memory();
for (&k, v) in map {
let v = pack_str(v)?;
builder.insert(u32_key(k), v)?;
}
let map = builder.into_map();
self.fst(&name, map.as_fst(), true)?;
} else {
let table: Vec<(u32, &str)> =
map.iter().map(|(&k, v)| (k, &**v)).collect();
self.codepoint_to_string_slice(&name, &table)?;
}
self.wtr.flush()?;
Ok(())
}
fn codepoint_to_string_slice(
&mut self,
name: &str,
table: &[(u32, &str)],
) -> Result<()> {
let ty = self.rust_codepoint_type();
writeln!(
self.wtr,
"pub const {}: &'static [({}, &'static str)] = &[",
name, ty
)?;
for &(cp, ref s) in table {
if let Some(cp) = self.rust_codepoint(cp) {
self.wtr.write_str(&format!("({}, {:?}), ", cp, s))?;
}
}
writeln!(self.wtr, "];")?;
Ok(())
}
/// Write a map that associates strings to codepoints.
pub fn string_to_codepoint(
&mut self,
name: &str,
map: &BTreeMap<String, u32>,
) -> Result<()> {
self.header()?;
self.separator()?;
let name = rust_const_name(name);
if self.opts.fst_dir.is_some() {
let mut builder = MapBuilder::memory();
for (k, &v) in map {
builder.insert(k.as_bytes(), v as u64)?;
}
let map = builder.into_map();
self.fst(&name, map.as_fst(), true)?;
} else {
let table: Vec<(&str, u32)> =
map.iter().map(|(k, &v)| (&**k, v)).collect();
self.string_to_codepoint_slice(&name, &table)?;
}
self.wtr.flush()?;
Ok(())
}
fn string_to_codepoint_slice(
&mut self,
name: &str,
table: &[(&str, u32)],
) -> Result<()> {
let ty = self.rust_codepoint_type();
writeln!(
self.wtr,
"pub const {}: &'static [(&'static str, {})] = &[",
name, ty
)?;
for &(ref s, cp) in table {
if let Some(cp) = self.rust_codepoint(cp) {
self.wtr.write_str(&format!("({:?}, {}), ", s, cp))?;
}
}
writeln!(self.wtr, "];")?;
Ok(())
}
/// Write a map that associates strings to `u64` values.
pub fn string_to_u64(
&mut self,
name: &str,
map: &BTreeMap<String, u64>,
) -> Result<()> {
self.header()?;
self.separator()?;
let name = rust_const_name(name);
if self.opts.fst_dir.is_some() {
let mut builder = MapBuilder::memory();
for (k, &v) in map {
builder.insert(k.as_bytes(), v)?;
}
let map = builder.into_map();
self.fst(&name, map.as_fst(), true)?;
} else {
let table: Vec<(&str, u64)> =
map.iter().map(|(k, &v)| (&**k, v)).collect();
self.string_to_u64_slice(&name, &table)?;
}
self.wtr.flush()?;
Ok(())
}
fn string_to_u64_slice(
&mut self,
name: &str,
table: &[(&str, u64)],
) -> Result<()> {
writeln!(
self.wtr,
"pub const {}: &'static [(&'static str, u64)] = &[",
name
)?;
for &(ref s, n) in table {
self.wtr.write_str(&format!("({:?}, {}), ", s, n))?;
}
writeln!(self.wtr, "];")?;
Ok(())
}
fn fst<D: AsRef<[u8]>>(
&mut self,
const_name: &str,
fst: &Fst<D>,
map: bool,
) -> Result<()> {
let fst_dir = self.opts.fst_dir.as_ref().unwrap();
let fst_file_name = format!("{}.fst", rust_module_name(const_name));
let fst_file_path = fst_dir.join(&fst_file_name);
File::create(fst_file_path)?.write_all(&fst.to_vec())?;
let ty = if map { "Map" } else { "Set" };
writeln!(
self.wtr,
"pub static {}: ::once_cell::sync::Lazy<::fst::{}<&'static [u8]>> =",
const_name, ty
)?;
writeln!(self.wtr, " ::once_cell::sync::Lazy::new(|| {{")?;
writeln!(self.wtr, " ::fst::{}::from(::fst::raw::Fst::new(", ty)?;
writeln!(
self.wtr,
" &include_bytes!({:?})[..]).unwrap())",
fst_file_name
)?;
writeln!(self.wtr, " }});")?;
Ok(())
}
pub fn dense_regex<T: AsRef<[S]>, S: StateID>(
&mut self,
const_name: &str,
re: &Regex<DenseDFA<T, S>>,
) -> Result<()> {
self.header()?;
self.separator()?;
let rust_name = rust_module_name(const_name);
let idty = rust_uint_type::<S>();
let fname_fwd_be = format!("{}.fwd.bigendian.dfa", rust_name);
let fname_rev_be = format!("{}.rev.bigendian.dfa", rust_name);
let fname_fwd_le = format!("{}.fwd.littleendian.dfa", rust_name);
let fname_rev_le = format!("{}.rev.littleendian.dfa", rust_name);
let ty = format!(
"Regex<::regex_automata::DenseDFA<&'static [{}], {}>>",
idty, idty
);
{
let dfa_dir = self.opts.dfa_dir.as_ref().unwrap();
File::create(dfa_dir.join(&fname_fwd_be))?
.write_all(&re.forward().to_bytes_big_endian()?)?;
File::create(dfa_dir.join(&fname_rev_be))?
.write_all(&re.reverse().to_bytes_big_endian()?)?;
File::create(dfa_dir.join(&fname_fwd_le))?
.write_all(&re.forward().to_bytes_little_endian()?)?;
File::create(dfa_dir.join(&fname_rev_le))?
.write_all(&re.reverse().to_bytes_little_endian()?)?;
}
writeln!(self.wtr, "#[cfg(target_endian = \"big\")]")?;
self.write_regex_static(
const_name,
&ty,
"DenseDFA",
idty,
&fname_fwd_be,
&fname_rev_be,
)?;
self.separator()?;
writeln!(self.wtr, "#[cfg(target_endian = \"little\")]")?;
self.write_regex_static(
const_name,
&ty,
"DenseDFA",
idty,
&fname_fwd_le,
&fname_rev_le,
)?;
Ok(())
}
pub fn sparse_regex<T: AsRef<[u8]>, S: StateID>(
&mut self,
const_name: &str,
re: &Regex<SparseDFA<T, S>>,
) -> Result<()> {
self.header()?;
self.separator()?;
let rust_name = rust_module_name(const_name);
let idty = rust_uint_type::<S>();
let fname_fwd_be = format!("{}.fwd.bigendian.dfa", rust_name);
let fname_rev_be = format!("{}.rev.bigendian.dfa", rust_name);