1use std::any::{type_name, Any};
3use std::borrow::{Borrow, BorrowMut};
4use std::cell::{Ref, RefCell, RefMut};
5use std::fmt::{Debug, Error, Formatter};
6use std::ops::{Deref, DerefMut};
7use std::rc::Rc;
8
9use better_any::{Tid, TidAble, TidExt};
10
11use crate::errors::ANTLRError;
12use crate::interval_set::Interval;
13use crate::parser::ParserNodeType;
14use crate::rule_context::{BaseRuleContext, CustomRuleContext, RuleContext};
15use crate::token::Token;
16use crate::token_factory::TokenFactory;
17use crate::tree::{ParseTree, ParseTreeVisitor, TerminalNode, Tree, VisitableDyn};
18use crate::CoerceTo;
19
20#[allow(missing_docs)]
25pub trait ParserRuleContext<'input>:
26 ParseTree<'input> + RuleContext<'input> + Debug + Tid<'input>
27{
28 fn set_exception(&self, _e: ANTLRError) {}
29
30 fn set_start(&self, _t: Option<<Self::TF as TokenFactory<'input>>::Tok>) {}
31
32 fn start<'a>(&'a self) -> Ref<'a, <Self::TF as TokenFactory<'input>>::Inner>
37 where
38 'input: 'a,
39 {
40 unimplemented!()
41 }
42 fn start_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
43 where
44 'input: 'a,
45 {
46 unimplemented!()
47 }
48
49 fn set_stop(&self, _t: Option<<Self::TF as TokenFactory<'input>>::Tok>) {}
50 fn stop<'a>(&'a self) -> Ref<'a, <Self::TF as TokenFactory<'input>>::Inner>
56 where
57 'input: 'a,
58 {
59 unimplemented!()
60 }
61 fn stop_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
62 where
63 'input: 'a,
64 {
65 unimplemented!()
66 }
67
68 fn add_child(&self, _child: Rc<<Self::Ctx as ParserNodeType<'input>>::Type>) {}
72 fn remove_last_child(&self) {}
73
74 fn child_of_type<T>(&self, pos: usize) -> Option<Rc<T>>
78 where
79 T: ParserRuleContext<'input, TF = Self::TF, Ctx = Self::Ctx> + 'input,
80 Self: Sized,
81 {
82 self.get_children()
83 .filter(|it| it.deref().self_id() == T::id())
84 .nth(pos)
85 .and_then(|it| it.downcast_rc().ok())
86 }
87
88 fn children_of_type<T>(&self) -> Vec<Rc<T>>
90 where
91 T: ParserRuleContext<'input, TF = Self::TF, Ctx = Self::Ctx> + 'input,
92 Self: Sized,
93 {
94 self.get_children()
95 .filter_map(|it| it.downcast_rc().ok())
97 .collect()
98 }
99
100 fn get_token(&self, ttype: isize, pos: usize) -> Option<Rc<TerminalNode<'input, Self::Ctx>>> {
101 self.get_children()
102 .filter_map(|it| it.downcast_rc::<TerminalNode<'input, Self::Ctx>>().ok())
104 .filter(|it| it.symbol.borrow().get_token_type() == ttype)
105 .nth(pos)
106 }
107
108 fn get_tokens(&self, ttype: isize) -> Vec<Rc<TerminalNode<'input, Self::Ctx>>> {
109 self.get_children()
110 .filter_map(|it| it.downcast_rc::<TerminalNode<'input, Self::Ctx>>().ok())
112 .filter(|it| it.symbol.borrow().get_token_type() == ttype)
115 .collect()
116 }
117
118 }
120
121pub trait RuleContextExt<'input>: ParserRuleContext<'input> {
124 fn to_string<Z>(self: &Rc<Self>, rule_names: Option<&[&str]>, stop: Option<Rc<Z>>) -> String
126 where
127 Z: ParserRuleContext<'input, Ctx = Self::Ctx, TF = Self::TF> + ?Sized + 'input,
128 Self::Ctx: ParserNodeType<'input, Type = Z>,
129 Self: CoerceTo<Z>;
130}
131
132impl<'input, T: ParserRuleContext<'input> + ?Sized + 'input> RuleContextExt<'input> for T {
133 fn to_string<Z>(self: &Rc<Self>, rule_names: Option<&[&str]>, stop: Option<Rc<Z>>) -> String
134 where
135 Z: ParserRuleContext<'input, Ctx = T::Ctx, TF = T::TF> + ?Sized + 'input,
136 T::Ctx: ParserNodeType<'input, Type = Z>,
137 T: CoerceTo<Z>,
138 {
139 let mut result = String::from("[");
140 let mut next: Option<Rc<Z>> = Some(self.clone().coerce_rc_to());
141 while let Some(ref p) = next {
142 if stop.is_some() && (stop.is_none() || Rc::ptr_eq(p, stop.as_ref().unwrap())) {
143 break;
144 }
145
146 if let Some(rule_names) = rule_names {
147 let rule_index = p.get_rule_index();
148 let rule_name = rule_names
149 .get(rule_index)
150 .map(|&it| it.to_owned())
151 .unwrap_or_else(|| rule_index.to_string());
152 result.extend(rule_name.chars());
153 result.push(' ');
154 } else {
155 if !p.is_empty() {
156 result.extend(p.get_invoking_state().to_string().chars());
157 result.push(' ');
158 }
159 }
160
161 next = p.get_parent().clone();
162 }
163
164 if result.chars().last() == Some(' ') {
165 result.pop();
166 }
167
168 result.push(']');
169 return result;
170 }
171}
172
173#[inline]
174#[doc(hidden)]
175pub fn cast<'a, T, Result>(ctx: &T) -> &Result
176where
177 T: ParserRuleContext<'a> + 'a + ?Sized,
178 Result: ParserRuleContext<'a, Ctx = T::Ctx> + 'a,
179{
180 ctx.downcast_ref().unwrap()
181 }
183
184#[inline]
187#[doc(hidden)]
188pub fn cast_mut<'a, T: ParserRuleContext<'a> + 'a + ?Sized, Result: 'a>(
191 ctx: &mut Rc<T>,
192) -> &mut Result {
193 unsafe {
198 let ptr = Rc::as_ptr(ctx) as *mut T as *mut Result;
199
200 &mut *ptr
201 }
202}
203
204pub struct BaseParserRuleContext<'input, Ctx: CustomRuleContext<'input>> {
222 base: BaseRuleContext<'input, Ctx>,
223
224 start: RefCell<<Ctx::TF as TokenFactory<'input>>::Tok>,
225 stop: RefCell<<Ctx::TF as TokenFactory<'input>>::Tok>,
226 pub exception: Option<Box<ANTLRError>>,
228 pub(crate) children: RefCell<Vec<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>>>,
230}
231
232better_any::tid! { impl<'i,Ctx> TidAble<'i> for BaseParserRuleContext<'i,Ctx> where Ctx:CustomRuleContext<'i> }
233
234impl<'input, Ctx: CustomRuleContext<'input>> Debug for BaseParserRuleContext<'input, Ctx> {
235 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
236 f.write_str(type_name::<Self>())
237 }
238}
239
240impl<'input, Ctx: CustomRuleContext<'input>> RuleContext<'input>
241 for BaseParserRuleContext<'input, Ctx>
242{
243 fn get_invoking_state(&self) -> isize {
244 self.base.get_invoking_state()
245 }
246
247 fn set_invoking_state(&self, t: isize) {
248 self.base.set_invoking_state(t)
249 }
250
251 fn get_parent_ctx(&self) -> Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>> {
252 self.base.get_parent_ctx()
253 }
254
255 fn set_parent(&self, parent: &Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>>) {
256 self.base.set_parent(parent)
257 }
258}
259
260impl<'input, Ctx: CustomRuleContext<'input>> CustomRuleContext<'input>
261 for BaseParserRuleContext<'input, Ctx>
262{
263 type TF = Ctx::TF;
264 type Ctx = Ctx::Ctx;
265
266 fn get_rule_index(&self) -> usize {
267 self.base.ext.get_rule_index()
268 }
269}
270
271impl<'input, Ctx: CustomRuleContext<'input>> Deref for BaseParserRuleContext<'input, Ctx> {
283 type Target = Ctx;
284
285 fn deref(&self) -> &Self::Target {
286 &self.base.ext
287 }
288}
289
290impl<'input, Ctx: CustomRuleContext<'input>> DerefMut for BaseParserRuleContext<'input, Ctx> {
291 fn deref_mut(&mut self) -> &mut Self::Target {
292 &mut self.base.ext
293 }
294}
295
296impl<'input, Ctx: CustomRuleContext<'input>> Borrow<Ctx> for BaseParserRuleContext<'input, Ctx> {
297 fn borrow(&self) -> &Ctx {
298 &self.base.ext
299 }
300}
301
302impl<'input, Ctx: CustomRuleContext<'input>> BorrowMut<Ctx> for BaseParserRuleContext<'input, Ctx> {
303 fn borrow_mut(&mut self) -> &mut Ctx {
304 &mut self.base.ext
305 }
306}
307
308impl<'input, Ctx: CustomRuleContext<'input> + TidAble<'input>> ParserRuleContext<'input>
309 for BaseParserRuleContext<'input, Ctx>
310{
311 fn set_exception(&self, _e: ANTLRError) { }
313
314 fn set_start(&self, t: Option<<Ctx::TF as TokenFactory<'input>>::Tok>) {
315 *self.start.borrow_mut() = t.unwrap_or(Ctx::TF::create_invalid().clone());
316 }
317
318 fn start<'a>(&'a self) -> Ref<'a, <Ctx::TF as TokenFactory<'input>>::Inner>
319 where
320 'input: 'a,
321 {
322 Ref::map(self.start.borrow(), |t| t.borrow())
323 }
324
325 fn start_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
326 where
327 'input: 'a,
328 {
329 self.start.borrow_mut()
330 }
331
332 fn set_stop(&self, t: Option<<Ctx::TF as TokenFactory<'input>>::Tok>) {
333 *self.stop.borrow_mut() = t.unwrap_or(Ctx::TF::create_invalid().clone());
334 }
335
336 fn stop<'a>(&'a self) -> Ref<'a, <Ctx::TF as TokenFactory<'input>>::Inner>
337 where
338 'input: 'a,
339 {
340 Ref::map(self.stop.borrow(), |t| t.borrow())
341 }
342
343 fn stop_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
344 where
345 'input: 'a,
346 {
347 self.stop.borrow_mut()
348 }
349
350 fn add_child(&self, child: Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>) {
366 self.children.borrow_mut().push(child);
367 }
368
369 fn remove_last_child(&self) {
370 self.children.borrow_mut().pop();
371 }
372
373 }
385
386impl<'input, Ctx: CustomRuleContext<'input>> Tree<'input> for BaseParserRuleContext<'input, Ctx> {
387 fn get_parent(&self) -> Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>> {
388 self.get_parent_ctx()
389 }
390
391 fn has_parent(&self) -> bool {
392 self.base.parent_ctx.borrow().is_some()
393 }
394
395 fn get_payload(&self) -> Box<dyn Any> {
396 unimplemented!()
397 }
398
399 fn get_child(&self, i: usize) -> Option<Rc<<Self::Ctx as ParserNodeType<'input>>::Type>> {
400 self.children.borrow().get(i).cloned()
401 }
402
403 fn get_child_count(&self) -> usize {
404 self.children.borrow().len()
405 }
406
407 }
417
418impl<'input, Ctx: CustomRuleContext<'input> + TidAble<'input>> ParseTree<'input>
419 for BaseParserRuleContext<'input, Ctx>
420{
421 fn get_source_interval(&self) -> Interval {
422 Interval {
423 a: self.start().get_token_index(),
424 b: self.stop().get_token_index(),
425 }
426 }
427
428 fn get_text(&self) -> String {
429 let children = self.get_children();
430 let mut result = String::new();
431
432 for child in children {
433 result += &child.get_text()
434 }
435
436 result
437 }
438}
439#[allow(missing_docs)]
440impl<'input, Ctx: CustomRuleContext<'input> + 'input> BaseParserRuleContext<'input, Ctx> {
441 pub fn new_parser_ctx(
442 parent_ctx: Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>>,
443 invoking_state: isize,
444 ext: Ctx,
445 ) -> Self {
446 Self {
447 base: BaseRuleContext::new_parser_ctx(parent_ctx, invoking_state, ext),
448 start: RefCell::new(Ctx::TF::create_invalid()),
449 stop: RefCell::new(Ctx::TF::create_invalid()),
450 exception: None,
451 children: RefCell::new(vec![]),
452 }
453 }
454 pub fn copy_from<T: ParserRuleContext<'input, TF = Ctx::TF, Ctx = Ctx::Ctx> + ?Sized>(
455 ctx: &T,
456 ext: Ctx,
457 ) -> Self {
458 Self {
459 base: BaseRuleContext::new_parser_ctx(
460 ctx.get_parent_ctx(),
461 ctx.get_invoking_state(),
462 ext,
463 ),
464 start: RefCell::new(ctx.start_mut().clone()),
465 stop: RefCell::new(ctx.stop_mut().clone()),
466 exception: None,
467 children: RefCell::new(ctx.get_children().collect()),
468 }
469 }
470
471 }
475
476#[doc(hidden)]
483pub trait DerefSeal: Deref {}
484
485impl<'input, T, I> ParserRuleContext<'input> for T
486where
487 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
488 I: ParserRuleContext<'input> + 'input + ?Sized,
489{
490 fn set_exception(&self, e: ANTLRError) {
491 self.deref().set_exception(e)
492 }
493
494 fn set_start(&self, t: Option<<Self::TF as TokenFactory<'input>>::Tok>) {
495 self.deref().set_start(t)
496 }
497
498 fn start<'a>(&'a self) -> Ref<'a, <Self::TF as TokenFactory<'input>>::Inner>
499 where
500 'input: 'a,
501 {
502 self.deref().start()
503 }
504
505 fn start_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
506 where
507 'input: 'a,
508 {
509 self.deref().start_mut()
510 }
511
512 fn set_stop(&self, t: Option<<Self::TF as TokenFactory<'input>>::Tok>) {
513 self.deref().set_stop(t)
514 }
515
516 fn stop<'a>(&'a self) -> Ref<'a, <Self::TF as TokenFactory<'input>>::Inner>
517 where
518 'input: 'a,
519 {
520 self.deref().stop()
521 }
522
523 fn stop_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
524 where
525 'input: 'a,
526 {
527 self.deref().stop_mut()
528 }
529
530 fn add_child(&self, child: Rc<<I::Ctx as ParserNodeType<'input>>::Type>) {
531 self.deref().add_child(child)
532 }
533
534 fn remove_last_child(&self) {
535 self.deref().remove_last_child()
536 }
537
538 }
544
545impl<'input, T, I> RuleContext<'input> for T
546where
547 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
548 I: ParserRuleContext<'input> + 'input + ?Sized,
549{
550 fn get_invoking_state(&self) -> isize {
551 self.deref().get_invoking_state()
552 }
553
554 fn set_invoking_state(&self, t: isize) {
555 self.deref().set_invoking_state(t)
556 }
557
558 fn is_empty(&self) -> bool {
559 self.deref().is_empty()
560 }
561
562 fn get_parent_ctx(&self) -> Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>> {
563 self.deref().get_parent_ctx()
564 }
565
566 fn set_parent(&self, parent: &Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>>) {
567 self.deref().set_parent(parent)
568 }
569}
570
571impl<'input, T, I> ParseTree<'input> for T
572where
573 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
574 I: ParserRuleContext<'input> + 'input + ?Sized,
575{
576 fn get_source_interval(&self) -> Interval {
577 self.deref().get_source_interval()
578 }
579
580 fn get_text(&self) -> String {
581 self.deref().get_text()
582 }
583}
584
585impl<'input, T, I> Tree<'input> for T
586where
587 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
588 I: ParserRuleContext<'input> + 'input + ?Sized,
589{
590 fn get_parent(&self) -> Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>> {
591 self.deref().get_parent()
592 }
593
594 fn has_parent(&self) -> bool {
595 self.deref().has_parent()
596 }
597
598 fn get_payload(&self) -> Box<dyn Any> {
599 self.deref().get_payload()
600 }
601
602 fn get_child(&self, i: usize) -> Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>> {
603 self.deref().get_child(i)
604 }
605
606 fn get_child_count(&self) -> usize {
607 self.deref().get_child_count()
608 }
609
610 fn get_children<'a>(
611 &'a self,
612 ) -> Box<dyn Iterator<Item = Rc<<Self::Ctx as ParserNodeType<'input>>::Type>> + 'a>
613 where
614 'input: 'a,
615 {
616 self.deref().get_children()
617 }
618
619 }
621
622impl<'input, T, I> CustomRuleContext<'input> for T
623where
624 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
625 I: ParserRuleContext<'input> + 'input + ?Sized,
626{
627 type TF = I::TF;
628 type Ctx = I::Ctx;
629
630 fn get_rule_index(&self) -> usize {
631 self.deref().get_rule_index()
632 }
633
634 fn get_alt_number(&self) -> isize {
637 self.deref().get_alt_number()
638 }
639
640 fn set_alt_number(&self, _alt_number: isize) {
641 self.deref().set_alt_number(_alt_number)
642 }
643}
644
645