forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
670 lines (616 loc) · 21.7 KB
/
Copy pathbuild.rs
File metadata and controls
670 lines (616 loc) · 21.7 KB
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
#![allow(
clippy::disallowed_methods,
reason = "build scripts cannot use rustpython-host_env"
)]
// spell-checker:ignore decomp DECOMP ossl osslconf
extern crate alloc;
use core::num::NonZeroUsize;
use alloc::collections::{BTreeMap, BTreeSet};
use std::{
env,
fs::{self, File},
io::{self, BufRead, BufReader, BufWriter, Write},
path::{Path, PathBuf},
thread,
};
use icu_properties::props::{EnumeratedProperty, GeneralCategory, NumericType};
fn generate_unicode_3_2() {
let path = PathBuf::from(env::var("OUT_DIR").unwrap())
.join("generated")
.join("unicode_3_2.rs");
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut writer = BufWriter::new(File::create(&path).unwrap());
let base = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("unicode")
.join("ucd32");
write_derived(
&base,
"DerivedGeneralCategory-3.2.0.txt",
"GENERAL_CATEGORY",
"(u32, u32, GeneralCategory)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, id, _| {
let id = parse_general(id);
if id != GeneralCategory::Unassigned {
Some((start, end, id))
} else {
None
}
},
|writer, mut values| {
values.sort_unstable_by_key(|(start, _, _)| *start);
write!(writer, "[").unwrap();
for (start, end, id) in values {
write!(writer, "({start}, {end}, GeneralCategory::{id:?}),").unwrap();
}
write!(writer, "];").unwrap();
},
);
write_derived(
&base,
"DerivedEastAsianWidth-3.2.0.txt",
"EAST_ASIAN_WIDTH",
"(u32, u32, EastAsianWidth)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, id, _| {
let id = parse_eaw(id);
if id != "EastAsianWidth::Neutral" {
Some((start, end, id))
} else {
None
}
},
|writer, mut values| {
values.sort_unstable_by_key(|(start, _, _)| *start);
write!(writer, "[").unwrap();
for (start, end, id) in values {
write!(writer, "({start}, {end}, {id}),").unwrap();
}
write!(writer, "];").unwrap();
},
);
write_derived(
&base,
"DerivedBidiClass-3.2.0.txt",
"BIDI_CLASS",
"(u32, u32, BidiClass)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, id, _| {
let id = parse_bidi(id);
if id != "BidiClass::LeftToRight" {
Some((start, end, id))
} else {
None
}
},
|writer, mut values| {
values.sort_unstable_by_key(|(start, _, _)| *start);
write!(writer, "[").unwrap();
for (start, end, id) in values {
write!(writer, "({start}, {end}, {id}),").unwrap();
}
write!(writer, "];").unwrap();
},
);
write_derived(
&base,
"DerivedBinaryProperties-3.2.0.txt",
"BIDI_MIRRORED",
"(u32, u32)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, id, _| {
assert_eq!(
"Bidi_Mirrored",
id.trim(),
"DerivedBinaryProperties-3.2.0 only has Bidi_Mirrored"
);
Some((start, end))
},
|writer, mut values| {
values.sort_unstable_by_key(|(start, _)| *start);
writeln!(writer, "{values:?};").unwrap();
},
);
write_derived(
&base,
"DerivedCombiningClass-3.2.0.txt",
"COMBINING_CLASS",
"(u32, u32, CanonicalCombiningClass)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, id, _| {
let id: u8 = id.parse().unwrap();
if id == 0 {
return None;
}
Some((start, end, id))
},
|writer, mut values| {
values.sort_unstable_by_key(|(start, _, _)| *start);
write!(writer, "[").unwrap();
for (start, end, id) in values {
write!(
writer,
"({start}, {end}, CanonicalCombiningClass::from_icu4c_value({id})),"
)
.unwrap();
}
writeln!(writer, "];").unwrap();
},
);
}
fn generate_numeric_type() {
let path = PathBuf::from(env::var("OUT_DIR").unwrap())
.join("generated")
.join("unicode_num_type.rs");
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut writer = BufWriter::new(File::create(&path).unwrap());
let base = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("unicode")
.join("ucd32");
write_derived(
&base,
"DerivedNumericType-3.2.0.txt",
"NUMERIC_TYPE_DIFF",
"(u32, u32, NumericType)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, id, _| {
let id = parse_numeric_type_str(id);
let differs = (start..=end).any(|c| match char::from_u32(c) {
Some(c) => {
let modern = parse_numeric_type_val(NumericType::for_char(c));
modern != id
}
None => true,
});
if differs {
Some((start, end, id))
} else {
None
}
},
|writer, mut values| {
values.sort_unstable_by_key(|(start, _, _)| *start);
write!(writer, "[").unwrap();
for (start, end, id) in values {
write!(writer, "({start}, {end}, {id}),").unwrap();
}
writeln!(writer, "];").unwrap();
},
);
}
fn generate_numeric_value() {
let path = PathBuf::from(env::var("OUT_DIR").unwrap())
.join("generated")
.join("unicode_numeric_value.rs");
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut writer = BufWriter::new(File::create(&path).unwrap());
// Ideally, this would store the diffs between the two tables. However, we need 3.2.0
// membership as well as different chars. The final tables are both smaller than storing the
// full 3.2.0 value table.
let ucd32 = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("unicode")
.join("ucd32");
let mut ucd32_diffs = BTreeMap::new();
let mut ucd32_member = BTreeSet::new();
let numeric_32 =
BufReader::new(File::open(ucd32.join("DerivedNumericValues-3.2.0.txt")).unwrap());
parse_unicode_3_2(
numeric_32,
NonZeroUsize::new(1).unwrap(),
&mut io::empty(),
|start, end, value, _| {
let value: f64 = value
.parse()
.expect("Unicode data contains valid properties");
ucd32_diffs.insert((start, end), value);
ucd32_member.insert((start, end));
Option::<()>::None
},
|_writer, _values| {},
);
let ucd_latest = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("unicode")
.join("latest");
write_derived(
&ucd_latest,
"DerivedNumericValues.txt",
"NUMERIC_VALUES",
"(u32, u32, f64)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, end, value, _| {
let value: f64 = value
.parse()
.expect("Unicode data contains valid properties");
if ucd32_diffs
.get(&(start, end))
.is_some_and(|old_v| *old_v == value)
{
ucd32_diffs.remove(&(start, end));
}
Some((start, end, value))
},
|writer, mut values| {
values.sort_unstable_by_key(|(ch, _, _)| *ch);
writeln!(writer, "{values:?};").unwrap();
},
);
// TODO: More flexible parser
writeln!(
writer,
"static NUMERIC_VALUES_DIFF: &[(u32, u32, f64)] = &["
)
.unwrap();
for ((start, end), value) in ucd32_diffs {
write!(writer, "({start}, {end}, {value:?}),").unwrap();
}
writeln!(writer, "];").unwrap();
// Compress membership table
let mut iter = ucd32_member.iter();
let &(mut start_prev, mut end_prev) = iter.next().unwrap();
let mut membership = Vec::new();
for &(start, end) in iter {
if start <= end_prev + 1 {
end_prev = end_prev.max(end);
} else {
membership.push((start_prev, end_prev));
start_prev = start;
end_prev = end;
}
}
membership.push((start_prev, end_prev));
membership.sort_unstable_by_key(|&(start, _)| start);
writeln!(writer, "static NUMERIC_VAL_EXISTS_32: &[(u32, u32)] = &").unwrap();
write!(writer, "{membership:?};").unwrap();
}
fn generate_unicode_latest() {
let path = PathBuf::from(env::var("OUT_DIR").unwrap())
.join("generated")
.join("unicode_latest.rs");
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut writer = BufWriter::new(File::create(&path).unwrap());
let base = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("unicode")
.join("latest");
// NOTE:
// This ONLY parses compatibility decomposition because Python exposes the tags. The tags are
// the "<square>", "<circle>", et cetera bits before the decomposition. Thus, we can save space
// by using icu4x's CanonicalDecomposer for non-compatibility decomposition.
let mut decomp_ranges = Vec::new();
write_derived(
&base,
"UnicodeData.txt",
"DECOMP_COMPAT",
"(u32, DecompositionType, usize)",
NonZeroUsize::new(5).unwrap(),
&mut writer,
|start, _end, value, _| {
// We're building a sparse array. Most characters don't decompose, so we don't
// need to literally store a row for each char.
if value.is_empty() {
return None;
}
let (dtype, decomp) = value.split_once('>').map(|(dtype, decomp)| {
let dtype = dtype.strip_prefix('<').unwrap_or_else(|| {
panic!("Compatibility decomp; expected <tag>\n\tgot: {value}")
});
(
parse_decomp_type(dtype),
decomp
.split_whitespace()
.map(|s| u32::from_str_radix(s, 16).unwrap()),
)
})?;
decomp_ranges.extend(decomp);
let end = decomp_ranges.len();
Some((start, dtype, end))
},
|writer, values| {
// UnicodeData.txt should already be sorted
write!(writer, "[").unwrap();
for (start, dtype, end) in values {
write!(writer, "({start}, DecompositionType::{dtype:?}, {end}),").unwrap();
}
writeln!(writer, "];").unwrap();
},
);
writeln!(writer, "static DECOMP_RANGE: &[u32] = &{decomp_ranges:?};").unwrap();
// Normalization corrections is super small - only a handful chars at the time of writing.
write_derived(
&base,
"NormalizationCorrections.txt",
"DECOMP_UPDATES",
"(u32, u32)",
NonZeroUsize::new(1).unwrap(),
&mut writer,
|start, _end, value, line| {
let original = u32::from_str_radix(value.trim(), 16).unwrap_or_else(|e| {
panic!("field 2 of decomp corrections should be a char in hex: {value} {e}")
});
let version = line
.rsplit(';')
.next()
.unwrap_or_else(|| {
panic!("field 4 of decomp corrections should be a UCD version: {line}")
})
.split_once('#')
.unwrap()
.0
.trim();
// `version` = when the char was updated. Therefore, we use the incorrect chars past
// 3.2.0 but skip the chars fixed in 3.2.0 because they'll already be right.
if version != "3.2.0" {
Some((start, original))
} else {
None
}
},
|writer, mut values| {
values.sort_unstable_by_key(|(c, _)| *c);
write!(writer, "{values:?};").unwrap();
},
);
}
#[expect(clippy::too_many_arguments)]
fn write_derived<W, P, FW, T>(
base: &Path,
file_name: &str,
static_name: &str,
array_type: &str,
field: NonZeroUsize,
writer: &mut W,
parse: P,
write_vec: FW,
) where
W: Write,
P: FnMut(u32, u32, &str, &str) -> Option<T>,
FW: FnMut(&mut W, Vec<T>),
{
let path = base.join(file_name);
let reader = BufReader::new(File::open(path).unwrap());
writeln!(writer, "static {static_name}: &[{array_type}] = &").unwrap();
parse_unicode_3_2(reader, field, writer, parse, write_vec);
}
/// Parse Unicode 3.2.0 property files.
fn parse_unicode_3_2<W, P, FW, T>(
reader: impl BufRead,
field: NonZeroUsize,
writer: &mut W,
mut parse: P,
mut write_vec: FW,
) where
W: Write,
P: FnMut(u32, u32, &str, &str) -> Option<T>,
FW: FnMut(&mut W, Vec<T>),
{
let mut parsed = Vec::new();
for line in reader.lines().map(Result::unwrap) {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut fields = line.split(';');
let range = fields.next().expect("Unicode data is missing a char range");
let id = fields
.nth(field.get().saturating_sub(1))
.expect("Unicode data is missing a property");
let (start, end) = match range.split_once("..") {
Some((left, right)) => {
let start = u32::from_str_radix(left.trim(), 16).unwrap();
let end = u32::from_str_radix(right.trim(), 16).unwrap();
(start, end)
}
None => {
let start = u32::from_str_radix(range.trim(), 16).unwrap();
(start, start)
}
};
let id = id.split_once('#').map_or(id, |(left, _)| left).trim();
if let Some(val) = parse(start, end, id, line) {
parsed.push(val);
}
}
write_vec(writer, parsed);
}
fn parse_general(id: &str) -> GeneralCategory {
match id.trim() {
"Cn" => GeneralCategory::Unassigned,
"Lu" => GeneralCategory::UppercaseLetter,
"Ll" => GeneralCategory::LowercaseLetter,
"Lt" => GeneralCategory::TitlecaseLetter,
"Lm" => GeneralCategory::ModifierLetter,
"Lo" => GeneralCategory::OtherLetter,
"Mn" => GeneralCategory::NonspacingMark,
"Mc" => GeneralCategory::SpacingMark,
"Me" => GeneralCategory::EnclosingMark,
"Nd" => GeneralCategory::DecimalNumber,
"Nl" => GeneralCategory::LetterNumber,
"No" => GeneralCategory::OtherNumber,
"Zs" => GeneralCategory::SpaceSeparator,
"Zl" => GeneralCategory::LineSeparator,
"Zp" => GeneralCategory::ParagraphSeparator,
"Cc" => GeneralCategory::Control,
"Cf" => GeneralCategory::Format,
"Co" => GeneralCategory::PrivateUse,
"Cs" => GeneralCategory::Surrogate,
"Pd" => GeneralCategory::DashPunctuation,
"Ps" => GeneralCategory::OpenPunctuation,
"Pe" => GeneralCategory::ClosePunctuation,
"Pc" => GeneralCategory::ConnectorPunctuation,
"Pi" => GeneralCategory::InitialPunctuation,
"Pf" => GeneralCategory::FinalPunctuation,
"Po" => GeneralCategory::OtherPunctuation,
"Sm" => GeneralCategory::MathSymbol,
"Sc" => GeneralCategory::CurrencySymbol,
"Sk" => GeneralCategory::ModifierSymbol,
"So" => GeneralCategory::OtherSymbol,
invalid => unreachable!("Unicode data contains valid properties: {invalid}"),
}
}
fn parse_eaw(id: &str) -> &'static str {
match id.trim() {
"N" => "EastAsianWidth::Neutral",
"A" => "EastAsianWidth::Ambiguous",
"H" => "EastAsianWidth::Halfwidth",
"F" => "EastAsianWidth::Fullwidth",
"Na" => "EastAsianWidth::Narrow",
"W" => "EastAsianWidth::Wide",
invalid => unreachable!("Unicode data contains valid properties: {invalid}"),
}
}
fn parse_bidi(id: &str) -> &'static str {
match id.trim() {
"L" => "BidiClass::LeftToRight",
"R" => "BidiClass::RightToLeft",
"EN" => "BidiClass::EuropeanNumber",
"ES" => "BidiClass::EuropeanSeparator",
"ET" => "BidiClass::EuropeanTerminator",
"AN" => "BidiClass::ArabicNumber",
"CS" => "BidiClass::CommonSeparator",
"B" => "BidiClass::ParagraphSeparator",
"S" => "BidiClass::SegmentSeparator",
"WS" => "BidiClass::WhiteSpace",
"ON" => "BidiClass::OtherNeutral",
"LRE" => "BidiClass::LeftToRightEmbedding",
"LRO" => "BidiClass::LeftToRightOverride",
"AL" => "BidiClass::ArabicLetter",
"RLE" => "BidiClass::RightToLeftEmbedding",
"RLO" => "BidiClass::RightToLeftOverride",
"PDF" => "BidiClass::PopDirectionalFormat",
"NSM" => "BidiClass::NonspacingMark",
"BN" => "BidiClass::BoundaryNeutral",
"FSI" => "BidiClass::FirstStrongIsolate",
"LRI" => "BidiClass::LeftToRightIsolate",
"RLI" => "BidiClass::RightToLeftIsolate",
"PDI" => "BidiClass::PopDirectionalIsolate",
invalid => unreachable!("Unicode data contains valid properties: {invalid}"),
}
}
fn parse_numeric_type_val(val: NumericType) -> &'static str {
match val {
NumericType::None => "none",
NumericType::Decimal => "decimal",
NumericType::Digit => "digit",
NumericType::Numeric => "numeric",
_ => unreachable!("Unicode data contains valid properties"),
}
}
fn parse_numeric_type_str(id: &str) -> &'static str {
match id {
"none" => "NumericType::None",
"decimal" => "NumericType::Decimal",
"digit" => "NumericType::Digit",
"numeric" => "NumericType::Numeric",
invalid => unreachable!("Unicode data contains valid properties: {invalid}"),
}
}
#[derive(Debug, Default)]
enum DecompositionType {
#[default]
Canonical,
Compat,
Circle,
Final,
Font,
Fraction,
Initial,
Isolated,
Medial,
Narrow,
Nobreak,
Small,
Square,
Sub,
Super,
Vertical,
Wide,
}
fn parse_decomp_type(id: &str) -> DecompositionType {
match id {
"canonical" => DecompositionType::Canonical,
"compat" => DecompositionType::Compat,
"circle" => DecompositionType::Circle,
"final" => DecompositionType::Final,
"font" => DecompositionType::Font,
"fraction" => DecompositionType::Fraction,
"initial" => DecompositionType::Initial,
"isolated" => DecompositionType::Isolated,
"medial" => DecompositionType::Medial,
"narrow" => DecompositionType::Narrow,
"noBreak" => DecompositionType::Nobreak,
"small" => DecompositionType::Small,
"square" => DecompositionType::Square,
"sub" => DecompositionType::Sub,
"super" => DecompositionType::Super,
"vertical" => DecompositionType::Vertical,
"wide" => DecompositionType::Wide,
invalid => unreachable!("Unicode data contains valid properties: {invalid}"),
}
}
fn main() {
println!(r#"cargo::rustc-check-cfg=cfg(osslconf, values("OPENSSL_NO_COMP"))"#);
println!(r#"cargo::rustc-check-cfg=cfg(openssl_vendored)"#);
#[allow(
clippy::unusual_byte_groupings,
reason = "hex groups follow OpenSSL version field boundaries"
)]
let ossl_vers = [
(0x1_00_01_00_0, "ossl101"),
(0x1_00_02_00_0, "ossl102"),
(0x1_01_00_00_0, "ossl110"),
(0x1_01_00_07_0, "ossl110g"),
(0x1_01_00_08_0, "ossl110h"),
(0x1_01_01_00_0, "ossl111"),
(0x1_01_01_04_0, "ossl111d"),
(0x3_00_00_00_0, "ossl300"),
(0x3_01_00_00_0, "ossl310"),
(0x3_02_00_00_0, "ossl320"),
(0x3_03_00_00_0, "ossl330"),
];
for (_, cfg) in ossl_vers {
println!("cargo::rustc-check-cfg=cfg({cfg})");
}
#[cfg(feature = "ssl-openssl")]
{
#[allow(
clippy::unusual_byte_groupings,
reason = "OpenSSL version number is parsed with grouped hex fields"
)]
if let Ok(v) = std::env::var("DEP_OPENSSL_VERSION_NUMBER") {
println!("cargo:rustc-env=OPENSSL_API_VERSION={v}");
// cfg setup from openssl crate's build script
let version = u64::from_str_radix(&v, 16).unwrap();
for (ver, cfg) in ossl_vers {
if version >= ver {
println!("cargo:rustc-cfg={cfg}");
}
}
}
if let Ok(v) = std::env::var("DEP_OPENSSL_CONF") {
for conf in v.split(',') {
println!("cargo:rustc-cfg=osslconf=\"{conf}\"");
}
}
// it's possible for openssl-sys to link against the system openssl under certain conditions,
// so let the ssl module know to only perform a probe if we're actually vendored
if std::env::var("DEP_OPENSSL_VENDORED").is_ok_and(|s| s == "1") {
println!("cargo::rustc-cfg=openssl_vendored")
}
}
println!("cargo:rerun-if-changed=unicode/ucd32");
println!("cargo:rerun-if-changed=unicode/latest");
let t_32 = thread::spawn(generate_unicode_3_2);
let t_numeric_type = thread::spawn(generate_numeric_type);
let t_numeric_value = thread::spawn(generate_numeric_value);
let t_latest = thread::spawn(generate_unicode_latest);
t_32.join().unwrap();
t_numeric_type.join().unwrap();
t_numeric_value.join().unwrap();
t_latest.join().unwrap();
}