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
use crate::bytes::BytesTrait;
use crate::parser::token_name;
use crate::{Bytes, LexState, Loc};

#[cfg(feature = "compile-with-external-structures")]
use crate::containers::ExternalList;
#[cfg(feature = "compile-with-external-structures")]
type List<T> = ExternalList<T>;
#[cfg(not(feature = "compile-with-external-structures"))]
type List<T> = Vec<T>;

/// Trait with common methods of Token (Rust- or external-based)
pub trait TokenTrait: Clone + PartialEq + Eq + std::fmt::Debug {
    /// Constructor
    fn new(
        token_type: i32,
        token_value: Bytes,
        loc: Loc,
        lex_state_before: LexState,
        lex_state_after: LexState,
    ) -> Self;

    /// Returns a byte array of the token value
    fn as_bytes(&self) -> &[u8] {
        self.token_value().as_raw()
    }

    /// Consumes a token and returns an owned byte array of the token value
    fn into_bytes(self) -> List<u8>
    where
        Self: Sized,
    {
        self.into_token_value().into_raw()
    }

    /// Converts token value into `&str`
    fn as_str_lossy(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(self.token_value().as_raw())
    }

    /// Converts token to a string, replaces unknown chars to `U+FFFD`
    fn to_string_lossy(&self) -> String {
        self.token_value().to_string_lossy()
    }

    /// Converts token to a string
    fn to_string(&self) -> Result<String, std::string::FromUtf8Error> {
        self.token_value().to_string()
    }

    /// Consumes a token and converts it into a string
    fn into_string(self) -> Result<String, std::string::FromUtf8Error>
    where
        Self: Sized,
    {
        self.into_token_value().into_string()
    }

    /// Returns type of the token
    fn token_type(&self) -> i32;

    /// Returns name of the token
    fn token_name(&self) -> &'static str {
        token_name(self.token_type())
    }

    /// Returns value of the token
    fn token_value(&self) -> &Bytes;

    /// Sets token value
    fn set_token_value(&mut self, token_value: Bytes);

    /// Consumes self, returns owned values of the token
    fn into_token_value(self) -> Bytes;

    /// Returns location of the token
    fn loc(&self) -> Loc;

    /// Returns lex state **before** reading the token
    fn lex_state_before(&self) -> LexState;

    /// Returns lex state **after** reading the token
    fn lex_state_after(&self) -> LexState;
}

#[cfg(not(feature = "compile-with-external-structures"))]
mod token {
    use super::{Bytes, BytesTrait, LexState, Loc, TokenTrait};

    /// A token that is emitted by a lexer and consumed by a parser
    #[derive(Clone, PartialEq, Eq)]
    #[repr(C)]
    pub struct Token {
        /// Numeric representation of the token type,
        /// e.g. 42 (for example) for tINTEGER
        token_type: i32,

        /// Value of the token,
        /// e.g "42" for 42
        token_value: Bytes,

        /// Location of the token
        loc: Loc,

        /// Lex state **before** reading the token
        lex_state_before: LexState,

        /// Lex state **after** reading the token
        lex_state_after: LexState,
    }

    impl std::fmt::Debug for Token {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(&format!(
                "[{}, {:?}, {}...{}]",
                self.token_name(),
                self.token_value.to_string_lossy(),
                self.loc.begin,
                self.loc.end,
            ))
        }
    }

    impl TokenTrait for Token {
        fn new(
            token_type: i32,
            token_value: Bytes,
            loc: Loc,
            lex_state_before: LexState,
            lex_state_after: LexState,
        ) -> Self {
            Self {
                token_type,
                token_value,
                loc,
                lex_state_before,
                lex_state_after,
            }
        }

        fn token_type(&self) -> i32 {
            self.token_type
        }

        fn token_value(&self) -> &Bytes {
            &self.token_value
        }

        fn set_token_value(&mut self, token_value: Bytes) {
            self.token_value = token_value
        }

        fn into_token_value(self) -> Bytes {
            self.token_value
        }

        fn loc(&self) -> Loc {
            self.loc
        }

        fn lex_state_before(&self) -> LexState {
            self.lex_state_before
        }

        fn lex_state_after(&self) -> LexState {
            self.lex_state_after
        }
    }
}

#[cfg(feature = "compile-with-external-structures")]
mod token {
    use super::TokenTrait;
    use crate::containers::size::TOKEN_SIZE;
    use crate::{Bytes, BytesTrait, LexState, Loc};

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct TokenBlob {
        blob: [u8; TOKEN_SIZE],
    }

    /// Byte sequence based on external implementation
    #[repr(C)]
    pub struct Token {
        blob: TokenBlob,
    }

    impl std::fmt::Debug for Token {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(&format!(
                "[{}, {:?}, {}...{}]",
                self.token_name(),
                self.token_value().to_string_lossy(),
                self.loc().begin,
                self.loc().end,
            ))
        }
    }

    impl Clone for Token {
        fn clone(&self) -> Self {
            Self::new(
                self.token_type(),
                self.token_value().clone(),
                self.loc().clone(),
                self.lex_state_before(),
                self.lex_state_after(),
            )
        }
    }

    impl PartialEq for Token {
        fn eq(&self, other: &Self) -> bool {
            (self.token_type() == other.token_type())
                && (self.token_value() == other.token_value())
                && (self.loc() == other.loc())
                && (self.lex_state_before() == other.lex_state_before())
                && (self.lex_state_after() == other.lex_state_after())
        }
    }

    impl Eq for Token {}

    impl Drop for Token {
        fn drop(&mut self) {
            unsafe { lib_ruby_parser_token_blob_free(self.blob) }
        }
    }

    use crate::bytes::bytes::BytesBlob;
    extern "C" {
        fn lib_ruby_parser_token_blob_new(
            token_type: i32,
            token_value: BytesBlob,
            loc: Loc,
            lex_state_before: i32,
            lex_state_after: i32,
        ) -> TokenBlob;
        fn lib_ruby_parser_token_blob_get_token_type(token_blob: TokenBlob) -> i32;
        fn lib_ruby_parser_token_blob_borrow_token_value(
            token_blob: *const TokenBlob,
        ) -> *const BytesBlob;
        fn lib_ruby_parser_token_set_token_value(
            token_blob: TokenBlob,
            bytes_blob: BytesBlob,
        ) -> TokenBlob;
        fn lib_ruby_parser_token_blob_into_token_value(token_blob: TokenBlob) -> BytesBlob;
        fn lib_ruby_parser_token_blob_borrow_loc(token_blob: TokenBlob) -> Loc;
        fn lib_ruby_parser_token_blob_get_lex_state_before(token_blob: TokenBlob) -> i32;
        fn lib_ruby_parser_token_blob_get_lex_state_after(token_blob: TokenBlob) -> i32;
        fn lib_ruby_parser_token_blob_free(token_blob: TokenBlob);
    }

    impl TokenTrait for Token {
        fn new(
            token_type: i32,
            token_value: Bytes,
            loc: Loc,
            lex_state_before: LexState,
            lex_state_after: LexState,
        ) -> Self {
            let blob = unsafe {
                lib_ruby_parser_token_blob_new(
                    token_type,
                    token_value.into_blob(),
                    loc,
                    lex_state_before.get(),
                    lex_state_after.get(),
                )
            };
            Self { blob }
        }

        fn token_type(&self) -> i32 {
            unsafe { lib_ruby_parser_token_blob_get_token_type(self.blob) }
        }

        fn token_value(&self) -> &Bytes {
            let token_blob_ptr: *const TokenBlob = &self.blob;
            let bytes_ptr = unsafe {
                lib_ruby_parser_token_blob_borrow_token_value(token_blob_ptr) as *const Bytes
            };
            unsafe { bytes_ptr.as_ref().unwrap() }
        }

        fn set_token_value(&mut self, token_value: Bytes) {
            self.blob =
                unsafe { lib_ruby_parser_token_set_token_value(self.blob, token_value.into_blob()) }
        }

        fn into_token_value(self) -> Bytes {
            let bytes_blob = unsafe { lib_ruby_parser_token_blob_into_token_value(self.blob) };
            std::mem::forget(self);
            Bytes { blob: bytes_blob }
        }

        fn loc(&self) -> Loc {
            unsafe { lib_ruby_parser_token_blob_borrow_loc(self.blob) }
        }

        fn lex_state_before(&self) -> LexState {
            let value = unsafe { lib_ruby_parser_token_blob_get_lex_state_before(self.blob) };
            let mut lex_state = LexState::default();
            lex_state.set(value);
            lex_state
        }

        fn lex_state_after(&self) -> LexState {
            let value = unsafe { lib_ruby_parser_token_blob_get_lex_state_after(self.blob) };
            let mut lex_state = LexState::default();
            lex_state.set(value);
            lex_state
        }
    }

    #[cfg(test)]
    mod tests {
        use super::{Bytes, BytesTrait, LexState, Loc, Token, TokenTrait, TOKEN_SIZE};

        #[test]
        fn test_size() {
            assert_eq!(std::mem::size_of::<Token>(), TOKEN_SIZE);
        }

        fn lex_state(value: i32) -> LexState {
            let mut lex_state = LexState::default();
            lex_state.set(value);
            lex_state
        }

        fn new_token() -> Token {
            Token::new(
                1,
                Bytes::new(vec![1, 2, 3]),
                Loc { begin: 1, end: 2 },
                lex_state(1),
                lex_state(2),
            )
        }

        #[test]
        fn test_new() {
            let token = new_token();
            drop(token);
        }

        #[test]
        fn test_token_type() {
            let token = new_token();
            assert_eq!(token.token_type(), 1)
        }

        #[test]
        fn test_token_value() {
            let token = new_token();
            assert_eq!(token.token_value(), &Bytes::new(vec![1, 2, 3]));
        }

        #[test]
        fn test_set_token_value() {
            let mut token = new_token();
            token.set_token_value(Bytes::new(vec![4, 5, 6]));
            assert_eq!(token.token_value(), &Bytes::new(vec![4, 5, 6]));
        }

        #[test]
        fn test_into_token_value() {
            let token = new_token();
            assert_eq!(token.into_token_value(), Bytes::new(vec![1, 2, 3]))
        }

        #[test]
        fn test_loc() {
            let token = new_token();
            assert_eq!(token.loc(), Loc { begin: 1, end: 2 });
        }

        #[test]
        fn test_lex_state_before() {
            let token = new_token();
            assert_eq!(token.lex_state_before(), lex_state(1));
        }

        #[test]
        fn test_lex_state_after() {
            let token = new_token();
            assert_eq!(token.lex_state_after(), lex_state(2));
        }
    }
}

pub use token::Token;