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
//! Base parser implementation
use std::borrow::Borrow;
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use crate::atn::ATN;
use crate::atn_simulator::IATNSimulator;
use crate::error_listener::{ConsoleErrorListener, ErrorListener, ProxyErrorListener};
use crate::error_strategy::ErrorStrategy;
use crate::errors::ANTLRError;
use crate::interval_set::IntervalSet;
use crate::parser_atn_simulator::ParserATNSimulator;
use crate::parser_rule_context::ParserRuleContext;
use crate::recognizer::{Actions, Recognizer};
use crate::rule_context::{states_stack, CustomRuleContext, RuleContext};
use crate::tid::TidAble;
use crate::token::{Token, TOKEN_EOF};
use crate::token_factory::{TokenAware, TokenFactory};
use crate::token_stream::TokenStream;
use crate::tree::{ErrorNode, Listenable, ParseTreeListener, TerminalNode};
use crate::utils::cell_update;
use crate::vocabulary::Vocabulary;
use crate::{CoerceFrom, CoerceTo};
/// parser functionality required for `ParserATNSimulator` to work
#[allow(missing_docs)] // todo rewrite it so downstream crates actually could meaningfully implement it
pub trait Parser<'input>: Recognizer<'input> {
fn get_interpreter(&self) -> &ParserATNSimulator;
fn get_token_factory(&self) -> &'input Self::TF;
fn get_parser_rule_context(&self) -> &Rc<<Self::Node as ParserNodeType<'input>>::Type>;
// fn set_parser_rule_context(&self, v: ParserRuleContext);
fn consume(&mut self, err_handler: &mut impl ErrorStrategy<'input, Self>)
where
Self: Sized;
// fn get_parse_listeners(&self) -> Vec<ParseTreeListener>;
//fn sempred(&mut self, _localctx: Option<&dyn ParserRuleContext>, rule_index: i32, action_index: i32) -> bool { true }
fn precpred(
&self,
localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>,
precedence: i32,
) -> bool;
// fn get_error_handler(&self) -> ErrorStrategy;
// fn set_error_handler(&self, e: ErrorStrategy);
fn get_input_stream_mut(&mut self) -> &mut dyn TokenStream<'input, TF = Self::TF>;
fn get_input_stream(&self) -> &dyn TokenStream<'input, TF = Self::TF>;
fn get_current_token(&self) -> &<Self::TF as TokenFactory<'input>>::Tok;
fn get_expected_tokens(&self) -> IntervalSet;
fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>)
where
Self: Sized;
fn remove_error_listeners(&mut self);
fn notify_error_listeners(
&self,
msg: String,
offending_token: Option<isize>,
err: Option<&ANTLRError>,
);
fn get_error_lister_dispatch<'a>(&'a self) -> Box<dyn ErrorListener<'input, Self> + 'a>
where
Self: Sized;
fn is_expected_token(&self, symbol: i32) -> bool;
fn get_precedence(&self) -> i32;
fn get_state(&self) -> i32;
fn set_state(&mut self, v: i32);
fn get_rule_invocation_stack(&self) -> Vec<String>;
}
// trait CsvContext<'input>: for<'x> Listenable<'input, dyn CsvParseTreeListener<'input,CsvTreeNodeType> + 'x> + ParserRuleContext<'input,TF=CommonTokenFactory,Ctx=CsvTreeNodeType>{}
//
// struct CsvTreeNodeType;
// impl<'a> ParserNodeType<'a> for CsvTreeNodeType{
// type Type = dyn CsvContext<'a>;
// }
// workaround trait for rustc not being able to handle cycles in trait defenition yet, e.g. `trait A: Super<Assoc=dyn A>{}`
// whyyy rustc... whyyy... (╯°□°)╯︵ ┻━┻ It would have been so much cleaner.
/// Workaround trait for rustc current limitations.
///
/// Basically you can consider it as if context trait for generated parser has been implemented as
/// ```text
/// trait GenratedParserContext:ParserRuleContext<Ctx=dyn GeneratedParserContext>{ ... }
/// ```
/// which is not possible, hence this a bit ugly workaround.
///
/// Implemented by generated parser for the type that is going to carry information about
/// parse tree node.
pub trait ParserNodeType<'input>: TidAble<'input> + Sized {
/// Shortcut for `Type::TF`
type TF: TokenFactory<'input> + 'input;
/// Actual type of the parse tree node
type Type: ?Sized + ParserRuleContext<'input, Ctx = Self, TF = Self::TF> + 'input;
// type Visitor: ?Sized + ParseTreeVisitor<'input, Self>;
}
/// ### Main underlying Parser struct
///
/// It is a member of generated parser struct, so
/// almost always you don't need to create it yourself.
/// Generated parser hides complexity of this struct and expose required flexibility via generic parameters
pub struct BaseParser<
'input,
Ext, //: 'static, //: ParserRecog<'input, Self> + 'static, // user provided behavior, such as semantic predicates
I: TokenStream<'input>, // input stream
Ctx: ParserNodeType<'input, TF = I::TF>, // Ctx::Type is trait object type for tree node of the parser
T: ParseTreeListener<'input, Ctx> + ?Sized = dyn ParseTreeListener<'input, Ctx>,
> {
interp: Rc<ParserATNSimulator>,
/// Rule context parser is currently processing
pub ctx: Option<Rc<Ctx::Type>>,
/// Track the {@link ParserRuleContext} objects during the parse and hook
/// them up using the {@link ParserRuleContext#children} list so that it
/// forms a parse tree. The {@link ParserRuleContext} returned from the start
/// rule represents the root of the parse tree.
///
/// <p>Note that if we are not building parse trees, rule contexts only point
/// upwards. When a rule exits, it returns the context bute that gets garbage
/// collected if nobody holds a reference. It points upwards but nobody
/// points at it. </p>
///
/// <p>When we build parse trees, we are adding all of these contexts to
/// {@link ParserRuleContext#children} list. Contexts are then not candidates
/// for garbage collection.</p>
///
/// Returns {@code true} if a complete parse tree will be constructed while
/// parsing, otherwise {@code false}
pub build_parse_trees: bool,
/// true if parser reached EOF
pub matched_eof: bool,
state: i32,
/// Token stream that is currently used by this parser
pub input: I,
precedence_stack: Vec<i32>,
/// Listeners paired with the id handed out by [`BaseParser::add_parse_listener`].
/// The id, not the listener's address, is what [`ListenerId`] refers to.
parse_listeners: Vec<(usize, Box<T>)>,
_syntax_errors: Cell<i32>,
error_listeners: RefCell<Vec<Box<dyn ErrorListener<'input, Self>>>>,
ext: Ext,
pd: PhantomData<fn() -> &'input str>,
}
crate::tid! {
impl<'input, Ext, I, Ctx, T> TidAble<'input> for BaseParser<'input,Ext, I, Ctx, T>
where I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized
}
impl<'input, Ext, I, Ctx, T> Deref for BaseParser<'input, Ext, I, Ctx, T>
where
Ext: ParserRecog<'input, Self>,
I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized,
// Ctx::Type: Listenable<T>,
{
type Target = Ext;
fn deref(&self) -> &Self::Target {
&self.ext
}
}
impl<'input, Ext, I, Ctx, T> DerefMut for BaseParser<'input, Ext, I, Ctx, T>
where
Ext: ParserRecog<'input, Self>,
I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized,
// Ctx::Type: Listenable<T>,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.ext
}
}
///
pub trait ParserRecog<'a, P: Recognizer<'a>>: Actions<'a, P> {}
impl<'input, Ext, I, Ctx, T> Recognizer<'input> for BaseParser<'input, Ext, I, Ctx, T>
where
Ext: ParserRecog<'input, Self>,
I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized,
// Ctx::Type: Listenable<T>,
{
type Node = Ctx;
fn sempred(
&mut self,
localctx: Option<&Ctx::Type>,
rule_index: i32,
action_index: i32,
) -> bool {
<Ext as Actions<'input, Self>>::sempred(localctx, rule_index, action_index, self)
}
fn get_rule_names(&self) -> &[&str] {
self.ext.get_rule_names()
}
fn get_vocabulary(&self) -> &dyn Vocabulary {
self.ext.get_vocabulary()
}
fn get_grammar_file_name(&self) -> &str {
self.ext.get_grammar_file_name()
}
fn get_atn(&self) -> &ATN {
self.interp.atn()
}
}
impl<'input, Ext, I, Ctx, T> TokenAware<'input> for BaseParser<'input, Ext, I, Ctx, T>
where
Ext: ParserRecog<'input, Self>,
I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized,
// Ctx::Type: Listenable<T>,
{
type TF = I::TF;
}
impl<'input, Ext, I, Ctx, T> Parser<'input> for BaseParser<'input, Ext, I, Ctx, T>
where
Ext: ParserRecog<'input, Self>,
I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized,
Ctx::Type:
Listenable<T> + CoerceFrom<TerminalNode<'input, Ctx>> + CoerceFrom<ErrorNode<'input, Ctx>>,
// TerminalNode<'input, Ctx>: CoerceTo<Ctx::Type>,
// ErrorNode<'input, Ctx>: CoerceTo<Ctx::Type>,
{
fn get_interpreter(&self) -> &ParserATNSimulator {
self.interp.as_ref()
}
fn get_token_factory(&self) -> &'input Self::TF {
// &**crate::common_token_factory::COMMON_TOKEN_FACTORY_DEFAULT
self.input.get_token_source().get_token_factory()
}
#[inline(always)]
fn get_parser_rule_context(&self) -> &Rc<Ctx::Type> {
self.ctx.as_ref().unwrap()
}
fn consume(&mut self, err_handler: &mut impl ErrorStrategy<'input, Self>) {
let o = self.get_current_token().clone();
if o.borrow().get_token_type() != TOKEN_EOF {
self.input.consume();
}
if self.build_parse_trees || !self.parse_listeners.is_empty() {
if err_handler.in_error_recovery_mode(self) {
// todo report ructc inference issue
let node: Rc<ErrorNode<'_, Ctx>> = self.create_error_node(o.clone());
self.ctx
.as_deref()
.unwrap()
.add_child(node.clone().coerce_rc_to());
for (_, listener) in &mut self.parse_listeners {
listener.visit_error_node(&*node)
}
} else {
let node: Rc<TerminalNode<'_, Ctx>> = self.create_token_node(o.clone());
self.ctx
.as_deref()
.unwrap()
.add_child(node.clone().coerce_rc_to());
for (_, listener) in &mut self.parse_listeners {
listener.visit_terminal(&*node)
}
}
}
}
fn precpred(&self, _localctx: Option<&Ctx::Type>, precedence: i32) -> bool {
// localctx.map(|it|println!("check at{}",it.to_string_tree(self)));
// println!("{}",self.get_precedence());
precedence >= self.get_precedence()
}
fn get_input_stream_mut(&mut self) -> &mut dyn TokenStream<'input, TF = Self::TF> {
&mut self.input //.as_mut()
}
fn get_input_stream(&self) -> &dyn TokenStream<'input, TF = Self::TF> {
&self.input
}
#[inline]
fn get_current_token(&self) -> &<Self::TF as TokenFactory<'input>>::Tok {
self.input.get(self.input.index())
}
fn get_expected_tokens(&self) -> IntervalSet {
let states_stack = states_stack(self.ctx.as_ref().unwrap().clone());
self.interp
.atn()
.get_expected_tokens(self.state, states_stack)
}
fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>) {
self.error_listeners.borrow_mut().push(listener)
}
fn remove_error_listeners(&mut self) {
self.error_listeners.borrow_mut().clear();
}
fn notify_error_listeners(
&self,
msg: String,
offending_token: Option<isize>,
err: Option<&ANTLRError>,
) {
cell_update(&self._syntax_errors, |it| it + 1);
let offending_token: Option<&_> = match offending_token {
None => Some(self.get_current_token().borrow()),
Some(x) => Some(self.input.get(x).borrow()),
};
let line = offending_token.map(|x| x.get_line()).unwrap_or(-1);
let column = offending_token.map(|x| x.get_column()).unwrap_or(-1);
for listener in self.error_listeners.borrow().iter() {
listener.syntax_error(self, offending_token, line, column, &msg, err)
}
}
fn get_error_lister_dispatch<'a>(&'a self) -> Box<dyn ErrorListener<'input, Self> + 'a> {
Box::new(ProxyErrorListener {
delegates: self.error_listeners.borrow(),
})
}
fn is_expected_token(&self, _symbol: i32) -> bool {
unimplemented!()
}
fn get_precedence(&self) -> i32 {
*self.precedence_stack.last().unwrap_or(&-1)
}
#[inline(always)]
fn get_state(&self) -> i32 {
self.state
}
#[inline(always)]
fn set_state(&mut self, v: i32) {
self.state = v;
}
fn get_rule_invocation_stack(&self) -> Vec<String> {
let mut vec = Vec::new();
let rule_names = self.get_rule_names();
let mut ctx = self.get_parser_rule_context().clone();
loop {
let rule_index = ctx.get_rule_index();
vec.push(rule_names.get(rule_index).unwrap_or(&"n/a").to_string());
ctx = if let Some(parent) = ctx.get_parent_ctx() {
parent
} else {
break;
}
}
vec
}
// fn get_rule_invocation_stack(&self, c: _) -> Vec<String> {
// unimplemented!()
// }
}
#[allow(missing_docs)] // todo docs
impl<'input, Ext, I, Ctx, T> BaseParser<'input, Ext, I, Ctx, T>
where
Ext: ParserRecog<'input, Self>,
I: TokenStream<'input>,
Ctx: ParserNodeType<'input, TF = I::TF>,
T: ParseTreeListener<'input, Ctx> + ?Sized,
Ctx::Type:
Listenable<T> + CoerceFrom<TerminalNode<'input, Ctx>> + CoerceFrom<ErrorNode<'input, Ctx>>,
// TerminalNode<'input, Ctx>: CoerceTo<Ctx::Type>,
// ErrorNode<'input, Ctx>: CoerceTo<Ctx::Type>,
{
pub fn new_base_parser(input: I, interpreter: Rc<ParserATNSimulator>, ext: Ext) -> Self {
Self {
interp: interpreter,
ctx: None,
build_parse_trees: true,
matched_eof: false,
state: -1,
input,
precedence_stack: vec![0],
parse_listeners: vec![],
_syntax_errors: Cell::new(0),
error_listeners: RefCell::new(vec![Box::new(ConsoleErrorListener {})]),
ext,
pd: PhantomData,
}
}
//
// fn reset(&self) { unimplemented!() }
#[inline]
pub fn match_token(
&mut self,
ttype: i32,
err_handler: &mut impl ErrorStrategy<'input, Self>,
) -> Result<<I::TF as TokenFactory<'input>>::Tok, ANTLRError> {
let mut token = self.get_current_token().clone();
if token.borrow().get_token_type() == ttype {
if ttype == TOKEN_EOF {
self.matched_eof = true;
}
err_handler.report_match(self);
self.consume(err_handler);
} else {
token = err_handler.recover_inline(self)?;
if self.build_parse_trees && token.borrow().get_token_index() == -1 {
self.ctx
.as_ref()
.unwrap()
.add_child(self.create_error_node(token.clone()).coerce_rc_to());
}
}
Ok(token)
}
#[inline]
pub fn match_wildcard(
&mut self,
err_handler: &mut impl ErrorStrategy<'input, Self>,
) -> Result<<I::TF as TokenFactory<'input>>::Tok, ANTLRError> {
let mut t = self.get_current_token().clone();
if t.borrow().get_token_type() > 0 {
err_handler.report_match(self);
self.consume(err_handler);
} else {
t = err_handler.recover_inline(self)?;
if self.build_parse_trees && t.borrow().get_token_index() == -1 {
self.ctx
.as_ref()
.unwrap()
.add_child(self.create_error_node(t.clone()).coerce_rc_to());
}
}
Ok(t)
}
/// Adds parse listener for this parser
/// returns `listener_id` that can be used later to get listener back
///
/// Embedded listener currently must outlive `'input`. If you need to have arbitrary listener use ParseTreeWalker.
///
/// # Panics
///
/// Panics if `usize::MAX` listeners have already been added in this process, since
/// listener ids are never reused.
///
/// ### Example for listener usage:
/// todo
pub fn add_parse_listener<L>(&mut self, listener: Box<L>) -> ListenerId<L>
where
L: CoerceTo<T>,
{
let id = ListenerId::next();
// `remove_parse_listener` turns this box back into a `Box<L>`. That is sound only
// because the `CoerceTo` contract makes `coerce_box_to` return the caller's box itself.
self.parse_listeners
.push((id.actual_id, listener.coerce_box_to()));
id
}
/// Removes parse listener with corresponding `listener_id`, casts it back to user type and returns it to the caller.
/// `listener_id` is returned when listener is added via `add_parse_listener`
pub fn remove_parse_listener<L>(&mut self, listener_id: ListenerId<L>) -> Box<L>
where
L: CoerceTo<T>,
{
let index = self
.parse_listeners
.iter()
.position(|(id, _)| *id == listener_id.actual_id)
.expect("listener not found");
let (_, listener) = self.parse_listeners.remove(index);
// SAFETY: `into_listener` requires `listener` to own the value passed to the
// `add_parse_listener` call that returned `listener_id`.
// - Ids come from a process-global counter that panics rather than wrapping (see
// `mint_listener_id`), so they are never reused: a match on `actual_id` identifies
// exactly that call, and `listener` is the box it stored. A listener dropped by
// `remove_parse_listeners` leaves no matching id behind, so the search above finds
// nothing and panics rather than reaching this point. Ids are also unique across
// parser instances, so an id from another parser cannot match either.
// - That call stored `coerce_box_to()` of the caller's `Box<L>`, which the `CoerceTo`
// contract (an `unsafe trait`) requires to be the same box holding the same value,
// only unsized. So `listener` owns the value that was passed in.
// - If this `L` differs from the type that call was handed, it is a supertype reached
// through `ListenerId`'s covariance, and the result is what coercing the original
// `Box` to `Box<L>` would give.
unsafe { listener_id.into_listener(listener) }
}
/// Removes all added parse listeners without returning them
pub fn remove_parse_listeners(&mut self) {
self.parse_listeners.clear()
}
pub fn trigger_enter_rule_event(&mut self) -> Result<(), ANTLRError> {
let ctx = self.ctx.as_deref().unwrap();
for (_, listener) in self.parse_listeners.iter_mut() {
// listener.enter_every_rule(ctx);
ctx.enter(listener)?;
}
Ok(())
}
pub fn trigger_exit_rule_event(&mut self) -> Result<(), ANTLRError> {
let ctx = self.ctx.as_deref().unwrap();
for (_, listener) in self.parse_listeners.iter_mut().rev() {
ctx.exit(listener)?;
// listener.exit_every_rule(ctx);
}
Ok(())
}
//
// fn set_token_factory(&self, factory: TokenFactory) { unimplemented!() }
//
//
// fn get_atn_with_bypass_alts(&self) { unimplemented!() }
//
// fn compile_parse_tree_pattern(&self, pattern, patternRuleIndex: Lexer, lexer: Lexer) { unimplemented!() }
//
// fn set_input_stream(&self, input: TokenStream) { unimplemented!() }
//
// fn set_token_stream(&self, input: TokenStream) { unimplemented!() }
fn add_context_to_parse_tree(&mut self) {
let parent = self.ctx.as_ref().unwrap().get_parent_ctx();
if let Some(parent) = parent {
parent.add_child(self.ctx.clone().unwrap())
}
}
#[inline]
pub fn enter_rule(&mut self, localctx: Rc<Ctx::Type>, state: i32, _rule_index: usize) {
self.set_state(state);
localctx.set_start(self.input.lt(1).cloned());
self.ctx = Some(localctx);
// let mut localctx = Rc::get_mut(self.ctx.as_mut().unwrap()).unwrap();
if self.build_parse_trees {
self.add_context_to_parse_tree()
}
}
#[inline]
pub fn exit_rule(&mut self) -> Result<(), ANTLRError> {
if self.matched_eof {
self.ctx
.as_ref()
.unwrap()
.set_stop(self.input.lt(1).cloned())
} else {
self.ctx
.as_ref()
.unwrap()
.set_stop(self.input.lt(-1).cloned())
}
self.trigger_exit_rule_event()?;
self.set_state(self.get_parser_rule_context().get_invoking_state());
let parent = self.ctx.as_ref().unwrap().get_parent_ctx();
// mem::replace(&mut self.ctx, parent);
self.ctx = parent;
Ok(())
}
// todo make new_ctx not option
#[inline]
pub fn enter_outer_alt(
&mut self,
new_ctx: Option<Rc<Ctx::Type>>,
alt_num: i32,
) -> Result<(), ANTLRError> {
if let Some(new_ctx) = new_ctx {
new_ctx.set_alt_number(alt_num);
let ctx = self.ctx.as_ref().unwrap();
if self.build_parse_trees && self.ctx.is_some() && !Rc::ptr_eq(&new_ctx, ctx) {
if let Some(parent) = ctx.get_parent_ctx() {
parent.remove_last_child();
parent.add_child(new_ctx.clone())
}
}
self.ctx = Some(new_ctx);
}
self.trigger_enter_rule_event()
}
pub fn enter_recursion_rule(
&mut self,
localctx: Rc<Ctx::Type>,
state: i32,
_rule_index: usize,
precedence: i32,
) {
self.set_state(state);
self.precedence_stack.push(precedence);
localctx.set_start(self.input.lt(1).cloned());
//println!("{}",self.input.lt(1).map(Token::to_owned).unwrap());
self.ctx = Some(localctx);
}
pub fn push_new_recursion_context(
&mut self,
localctx: Rc<Ctx::Type>,
state: i32,
_rule_index: usize,
) -> Result<(), ANTLRError> {
let prev = self.ctx.take().unwrap();
prev.set_parent(&Some(localctx.clone()));
prev.set_invoking_state(state);
prev.set_stop(self.input.lt(-1).cloned());
// println!("{}",prev.get_start().unwrap());
localctx.set_start(Some(prev.start_mut().clone()));
self.ctx = Some(localctx);
if self.build_parse_trees {
self.ctx.as_ref().unwrap().add_child(prev);
}
self.trigger_enter_rule_event()
}
pub fn unroll_recursion_context(
&mut self,
parent_ctx: Option<Rc<Ctx::Type>>,
) -> Result<(), ANTLRError> {
self.precedence_stack.pop();
let retctx = self.ctx.clone().unwrap();
retctx.set_stop(self.input.lt(-1).cloned());
if !self.parse_listeners.is_empty() {
while self.ctx.as_ref().map(Rc::as_ptr) != parent_ctx.as_ref().map(Rc::as_ptr) {
self.trigger_exit_rule_event()?;
self.ctx = self.ctx.as_ref().unwrap().get_parent_ctx()
}
} else {
self.ctx = parent_ctx;
}
//self.ctx is now parent
retctx.set_parent(&self.ctx);
// println!("{:?}",self.ctx.as_ref().map(|it|it.to_string_tree(self)));
if self.build_parse_trees && self.ctx.is_some() {
self.ctx.as_ref().unwrap().add_child(retctx);
}
Ok(())
}
fn create_token_node(
&self,
token: <I::TF as TokenFactory<'input>>::Tok,
) -> Rc<TerminalNode<'input, Ctx>> {
TerminalNode::new(token).into()
}
fn create_error_node(
&self,
token: <I::TF as TokenFactory<'input>>::Tok,
) -> Rc<ErrorNode<'input, Ctx>> {
ErrorNode::new(token).into()
}
/// Text representation of generated DFA for debugging purposes
pub fn dump_dfa(&self) {
let mut seen_one = false;
for dfa in self.interp.decision_to_dfa() {
let dfa = dfa.read();
// because s0 is saved in dfa for Rust version
if dfa.states.len() > 1 + (dfa.is_precedence_dfa() as usize) {
if seen_one {
println!()
}
println!("Decision {}:", dfa.decision);
print!("{}", dfa.to_string(self.get_vocabulary()));
seen_one = true;
}
}
}
// fn get_invoking_context(&self, ruleIndex: i32) -> ParserRuleContext { unimplemented!() }
//
// fn in_context(&self, context: ParserRuleContext) -> bool { unimplemented!() }
//
// fn get_expected_tokens_within_current_rule(&self) -> * IntervalSet { unimplemented!() }
//
//
// fn get_rule_index(&self, ruleName: String) -> int { unimplemented!() }
//
// fn get_dfaStrings(&self) -> String { unimplemented!() }
//
// fn get_source_name(&self) -> String { unimplemented!() }
//
// fn set_trace(&self, trace: * TraceListener) { unimplemented!() }
}
/// Source of [`ListenerId::actual_id`].
///
/// Deliberately process-global rather than per parser. Ids must be unique across parser
/// instances as well as over time: a `ListenerId` from one parser can be passed to
/// `remove_parse_listener` on another parser of the same grammar and it type checks, so a
/// per-parser counter would let two parsers both hand out id `0` and one would resurrect the
/// other's listener at the wrong type.
static NEXT_LISTENER_ID: AtomicUsize = AtomicUsize::new(0);
/// Takes the current value of `counter` and advances it by one, panicking instead of wrapping.
///
/// A plain `fetch_add` wraps around on overflow, which on a 32-bit target would hand out id `0`
/// again after 2^32 listeners. The increment is checked instead: once the counter reaches
/// `usize::MAX` it stays there and every further call panics, so no value is returned twice.
///
/// `Relaxed` is enough: each successful `compare_exchange_weak` is an atomic read-modify-write
/// that moves the counter from `n` to `n + 1`, so no two callers can both succeed from the same
/// `n`, whatever the ordering, and no other memory is being synchronised through it.
///
/// # Panics
///
/// Panics if `counter` is already at `usize::MAX`.
fn mint_listener_id(counter: &AtomicUsize) -> usize {
// Open-coded `fetch_update`, which is deprecated from Rust 1.99; its replacement,
// `try_update`, needs 1.95, above this crate's `rust-version`.
let mut current = counter.load(Ordering::Relaxed);
loop {
let next = current.checked_add(1).expect("listener ids exhausted");
match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
Ok(id) => return id,
Err(actual) => current = actual,
}
}
}
/// Allows to safely cast listener back to user type
#[derive(Debug)]
pub struct ListenerId<T: ?Sized> {
pub(crate) actual_id: usize,
phantom: PhantomData<fn() -> T>,
}
impl<T: ?Sized> ListenerId<T> {
/// Mints an id that has never been used before and never will be again.
///
/// This is the whole basis of [`ListenerId::into_listener`]'s soundness, so the counter
/// must only ever move forwards, and must not wrap: see [`mint_listener_id`].
///
/// # Panics
///
/// Panics if listener ids are exhausted.
fn next() -> ListenerId<T> {
ListenerId {
actual_id: mint_listener_id(&NEXT_LISTENER_ID),
phantom: PhantomData,
}
}
}
impl<T> ListenerId<T> {
/// # Safety
///
/// `boxed` must own the value that was passed to the [`BaseParser::add_parse_listener`]
/// call which returned this `ListenerId`, so that its pointee really is a `T`.
///
/// Matching `actual_id` establishes that `boxed` is the box that call stored, because ids
/// come from [`NEXT_LISTENER_ID`] and are never reused: an id identifies one
/// `add_parse_listener` call for the lifetime of the process, and that call fixes the type.
/// It would *not* be enough if `actual_id` were the listener's address, since an address is
/// only unique among values alive at the same time and could be reused after a drop.
///
/// That the stored box owns the value passed in, rather than some other value, is not
/// something a matching id can show. It holds because `add_parse_listener` stores
/// `coerce_box_to()` of the caller's box, and [`CoerceTo`] is an `unsafe trait` whose
/// implementations must return their argument's allocation, only unsized.
unsafe fn into_listener<U: ?Sized>(self, boxed: Box<U>) -> Box<T> {
Box::from_raw(Box::into_raw(boxed) as *mut T)
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicUsize;
use super::mint_listener_id;
#[test]
#[should_panic(expected = "listener ids exhausted")]
fn listener_ids_panic_instead_of_wrapping() {
let counter = AtomicUsize::new(usize::MAX - 2);
assert_eq!(mint_listener_id(&counter), usize::MAX - 2);
assert_eq!(mint_listener_id(&counter), usize::MAX - 1);
// The counter is now at `usize::MAX`. Wrapping would return it and then `0` again.
mint_listener_id(&counter);
}
}