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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
use std::borrow::Cow;
use std::iter;
use std::mem::{align_of, size_of};
use std::slice;
use std::ops::{Deref, DerefMut};
use std::cmp::Ordering;
use bit_matrix::BitMatrix;
use bit_matrix::submatrix::{BitSubMatrix, BitSubMatrixMut};
use cfg::{
Cfg,
BinarizedCfg,
ContextFree,
ContextFreeRef,
GrammarRule,
Symbol,
};
use cfg::rule::builder::RuleBuilder;
use cfg::rule::container::RuleContainer;
use cfg::sequence::builder::SequenceRuleBuilder;
use cfg::history::*;
use cfg::sequence::Sequence;
use cfg::usefulness::Usefulness;
use cfg::remap::{Remap, Mapping};
use optional::Optioned;
use item::Dot;
pub struct Grammar {
inherit: Cfg<History, History>,
start: Option<Symbol>,
}
impl Grammar {
pub fn new() -> Self {
Grammar {
inherit: Cfg::new(),
start: None,
}
}
pub fn set_start(&mut self, start: Symbol) {
self.start = Some(start);
}
pub fn get_start(&self) -> Symbol {
self.start.unwrap()
}
pub fn rule(&mut self, lhs: Symbol) -> RuleBuilder<&mut Cfg<History, History>, BuildHistory> {
let rule_count = self.inherit.rules().count() + self.sequence_rules().len();
self.inherit.rule(lhs).default_history(BuildHistory::new(rule_count))
}
pub fn sequence(&mut self, lhs: Symbol)
-> SequenceRuleBuilder<History, &mut Vec<Sequence<History>>, BuildHistory>
{
let rule_count = self.inherit.rules().count() + self.sequence_rules().len();
self.inherit.sequence(lhs).default_history(BuildHistory::new(rule_count))
}
pub fn binarize(&self) -> BinarizedGrammar {
BinarizedGrammar {
inherit: self.inherit.binarize(),
start: self.start,
}
}
pub fn into_internal_grammar(&self) -> InternalGrammar {
InternalGrammar::from_grammar(self)
}
}
impl Deref for Grammar {
type Target = Cfg<History, History>;
fn deref(&self) -> &Self::Target {
&self.inherit
}
}
impl DerefMut for Grammar {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inherit
}
}
#[derive(Clone)]
pub struct BinarizedGrammar {
inherit: BinarizedCfg<History>,
start: Option<Symbol>,
}
impl BinarizedGrammar {
pub fn new() -> Self {
BinarizedGrammar {
inherit: BinarizedCfg::new(),
start: None,
}
}
pub fn set_start(&mut self, start: Symbol) {
self.start = Some(start);
}
pub fn get_start(&self) -> Symbol {
self.start.unwrap()
}
}
impl Deref for BinarizedGrammar {
type Target = BinarizedCfg<History>;
fn deref(&self) -> &Self::Target {
&self.inherit
}
}
impl DerefMut for BinarizedGrammar {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inherit
}
}
pub struct BuildHistory {
num_rules: usize,
}
impl BuildHistory {
pub fn new(num_rules: usize) -> Self {
BuildHistory { num_rules: num_rules }
}
}
impl HistorySource<History> for BuildHistory {
fn build(&mut self, _lhs: Symbol, rhs: &[Symbol]) -> History {
let ret = History::new(self.num_rules as u32, rhs.len());
self.num_rules += 1;
ret
}
}
#[derive(Copy, Clone, Debug)]
pub struct PredictionTransition {
pub symbol: Symbol,
pub dot: Dot,
}
impl PredictionTransition {
#[inline(always)]
pub fn dot(&self) -> DotKind {
let top_bit = 0x8000_0000;
if self.dot & top_bit == top_bit {
DotKind::Completed(self.dot & !top_bit)
} else {
DotKind::Medial(self.dot)
}
}
}
pub enum DotKind {
Medial(Dot),
Completed(Dot),
}
#[derive(Clone)]
pub struct InternalGrammar {
parts: InternalGrammarParts,
prediction_matrix_ptr: *mut u32,
inverse_prediction: *mut [PredictionTransition],
inverse_prediction_index: *mut [u32],
events_flat: *mut [Event],
tracing_flat: *mut [Option<ExternalDottedRule>],
nulling_eliminated: *mut [NullingEliminated],
rules_flat: *mut [Option<Symbol>],
eval: *mut [RuleOrigin],
to_external: *mut [Symbol],
to_internal: *mut [Option<Symbol>],
nulling_intermediate: *mut [NullingIntermediateRule],
}
#[derive(Clone)]
pub struct InternalGrammarParts {
pub storage: Cow<'static, [u8]>,
pub num_syms: usize,
pub num_rules: usize,
pub num_internal_syms: usize,
pub num_external_syms: usize,
pub num_nulling_intermediate: usize,
pub start_sym: Symbol,
pub trivial_derivation: bool,
}
pub type ExternalDottedRule = (u32, u32);
pub type RuleOrigin = Option<u32>;
pub type EventId = Optioned<u32>;
pub type MinimalDistance = Optioned<u32>;
pub type Event = (EventId, MinimalDistance);
pub type NullingRule = (Symbol, [Option<Symbol>; 2]);
pub type NullingEliminated = Option<(Symbol, bool)>;
pub type NullingIntermediateRule = (Symbol, Symbol, Symbol);
#[derive(Debug)]
pub struct InternalGrammarSlices<'a> {
prediction_matrix: BitSubMatrix<'a>,
pub inverse_prediction: &'a [PredictionTransition],
pub inverse_prediction_index: &'a [u32],
pub events_prediction: &'a [Event],
pub events1: &'a [Event],
pub events2: &'a [Event],
pub eval: &'a [RuleOrigin],
pub rules: RuleSlices<'a>,
pub tracing_pred: &'a [Option<ExternalDottedRule>],
pub nulling_eliminated: &'a [NullingEliminated],
pub tracing: &'a [Option<ExternalDottedRule>],
to_external: &'a [Symbol],
pub to_internal: &'a [Option<Symbol>],
nulling_intermediate: &'a [NullingIntermediateRule],
}
pub struct InternalGrammarSlicesMut<'a> {
pub prediction_matrix: BitSubMatrixMut<'a>,
pub inverse_prediction: &'a mut [PredictionTransition],
pub inverse_prediction_index: &'a mut [u32],
pub events_pred: &'a mut [Event],
pub events1: &'a mut [Event],
pub events2: &'a mut [Event],
pub tracing_pred: &'a mut [Option<ExternalDottedRule>],
pub tracing: &'a mut [Option<ExternalDottedRule>],
pub nulling_eliminated: &'a mut [NullingEliminated],
pub rules: RuleSlicesMut<'a>,
pub eval: &'a mut [RuleOrigin],
to_external: &'a mut [Symbol],
to_internal: &'a mut [Option<Symbol>],
nulling_intermediate: &'a mut [NullingIntermediateRule],
}
#[derive(Clone, Default, Debug)]
pub struct History {
dots: Vec<RuleDot>,
origin: RuleOrigin,
nullable: NullingEliminated,
}
#[derive(Copy, Clone, Debug)]
pub struct RuleDot {
event: Option<(EventId, ExternalDottedRule)>,
distance: MinimalDistance,
}
impl RuleDot {
fn new(id: u32, pos: usize) -> Self {
RuleDot {
event: Some((Optioned::none(), (id, pos as u32))),
distance: Optioned::none(),
}
}
pub fn none() -> Self {
RuleDot {
event: None,
distance: Optioned::none(),
}
}
pub fn trace(&self) -> Option<ExternalDottedRule> {
self.event.map(|x| x.1)
}
}
impl Into<Event> for RuleDot {
fn into(self) -> Event {
(self.event.and_then(|x| x.0.into()).into(), self.distance)
}
}
impl History {
pub fn new(id: u32, len: usize) -> Self {
History {
origin: Some(id),
dots: (0 .. len + 1).map(|i| RuleDot::new(id, i)).collect(),
..History::default()
}
}
pub fn origin(&self) -> RuleOrigin {
self.origin
}
pub fn dots(&self) -> &[RuleDot] {
&self.dots[..]
}
}
impl Action for History {
fn no_op(&self) -> Self {
History::default()
}
}
impl Binarize for History {
fn binarize<R>(&self, _rule: &R, depth: usize) -> Self {
let none = RuleDot::none();
let dots = if !self.dots.is_empty() {
let dot_len = self.dots.len();
if depth == 0 {
if dot_len == 2 {
[self.dots[0], none, self.dots[1]]
} else if dot_len >= 3 {
[self.dots[0], self.dots[dot_len - 2], self.dots[dot_len - 1]]
} else {
[self.dots[0], none, none]
}
} else {
[none, self.dots[dot_len - 2 - depth], none]
}
} else {
[none; 3]
};
let origin = if depth == 0 {
self.origin
} else {
None
};
History {
origin: origin,
dots: dots[..].to_vec(),
nullable: self.nullable,
}
}
}
impl EliminateNulling for History {
fn eliminate_nulling<R>(&self, rule: &R, subset: BinarizedRhsSubset) -> Self where
R: GrammarRule {
if let BinarizedRhsSubset::All = subset {
History {
origin: self.origin,
..History::default()
}
} else {
let right = if let BinarizedRhsSubset::Right = subset { true } else { false };
let sym = rule.rhs()[right as usize];
History {
nullable: Some((sym, right)),
..self.clone()
}
}
}
}
#[derive(Copy, Clone)]
enum SymKind {
Element,
Separator,
Other,
}
impl RewriteSequence for History {
type Rewritten = History;
fn top(&self, rhs: Symbol, sep: Option<Symbol>, new_rhs: &[Symbol]) -> Self {
let mut bottom = self.bottom(rhs, sep, new_rhs);
bottom.origin = self.origin;
bottom
}
fn bottom(&self, rhs: Symbol, sep: Option<Symbol>, new_rhs: &[Symbol]) -> Self {
let syms = new_rhs.iter().map(|&sym| {
if sym == rhs {
SymKind::Element
} else if Some(sym) == sep {
SymKind::Separator
} else {
SymKind::Other
}
}).chain(iter::once(SymKind::Other));
let mut to_left = SymKind::Other;
let dots = syms.map(|to_right| {
let dot = match (to_left, to_right) {
(_, SymKind::Separator) => self.dots[1],
(SymKind::Separator, _) => self.dots[2],
(SymKind::Element, _) => self.dots[1],
(_, SymKind::Element) => self.dots[0],
_ => RuleDot::none()
};
to_left = to_right;
dot
}).collect();
History {
dots: dots,
..History::default()
}
}
}
impl BinarizedGrammar {
fn make_proper(mut self: BinarizedGrammar) -> BinarizedGrammar {
let start = self.get_start();
{
let mut usefulness = Usefulness::new(&mut *self).reachable([start]);
if !usefulness.all_useful() {
println!("warning: grammar has useless rules");
usefulness.remove_useless_rules();
}
};
self
}
pub fn generate_special_start(mut self: BinarizedGrammar) -> BinarizedGrammar {
let previous_start = self.get_start();
let new_start = self.sym();
let new_history = History {
dots: vec![RuleDot::none(), RuleDot::none()],
origin: None,
nullable: None,
};
self.rule(new_start).rhs_with_history([previous_start], new_history);
self.set_start(new_start);
self
}
pub fn eliminate_nulling(mut self: BinarizedGrammar) -> (BinarizedGrammar, BinarizedGrammar) {
let nulling_grammar = BinarizedGrammar {
inherit: self.eliminate_nulling_rules(),
start: Some(self.get_start()),
};
(self, nulling_grammar)
}
fn remap_symbols(mut self: BinarizedGrammar) -> (BinarizedGrammar, Mapping) {
let num_syms = self.sym_source().num_syms();
let mut order = BitMatrix::new(num_syms, num_syms);
for rule in self.rules() {
if rule.rhs().len() == 1 {
let left = rule.lhs().usize();
let right = rule.rhs()[0].usize();
match left.cmp(&right) {
Ordering::Less => {
order.set(left, right, true);
}
Ordering::Greater => {
order.set(right, left, true);
}
Ordering::Equal => {}
}
}
}
order.transitive_closure();
let mut maps = {
let mut remap = Remap::new(&mut *self);
remap.remove_unused_symbols();
remap.reorder_symbols(|left, right| {
let (left, right) = (left.usize(), right.usize());
if order[(left, right)] {
Ordering::Less
} else if order[(right, left)] {
Ordering::Greater
} else {
Ordering::Equal
}
});
remap.get_mapping()
};
let start = self.get_start();
if let Some(internal_start) = maps.to_internal[start.usize()] {
self.set_start(internal_start);
} else {
let internal_start = Symbol::from(maps.to_external.len());
maps.to_internal[start.usize()] = Some(internal_start);
maps.to_external.push(start);
self.set_start(internal_start);
}
(self, maps)
}
pub fn process(self: BinarizedGrammar) -> (BinarizedGrammar, BinarizedGrammar) {
let (grammar, nulling) = self.make_proper().eliminate_nulling();
(grammar, nulling)
}
}
impl InternalGrammar {
pub fn from_grammar(grammar: &Grammar) -> Self {
Self::from_binarized_grammar(grammar.binarize())
}
pub fn from_binarized_grammar(grammar: BinarizedGrammar) -> Self {
let grammar = grammar.make_proper();
Self::from_proper_binarized_grammar(grammar)
}
pub fn from_proper_binarized_grammar(grammar: BinarizedGrammar) -> Self {
let (grammar, nulling) = grammar.eliminate_nulling();
Self::from_processed_grammar(grammar, nulling)
}
pub fn from_processed_grammar(grammar: BinarizedGrammar, nulling: BinarizedGrammar) -> Self {
let (grammar, maps) = grammar.remap_symbols();
Self::from_processed_grammar_with_maps(grammar, maps, nulling)
}
pub fn from_processed_grammar_with_maps(
mut grammar: BinarizedGrammar,
maps: Mapping,
nulling: BinarizedGrammar)
-> Self
{
grammar.sort_by(|a, b| a.lhs().cmp(&b.lhs()));
let num_syms = grammar.sym_source().num_syms();
let num_rules = grammar.rules().count();
let trivial_derivation = nulling.rules().any(|rule| Some(rule.lhs()) == nulling.start);
let nulling_intermediate = nulling.rules().filter_map(|rule| {
if rule.history().origin.is_none() && rule.rhs().len() == 2 {
Some((rule.lhs(), rule.rhs()[0], rule.rhs()[1]))
} else {
None
}
}).collect::<Vec<_>>();
let mut result = InternalGrammar::from_parts(InternalGrammarParts {
storage: Cow::Borrowed(&[]),
num_syms: num_syms,
num_internal_syms: maps.to_external.len(),
num_external_syms: maps.to_internal.len(),
num_rules: num_rules,
start_sym: grammar.get_start(),
trivial_derivation: trivial_derivation,
num_nulling_intermediate: nulling_intermediate.len(),
});
result.populate_rules(&grammar, &maps);
result.populate_nulling_rules(nulling_intermediate);
let inverse_prediction = result.compute_inverse_prediction();
result.populate_predictions(inverse_prediction);
result
}
fn populate_rules(&mut self, grammar: &BinarizedGrammar, maps: &Mapping) {
let num_rules = self.parts.num_rules;
let mut slices = self.as_slices_mut();
let (tracing1, tracing2) = slices.tracing.split_at_mut(num_rules);
for elem in slices.events_pred.iter_mut() {
*elem = (Optioned::none(), Optioned::none());
}
let iter = slices.rules.rules_mut()
.zip(slices.eval)
.zip(slices.events1)
.zip(slices.events2)
.zip(slices.nulling_eliminated)
.zip(tracing1.iter_mut())
.zip(tracing2.iter_mut());
for (rule, ((((((mut dst_rule, eval), event1), event2), nulling), t1), t2))
in grammar.rules().zip(iter) {
*dst_rule.lhs = Some(rule.lhs());
*dst_rule.rhs0 = Some(rule.rhs()[0]);
*dst_rule.rhs1 = rule.rhs().get(1).cloned();
*eval = rule.history().origin;
*nulling = rule.history().nullable;
if let Some(&(pred_event, pred_tracing)) = rule.history().dots[0].event.as_ref() {
slices.events_pred[rule.lhs().usize()] = (
pred_event,
rule.history().dots[0].distance
);
slices.tracing_pred[rule.lhs().usize()] = Some(pred_tracing);
}
*event1 = rule.history().dots[1].into();
*event2 = rule.history().dots[2].into();
*t1 = rule.history().dots[1].trace();
*t2 = rule.history().dots[2].trace();
}
for (dst, src) in slices.to_external.iter_mut().zip(maps.to_external.iter()) {
*dst = *src;
}
for (dst, src) in slices.to_internal.iter_mut().zip(maps.to_internal.iter()) {
*dst = *src;
}
}
fn populate_nulling_rules(&mut self, nulling_intermediate: Vec<(Symbol, Symbol, Symbol)>) {
let mut slices = self.as_slices_mut();
for (dst, src) in slices.nulling_intermediate.iter_mut().zip(nulling_intermediate) {
*dst = src;
}
}
fn compute_inverse_prediction(&self) -> Vec<Vec<PredictionTransition>> {
let mut slices = self.as_slices();
let mut inverse_prediction = iter::repeat(vec![]).take(self.parts.num_syms).collect::<Vec<_>>();
for (dot, rule) in slices.rules.rules().enumerate() {
let transition = PredictionTransition {
symbol: rule.lhs,
dot: if rule.rhs1() == None {
dot as Dot | 0x8000_0000
} else {
dot as Dot
}
};
inverse_prediction[rule.rhs0().usize()].push(transition);
}
inverse_prediction
}
fn populate_predictions(&mut self, inverse_prediction: Vec<Vec<PredictionTransition>>) {
let num_syms = self.parts.num_syms;
let mut slices = self.as_slices_mut();
let mut prediction_matrix = &mut slices.prediction_matrix;
for rule in slices.rules.rules_mut() {
prediction_matrix.set(rule.lhs().usize(), rule.rhs0().usize(), true);
}
slices.inverse_prediction_index[0] = 0;
let mut idx = 0;
let indices = slices.inverse_prediction_index[1..].iter_mut();
for (src, dst) in inverse_prediction.iter().zip(indices) {
idx += src.len() as u32;
*dst = idx;
}
for (src, dst) in inverse_prediction.into_iter().flat_map(|v| v.into_iter())
.zip(slices.inverse_prediction.iter_mut()) {
*dst = src;
}
prediction_matrix.transitive_closure();
for i in 0..num_syms {
prediction_matrix.set(i, i, true);
}
}
pub fn to_parts(&self) -> InternalGrammarParts {
self.parts.clone()
}
pub fn from_parts(mut parts: InternalGrammarParts) -> Self {
let (len, offset) = grammar_storage_offsets(&parts);
let end = offset[LEN_LEN];
if parts.storage.is_empty() {
parts.storage = Cow::Owned(vec![0; end]);
}
assert!(parts.storage.len() >= end);
let field = unsafe {(
parts.storage[offset[0]..].as_ptr() as *mut _,
slice::from_raw_parts_mut(parts.storage[offset[1]..].as_ptr() as *mut _, len[1]),
slice::from_raw_parts_mut(parts.storage[offset[2]..].as_ptr() as *mut _, len[2]),
slice::from_raw_parts_mut(parts.storage[offset[3]..].as_ptr() as *mut _, len[3]),
slice::from_raw_parts_mut(parts.storage[offset[4]..].as_ptr() as *mut _, len[4]),
slice::from_raw_parts_mut(parts.storage[offset[5]..].as_ptr() as *mut _, len[5]),
slice::from_raw_parts_mut(parts.storage[offset[6]..].as_ptr() as *mut _, len[6]),
slice::from_raw_parts_mut(parts.storage[offset[7]..].as_ptr() as *mut _, len[7]),
slice::from_raw_parts_mut(parts.storage[offset[8]..].as_ptr() as *mut _, len[8]),
slice::from_raw_parts_mut(parts.storage[offset[9]..].as_ptr() as *mut _, len[9]),
slice::from_raw_parts_mut(parts.storage[offset[10]..].as_ptr() as *mut _, len[10]),
)};
InternalGrammar {
prediction_matrix_ptr: field.0,
rules_flat: field.1,
eval: field.2,
nulling_eliminated: field.3,
inverse_prediction_index: field.4,
inverse_prediction: field.5,
events_flat: field.6,
tracing_flat: field.7,
to_external: field.8,
to_internal: field.9,
nulling_intermediate: field.10,
parts: parts,
}
}
#[inline]
pub fn as_slices_mut(&mut self) -> InternalGrammarSlicesMut {
unsafe {
let &InternalGrammarParts { num_rules, num_syms, .. } = &self.parts;
let (rhs0, rest) = (*self.rules_flat).split_at_mut(num_rules);
let (rhs1, lhs) = rest.split_at_mut(num_rules);
let (events_pred, rest) = (*self.events_flat).split_at_mut(num_syms);
let (events1, events2) = rest.split_at_mut(num_rules);
let (tracing_pred, tracing) = (*self.tracing_flat).split_at_mut(num_syms);
let prediction_matrix = BitSubMatrixMut::from_raw_parts(
self.prediction_matrix_ptr as *mut _,
num_syms,
num_syms
);
InternalGrammarSlicesMut {
prediction_matrix: prediction_matrix,
inverse_prediction: &mut *self.inverse_prediction,
inverse_prediction_index: &mut *self.inverse_prediction_index,
events_pred: events_pred,
events1: events1,
events2: events2,
tracing_pred: tracing_pred,
tracing: tracing,
nulling_eliminated: &mut *self.nulling_eliminated,
rules: RuleSlicesMut {
lhs: lhs,
rhs0: rhs0,
rhs1: rhs1,
},
eval: &mut *self.eval,
to_external: &mut *self.to_external,
to_internal: &mut *self.to_internal,
nulling_intermediate: &mut *self.nulling_intermediate,
}
}
}
#[inline(always)]
pub fn as_slices(&self) -> InternalGrammarSlices {
unsafe {
let &InternalGrammarParts { num_rules, num_syms, .. } = &self.parts;
let (events_pred, rest) = (*self.events_flat).split_at(num_syms);
let (events1, events2) = rest.split_at(num_rules);
let (tracing_pred, tracing) = (*self.tracing_flat).split_at(num_syms);
let prediction_matrix = BitSubMatrix::from_raw_parts(
self.prediction_matrix_ptr as *const _,
num_syms,
num_syms
);
InternalGrammarSlices {
prediction_matrix: prediction_matrix,
inverse_prediction: &*self.inverse_prediction,
inverse_prediction_index: &*self.inverse_prediction_index,
events_prediction: events_pred,
events1: events1,
events2: events2,
tracing_pred: tracing_pred,
tracing: tracing,
nulling_eliminated: &*self.nulling_eliminated,
rules: self.rules(),
eval: &*self.eval,
to_external: &*self.to_external,
to_internal: &*self.to_internal,
nulling_intermediate: &*self.nulling_intermediate,
}
}
}
#[inline]
pub fn prediction_matrix(&self) -> BitSubMatrix {
self.as_slices().prediction_matrix
}
#[inline(always)]
pub fn inverse_prediction(&self) -> &[PredictionTransition] {
unsafe { &*self.inverse_prediction }
}
#[inline]
pub fn num_syms(&self) -> usize {
self.parts.num_syms
}
#[inline]
pub fn num_rules(&self) -> usize {
self.parts.num_rules
}
#[inline]
pub fn num_pos(&self) -> usize {
self.parts.num_rules * 2
}
#[inline]
pub fn start_sym(&self) -> Symbol {
self.parts.start_sym
}
#[inline]
pub fn has_trivial_derivation(&self) -> bool {
self.parts.trivial_derivation
}
#[inline]
pub fn nulling(&self, pos: u32) -> NullingEliminated {
unsafe {
let nulling_eliminated = &*self.nulling_eliminated;
nulling_eliminated.get(pos as usize).and_then(|&ne| ne)
}
}
#[inline]
pub fn events(&self) -> (&[Event], &[Event]) {
unsafe {
let events_flat = &*self.events_flat;
events_flat.split_at(self.num_syms())
}
}
#[inline]
pub fn trace(&self) -> [&[Option<ExternalDottedRule>]; 3] {
let slices = self.as_slices();
let (trace1, trace2) = slices.tracing.split_at(self.num_rules());
[slices.tracing_pred, trace1, trace2]
}
#[inline]
pub fn complete_over(&self, dot: Dot, sym: Symbol) -> bool {
let rhs1 = self.rules().rhs1;
rhs1[dot as usize] == Some(sym)
}
#[inline]
pub fn rules(&self) -> RuleSlices {
unsafe {
let (rhs0, rest) = (*self.rules_flat).split_at(self.num_rules());
let (rhs1, lhs) = rest.split_at(self.num_rules());
RuleSlices {
lhs: lhs,
rhs0: rhs0,
rhs1: rhs1,
}
}
}
#[inline]
pub fn get_rhs0(&self, dot: Dot) -> Symbol {
let rules = self.rules().rhs0;
rules[dot as usize].unwrap()
}
#[inline]
pub fn get_rhs1(&self, dot: Dot) -> Option<Symbol> {
let rules = self.rules().rhs1;
rules[dot as usize]
}
#[inline]
pub fn get_lhs(&self, dot: Dot) -> Symbol {
let rules = self.rules().lhs;
rules[dot as usize].unwrap()
}
#[inline]
pub fn get_eval(&self, dot: Dot) -> RuleOrigin {
unsafe {
(&*self.eval).get(dot as usize).and_then(|&eval| eval)
}
}
pub fn eliminated_nulling_intermediate(&self) -> &[NullingIntermediateRule] {
unsafe {
&*self.nulling_intermediate
}
}
#[inline(always)]
pub fn inverse_prediction_of(&self, sym: Symbol) -> &[PredictionTransition] {
let slices = self.as_slices();
let idxs = &slices.inverse_prediction_index[sym.usize() .. sym.usize() + 2];
let range = idxs[0] as usize .. idxs[1] as usize;
&self.inverse_prediction()[range]
}
#[inline(always)]
pub fn to_internal(&self, symbol: Symbol) -> Option<Symbol> {
if self.parts.num_external_syms == 0 {
Some(symbol)
} else {
self.as_slices().to_internal[symbol.usize()]
}
}
#[inline]
pub fn to_external(&self, symbol: Symbol) -> Symbol {
if self.parts.num_internal_syms == 0 {
symbol
} else {
self.as_slices().to_external[symbol.usize()]
}
}
}
const LEN_LEN: usize = 11;
const OFFSET_LEN: usize = LEN_LEN + 1;
#[inline]
fn grammar_storage_offsets(parts: &InternalGrammarParts)
-> ([usize; LEN_LEN], [usize; OFFSET_LEN])
{
let &InternalGrammarParts {
num_syms,
num_rules,
num_internal_syms,
num_external_syms,
num_nulling_intermediate,
..
} = parts;
let pred_columns = (num_syms + 32 - 1) / 32;
let table = [
(pred_columns * num_syms, size_and_align_of::<u32>()),
(num_rules * 3, size_and_align_of::<Option<Symbol>>()),
(num_rules, size_and_align_of::<RuleOrigin>()),
(num_rules, size_and_align_of::<NullingEliminated>()),
(num_syms + 1, size_and_align_of::<u32>()),
(num_rules, size_and_align_of::<PredictionTransition>()),
(num_syms + num_rules * 2, size_and_align_of::<Event>()),
(num_syms + num_rules * 2, size_and_align_of::<Option<ExternalDottedRule>>()),
(num_internal_syms, size_and_align_of::<Symbol>()),
(num_external_syms, size_and_align_of::<Option<Symbol>>()),
(num_nulling_intermediate, size_and_align_of::<NullingIntermediateRule>()),
];
let mut len_ary = [0; LEN_LEN];
let mut offset_ary = [0; OFFSET_LEN];
let mut cur_offset = 0;
{
let src = table[..].iter().cloned().zip(
table[1..].iter().map(|elem| (elem.1).1).chain(iter::once(1))
);
let dst = len_ary.iter_mut().zip(offset_ary[1..].iter_mut());
for (((len, (size, _)),
align),
(dst_len, offset)) in src.zip(dst) {
*dst_len = len;
cur_offset = round_up_to_next(cur_offset + size * len, align);
*offset = cur_offset;
}
};
(len_ary, offset_ary)
}
#[inline]
fn size_and_align_of<T>() -> (usize, usize) {
(size_of::<T>(), align_of::<T>())
}
#[inline]
fn round_up_to_next(unrounded: usize, target_alignment: usize) -> usize {
assert!(target_alignment.is_power_of_two());
(unrounded + target_alignment - 1) & !(target_alignment - 1)
}
pub struct BinaryRule {
lhs: Symbol,
rhs0: Symbol,
rhs1: Option<Symbol>,
}
impl BinaryRule {
fn new(lhs: Symbol, rhs0: Symbol, rhs1: Option<Symbol>) -> Self {
BinaryRule {
lhs: lhs,
rhs0: rhs0,
rhs1: rhs1,
}
}
pub fn lhs(&self) -> Symbol {
self.lhs
}
pub fn rhs0(&self) -> Symbol {
self.rhs0
}
pub fn rhs1(&self) -> Option<Symbol> {
self.rhs1
}
}
struct BinaryRuleMut<'a> {
lhs: &'a mut Option<Symbol>,
rhs0: &'a mut Option<Symbol>,
rhs1: &'a mut Option<Symbol>,
}
impl<'a> BinaryRuleMut<'a> {
fn lhs(&self) -> Symbol {
self.lhs.unwrap()
}
fn rhs0(&self) -> Symbol {
self.rhs0.unwrap()
}
}
#[derive(Debug)]
pub struct RuleSlices<'a> {
pub lhs: &'a [Option<Symbol>],
pub rhs0: &'a [Option<Symbol>],
pub rhs1: &'a [Option<Symbol>],
}
impl<'a> RuleSlices<'a> {
pub fn rules(&mut self) -> Rules<'a> {
Rules {
lhs: self.lhs.iter(),
rhs0: self.rhs0.iter(),
rhs1: self.rhs1.iter(),
}
}
}
pub struct RuleSlicesMut<'a> {
pub lhs: &'a mut [Option<Symbol>],
pub rhs0: &'a mut [Option<Symbol>],
pub rhs1: &'a mut [Option<Symbol>],
}
impl<'a> RuleSlicesMut<'a> {
fn rules_mut(&'a mut self) -> RulesMut<'a> {
RulesMut {
lhs: self.lhs.iter_mut(),
rhs0: self.rhs0.iter_mut(),
rhs1: self.rhs1.iter_mut(),
}
}
}
pub struct Rules<'a> {
lhs: slice::Iter<'a, Option<Symbol>>,
rhs0: slice::Iter<'a, Option<Symbol>>,
rhs1: slice::Iter<'a, Option<Symbol>>,
}
impl<'a> Iterator for Rules<'a> {
type Item = BinaryRule;
fn next(&mut self) -> Option<BinaryRule> {
match (self.lhs.next(), self.rhs0.next(), self.rhs1.next()) {
(Some(&Some(lhs)), Some(&Some(rhs0)), Some(&None)) => {
Some(BinaryRule::new(lhs, rhs0, None))
}
(Some(&Some(lhs)), Some(&Some(rhs0)), Some(&Some(rhs1))) => {
Some(BinaryRule::new(lhs, rhs0, Some(rhs1)))
}
_ => None
}
}
}
struct RulesMut<'a> {
lhs: slice::IterMut<'a, Option<Symbol>>,
rhs0: slice::IterMut<'a, Option<Symbol>>,
rhs1: slice::IterMut<'a, Option<Symbol>>,
}
impl<'a> Iterator for RulesMut<'a> {
type Item = BinaryRuleMut<'a>;
fn next(&mut self) -> Option<BinaryRuleMut<'a>> {
match (self.lhs.next(), self.rhs0.next(), self.rhs1.next()) {
(Some(lhs), Some(rhs0), Some(rhs1)) => {
Some(BinaryRuleMut {
lhs: lhs,
rhs0: rhs0,
rhs1: rhs1,
})
}
_ => None
}
}
}