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
use std::borrow::Cow::{Borrowed, Owned};
use std::borrow::{Borrow, Cow};
use std::cell::{Cell, RefCell};
use std::ops::DerefMut;
use std::rc::Rc;

use crate::char_stream::{CharStream, InputData};
use crate::error_listener::{ConsoleErrorListener, ErrorListener};
use crate::errors::ANTLRError;
use crate::int_stream::IntStream;
use crate::lexer_atn_simulator::{ILexerATNSimulator, LexerATNSimulator};
use crate::parser::ParserNodeType;
use crate::parser_rule_context::ParserRuleContext;
use crate::recognizer::{Actions, Recognizer};
use crate::rule_context::EmptyContextType;
use crate::token::{Token, TOKEN_INVALID_TYPE};
use crate::token_factory::{CommonTokenFactory, TokenAware, TokenFactory};
use crate::token_source::TokenSource;

pub trait Lexer<'input>:
    TokenSource<'input>
    + Recognizer<'input, Node = EmptyContextType<'input, <Self as TokenAware<'input>>::TF>>
{
    /// Sets channel where current token will be pushed
    ///
    /// By default two channels are available:
    ///  - `LEXER_DEFAULT_TOKEN_CHANNEL`
    ///  - `LEXER_HIDDEN`
    fn set_channel(&mut self, v: isize);

    /// Pushes current mode to internal mode stack and sets `m` as current lexer mode
    /// `pop_mode should be used to recover previous mode
    fn push_mode(&mut self, m: usize);

    /// Pops mode from internal mode stack
    fn pop_mode(&mut self) -> Option<usize>;

    /// Sets type of the current token
    /// Called from action to override token that will be emitted by lexer
    fn set_type(&mut self, t: isize);

    /// Sets lexer mode discarding current one
    fn set_mode(&mut self, m: usize);

    /// Used to informs lexer that it should consider next token as a continuation of the current one
    fn more(&mut self);

    /// Tells lexer to completely ignore and not emit current token.
    fn skip(&mut self);

    fn reset(&mut self);

    fn get_interpreter(&self) -> Option<&LexerATNSimulator>;
}

/// **! Usually generated by ANTLR !**
///
/// This trait combines everything that can be used to extend Lexer behavior
pub trait LexerRecog<'a, T: Recognizer<'a>>: Actions<'a, T> + Sized + 'static {
    /// Callback to extend emit behavior
    fn before_emit(_lexer: &mut T) {}
}

pub struct BaseLexer<
    'input,
    T: LexerRecog<'input, Self> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input> = CommonTokenFactory,
> {
    pub interpreter: Option<LexerATNSimulator>,
    pub input: Option<Input>,
    recog: T,

    factory: &'input TF,

    error_listeners: RefCell<Vec<Box<dyn ErrorListener<'input, Self>>>>,

    pub token_start_char_index: isize,
    pub token_start_line: isize,
    pub token_start_column: isize,
    current_pos: Rc<LexerPosition>,
    pub token_type: isize,
    pub token: Option<TF::Tok>,
    hit_eof: bool,
    pub channel: isize,
    mode_stack: Vec<usize>,
    pub mode: usize,
    /// text of token if overridden by user action
    pub text: Option<<TF::Data as ToOwned>::Owned>,
}

pub(crate) struct LexerPosition {
    pub(crate) line: Cell<isize>,
    pub(crate) char_position_in_line: Cell<isize>,
}

impl<'input, T, Input, TF> Recognizer<'input> for BaseLexer<'input, T, Input, TF>
where
    T: LexerRecog<'input, Self> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input>,
{
    type Node = EmptyContextType<'input, TF>;

    fn sempred(
        &mut self,
        _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>,
        rule_index: isize,
        action_index: isize,
    ) -> bool {
        <T as Actions<'input, Self>>::sempred(_localctx, rule_index, action_index, self)
    }

    fn action(
        &mut self,
        _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>,
        rule_index: isize,
        action_index: isize,
    ) {
        <T as Actions<'input, Self>>::action(_localctx, rule_index, action_index, self)
    }
}

pub const LEXER_DEFAULT_MODE: usize = 0;
pub const LEXER_MORE: isize = -2;
pub const LEXER_SKIP: isize = -3;

pub const LEXER_DEFAULT_TOKEN_CHANNEL: isize = super::token::TOKEN_DEFAULT_CHANNEL;
pub const LEXER_HIDDEN: isize = super::token::TOKEN_HIDDEN_CHANNEL;
pub const LEXER_MIN_CHAR_VALUE: isize = 0x0000;
pub const LEXER_MAX_CHAR_VALUE: isize = 0x10FFFF;

impl<'input, T, Input, TF> BaseLexer<'input, T, Input, TF>
where
    T: LexerRecog<'input, Self> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input>,
{
    fn emit_token(&mut self, token: TF::Tok) { self.token = Some(token); }

    fn emit(&mut self) {
        <T as LexerRecog<Self>>::before_emit(self);
        let stop = self.get_char_index() - 1;
        let token = self.factory.create(
            Some(self.input.as_mut().unwrap()),
            self.token_type,
            self.text.take(),
            self.channel,
            self.token_start_char_index,
            stop,
            self.token_start_line,
            self.token_start_column,
        );
        self.emit_token(token);
    }

    fn emit_eof(&mut self) {
        let token = self.factory.create(
            None::<&mut Input>,
            super::int_stream::EOF,
            None,
            LEXER_DEFAULT_TOKEN_CHANNEL,
            self.get_char_index(),
            self.get_char_index() - 1,
            self.get_line(),
            self.get_char_position_in_line(),
        );
        self.emit_token(token)
    }

    pub fn get_type(&self) -> isize { self.token_type }

    pub fn get_char_index(&self) -> isize { self.input.as_ref().unwrap().index() }

    /// Current token text
    pub fn get_text<'a>(&'a self) -> Cow<'a, TF::Data>
    where
        'input: 'a,
    {
        self.text
            .as_ref()
            .map(|it| Borrowed(it.borrow()))
            // .unwrap_or("")
            .unwrap_or_else(|| {
                self.input
                    .as_ref()
                    .unwrap()
                    .get_text(self.token_start_char_index, self.get_char_index() - 1)
                    .into()
            })
    }

    /// Used from lexer actions to override text of the token that will be emitted next
    pub fn set_text(&mut self, _text: <TF::Data as ToOwned>::Owned) { self.text = Some(_text); }

    fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() }

    fn get_char_error_display(&self, _c: char) -> String { unimplemented!() }

    /// Add error listener
    pub fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>) {
        self.error_listeners.borrow_mut().push(listener);
    }

    pub fn remove_error_listeners(&mut self) { self.error_listeners.borrow_mut().clear(); }

    pub fn new_base_lexer(
        input: Input,
        interpreter: LexerATNSimulator,
        recog: T,
        factory: &'input TF,
    ) -> Self {
        let mut lexer = Self {
            interpreter: Some(interpreter),
            input: Some(input),
            recog,
            factory,
            error_listeners: RefCell::new(vec![Box::new(ConsoleErrorListener {})]),
            token_start_char_index: 0,
            token_start_line: 0,
            token_start_column: 0,
            current_pos: Rc::new(LexerPosition {
                line: Cell::new(1),
                char_position_in_line: Cell::new(0),
            }),
            token_type: super::token::TOKEN_INVALID_TYPE,
            text: None,
            token: None,
            hit_eof: false,
            channel: super::token::TOKEN_DEFAULT_CHANNEL,
            //            token_factory_source_pair: None,
            mode_stack: Vec::new(),
            mode: self::LEXER_DEFAULT_MODE,
        };
        let pos = lexer.current_pos.clone();
        lexer.interpreter.as_mut().unwrap().current_pos = pos;
        lexer
    }
}

impl<'input, T, Input, TF> TokenAware<'input> for BaseLexer<'input, T, Input, TF>
where
    T: LexerRecog<'input, Self> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input>,
{
    type TF = TF;
}

impl<'input, T, Input, TF> TokenSource<'input> for BaseLexer<'input, T, Input, TF>
where
    T: LexerRecog<'input, Self> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input>,
{
    #[inline]
    #[allow(unused_labels)]
    fn next_token(&mut self) -> <Self::TF as TokenFactory<'input>>::Tok {
        assert!(self.input.is_some());

        let _marker = self.input.as_mut().unwrap().mark();
        'outer: loop {
            if self.hit_eof {
                self.emit_eof();
                break;
            }
            self.token = None;
            self.channel = LEXER_DEFAULT_TOKEN_CHANNEL;
            self.token_start_column = self
                .interpreter
                .as_ref()
                .unwrap()
                .get_char_position_in_line();
            self.token_start_line = self.interpreter.as_ref().unwrap().get_line();
            self.text = None;
            let index = self.get_input_stream().unwrap().index();
            self.token_start_char_index = index;

            'inner: loop {
                let ttype;
                self.token_type = TOKEN_INVALID_TYPE;
                {
                    // detach from self, to allow self to be passed deeper
                    let mut interpreter = self.interpreter.take().unwrap();
                    //                    let mut input = self.input.take().unwrap();
                    let result = interpreter.match_token(self.mode, self);
                    self.interpreter = Some(interpreter);

                    ttype = match result {
                        Ok(ttype) => {
                            //                            println!("new mode {}",self.mode);
                            ttype
                        }
                        Err(err) => {
                            //                            println!("error, recovering");
                            notify_listeners(&mut self.error_listeners.borrow_mut(), &err, self);
                            self.interpreter
                                .as_mut()
                                .unwrap()
                                .recover(err, self.input.as_mut().unwrap().deref_mut());
                            LEXER_SKIP
                        }
                    };
                    //                    self.input = Some(input)
                }
                if self.get_input_stream().unwrap().la(1) == super::int_stream::EOF {
                    self.hit_eof = true;
                }

                if self.token_type == TOKEN_INVALID_TYPE {
                    self.token_type = ttype;
                }

                if self.token_type == LEXER_SKIP {
                    continue 'outer;
                }

                if self.token_type != LEXER_MORE {
                    break;
                }
            }

            if self.token.is_none() {
                self.emit();
                break;
            }
        }
        self.input.as_mut().unwrap().release(_marker);
        self.token.take().unwrap()
    }

    fn get_line(&self) -> isize { self.current_pos.line.get() }

    fn get_char_position_in_line(&self) -> isize { self.current_pos.char_position_in_line.get() }

    fn get_input_stream(&mut self) -> Option<&mut dyn IntStream> {
        match &mut self.input {
            None => None,
            Some(x) => Some(x as _),
        }
    }

    fn get_source_name(&self) -> String {
        self.input
            .as_ref()
            .map(|it| it.get_source_name())
            .unwrap_or("<none>".to_string())
    }

    //    fn set_token_factory<'c: 'b>(&mut self, f: &'c TokenFactory) {
    //        self.factory = f;
    //    }

    fn get_token_factory(&self) -> &'input TF { self.factory }
}

#[cold]
#[inline(never)]
fn notify_listeners<'input, T, Input, TF>(
    liseners: &mut Vec<Box<dyn ErrorListener<'input, BaseLexer<'input, T, Input, TF>>>>,
    e: &ANTLRError,
    lexer: &BaseLexer<'input, T, Input, TF>,
) where
    T: LexerRecog<'input, BaseLexer<'input, T, Input, TF>> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input>,
{
    let text = format!(
        "token recognition error at: '{}'",
        lexer
            .input
            .as_ref()
            .unwrap()
            .get_text(lexer.token_start_char_index, lexer.get_char_index())
            .borrow()
            .to_display()
    );
    for listener in liseners.iter_mut() {
        listener.syntax_error(
            lexer,
            None,
            lexer.token_start_line,
            lexer.token_start_column,
            &text,
            Some(e),
        )
    }
}

impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF>
where
    T: LexerRecog<'input, Self> + 'static,
    Input: CharStream<TF::From>,
    TF: TokenFactory<'input>,
{
    fn set_channel(&mut self, v: isize) { self.channel = v; }

    fn push_mode(&mut self, m: usize) {
        self.mode_stack.push(self.mode);
        self.mode = m;
    }

    fn pop_mode(&mut self) -> Option<usize> {
        self.mode_stack.pop().map(|mode| {
            self.mode = mode;
            mode
        })
    }

    fn set_type(&mut self, t: isize) { self.token_type = t; }

    fn set_mode(&mut self, m: usize) { self.mode = m; }

    fn more(&mut self) { self.set_type(LEXER_MORE) }

    fn skip(&mut self) { self.set_type(LEXER_SKIP) }

    fn reset(&mut self) { unimplemented!() }

    fn get_interpreter(&self) -> Option<&LexerATNSimulator> { self.interpreter.as_ref() }
}