-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathparser.rs
2830 lines (2484 loc) · 95.8 KB
/
parser.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
// In this file, "Kallmeyer 2018" refers to the
// slides for "Parsing: Earley parsing", Winter 2017/2018,
// Laura Kallmeyer, Heinrich Heine Universitaet, Dusseldorf,
// https://user.phil-fak.uni-duesseldorf.de/~kallmeyer/Parsing/earley.pdf
// (Retrieved 18 Sep 2024).
use std::{
fmt::{Debug, Display},
hash::Hash,
ops::Range,
sync::{Arc, Mutex},
};
use crate::{earley::lexer::MatchingLexemesIdx, HashMap, HashSet, Instant};
use anyhow::{bail, ensure, Result};
use derivre::{NextByte, RegexAst, StateID};
use serde::{Deserialize, Serialize};
use toktrie::{
parse_numeric_token, Recognizer, SimpleVob, TokEnv, TokTrie, TokenId, INVALID_TOKEN,
};
use crate::{
api::{ParserLimits, StopReason},
earley::{lexer::Lexer, lexerspec::LexemeClass},
id32_type,
};
use super::{
grammar::{CGrammar, CSymIdx, CSymbol, RhsPtr},
lexer::{LexerResult, PreLexeme},
lexerspec::{Lexeme, LexemeIdx, LexemeSpec, LexerSpec},
perf::ParserPerfCounters,
regexvec::{LexemeSet, LexerStats},
};
const TRACE: bool = false;
const DEBUG: bool = true;
pub(crate) const ITEM_TRACE: bool = false;
macro_rules! trace {
($($arg:tt)*) => {
if cfg!(feature = "logging") && TRACE {
eprintln!($($arg)*);
}
}
}
macro_rules! debug {
($($arg:tt)*) => {
if cfg!(feature = "logging") && DEBUG {
eprintln!($($arg)*);
}
}
}
macro_rules! item_trace {
($($arg:tt)*) => {
if ITEM_TRACE {
eprint!(" ");
eprintln!($($arg)*);
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct Item {
data: u64,
}
#[derive(Clone)]
struct SavedParserState {
lexer_stack_length: usize,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct ParserStats {
pub compute_time_us: u64,
pub rows: usize,
pub cached_rows: usize,
pub all_items: usize,
pub lexer_cost: u64,
pub slices_applied: usize,
pub trie_nodes_walked: usize,
pub definitive_bytes: usize,
pub lexer_ops: usize,
pub num_lex_errors: usize,
pub num_lexemes: usize,
}
#[derive(Debug, Clone)]
pub struct XorShift {
seed: u32,
}
impl XorShift {
pub fn new(seed: u32) -> Self {
XorShift { seed }
}
pub fn new_str(s: &str) -> Self {
XorShift {
seed: XorShift::fnv1a_32(s.as_bytes()),
}
}
#[allow(clippy::should_implement_trait)]
pub fn next(&mut self) -> u32 {
let mut x = self.seed;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
self.seed = x;
x
}
pub fn from_range(&mut self, r: Range<usize>) -> usize {
assert!(r.start < r.end);
assert!(r.end < u32::MAX as usize);
r.start + (self.next() as usize) % (r.end - r.start)
}
pub fn one_in(&mut self, n: u32) -> bool {
self.next() % n == 0
}
pub fn next_alt(&mut self) -> u32 {
let mut x = self.seed;
x ^= x << 15;
x ^= x >> 4;
x ^= x << 23;
self.seed = x;
x
}
pub fn fnv1a_32(s: &[u8]) -> u32 {
let mut hash: u32 = 0x811c9dc5;
for byte in s {
hash ^= *byte as u32;
hash = hash.wrapping_mul(0x01000193);
}
hash
}
pub fn sample_from_vob(&mut self, vob: &SimpleVob) -> u32 {
let nset = vob.num_set();
assert!(nset > 0);
if nset > vob.len() / 10 {
loop {
let idx = self.from_range(0..vob.len());
if vob[idx] {
return idx as u32;
}
}
} else {
let choices = vob.to_list();
choices[self.from_range(0..choices.len())]
}
}
}
impl Default for XorShift {
fn default() -> Self {
XorShift { seed: 0xdeadf00d }
}
}
#[derive(Debug, Default, Clone)]
pub struct ParserMetrics {
pub rand: XorShift,
pub message: String,
pub slicer_leftover_us: usize,
}
impl ParserStats {
pub fn delta(&self, previous: &ParserStats) -> ParserStats {
ParserStats {
rows: self.rows.saturating_sub(previous.rows),
cached_rows: self.cached_rows.saturating_sub(previous.cached_rows),
definitive_bytes: self
.definitive_bytes
.saturating_sub(previous.definitive_bytes),
lexer_ops: self.lexer_ops.saturating_sub(previous.lexer_ops),
num_lexemes: self.num_lexemes.saturating_sub(previous.num_lexemes),
num_lex_errors: self.num_lex_errors.saturating_sub(previous.num_lex_errors),
all_items: self.all_items.saturating_sub(previous.all_items),
lexer_cost: self.lexer_cost.saturating_sub(previous.lexer_cost),
compute_time_us: self
.compute_time_us
.saturating_sub(previous.compute_time_us),
slices_applied: self.slices_applied.saturating_sub(previous.slices_applied),
trie_nodes_walked: self
.trie_nodes_walked
.saturating_sub(previous.trie_nodes_walked),
}
}
pub fn max(&self, other: &ParserStats) -> ParserStats {
ParserStats {
rows: self.rows.max(other.rows),
cached_rows: self.cached_rows.max(other.cached_rows),
definitive_bytes: self.definitive_bytes.max(other.definitive_bytes),
lexer_ops: self.lexer_ops.max(other.lexer_ops),
num_lexemes: self.num_lexemes.max(other.num_lexemes),
num_lex_errors: self.num_lex_errors.max(other.num_lex_errors),
all_items: self.all_items.max(other.all_items),
lexer_cost: self.lexer_cost.max(other.lexer_cost),
compute_time_us: self.compute_time_us.max(other.compute_time_us),
slices_applied: self.slices_applied.max(other.slices_applied),
trie_nodes_walked: self.trie_nodes_walked.max(other.trie_nodes_walked),
}
}
}
impl Display for ParserStats {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string_pretty(self).unwrap())
}
}
id32_type!(GrammarStackPtr);
#[derive(Clone, Debug)]
struct GrammarStackNode {
back_ptr: GrammarStackPtr,
token_horizon: u32,
grammar_id: LexemeClass,
start_item: Item,
start_item_idx: usize,
}
// In this, code a "Row" is what is usually called an Earley set in the literature.
// The term "row" comes from Kallmeyer 2018, which uses a chart parsing algorithm
// in which the rows are Earley sets.
#[derive(Clone)]
struct Row {
first_item: u32,
last_item: u32,
grammar_stack_ptr: GrammarStackPtr,
// The lexer state below only allows certain lexemes.
// The allowed lexemes (aka acceptable
// lexemes, aka relevant lexemes) are those which the recognizer
// will accept in the next row. They are all and only those lexemes
// which can lead to a successful parse.
lexer_start_state: StateID,
lexeme_idx: MatchingLexemesIdx,
}
impl Row {
fn item_indices(&self) -> Range<usize> {
self.first_item as usize..self.last_item as usize
}
}
// In this code, an "Item" is what is called in the literature, an
// "Earley item".
impl Item {
#[allow(dead_code)]
const NULL: Self = Item { data: 0 };
fn new(rule: RhsPtr, start: usize) -> Self {
Item {
data: rule.as_index() as u64 | ((start as u64) << 32),
}
}
fn rhs_ptr(&self) -> RhsPtr {
RhsPtr::from_index(self.data as u32)
}
fn start_pos(&self) -> usize {
(self.data >> 32) as usize
}
fn advance_dot(&self) -> Self {
Item {
data: self.data + 1,
}
}
fn rewind_dot(&self) -> Self {
Item {
data: self.data - 1,
}
}
}
impl Debug for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let rule = self.rhs_ptr();
write!(f, "Item(rhs={} @{})", rule.as_index(), self.start_pos())
}
}
// This structure implements the Earley table, and in particular working data
// used when processing a row.
#[derive(Clone)]
struct Scratch {
grammar: Arc<CGrammar>,
// The current "working row"
row_start: usize,
row_end: usize,
// these two are not really "scratch" - they are just here for convenience
// grammar_stack only grows, until the trie is finished
items: Vec<Item>,
grammar_stack: Vec<GrammarStackNode>,
push_allowed_grammar_ids: SimpleVob,
push_allowed_lexemes: LexemeSet,
push_grm_top: GrammarStackPtr,
push_lexeme_idx: MatchingLexemesIdx,
// Is this Earley table in "definitive" mode?
// 'definitive' is set when the new lexeme is being 'defined',
// as indicated by the creation of a 'struct Rowinfo' to track
// the lexeme. The opposite of definitive mode is "speculative"
// mode, which is used for computing the token mask on the
// pre-lexemes.
definitive: bool,
}
#[derive(Clone)]
struct RowInfo {
// TODO: possibly use u32 not usize here
start_byte_idx: usize,
lexeme: Lexeme,
token_idx_start: usize,
token_idx_stop: usize,
}
impl RowInfo {
fn apply_token_idx(&mut self, idx: usize) {
self.token_idx_start = self.token_idx_start.min(idx);
self.token_idx_stop = self.token_idx_stop.max(idx);
}
fn set_token_idx(&mut self, idx: usize) {
self.token_idx_start = idx;
self.token_idx_stop = idx;
}
fn dbg(&self, lexer: &Lexer) -> String {
format!(
"token_idx: {}-{}; b:{}; {}",
self.token_idx_start,
self.token_idx_stop,
self.start_byte_idx,
lexer.dbg_lexeme(&self.lexeme),
)
}
}
// State transition is:
// if (next_lexeme, next_lexer_state) := lexer(top.lexer_state, next_byte) {
// row_idx = scan(top.row_idx, next_lexeme)
// push(LexerState { row_idx, next_byte, next_lexer_state })
// }
//
// The LLM thinks in tokens, while the parser only deals with lexemes.
// There is no easy translation between these, and the parser cannot work
// with tokens. On the other hand, forcing the LLM to deal with lexemes will increase
// token perplexity and degrade the quality of the LLM's output.
//
// The data structure used to resolve this "impedance mismatch" is a stack of 'LexerState' items.
// Tokens are broken down into single bytes when they go into this stack,
// and the bytes are assembled into lexemes by the lexer.
// The 'LexerState' items are left on the stack (unless backtracking).
//
// The stack of lexer states also manages a virtual stack of Earley sets, via the
// 'row_idx' field. The current Earley table/stack is rows 0 through 'row_idx'.
#[derive(Clone, Copy, Debug)]
struct LexerState {
row_idx: u32, // Index of corresponding row (Earley set)
lexer_state: StateID, // state after consuming 'byte'
byte: Option<u8>,
}
#[derive(Clone)]
struct Captures {
capture_list: Vec<(String, Vec<u8>)>,
capture_map: HashMap<String, Vec<u8>>,
}
impl Captures {
fn new() -> Self {
Captures {
capture_list: vec![],
capture_map: HashMap::default(),
}
}
fn push(&mut self, cap: (String, Vec<u8>)) {
let (name, bytes) = cap;
// in Guidance, the __LIST_APPEND: ones are supposed to be appended not overwritten
if !name.starts_with("__LIST_APPEND:") {
if let Some(old) = self.capture_map.get(&name) {
if old == &bytes {
return;
}
}
}
self.capture_list.push((name.clone(), bytes.clone()));
self.capture_map.insert(name, bytes);
}
}
#[derive(Clone)]
struct ParserState {
grammar: Arc<CGrammar>,
tok_env: TokEnv,
scratch: Scratch,
trie_lexer_stack: usize,
trie_grammar_stack: usize,
captures: Captures,
special_token_marker_token: TokenId,
// These are updated also in speculative mode.
// Both are stacks only in the sense that items can be popped on backtracking
// (when walking the token trie). Otherwise, they represent the full parsing
// history - items are not popped in definitive mode.
lexer_stack: Vec<LexerState>,
lexer_stack_top_eos: bool,
rows: Vec<Row>,
rows_valid_end: usize,
trace_byte_stack: Vec<u8>,
trace_stats0: ParserStats,
trace_start: Instant,
// These are only updated in definitive mode.
row_infos: Vec<RowInfo>,
token_idx: usize,
bytes: Vec<u8>,
// use u32 to save space
byte_to_token_idx: Vec<u32>,
last_force_bytes_len: usize,
stats: ParserStats,
perf_counters: Arc<ParserPerfCounters>,
limits: ParserLimits,
metrics: ParserMetrics,
max_all_items: usize,
parser_error: Option<String>,
backtrack_byte_count: usize,
shared_box: Box<SharedState>,
}
#[derive(Clone, Default)]
struct SharedState {
lexer_opt: Option<Lexer>,
}
impl SharedState {
#[inline(always)]
fn lexer_mut(&mut self) -> &mut Lexer {
self.lexer_opt.as_mut().unwrap()
}
#[inline(always)]
fn lexer(&self) -> &Lexer {
self.lexer_opt.as_ref().unwrap()
}
}
#[derive(Clone)]
pub struct Parser {
shared: Arc<Mutex<Box<SharedState>>>,
state: ParserState,
}
impl Scratch {
fn new(grammar: Arc<CGrammar>) -> Self {
Scratch {
push_allowed_lexemes: grammar.lexer_spec().alloc_lexeme_set(),
push_allowed_grammar_ids: grammar.lexer_spec().alloc_grammar_set(),
push_grm_top: GrammarStackPtr::new(0),
push_lexeme_idx: MatchingLexemesIdx::Single(LexemeIdx::new(0)),
grammar,
row_start: 0,
row_end: 0,
items: vec![],
grammar_stack: vec![],
definitive: true,
}
}
// Set current working Earley to empty set
// The set backing data is at `pos`
fn new_row(&mut self, pos: usize) {
self.row_start = pos;
self.row_end = pos;
}
// Number of items in the current working Earley set
fn row_len(&self) -> usize {
self.row_end - self.row_start
}
// Add a new row to the Earley table. It will be the
// current, working, row.
fn work_row(&self, lexer_start_state: StateID) -> Row {
Row {
first_item: self.row_start as u32,
last_item: self.row_end as u32,
grammar_stack_ptr: self.push_grm_top,
lexer_start_state,
lexeme_idx: self.push_lexeme_idx,
}
}
// Make sure there is enough space in the Earley table,
// usually in preparation for adding Earley items.
#[inline(always)]
fn ensure_items(&mut self, n: usize) {
self.items.reserve(n.saturating_sub(self.items.len()));
}
fn push_grammar_stack(&mut self, node: GrammarStackNode) {
if self.definitive {
debug!("push_grammar_stack: {:?}", node);
}
let ptr = GrammarStackPtr::new(self.grammar_stack.len());
self.grammar_stack.push(node);
self.push_grm_top = ptr;
}
// Add a new Earley item with default values to the Earley table. It is
// "just" added in the sense that no checks are performed, except the one
// that ensures there is enough space in the table. The other checks are
// assumed to be unnecessary or to have been performed. For example, it
// is assumed the caller knows that this Earley item will be unique.
#[inline(always)]
fn just_add(&mut self, item: Item, _origin_item_idx: usize, info: &str) {
if self.items.len() == self.row_end {
self.items.push(item);
} else {
self.items[self.row_end] = item;
}
if self.definitive {
debug!(
" addu: {} ({})",
self.item_to_string(self.row_end),
info
);
}
self.row_end += 1;
}
// Find 'item' in the current, working, row.
#[inline(always)]
fn find_item(&self, item: Item) -> Option<usize> {
self.items[self.row_start..self.row_end]
.iter()
.position(|&x| x == item)
.map(|x| x + self.row_start)
}
// Ensure that Earley table 'self' contains
// Earley item 'item'. That is, look for 'item' in 'self',
// and add 'item' to 'self' if it is not there already.
#[inline(always)]
fn add_unique(&mut self, item: Item, origin_item_idx: usize, info: &str) {
if self.find_item(item).is_none() {
self.just_add(item, origin_item_idx, info);
}
}
// Write item at index 'idx' as a string.
fn item_to_string(&self, idx: usize) -> String {
item_to_string(&self.grammar, &self.items[idx])
}
}
macro_rules! ensure_internal {
($cond:expr, $msg:expr) => {
ensure!($cond, "Internal error: {}", $msg)
};
}
impl ParserState {
// Create a new state for an empty parser.
// The parser starts in definitive mode.
fn new(
tok_env: TokEnv,
grammar: Arc<CGrammar>,
mut limits: ParserLimits,
perf_counters: Arc<ParserPerfCounters>,
) -> Result<(Self, Lexer)> {
let start = grammar.start();
let mut lexer = Lexer::from(grammar.lexer_spec(), &mut limits, true)?;
if limits.precompute_large_lexemes {
let t0 = crate::Instant::now();
lexer.dfa.set_fuel(limits.initial_lexer_fuel);
for spec in &grammar.lexer_spec().lexemes {
let w = lexer.dfa.lexeme_weight(spec.idx);
if w > 1000 {
// println!(
// "precomputing lexeme {} (w={w}) f={}",
// lexer.lexer_spec().lexeme_def_to_string(spec.idx),
// lexer.dfa.get_fuel()
// );
let mut allowed = grammar.lexer_spec().alloc_lexeme_set();
allowed.add(spec.idx);
lexer.precompute_for(tok_env.tok_trie(), &allowed);
// println!("fuel={}", lexer.dfa.get_fuel());
}
}
perf_counters.precompute.record(t0.elapsed());
if lexer.dfa.has_error() {
bail!("lexer precomputation failed; either increase limits.initial_lexer_fuel or disable limits.precompute_large_lexemes");
}
}
let scratch = Scratch::new(Arc::clone(&grammar));
let lexer_state = lexer.a_dead_state(); // placeholder
let spec_tok = tok_env
.tok_trie()
.greedy_tokenize(&[TokTrie::SPECIAL_TOKEN_MARKER]);
let special_marker_token = if spec_tok.len() == 1 {
spec_tok[0]
} else {
INVALID_TOKEN
};
let mut r = ParserState {
grammar,
tok_env,
special_token_marker_token: special_marker_token,
trie_lexer_stack: usize::MAX,
rows: vec![],
rows_valid_end: 0,
row_infos: vec![],
captures: Captures::new(),
scratch,
stats: ParserStats::default(),
metrics: ParserMetrics::default(),
trace_stats0: ParserStats::default(),
trace_byte_stack: vec![],
trace_start: Instant::now(),
token_idx: 0,
byte_to_token_idx: vec![],
bytes: vec![],
last_force_bytes_len: usize::MAX,
max_all_items: usize::MAX,
limits,
backtrack_byte_count: 0,
lexer_stack_top_eos: false,
lexer_stack: vec![LexerState {
row_idx: 0,
lexer_state,
byte: None,
}],
trie_grammar_stack: 0,
parser_error: None,
shared_box: Box::new(SharedState {
lexer_opt: Some(lexer),
}),
perf_counters,
};
r.scratch.grammar_stack.push(GrammarStackNode {
back_ptr: GrammarStackPtr::new(0),
token_horizon: u32::MAX,
grammar_id: LexemeClass::ROOT,
start_item: Item::new(RhsPtr::from_index(0), 0),
start_item_idx: 0,
});
// Initialize the Earley table with the predictions in
// row 0.
for rule in r.grammar.rules_of(start) {
r.scratch.add_unique(Item::new(*rule, 0), 0, "init");
}
debug!("initial push");
let _ = r.push_row(0, &Lexeme::bogus());
ensure_internal!(
r.num_rows() == 1 && r.rows.len() == 1,
"initial push failed"
);
assert!(r.lexer_stack.len() == 1);
// Set the correct initial lexer state
if !r.lexer_spec().allow_initial_skip {
// Disallow initial SKIP if asked to.
// This is done, for example, we are trying to force
// the generation of JSON to start.
let skip_id = r.lexer_spec().skip_id(LexemeClass::ROOT);
let mut possible = r
.lexer()
.possible_lexemes(r.rows[0].lexer_start_state)
.clone();
possible.remove(skip_id);
let new_state = r.lexer_mut().start_state(&possible);
r.rows[0].lexer_start_state = new_state;
debug!(
"disallowing initial SKIP; {}",
r.allowed_lexemes_dbg(new_state)
);
}
let state = r.rows[0].lexer_start_state;
r.lexer_stack[0].lexer_state = state;
r.assert_definitive();
let lexer = std::mem::take(&mut r.shared_box).lexer_opt.unwrap();
r.stats.lexer_cost = lexer.dfa.total_fuel_spent();
Ok((r, lexer))
}
#[inline(always)]
fn lexer(&self) -> &Lexer {
self.shared_box.lexer()
}
#[inline(always)]
fn lexer_mut(&mut self) -> &mut Lexer {
self.shared_box.lexer_mut()
}
fn with_items_limit<T>(
&mut self,
limit: usize,
lbl: &str,
f: impl FnOnce(&mut Self) -> T,
) -> T {
self.max_all_items = self.stats.all_items + limit;
let r = f(self);
if self.stats.all_items > self.max_all_items && self.parser_error.is_none() {
self.parser_error = Some(format!(
"Too many items (limit {}; {}); try avoiding single-byte/short lexemes",
limit, lbl
));
}
self.max_all_items = usize::MAX;
r
}
fn compute_bias(&mut self, computer: &dyn BiasComputer, start: &[u8]) -> SimpleVob {
let t0 = Instant::now();
let limits = self.limits.clone();
let dfa = &mut self.lexer_mut().dfa;
dfa.set_fuel(limits.step_lexer_fuel);
dfa.set_max_states(limits.max_lexer_states);
let mut set = self.with_items_limit(limits.step_max_items, "mask", |state| {
let mut r = ParserRecognizer { state };
computer.compute_bias(&mut r, start)
});
self.stats.lexer_cost = self.lexer().dfa.total_fuel_spent();
// The SPECIAL_TOKEN_MARKER should never be allowed by itself
if self.special_token_marker_token != INVALID_TOKEN {
set.disallow_token(self.special_token_marker_token);
}
if start.is_empty() {
self.run_speculative("token_ranges", |state| {
if state.flush_lexer() {
for spec in state.token_range_lexemes() {
for range in &spec.token_ranges {
set.allow_range(range.clone());
}
}
}
});
}
if set.is_zero() {
// nothing allowed
// we're going to be stopped outside - we better flush the lexer
let _ = self.flush_lexer();
}
let eos = computer.trie().eos_token();
if eos != INVALID_TOKEN && start.is_empty() && self.lexer_allows_eos() {
set.allow_token(eos);
}
let d = t0.elapsed();
self.stats.compute_time_us += d.as_micros() as u64;
self.perf_counters.compute_bias.record(d);
set
}
fn after_dots(&self) -> impl Iterator<Item = RhsPtr> + '_ {
self.curr_row()
.item_indices()
.map(|i| self.scratch.items[i].rhs_ptr())
}
fn after_dots_symdata(&self) -> impl Iterator<Item = &CSymbol> + '_ {
self.after_dots().map(|pos| self.grammar.sym_data_dot(pos))
}
fn can_advance_inner(&self) -> bool {
for data in self.after_dots_symdata() {
if data.idx == CSymIdx::NULL {
continue;
}
if data.is_terminal || data.gen_grammar.is_some() {
return true;
}
}
false
}
pub fn can_advance(&self) -> bool {
self.has_pending_lexeme_bytes() || self.can_advance_inner()
}
pub fn has_pending_lexeme_bytes(&self) -> bool {
let row_idx = self.num_rows() - 1;
for back in self.lexer_stack.iter().rev() {
if back.row_idx as usize != row_idx {
break;
}
if back.byte.is_some() {
return true;
}
}
false
}
// Does the parse succeed in this Earley set?
// That is, does this Earley set contain a completed
// start rule?
fn row_is_accepting(&self) -> bool {
for pos in self.after_dots() {
let after_dot = self.grammar.sym_idx_dot(pos);
if after_dot == CSymIdx::NULL {
let lhs = self.grammar.sym_idx_lhs(pos);
if lhs == self.grammar.start() {
return true;
}
}
}
false
}
pub fn lexer_allows_eos(&mut self) -> bool {
if self.has_pending_lexeme_bytes() {
let lexer_state = self.lexer_state().lexer_state;
self.lexer_mut().allows_eos(lexer_state)
} else {
// empty lexemes are not allowed
false
}
}
fn item_to_string(&self, idx: usize) -> String {
self.scratch.item_to_string(idx)
}
fn print_row(&self, row_idx: usize) {
let row = &self.rows[row_idx];
println!(
"row {}; lexer_stack={} top_state={:?}",
row_idx,
self.lexer_stack.len(),
self.lexer_stack.last().unwrap().lexer_state
);
println!(
" allowed: {}",
self.allowed_lexemes_dbg(row.lexer_start_state)
);
if row_idx < self.row_infos.len() {
let info = &self.row_infos[row_idx];
if info.lexeme.is_bogus() {
println!(" lexeme: placeholder");
} else {
println!(" lexeme: {}", self.lexer().dbg_lexeme(&info.lexeme));
}
} else {
println!(" speculative");
}
for i in row.item_indices() {
println!(" {}", self.item_to_string(i));
}
}
#[inline(always)]
fn lexer_state(&self) -> LexerState {
self.lexer_stack[self.lexer_stack.len() - 1]
}
/// Current size of the Earley table -- that is,
/// the number of Earley sets.
#[inline(always)]
pub fn num_rows(&self) -> usize {
// The number of rows is taken, not from the physical Earley table,
// but from the virtual Earley stack kept in the lexer state.
self.lexer_state().row_idx as usize + 1
}
#[inline(always)]
fn pop_lexer_states(&mut self, n: usize) {
self.lexer_stack
.truncate(self.lexer_stack.len().saturating_sub(n));
}
#[allow(dead_code)]
pub fn print_stats(&mut self) {
println!("stats: {:?}", self.stats);
self.stats = ParserStats::default();
}
fn assert_definitive(&self) {
assert!(self.scratch.definitive);
assert!(self.backtrack_byte_count == 0);
if self.num_rows() != self.row_infos.len() {
panic!(
"num_rows={} row_infos={}",
self.num_rows(),
self.row_infos.len()
);
}
}
pub fn get_bytes(&self) -> &[u8] {
&self.bytes
}
fn item_lhs(&self, item: &Item) -> CSymIdx {
self.grammar.sym_idx_lhs(item.rhs_ptr())
}
#[allow(dead_code)]
fn item_sym_data(&self, item: &Item) -> &CSymbol {
self.grammar.sym_data(self.item_lhs(item))
}
fn hidden_start(&self, lexer: &mut Lexer) -> usize {
let lexer_state = self.lexer_state().lexer_state;
let hidden_len = lexer.possible_hidden_len(lexer_state);
if hidden_len == 0 {
return usize::MAX;
}
let last_lexeme_visible_len = self.curr_row_bytes().len() - hidden_len;
let prefix_len = self.row_infos[self.num_rows() - 1].start_byte_idx;
prefix_len + last_lexeme_visible_len
}
pub fn temperature(&self) -> Option<f32> {
let mut temp = -1000.0f32;
for data in self.after_dots_symdata() {
if data.is_terminal {
temp = temp.max(data.props.temperature);
}
}
if temp < 0.00000001 {
None
} else {
Some(temp)
}
}
pub fn rollback(&mut self, n_bytes: usize) -> Result<()> {
debug!("rollback: {} bytes", n_bytes);
ensure!(self.parser_error.is_none(), "rollback: parser error");
self.assert_definitive();
ensure!(
n_bytes <= self.byte_to_token_idx.len(),
"rollback: too many bytes {} > {}",
n_bytes,
self.byte_to_token_idx.len()
);
self.check_lexer_bytes_invariant();
let new_len = self.byte_to_token_idx.len() - n_bytes;
self.byte_to_token_idx.truncate(new_len);
self.bytes.truncate(new_len);
self.lexer_stack.truncate(new_len + 1);
self.row_infos.truncate(self.num_rows());
self.token_idx = *self.byte_to_token_idx.last().unwrap_or(&0) as usize;
self.last_force_bytes_len = usize::MAX;
self.lexer_stack_top_eos = false;
self.rows_valid_end = self.num_rows();
self.assert_definitive();
self.check_lexer_bytes_invariant();
Ok(())