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 #[doc(hidden)]
132 fn accept_children<V>(&self, visitor: &mut V)
133 where
134 V: ParseTreeVisitor<'input, Self::Ctx> + ?Sized,
135 <Self::Ctx as ParserNodeType<'input>>::Type: VisitableDyn<V>;
136}
137
138impl<'input, T: ParserRuleContext<'input> + ?Sized + 'input> RuleContextExt<'input> for T {
139 fn to_string<Z>(self: &Rc<Self>, rule_names: Option<&[&str]>, stop: Option<Rc<Z>>) -> String
140 where
141 Z: ParserRuleContext<'input, Ctx = T::Ctx, TF = T::TF> + ?Sized + 'input,
142 T::Ctx: ParserNodeType<'input, Type = Z>,
143 T: CoerceTo<Z>,
144 {
145 let mut result = String::from("[");
146 let mut next: Option<Rc<Z>> = Some(self.clone().coerce_rc_to());
147 while let Some(ref p) = next {
148 if stop.is_some() && (stop.is_none() || Rc::ptr_eq(p, stop.as_ref().unwrap())) {
149 break;
150 }
151
152 if let Some(rule_names) = rule_names {
153 let rule_index = p.get_rule_index();
154 let rule_name = rule_names
155 .get(rule_index)
156 .map(|&it| it.to_owned())
157 .unwrap_or_else(|| rule_index.to_string());
158 result.extend(rule_name.chars());
159 result.push(' ');
160 } else {
161 if !p.is_empty() {
162 result.extend(p.get_invoking_state().to_string().chars());
163 result.push(' ');
164 }
165 }
166
167 next = p.get_parent().clone();
168 }
169
170 if result.chars().last() == Some(' ') {
171 result.pop();
172 }
173
174 result.push(']');
175 return result;
176 }
177
178 fn accept_children<V>(&self, visitor: &mut V)
179 where
180 V: ParseTreeVisitor<'input, Self::Ctx> + ?Sized,
181 <Self::Ctx as ParserNodeType<'input>>::Type: VisitableDyn<V>,
182 {
183 self.get_children()
184 .for_each(|child| child.accept_dyn(visitor))
185 }
186}
187
188#[inline]
189#[doc(hidden)]
190pub fn cast<'a, T, Result>(ctx: &T) -> &Result
191where
192 T: ParserRuleContext<'a> + 'a + ?Sized,
193 Result: ParserRuleContext<'a, Ctx = T::Ctx> + 'a,
194{
195 ctx.downcast_ref().unwrap()
196 }
198
199#[inline]
202#[doc(hidden)]
203pub fn cast_mut<'a, T: ParserRuleContext<'a> + 'a + ?Sized, Result: 'a>(
206 ctx: &mut Rc<T>,
207) -> &mut Result {
208 unsafe {
213 let ptr = Rc::as_ptr(ctx) as *mut T as *mut Result;
214
215 &mut *ptr
216 }
217}
218
219pub struct BaseParserRuleContext<'input, Ctx: CustomRuleContext<'input>> {
237 base: BaseRuleContext<'input, Ctx>,
238
239 start: RefCell<<Ctx::TF as TokenFactory<'input>>::Tok>,
240 stop: RefCell<<Ctx::TF as TokenFactory<'input>>::Tok>,
241 pub exception: Option<Box<ANTLRError>>,
243 pub(crate) children: RefCell<Vec<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>>>,
245}
246
247better_any::tid! { impl<'i,Ctx> TidAble<'i> for BaseParserRuleContext<'i,Ctx> where Ctx:CustomRuleContext<'i> }
248
249impl<'input, Ctx: CustomRuleContext<'input>> Debug for BaseParserRuleContext<'input, Ctx> {
250 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { f.write_str(type_name::<Self>()) }
251}
252
253impl<'input, Ctx: CustomRuleContext<'input>> RuleContext<'input>
254 for BaseParserRuleContext<'input, Ctx>
255{
256 fn get_invoking_state(&self) -> isize { self.base.get_invoking_state() }
257
258 fn set_invoking_state(&self, t: isize) { self.base.set_invoking_state(t) }
259
260 fn get_parent_ctx(&self) -> Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>> {
261 self.base.get_parent_ctx()
262 }
263
264 fn set_parent(&self, parent: &Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>>) {
265 self.base.set_parent(parent)
266 }
267}
268
269impl<'input, Ctx: CustomRuleContext<'input>> CustomRuleContext<'input>
270 for BaseParserRuleContext<'input, Ctx>
271{
272 type TF = Ctx::TF;
273 type Ctx = Ctx::Ctx;
274
275 fn get_rule_index(&self) -> usize { self.base.ext.get_rule_index() }
276}
277
278impl<'input, Ctx: CustomRuleContext<'input>> Deref for BaseParserRuleContext<'input, Ctx> {
290 type Target = Ctx;
291
292 fn deref(&self) -> &Self::Target { &self.base.ext }
293}
294
295impl<'input, Ctx: CustomRuleContext<'input>> DerefMut for BaseParserRuleContext<'input, Ctx> {
296 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.base.ext }
297}
298
299impl<'input, Ctx: CustomRuleContext<'input>> Borrow<Ctx> for BaseParserRuleContext<'input, Ctx> {
300 fn borrow(&self) -> &Ctx { &self.base.ext }
301}
302
303impl<'input, Ctx: CustomRuleContext<'input>> BorrowMut<Ctx> for BaseParserRuleContext<'input, Ctx> {
304 fn borrow_mut(&mut self) -> &mut Ctx { &mut self.base.ext }
305}
306
307impl<'input, Ctx: CustomRuleContext<'input> + TidAble<'input>> ParserRuleContext<'input>
308 for BaseParserRuleContext<'input, Ctx>
309{
310 fn set_exception(&self, _e: ANTLRError) { }
312
313 fn set_start(&self, t: Option<<Ctx::TF as TokenFactory<'input>>::Tok>) {
314 *self.start.borrow_mut() = t.unwrap_or(Ctx::TF::create_invalid().clone());
315 }
316
317 fn start<'a>(&'a self) -> Ref<'a, <Ctx::TF as TokenFactory<'input>>::Inner>
318 where
319 'input: 'a,
320 {
321 Ref::map(self.start.borrow(), |t| t.borrow())
322 }
323
324 fn start_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
325 where
326 'input: 'a,
327 {
328 self.start.borrow_mut()
329 }
330
331 fn set_stop(&self, t: Option<<Ctx::TF as TokenFactory<'input>>::Tok>) {
332 *self.stop.borrow_mut() = t.unwrap_or(Ctx::TF::create_invalid().clone());
333 }
334
335 fn stop<'a>(&'a self) -> Ref<'a, <Ctx::TF as TokenFactory<'input>>::Inner>
336 where
337 'input: 'a,
338 {
339 Ref::map(self.stop.borrow(), |t| t.borrow())
340 }
341
342 fn stop_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
343 where
344 'input: 'a,
345 {
346 self.stop.borrow_mut()
347 }
348
349 fn add_child(&self, child: Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>) {
365 self.children.borrow_mut().push(child);
366 }
367
368 fn remove_last_child(&self) { self.children.borrow_mut().pop(); }
369
370 }
382
383impl<'input, Ctx: CustomRuleContext<'input>> Tree<'input> for BaseParserRuleContext<'input, Ctx> {
384 fn get_parent(&self) -> Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>> {
385 self.get_parent_ctx()
386 }
387
388 fn has_parent(&self) -> bool { self.base.parent_ctx.borrow().is_some() }
389
390 fn get_payload(&self) -> Box<dyn Any> { unimplemented!() }
391
392 fn get_child(&self, i: usize) -> Option<Rc<<Self::Ctx as ParserNodeType<'input>>::Type>> {
393 self.children.borrow().get(i).cloned()
394 }
395
396 fn get_child_count(&self) -> usize { self.children.borrow().len() }
397
398 }
408
409impl<'input, Ctx: CustomRuleContext<'input> + TidAble<'input>> ParseTree<'input>
410 for BaseParserRuleContext<'input, Ctx>
411{
412 fn get_source_interval(&self) -> Interval {
413 Interval {
414 a: self.start().get_token_index(),
415 b: self.stop().get_token_index(),
416 }
417 }
418
419 fn get_text(&self) -> String {
420 let children = self.get_children();
421 let mut result = String::new();
422
423 for child in children {
424 result += &child.get_text()
425 }
426
427 result
428 }
429}
430#[allow(missing_docs)]
431impl<'input, Ctx: CustomRuleContext<'input> + 'input> BaseParserRuleContext<'input, Ctx> {
432 pub fn new_parser_ctx(
433 parent_ctx: Option<Rc<<Ctx::Ctx as ParserNodeType<'input>>::Type>>,
434 invoking_state: isize,
435 ext: Ctx,
436 ) -> Self {
437 Self {
438 base: BaseRuleContext::new_parser_ctx(parent_ctx, invoking_state, ext),
439 start: RefCell::new(Ctx::TF::create_invalid()),
440 stop: RefCell::new(Ctx::TF::create_invalid()),
441 exception: None,
442 children: RefCell::new(vec![]),
443 }
444 }
445 pub fn copy_from<T: ParserRuleContext<'input, TF = Ctx::TF, Ctx = Ctx::Ctx> + ?Sized>(
446 ctx: &T,
447 ext: Ctx,
448 ) -> Self {
449 Self {
450 base: BaseRuleContext::new_parser_ctx(
451 ctx.get_parent_ctx(),
452 ctx.get_invoking_state(),
453 ext,
454 ),
455 start: RefCell::new(ctx.start_mut().clone()),
456 stop: RefCell::new(ctx.stop_mut().clone()),
457 exception: None,
458 children: RefCell::new(ctx.get_children().collect()),
459 }
460 }
461
462 }
466
467#[doc(hidden)]
474pub trait DerefSeal: Deref {}
475
476impl<'input, T, I> ParserRuleContext<'input> for T
477where
478 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
479 I: ParserRuleContext<'input> + 'input + ?Sized,
480{
481 fn set_exception(&self, e: ANTLRError) { self.deref().set_exception(e) }
482
483 fn set_start(&self, t: Option<<Self::TF as TokenFactory<'input>>::Tok>) {
484 self.deref().set_start(t)
485 }
486
487 fn start<'a>(&'a self) -> Ref<'a, <Self::TF as TokenFactory<'input>>::Inner>
488 where
489 'input: 'a,
490 {
491 self.deref().start()
492 }
493
494 fn start_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
495 where
496 'input: 'a,
497 {
498 self.deref().start_mut()
499 }
500
501 fn set_stop(&self, t: Option<<Self::TF as TokenFactory<'input>>::Tok>) {
502 self.deref().set_stop(t)
503 }
504
505 fn stop<'a>(&'a self) -> Ref<'a, <Self::TF as TokenFactory<'input>>::Inner>
506 where
507 'input: 'a,
508 {
509 self.deref().stop()
510 }
511
512 fn stop_mut<'a>(&'a self) -> RefMut<'a, <Self::TF as TokenFactory<'input>>::Tok>
513 where
514 'input: 'a,
515 {
516 self.deref().stop_mut()
517 }
518
519 fn add_child(&self, child: Rc<<I::Ctx as ParserNodeType<'input>>::Type>) {
520 self.deref().add_child(child)
521 }
522
523 fn remove_last_child(&self) { self.deref().remove_last_child() }
524
525 }
531
532impl<'input, T, I> RuleContext<'input> for T
533where
534 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
535 I: ParserRuleContext<'input> + 'input + ?Sized,
536{
537 fn get_invoking_state(&self) -> isize { self.deref().get_invoking_state() }
538
539 fn set_invoking_state(&self, t: isize) { self.deref().set_invoking_state(t) }
540
541 fn is_empty(&self) -> bool { self.deref().is_empty() }
542
543 fn get_parent_ctx(&self) -> Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>> {
544 self.deref().get_parent_ctx()
545 }
546
547 fn set_parent(&self, parent: &Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>>) {
548 self.deref().set_parent(parent)
549 }
550}
551
552impl<'input, T, I> ParseTree<'input> for T
553where
554 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
555 I: ParserRuleContext<'input> + 'input + ?Sized,
556{
557 fn get_source_interval(&self) -> Interval { self.deref().get_source_interval() }
558
559 fn get_text(&self) -> String { self.deref().get_text() }
560}
561
562impl<'input, T, I> Tree<'input> for T
563where
564 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
565 I: ParserRuleContext<'input> + 'input + ?Sized,
566{
567 fn get_parent(&self) -> Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>> {
568 self.deref().get_parent()
569 }
570
571 fn has_parent(&self) -> bool { self.deref().has_parent() }
572
573 fn get_payload(&self) -> Box<dyn Any> { self.deref().get_payload() }
574
575 fn get_child(&self, i: usize) -> Option<Rc<<I::Ctx as ParserNodeType<'input>>::Type>> {
576 self.deref().get_child(i)
577 }
578
579 fn get_child_count(&self) -> usize { self.deref().get_child_count() }
580
581 fn get_children<'a>(
582 &'a self,
583 ) -> Box<dyn Iterator<Item = Rc<<Self::Ctx as ParserNodeType<'input>>::Type>> + 'a>
584 where
585 'input: 'a,
586 {
587 self.deref().get_children()
588 }
589
590 }
592
593impl<'input, T, I> CustomRuleContext<'input> for T
594where
595 T: DerefSeal<Target = I> + 'input + Debug + Tid<'input>,
596 I: ParserRuleContext<'input> + 'input + ?Sized,
597{
598 type TF = I::TF;
599 type Ctx = I::Ctx;
600
601 fn get_rule_index(&self) -> usize { self.deref().get_rule_index() }
602
603 fn get_alt_number(&self) -> isize { self.deref().get_alt_number() }
606
607 fn set_alt_number(&self, _alt_number: isize) { self.deref().set_alt_number(_alt_number) }
608}
609
610