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
use std::any::{Any, type_name, TypeId};
use std::borrow::{Borrow, BorrowMut};
use std::cell::{Ref, RefCell};
use std::fmt::{Debug, Error, Formatter};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;

use crate::common_token_factory::INVALID_TOKEN;
use crate::errors::ANTLRError;
use crate::interval_set::Interval;
use crate::rule_context::{BaseRuleContext, CustomRuleContext, EmptyCustomRuleContext, RuleContext};
use crate::token::{OwningToken, Token};
use crate::tree::{ErrorNode, ErrorNodeCtx, ParseTree, TerminalNode, TerminalNodeCtx, Tree};

pub trait ParserRuleContext: RuleContext + CustomRuleContext + ParseTree + Any + Debug {
    fn set_exception(&self, e: ANTLRError);

    fn set_start(&self, t: Option<OwningToken>);
    ///
    /// Get the initial token in this context.
    /// Note that the range from start to stop is inclusive, so for rules that do not consume anything
    /// (for example, zero length or error productions) this token may exceed stop.
    ///
    fn get_start(&self) -> Ref<'_, OwningToken>;

    fn set_stop(&self, t: Option<OwningToken>);
    ///
    /// Get the final token in this context.
    /// Note that the range from start to stop is inclusive, so for rules that do not consume anything
    /// (for example, zero length or error productions) this token may precede start.
    ///
    fn get_stop(&self) -> Ref<'_, OwningToken>;


    fn add_token_node(&self, token: TerminalNode) -> Rc<dyn ParserRuleContext>;
    fn add_error_node(&self, bad_token: ErrorNode) -> Rc<dyn ParserRuleContext>;

    fn add_child(&self, child: ParserRuleContextType);
    fn remove_last_child(&self);

    fn enter_rule(&self, listener: &mut dyn Any);
    fn exit_rule(&self, listener: &mut dyn Any);

    fn child_of_type<T: ParserRuleContext>(&self, pos: usize) -> Option<Rc<T>> where Self: Sized {
        let result = self.get_children().iter()
            .filter(|&it| it.deref().type_id() == TypeId::of::<T>())
            .nth(pos)
            .cloned();

        result.map(cast_rc)
    }

    // todo, return iterator
    fn children_of_type<T: ParserRuleContext>(&self) -> Vec<Rc<T>> where Self: Sized {
        self.get_children()
            .iter()
            .filter(|&it| it.deref().type_id() == TypeId::of::<T>())
            .map(|it| cast_rc::<T>(it.clone()))
            .collect()
    }

    fn get_token(&self, ttype: isize, pos: usize) -> Option<Rc<TerminalNode>> {
        self.get_children()
            .iter()
            .filter(|&it| it.deref().type_id() == TypeId::of::<TerminalNode>())
            .map(|it| cast_rc::<TerminalNode>(it.clone()))
            .filter(|it| it.symbol.get_token_type() == ttype)
            .nth(pos)
    }

    fn get_tokens(&self, ttype: isize) -> Vec<Rc<TerminalNode>> {
        self.get_children()
            .iter()
            .filter(|&it| it.deref().type_id() == TypeId::of::<TerminalNode>())
            .map(|it| cast_rc::<TerminalNode>(it.clone()))
            .filter(|it| it.symbol.get_token_type() == ttype)
            .collect()
    }

    fn upcast_any(&self) -> &dyn Any;

    fn upcast(&self) -> &dyn ParserRuleContext;
}

impl dyn ParserRuleContext {
    fn to_string(self: &Rc<Self>, rule_names: Option<&[&str]>, stop: Option<Rc<dyn ParserRuleContext>>) -> String {
        let mut result = String::from("[");
        let mut next: Option<Rc<dyn ParserRuleContext>> = Some(self.clone());
        while let Some(ref p) = next {
            if stop.is_some() && (stop.is_none() || Rc::ptr_eq(p, stop.as_ref().unwrap())) { break }


            if let Some(rule_names) = rule_names {
                let rule_index = p.get_rule_index();
                let rule_name = rule_names.get(rule_index).map(|&it| it.to_owned())
                    .unwrap_or_else(|| rule_index.to_string());
                result.extend(rule_name.chars());
                result.push(' ');
            } else {
                if !p.is_empty() {
                    result.extend(p.get_invoking_state().to_string().chars());
                    result.push(' ');
                }
            }

            next = p.get_parent().clone();
        }
        // not optimal but we don't care here
        if result.chars().last() == Some(' ') {
            result.pop();
        }

        result.push(']');
        return result
    }
}


//requires ParserRuleContext to be Sync
//lazy_static! {
//    pub static ref EMPTY_CTX: Box<dyn ParserRuleContext> =
//        Box::new(BaseParserRuleContext::new_parser_ctx(None,-1,CustomRuleContextInternal));
//}

pub type LexerContext = BaseParserRuleContext<EmptyCustomRuleContext>;

//todo do not calc this every time, maybe threadlocal? or it might be ok as it is because it is inlined
#[inline]
pub(crate) fn empty_ctx() -> Box<dyn ParserRuleContext> {
    Box::new(BaseParserRuleContext::new_parser_ctx(None, -1, EmptyCustomRuleContext))
}

#[inline]
fn cast_rc<T: ParserRuleContext>(ctx: Rc<dyn ParserRuleContext>) -> Rc<T> {
    // not sure how safe it is
    unsafe { Rc::from_raw(Rc::into_raw(ctx) as *const T) }
}

#[inline]
pub fn cast<T: ParserRuleContext + ?Sized, Result>(ctx: &T) -> &Result {
    unsafe { &*(ctx as *const T as *const Result) }
}

/// should be called from generated parser only
#[inline]
pub fn cast_mut<T: ParserRuleContext + ?Sized, Result>(ctx: &mut Rc<T>) -> &mut Result {
//    if Rc::strong_count(ctx) != 1 { panic!("cant mutate Rc with multiple strong ref count"); }
// is it safe because parser does not save/move mutable references anywhere.
// they are only used to write data immediately in the corresponding expression
    unsafe { &mut *(Rc::get_mut_unchecked(ctx) as *mut T as *mut Result) }
}


pub type ParserRuleContextType = Rc<dyn ParserRuleContext>;

pub struct BaseParserRuleContext<Ctx: CustomRuleContext> {
    base: BaseRuleContext<Ctx>,

    start: RefCell<OwningToken>,
    stop: RefCell<OwningToken>,
    exception: Option<Box<ANTLRError>>,
    /// List of children of current node
    pub(crate) children: RefCell<Vec<ParserRuleContextType>>,
}

impl<Ctx: CustomRuleContext> Debug for BaseParserRuleContext<Ctx> {
    default fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        f.write_str(type_name::<Self>())
    }
}

impl<Ctx: CustomRuleContext> RuleContext for BaseParserRuleContext<Ctx> {
    fn get_invoking_state(&self) -> isize {
        self.base.get_invoking_state()
    }

    fn set_invoking_state(&self, t: isize) {
        self.base.set_invoking_state(t)
    }

    fn get_parent_ctx(&self) -> Option<Rc<dyn ParserRuleContext>> {
        self.base.get_parent_ctx()
    }

    fn set_parent(&self, parent: &Option<Rc<dyn ParserRuleContext>>) {
        self.base.set_parent(parent)
    }
}

impl<Ctx: CustomRuleContext> CustomRuleContext for BaseParserRuleContext<Ctx> {
    fn get_rule_index(&self) -> usize { self.base.ext.get_rule_index() }
}

impl<Ctx: CustomRuleContext> Deref for BaseParserRuleContext<Ctx> {
    type Target = Ctx;

    fn deref(&self) -> &Self::Target {
        &self.base.ext
    }
}

impl<Ctx: CustomRuleContext> DerefMut for BaseParserRuleContext<Ctx> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.base.ext
    }
}

impl<Ctx: CustomRuleContext> Borrow<Ctx> for BaseParserRuleContext<Ctx> {
    fn borrow(&self) -> &Ctx {
        &self.base.ext
    }
}

impl<Ctx: CustomRuleContext> BorrowMut<Ctx> for BaseParserRuleContext<Ctx> {
    fn borrow_mut(&mut self) -> &mut Ctx {
        &mut self.base.ext
    }
}

impl<Ctx: CustomRuleContext> ParserRuleContext for BaseParserRuleContext<Ctx> {
    fn set_exception(&self, _e: ANTLRError) {
        // empty for this version
//        unimplemented!()
//        self.exception = Some(Box::new(e));
    }

    fn set_start(&self, t: Option<OwningToken>) {
        *self.start.borrow_mut() = t.unwrap_or((**INVALID_TOKEN).clone());
    }

    fn get_start(&self) -> Ref<'_, OwningToken> {
        self.start.borrow()
    }

    fn set_stop(&self, t: Option<OwningToken>) {
        *self.stop.borrow_mut() = t.unwrap_or((**INVALID_TOKEN).clone());
    }

    fn get_stop(&self) -> Ref<'_, OwningToken> {
        self.stop.borrow()
    }

    fn add_token_node(&self, token: TerminalNode) -> Rc<dyn ParserRuleContext> {
        let node: Rc<dyn ParserRuleContext> = Rc::new(token);
        self.children.borrow_mut().push(node.clone());
        node
    }

    fn add_error_node(&self, bad_token: ErrorNode) -> Rc<dyn ParserRuleContext> {
//        bad_token.base.parent_ctx =
        let node: Rc<dyn ParserRuleContext> = Rc::new(bad_token);
//        Backtrace::new().frames()[0].symbols()[0];

        self.children.borrow_mut().push(node.clone());
        node
    }

    fn add_child(&self, child: ParserRuleContextType) {
        self.children.borrow_mut().push(child);
    }

    fn remove_last_child(&self) {
        self.children.borrow_mut().pop();
    }

    fn enter_rule(&self, listener: &mut dyn Any) {
        Ctx::enter(self, listener)
    }

    fn exit_rule(&self, listener: &mut dyn Any) {
        Ctx::exit(self, listener)
    }

    fn upcast_any(&self) -> &dyn Any {
        self
    }

    fn upcast(&self) -> &dyn ParserRuleContext {
        self
    }
}

impl<Ctx: CustomRuleContext> Tree for BaseParserRuleContext<Ctx> {
    fn get_parent(&self) -> Option<ParserRuleContextType> {
        self.get_parent_ctx()
    }

    fn has_parent(&self) -> bool {
        self.base.parent_ctx.borrow().is_some()
    }

    fn get_payload(&self) -> Box<dyn Any> {
        unimplemented!()
    }

    fn get_child(&self, i: usize) -> Option<ParserRuleContextType> {
        self.children.borrow().get(i).cloned()
    }

    fn get_child_count(&self) -> usize {
        self.children.borrow().len()
    }

    fn get_children(&self) -> Ref<'_, Vec<ParserRuleContextType>> {
        self.children.borrow()
    }

    fn get_children_full(&self) -> &RefCell<Vec<ParserRuleContextType>> {
        &self.children
    }
}

impl<Ctx: CustomRuleContext> ParseTree for BaseParserRuleContext<Ctx> {
    fn get_source_interval(&self) -> Interval {
        Interval { a: self.start.borrow().get_token_index(), b: self.stop.borrow().get_token_index() }
    }

    default fn get_text(&self) -> String {
        let children = self.get_children();
        if children.len() == 0 {
            return String::new();
        }

        let mut result = String::new();

        for child in children.iter() {
            result += &child.get_text()
        }

        result
    }

//    fn to_string_tree(&self, r: &dyn Parser) -> String {
//
//    }
}

impl<Ctx: CustomRuleContext> BaseParserRuleContext<Ctx> {
    pub fn new_parser_ctx(parent_ctx: Option<ParserRuleContextType>, invoking_state: isize, ext: Ctx) -> Self {
        BaseParserRuleContext {
            base: BaseRuleContext::new_ctx(parent_ctx, invoking_state, ext),
            start: RefCell::new((**INVALID_TOKEN).clone()),
            stop: RefCell::new((**INVALID_TOKEN).clone()),
            exception: None,
            children: RefCell::new(vec![]),
        }
    }
    pub fn copy_from<T: ParserRuleContext + ?Sized>(ctx: &T, ext: Ctx) -> Self {
        BaseParserRuleContext {
            base: BaseRuleContext::new_ctx(ctx.get_parent_ctx(), ctx.get_invoking_state(), ext),
            start: RefCell::new(ctx.get_start().clone()),
            stop: RefCell::new(ctx.get_stop().clone()),
            exception: None,
            children: RefCell::new(ctx.get_children().iter().cloned().collect()),
        }
    }

    pub fn to_string(self: Rc<Self>, rule_names: Option<&[&str]>, stop: Option<Rc<dyn ParserRuleContext>>) -> String {
        (self as Rc<dyn ParserRuleContext>).to_string(rule_names, stop)
    }
}


///////////////////////////////////////////////
// Needed to reduce boilerplate in the generated code,
// because there is no simple way to implement trait for enum
// will not be necessary if some kind of variant types RFC will be merged
//////////////////////////////////////////////
/// workaround trait to overcome conflicting implementations error
pub trait DerefSeal: Deref {}

impl<T: DerefSeal<Target=I> + Debug + 'static, I: ParserRuleContext + ?Sized> ParserRuleContext for T {
    fn set_exception(&self, e: ANTLRError) { self.deref().set_exception(e) }

    fn set_start(&self, t: Option<OwningToken>) { self.deref().set_start(t) }

    fn get_start(&self) -> Ref<'_, OwningToken> { self.deref().get_start() }

    fn set_stop(&self, t: Option<OwningToken>) { self.deref().set_stop(t) }

    fn get_stop(&self) -> Ref<'_, OwningToken> { self.deref().get_stop() }

    fn add_token_node(&self, token: BaseParserRuleContext<TerminalNodeCtx>) -> Rc<dyn ParserRuleContext> { self.deref().add_token_node(token) }

    fn add_error_node(&self, bad_token: BaseParserRuleContext<ErrorNodeCtx>) -> Rc<dyn ParserRuleContext> { self.deref().add_error_node(bad_token) }

    fn add_child(&self, child: Rc<dyn ParserRuleContext>) { self.deref().add_child(child) }

    fn remove_last_child(&self) { self.deref().remove_last_child() }

    fn enter_rule(&self, listener: &mut dyn Any) { self.deref().enter_rule(listener) }

    fn exit_rule(&self, listener: &mut dyn Any) { self.deref().exit_rule(listener) }

    fn upcast_any(&self) -> &dyn Any { self.deref().upcast_any() }

    fn upcast(&self) -> &dyn ParserRuleContext { self.deref().upcast() }
}

impl<T: DerefSeal<Target=I> + Debug + 'static, I: ParserRuleContext + ?Sized> RuleContext for T {
    fn get_invoking_state(&self) -> isize { self.deref().get_invoking_state() }

    fn set_invoking_state(&self, t: isize) { self.deref().set_invoking_state(t) }

    fn is_empty(&self) -> bool { self.deref().is_empty() }

    fn get_parent_ctx(&self) -> Option<Rc<dyn ParserRuleContext>> { self.deref().get_parent_ctx() }

    fn set_parent(&self, parent: &Option<Rc<dyn ParserRuleContext>>) { self.deref().set_parent(parent) }
}

impl<T: DerefSeal<Target=I> + Debug + 'static, I: ParserRuleContext + ?Sized> ParseTree for T {
    fn get_source_interval(&self) -> Interval { self.deref().get_source_interval() }

    fn get_text(&self) -> String { self.deref().get_text() }
}

impl<T: DerefSeal<Target=I> + Debug + 'static, I: ParserRuleContext + ?Sized> Tree for T {
    fn get_parent(&self) -> Option<Rc<dyn ParserRuleContext>> { self.deref().get_parent() }

    fn has_parent(&self) -> bool { self.deref().has_parent() }

    fn get_payload(&self) -> Box<dyn Any> { self.deref().get_payload() }

    fn get_child(&self, i: usize) -> Option<Rc<dyn ParserRuleContext>> { self.deref().get_child(i) }

    fn get_child_count(&self) -> usize { self.deref().get_child_count() }

    fn get_children(&self) -> Ref<'_, Vec<Rc<dyn ParserRuleContext>>> { self.deref().get_children() }

    fn get_children_full(&self) -> &RefCell<Vec<Rc<dyn ParserRuleContext>>> { self.deref().get_children_full() }
}

impl<T: DerefSeal<Target=I> + Debug + 'static, I: ParserRuleContext + ?Sized> CustomRuleContext for T {
    fn get_rule_index(&self) -> usize { self.deref().get_rule_index() }

    fn get_alt_number(&self) -> isize { self.deref().get_alt_number() }

    fn set_alt_number(&self, _alt_number: isize) { self.deref().set_alt_number(_alt_number) }
}

//
//    fn get_text(&self) -> String { unimplemented!() }
//
//    fn add_terminal_node_child(&self, child: TerminalNode) -> TerminalNode { unimplemented!() }
//
//    fn get_child_of_type(&self, i: isize, childType: reflect.Type) -> RuleContext { unimplemented!() }
//
//    fn to_string_tree(&self, ruleNames Vec<String>, recog: Recognizer) -> String { unimplemented!() }
//
//    fn get_rule_context(&self) -> RuleContext { unimplemented!() }
//
//    fn accept(&self, visitor: ParseTreeVisitor) -> interface { unimplemented!() } {
//    return visitor.VisitChildren(prc)
//    }
//
//    fn get_token(&self, ttype: isize, i: isize) -> TerminalNode { unimplemented!() }
//
//    fn get_tokens(&self, ttype: isize) -> Vec<TerminalNode> { unimplemented!() }
//
//    fn get_payload(&self) -> interface { unimplemented!() } {
//    return: prc,
//    }
//
//    fn get_child(&self, ctxType: reflect.Type, i: isize) -> RuleContext { unimplemented!() }
//
//
//    fn get_typed_rule_context(&self, ctxType: reflect.Type, i: isize) -> RuleContext { unimplemented!() }
//
//    fn get_typed_rule_contexts(&self, ctxType: reflect.Type) -> Vec<RuleContext> { unimplemented!() }
//
//    fn get_child_count(&self) -> int { unimplemented!() }
//
//    fn get_source_interval(&self) -> * Interval { unimplemented!() }
//
//
//    fn String(&self, ruleNames Vec<String>, stop: RuleContext) -> String { unimplemented!() }
//
//    var RuleContextEmpty = NewBaseParserRuleContext(nil, - 1)
//
//    pub trait InterpreterRuleContext {
//    parser_rule_context
//    }
//
//    pub struct BaseInterpreterRuleContext {
//    base: BaseParserRuleContext,
//    }
//
//    fn new_base_interpreter_rule_context(parent BaseInterpreterRuleContext, invokingStateNumber: isize, ruleIndex: isize) -> * BaseInterpreterRuleContext { unimplemented!() }