preproc 0.2.0

a sane pre-processor for shaders and any other language
Documentation
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
use alloc::vec::Vec;
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
use core::ptr::null;

use beef::Cow;
use smallvec::SmallVec;

use crate::{
    exp::{self, Exp, Op},
    str_from_range, str_from_raw_parts, Config, Line,
};

const MASK: [i32; 17] = {
    let mut index = 0;
    let mut arr = [0; 17];
    loop {
        if index >= arr.len() {
            break;
        }
        arr[index] = ((1 << index) - 1) as i32;
        index += 1;
    }
    arr
};

#[inline(always)]
unsafe fn line<'a>(ptr: *const u8, mut ptr_end: *const u8) -> &'a str {
    // todo: bake inside the Parser::enter fn
    // remove '\r' if any
    let prev = ptr_end.sub(1);
    if ptr <= prev && *prev == b'\r' {
        ptr_end = prev;
    }
    str_from_raw_parts(ptr, ptr_end.offset_from(ptr) as usize)
}

// safety: `alen` and `b.len()` must be up to 16 characters long
#[inline(always)]
unsafe fn start_with(a: __m128i, alen: usize, b: &[u8]) -> bool {
    if alen < b.len() {
        // not enough characters
        return false;
    }

    let cmp_mask = _mm_movemask_epi8(_mm_cmpeq_epi8(a, _mm_loadu_si128(b.as_ptr() as *const _))); // 6 + 1 + 3  cycles
    return (cmp_mask & MASK[b.len()]) == MASK[b.len()];
}

struct Parser {
    ptr: *const u8,
    ptr_end: *const u8,
    line_count: usize,
    line_ptr: *const u8,
}

impl Parser {
    fn new() -> Self {
        Self {
            ptr: null(),
            ptr_end: null(),
            line_count: 0,
            line_ptr: null(),
        }
    }

    #[inline(always)]
    unsafe fn mask_and_find(&mut self, f: impl Fn(__m128i) -> i32) -> bool {
        while self.ptr < self.ptr_end {
            let chunk = _mm_loadu_si128(self.ptr as *const _); // 6 cycles
            let mask = (f)(chunk); // 8 cycles
            if mask != 0 {
                // found something
                let offset = mask.trailing_zeros() as usize;

                // out of bounds check
                self.ptr = self.ptr.add(offset);

                return true;
            } else {
                self.ptr = self.ptr.add(16);
            }
        }

        false
    }

    unsafe fn ignore_space(&mut self) -> bool {
        self.mask_and_find(|chunk| {
            !_mm_movemask_epi8(_mm_or_si128(
                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b' ' as i8)), // 0x20 (32)
                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\t' as i8)), // 0x0B (11)
            )) // 8 cycles
        })
    }

    unsafe fn find(&mut self, ch: u8) -> bool {
        self.mask_and_find(|chunk| {
            _mm_movemask_epi8(_mm_cmpeq_epi8(chunk, _mm_set1_epi8(ch as i8))) // 4 cycles
        })
    }

    unsafe fn find_space_or_enter(&mut self) -> bool {
        self.mask_and_find(|chunk| {
            _mm_movemask_epi8(_mm_or_si128(
                _mm_or_si128(
                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b' ' as i8)), // 0x20 (32)
                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\t' as i8)), // 0x0B (11)
                ),
                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\n' as i8)), // 0x0A (10)
            )) // 10 cycles
        })
    }

    #[inline(always)]
    fn enter(&mut self) {
        self.line_count += 1;
        self.line_ptr = self.ptr;
    }

    #[inline(always)]
    unsafe fn char_pos(&self) -> usize {
        str_from_range(self.line_ptr, self.ptr).chars().count()
    }

    unsafe fn exp<'a, 'b>(&mut self, config: &'b Config) -> Exp<'a> {
        // copied from exp.rs, but modified to support comments and newline
        //
        // uses the shunting yard algorithm
        // https://en.wikipedia.org/wiki/Shunting_yard_algorithm

        #[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
        enum Token {
            And = 0,
            Or = 1,
            Not = 2,
            Noop,
            LParen,
        }

        // translate a [`Token`] to a `Op` and precedence
        const OPERATORS: &[Op<'static>] = &[Op::And, Op::Or, Op::Not];
        const PRECEDENCE: &[usize] = &[0, 0, 1];

        let mut stack: SmallVec<[(Token, *const u8); 16]> = SmallVec::new();
        let mut ops = Vec::with_capacity(16);

        let comment_char = config
            .comment
            .as_bytes()
            .get(0)
            .copied()
            .unwrap_or_default() as i8;
        let comment_rem = config.comment.as_bytes().get(1..).unwrap_or_default();

        let mut token_ptr = self.ptr;

        let break_ch = _mm_set_epi8(
            0,
            0,
            0,
            0,
            0,
            comment_char, // 10
            b'\0' as i8,  // 9
            b'\r' as i8,  // 8
            b'\n' as i8,  // 7
            b'\t' as i8,  // 6
            b' ' as i8,   // 5
            b'!' as i8,   // 4
            b'&' as i8,   // 3
            b'(' as i8,   // 2
            b')' as i8,   // 1
            b'|' as i8,   // 0
        );

        loop {
            if self.ptr >= self.ptr_end {
                break;
            }

            let ch = *self.ptr;
            self.ptr = self.ptr.add(1);

            // doesn't need to check for utf8 continuation bits, because they will be handled in the variable section

            let break_mask =
                unsafe { _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_set1_epi8(ch as _), break_ch)) };

            if break_mask != 0 {
                if break_mask & 0b1111_1011_0110_0000 != 0 {
                    // accept and skip
                    token_ptr = self.ptr;
                    continue;
                }

                if break_mask & 0b1000_0000 != 0 {
                    // enter, roll back and break
                    self.ptr = self.ptr.sub(1);
                    break;
                }

                if break_mask & 0b0000_0100_0000_0000 != 0 {
                    // check if is a comment
                    // todo: usually just less than 4 chars, maybe just use a default `str::starts_with`
                    let chunk = _mm_loadu_si128(self.ptr as *const _); // 6 cycles
                    let len = self.ptr_end.offset_from(self.ptr) as usize;
                    if start_with(chunk, len, comment_rem) {
                        // roll back and break
                        self.ptr = self.ptr.sub(1);
                        break;
                    }
                }

                if break_mask & 0b0000_0100 != 0 {
                    token_ptr = self.ptr; // accept the token
                    stack.push((Token::LParen, self.ptr));
                    continue;
                }

                if break_mask & 0b0000_0010 != 0 {
                    token_ptr = self.ptr; // accept the token
                    loop {
                        if let Some((token, _)) = stack.pop() {
                            if token != Token::LParen {
                                ops.push(unsafe { *OPERATORS.get_unchecked(token as usize) });
                            } else {
                                break;
                            }
                        } else {
                            panic!("unmached `)` {}:{}", self.line_count, self.char_pos());
                        }
                    }
                    continue;
                }

                let op0;
                if break_mask & 0b0000_1000 != 0 {
                    // and
                    if self.ptr >= self.ptr_end || unsafe { *self.ptr } != b'&' {
                        panic!("expecting `&&` {}:{}", self.line_count, self.char_pos());
                    }
                    self.ptr = self.ptr.add(1);
                    op0 = Token::And;
                } else if break_mask & 0b0000_0001 != 0 {
                    // or
                    if self.ptr >= self.ptr_end || unsafe { *self.ptr } != b'|' {
                        panic!("expecting `||` {}:{}", self.line_count, self.char_pos());
                    }
                    self.ptr = self.ptr.add(1);
                    op0 = Token::Or;
                } else if break_mask & 0b0001_0000 != 0 {
                    // not
                    op0 = Token::Not;
                } else {
                    op0 = Token::Noop;
                }
                if op0 != Token::Noop {
                    token_ptr = self.ptr; // accept the token
                    loop {
                        let pre0 = unsafe { *PRECEDENCE.get_unchecked(op0 as usize) };
                        if let Some(&(op1, _)) = stack.last() {
                            if op1 == Token::LParen {
                                break;
                            }
                            let pre1 = unsafe { *PRECEDENCE.get_unchecked(op1 as usize) };
                            if pre0 <= pre1 {
                                ops.push(unsafe { *OPERATORS.get_unchecked(op1 as usize) });
                                stack.pop();
                                continue;
                            }
                        }
                        break;
                    }
                    stack.push((op0, self.ptr));
                    continue;
                }
            }

            // fast path for variable appending
            loop {
                if self.ptr >= self.ptr_end {
                    // accept the token and limit the ptr
                    self.ptr = self.ptr_end;
                } else {
                    // not very good vor short variable names
                    // ignore spaces
                    let break_mask = unsafe {
                        let chunk = _mm_loadu_si128(self.ptr as *const __m128i); // 6 cycles
                        _mm_movemask_epi8(_mm_or_si128(
                            _mm_or_si128(
                                _mm_or_si128(
                                    _mm_or_si128(
                                        _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\r' as i8)),
                                        _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\n' as i8)),
                                    ),
                                    _mm_or_si128(
                                        _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b' ' as i8)),
                                        _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\t' as i8)),
                                    ),
                                ),
                                _mm_or_si128(
                                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'!' as i8)),
                                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'&' as i8)),
                                ),
                            ),
                            _mm_or_si128(
                                _mm_or_si128(
                                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'(' as i8)),
                                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b')' as i8)),
                                ),
                                _mm_or_si128(
                                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'|' as i8)),
                                    _mm_cmpeq_epi8(chunk, _mm_set1_epi8(comment_char)),
                                ),
                            ),
                        )) // 19 + 3 cycles
                    };
                    if break_mask != 0 {
                        // found something
                        let break_offset = break_mask.trailing_zeros() as usize;
                        if break_offset > 0 {
                            // out of bounds check
                            self.ptr = self.ptr.add(break_offset);
                            if self.ptr > self.ptr_end {
                                self.ptr = self.ptr_end;
                            }
                            // accept the token
                        }
                    } else {
                        self.ptr = self.ptr.add(16);
                        continue;
                    }
                }

                // safety: str slice respect the utf8 chars continuation bytes, because it will only split in ascii chars
                let token = unsafe { str_from_range(token_ptr, self.ptr) };
                ops.push(Op::Var(token));

                token_ptr = self.ptr; // accept the token
                break;
            }
        }

        while let Some((token, _)) = stack.pop() {
            if token == Token::LParen {
                panic!("unmached `(` {}:{}", self.line_count, self.char_pos());
            }
            ops.push(unsafe { *OPERATORS.get_unchecked(token as usize) });
        }

        // todo: check if the expression is valid or not

        Exp { ops }
    }

    unsafe fn parse<'a, 'b>(
        &mut self,
        data: &'a str,
        config: &'b Config,
        mut f: impl FnMut(Line<'a>),
    ) {
        // make some assertions about the lenght of the comments
        assert!(
            config.comment.len() <= 16,
            "`comment` \"{}\" exceeded 16 chars limit",
            config.comment
        );

        self.ptr = data.as_ptr();
        self.ptr_end = self.ptr.add(data.len());

        self.line_count = 1;
        self.line_ptr = self.ptr;

        while self.ptr < self.ptr_end {
            if !self.ignore_space() {
                // nothing left
                break;
            }

            let ch = *self.ptr;

            if ch == b'\n' {
                // empty line, notice that the line pointer is inportant
                (f)(Line::Code(str_from_raw_parts(self.line_ptr, 0)));

                // consume '\n'
                self.ptr = self.ptr.add(1);

                self.enter();

                continue;
            }

            if ch == config.special_char {
                // directive
                self.ptr = self.ptr.add(1);

                let len = self.ptr_end.offset_from(self.ptr) as usize;
                if len != 0 {
                    let chunk = _mm_loadu_si128(self.ptr as *const _); // 6 cycles

                    if start_with(chunk, len, b"if") {
                        self.ptr = self.ptr.add(b"if".len());
                        (f)(Line::If(self.exp(config)));
                    } else if start_with(chunk, len, b"elif") {
                        self.ptr = self.ptr.add(b"elif".len());
                        (f)(Line::Elif(self.exp(config)));
                    } else if start_with(chunk, len, b"else") {
                        self.ptr = self.ptr.add(b"else".len());
                        (f)(Line::Else);
                    } else if start_with(chunk, len, b"endif") {
                        self.ptr = self.ptr.add(b"endif".len());
                        (f)(Line::Endif);
                    } else if start_with(chunk, len, b"undef") {
                        self.ptr = self.ptr.add(b"undef".len());

                        // todo: should "undef  \n" case be handled?
                        self.ignore_space();

                        let def_ptr = self.ptr;

                        // todo: usually just less than 4 chars, maybe just use a default `str::starts_with`
                        let chunk = _mm_loadu_si128(self.ptr as *const _); // 6 cycles
                        let len = self.ptr_end.offset_from(self.ptr) as usize;
                        if start_with(chunk, len, config.comment.as_bytes()) {
                            panic!(
                                "missing define name of `define` {}:{}",
                                self.line_count,
                                self.char_pos()
                            );
                        }

                        if !self.find_space_or_enter() {
                            self.ptr = self.ptr_end;
                        }

                        (f)(Line::Undef(str_from_range(def_ptr, self.ptr)));
                    } else if start_with(chunk, len, b"define") {
                        self.ptr = self.ptr.add(b"define".len());

                        // todo: should "undef  \n" case be handled?
                        self.ignore_space();

                        let def_ptr = self.ptr;

                        // todo: usually just less than 4 chars, maybe just use a default `str::starts_with`
                        let chunk = _mm_loadu_si128(self.ptr as *const _); // 6 cycles
                        let len = self.ptr_end.offset_from(self.ptr) as usize;
                        if start_with(chunk, len, config.comment.as_bytes()) {
                            panic!(
                                "missing define name of `define` {}:{}",
                                self.line_count,
                                self.char_pos()
                            );
                        }

                        if !self.find_space_or_enter() {
                            self.ptr = self.ptr_end;
                        }

                        (f)(Line::Def(str_from_range(def_ptr, self.ptr)));
                    } else if start_with(chunk, len, b"include") {
                        self.ptr = self.ptr.add(b"include".len());

                        self.ignore_space();

                        // assert the char is '\"'
                        if self.ptr >= self.ptr_end || *self.ptr != config.include_begin {
                            panic!(
                                "missing start delimiter '{:?}' of `include` {}:{}",
                                char::from_u32_unchecked(config.include_begin as _),
                                self.line_count,
                                self.char_pos()
                            );
                        }

                        // consume delimiter
                        self.ptr = self.ptr.add(1);

                        let inc_ptr = self.ptr;

                        // consume chars until find a \n or a \"

                        if !self.find(config.include_end) {
                            // assert the char is \"
                            panic!(
                                "missing end delimiter '{:?}' of `include` {}:{}",
                                char::from_u32_unchecked(config.include_begin as _),
                                self.line_count,
                                self.char_pos()
                            );
                        }

                        // send a event
                        (f)(Line::Inc(line(inc_ptr, self.ptr)));

                        // consume delimiter
                        self.ptr = self.ptr.add(1);
                    } else {
                        // unknown directives will be treated as lines of code
                        if !self.find(b'\n') {
                            // return the remaning of the the data without going out of bounds
                            self.ptr = self.ptr_end
                        }

                        (f)(Line::Code(line(self.line_ptr, self.ptr)));

                        // skip '\n'
                        self.ptr = self.ptr.add(1);

                        self.enter();

                        continue;
                    }

                    if self.ptr >= self.ptr_end {
                        break;
                    }
                }

                // account for "\r\n" line end format, this is important to avoid output extra `Line::Rem` events
                if *self.ptr == b'\r' {
                    self.ptr = self.ptr.add(1);
                    if self.ptr >= self.ptr_end {
                        break;
                    }
                }

                if *self.ptr != b'\n' {
                    // remaning of the line if any will be treaded as a remaning of a line of code,
                    // unsupported directives also are threaded this way

                    let rem_ptr = self.ptr;

                    if !self.find(b'\n') {
                        // return the remaning of the the data without going out of bounds
                        self.ptr = self.ptr_end;
                    }

                    (f)(Line::Rem(line(rem_ptr, self.ptr)));
                }

                // consume '\n'
                self.ptr = self.ptr.add(1);

                self.enter();

                continue;
            }

            if !self.find(b'\n') {
                // return the remaning of the the data without going out of bounds
                self.ptr = self.ptr_end
            }

            (f)(Line::Code(line(self.line_ptr, self.ptr)));

            // skip '\n'
            self.ptr = self.ptr.add(1);

            self.enter();
        }
    }
}

pub fn parse_file<'a>(input: &'a str, config: &Config, f: impl FnMut(Line<'a>)) {
    let mut parser = Parser::new();
    unsafe { parser.parse(input, config, f) };
}

pub fn parse_exp<'a>(exp: &'a str) -> Result<Exp<'a>, exp::Error> {
    // uses the shunting yard algorithm
    // https://en.wikipedia.org/wiki/Shunting_yard_algorithm

    #[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
    enum Token {
        And = 0,
        Or = 1,
        Not = 2,
        Noop,
        LParen,
    }

    // translate a [`Token`] to a `Op` and precedence
    const OPERATORS: &[Op<'static>] = &[Op::And, Op::Or, Op::Not];
    const PRECEDENCE: &[usize] = &[0, 0, 1];

    let mut stack: SmallVec<[(Token, usize); 16]> = SmallVec::new();
    let mut ops = Vec::with_capacity(16);

    let data = exp.as_bytes();
    let mut offset = 0;
    let mut token_offset = 0;

    let break_ch = unsafe {
        _mm_set_epi8(
            0,
            0,
            0,
            0,
            0,
            0,
            b'\0' as i8,
            b'\r' as i8,
            b'\n' as i8,
            b'\t' as i8, // 6
            b' ' as i8,  // 5
            b'!' as i8,  // 4
            b'&' as i8,  // 3
            b'(' as i8,  // 2
            b')' as i8,  // 1
            b'|' as i8,  // 0
        )
    };

    loop {
        if offset >= data.len() {
            break;
        }

        let ch = unsafe { *data.get_unchecked(offset) };
        offset += 1;

        // doesn't need to check for utf8 continuation bits, because they will be handled in the variable section

        let break_mask =
            unsafe { _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_set1_epi8(ch as _), break_ch)) };

        if break_mask != 0 {
            if break_mask & 0b1111_1111_1110_0000 != 0 {
                // accept and skip
                token_offset = offset;
                continue;
            }

            if break_mask & 0b0000_0100 != 0 {
                token_offset = offset; // accept the token
                stack.push((Token::LParen, offset));
                continue;
            }

            if break_mask & 0b0000_0010 != 0 {
                token_offset = offset; // accept the token
                loop {
                    if let Some((token, _)) = stack.pop() {
                        if token != Token::LParen {
                            ops.push(unsafe { *OPERATORS.get_unchecked(token as usize) });
                        } else {
                            break;
                        }
                    } else {
                        return Err(exp::Error {
                            offset: offset - 1,
                            len: 1,
                            message: Cow::borrowed("unmached `)`"),
                        });
                    }
                }
                continue;
            }

            let op0;
            if break_mask & 0b0000_1000 != 0 {
                // and
                if offset >= data.len() || unsafe { *data.get_unchecked(offset) } != b'&' {
                    return Err(exp::Error {
                        offset: offset - 1,
                        len: 1,
                        message: Cow::borrowed("expecting `&&`"),
                    });
                }
                offset += 1;
                op0 = Token::And;
            } else if break_mask & 0b0000_0001 != 0 {
                // or
                if offset >= data.len() || unsafe { *data.get_unchecked(offset) } != b'|' {
                    return Err(exp::Error {
                        offset: offset - 1,
                        len: 1,
                        message: Cow::borrowed("expecting `||`"),
                    });
                }
                offset += 1;
                op0 = Token::Or;
            } else if break_mask & 0b0001_0000 != 0 {
                // not
                op0 = Token::Not;
            } else {
                op0 = Token::Noop;
            }
            if op0 != Token::Noop {
                token_offset = offset; // accept the token
                loop {
                    let pre0 = unsafe { *PRECEDENCE.get_unchecked(op0 as usize) };
                    if let Some(&(op1, _)) = stack.last() {
                        if op1 == Token::LParen {
                            break;
                        }
                        let pre1 = unsafe { *PRECEDENCE.get_unchecked(op1 as usize) };
                        if pre0 <= pre1 {
                            ops.push(unsafe { *OPERATORS.get_unchecked(op1 as usize) });
                            stack.pop();
                            continue;
                        }
                    }
                    break;
                }
                stack.push((op0, offset));
                continue;
            }
        }

        // fast path for variable appending
        loop {
            if offset >= data.len() {
                // accept the token and clamp the offset
                offset = data.len();
            } else {
                // not very good vor short variable names
                // ignore spaces
                let break_mask = unsafe {
                    let chunk =
                        _mm_loadu_si128(data.get_unchecked(offset) as *const u8 as *const __m128i); // 6 cycles
                    _mm_movemask_epi8(_mm_or_si128(
                        _mm_or_si128(
                            _mm_or_si128(
                                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b' ' as i8)),
                                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\t' as i8)),
                            ),
                            _mm_or_si128(
                                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'!' as i8)),
                                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'&' as i8)),
                            ),
                        ),
                        _mm_or_si128(
                            _mm_or_si128(
                                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'(' as i8)),
                                _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b')' as i8)),
                            ),
                            _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'|' as i8)),
                        ),
                    )) // 13 + 3 cycles
                };
                if break_mask != 0 {
                    // found something
                    let break_offset = break_mask.trailing_zeros() as usize;
                    if break_offset > 0 {
                        // out of bounds check
                        offset += break_offset;
                        if offset > data.len() {
                            offset = data.len();
                        }
                        // accept the token
                    }
                } else {
                    offset += 16;
                    continue;
                }
            }

            // safety: str slice respect the utf8 chars continuation bytes, because it will only split in ascii chars
            let token = unsafe {
                str_from_raw_parts(data.get_unchecked(token_offset), offset - token_offset)
            };
            ops.push(Op::Var(token));

            token_offset = offset; // accept the token
            break;
        }
    }

    while let Some((token, offset)) = stack.pop() {
        if token == Token::LParen {
            return Err(exp::Error {
                offset: offset - 1,
                len: 1,
                message: Cow::borrowed("unmached `(`"),
            });
        }
        ops.push(unsafe { *OPERATORS.get_unchecked(token as usize) });
    }

    // todo: check if the expression is valid or not

    Ok(Exp { ops })
}

#[cfg(test)]
mod tests {
    use std::fmt::Write;

    use super::*;

    fn test(lines: &[Line]) {
        let mut text = String::default();

        for (i, line) in lines.iter().enumerate() {
            write!(text, "{}", line).unwrap();
            if i < lines.len() - 1 {
                text.push('\n');
            }
        }

        let config = Config::default();
        let mut parsed_lines = vec![];
        parse_file(&text, &config, |line| parsed_lines.push(line));

        assert_eq!(parsed_lines, lines, "{}", &text);
    }

    #[test]
    fn no_directives() {
        test(&[
            Line::Code("// some comment"),
            Line::Code(""),
            Line::Code("fn func() -> f32 {"),
            Line::Code("    return 1.0;"),
            Line::Code("}"),
        ]);
    }

    #[test]
    fn inc() {
        test(&[
            Line::Inc("other_fn_header.wgsl"),
            Line::Code("// some comment"),
            Line::Code(""),
            Line::Code("fn func() -> f32 {"),
            Line::Code("    return other_fn(0.0);"),
            Line::Code("}"),
        ]);
    }

    #[test]
    fn ifelse() {
        test(&[
            Line::Code("// some comment"),
            Line::Code(""),
            Line::Code("fn func() -> f32 {"),
            Line::If(Exp::from_str("SHADOWS").unwrap()),
            Line::Code("    return 0.0;"),
            Line::Else,
            Line::Code("    return 1.0;"),
            Line::Endif,
            Line::Code("}"),
        ]);
    }
}