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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
/*
    cc6502 - a subset of C compiler for the 6502 processor 
    Copyright (C) 2023 Bruno STEUX 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

    Contact info: bruno.steux@gmail.com
*/

// C preprocessor inspired by minipre (https://github.com/Diggsey/minipre)
// heavily extended in order to support inclusion of files (#include) and macros with parameters

use crate::error::Error;

extern crate regex;

use std::collections::BTreeMap;
use std::io::{BufReader, BufRead, Write};
use std::fs::File;
use std::path::Path;

use log::debug;

use regex::{Regex, RegexSet};
use std::borrow::Cow;

/// The context for preprocessing a file.
///
/// Contains a list of macros and their definitions.
///
#[derive(Debug, Clone)]
pub struct Context {
    current_filename: String,
    includes_stack: Vec<(String, u32)>,
    pub include_directories: Vec<String>,
    defs: BTreeMap<String, String>,
    regex_sets: Vec<RegexSet>,
    defs_ex: Vec::<Vec::<String>>, // Used for undefine to find the vector
    defs_ex_ex: Vec::<Vec::<String>>, // Used to contrust regex_set
    regexes: Vec::<Vec::<(Regex, String)>>,
    define_regex: Regex,
    pub literal_strings: Vec<String>,
    literal_strings_number: u32
}

impl Context {
    /// Creates a new, empty context with no macros defined.
    pub fn new(current_filename: &str) -> Self {
        let mut c = Context {
            current_filename: String::from(current_filename),
            includes_stack: Vec::<(String, u32)>::new(),
            include_directories: Vec::<String>::new(),
            defs: BTreeMap::new(),
            regex_sets: Vec::new(),
            defs_ex: Vec::new(), // Contains the simple string 
            defs_ex_ex: Vec::new(), // Contains the string regexps that will be fed into regex_set
            regexes: Vec::new(),
            define_regex: Regex::new(r"([a-zA-Z_][a-zA-Z0-9_]*)(?:\(((?:(?:[a-zA-Z_][a-zA-Z0-9_]*)\s*,\s*)*(?:(?:[a-zA-Z_][a-zA-Z0-9_]*))*)\))?\s*(.*)").unwrap(),
            literal_strings: Vec::new(),
            literal_strings_number: 0
        };
        c.regex_sets.push(RegexSet::empty());
        c.defs_ex.push(Vec::new());
        c.defs_ex_ex.push(Vec::new());
        c.regexes.push(Vec::new());
        c
    }
    /// Defines a macro within a context. 
    ///
    pub fn define<N: Into<String>, V: Into<String>>(&mut self, name: N, value: V) -> &mut Self {
        let n = name.into();
        let v = value.into();
        let rstring = format!("\\b{}\\b", &n);
        let regex = Regex::new(&rstring).unwrap();
        self.defs.insert(n.clone(), v.clone());
        self.defs_ex.last_mut().unwrap().push(n);
        self.defs_ex_ex.last_mut().unwrap().push(rstring);
        self.regexes.last_mut().unwrap().push((regex, v));
        *self.regex_sets.last_mut().unwrap() = RegexSet::new(self.defs_ex_ex.last().unwrap()).unwrap();
        if self.defs_ex.last().unwrap().len() >= 100 {
            // Create a new regex_set
            self.regex_sets.push(RegexSet::empty());
            self.defs_ex.push(Vec::new());
            self.defs_ex_ex.push(Vec::new());
            self.regexes.push(Vec::new());
        }
        self
    }
    /// ```
    pub fn define_ex<N: Into<String>>(&mut self, name: N, value: (String, String)) -> &mut Self {
        let n = name.into();
        let regex = Regex::new(&value.0).unwrap();
        self.defs.insert(n.clone(), value.0.clone());
        self.defs_ex.last_mut().unwrap().push(n);
        self.defs_ex_ex.last_mut().unwrap().push(value.0);
        self.regexes.last_mut().unwrap().push((regex, value.1));
        *self.regex_sets.last_mut().unwrap() = RegexSet::new(self.defs_ex_ex.last().unwrap()).unwrap();
        if self.defs_ex.last().unwrap().len() >= 100 {
            // Create a new regex_set
            self.regex_sets.push(RegexSet::empty());
            self.defs_ex.push(Vec::new());
            self.defs_ex_ex.push(Vec::new());
            self.regexes.push(Vec::new());
        }
        self
    }

    /// 
    pub fn undefine<N: Into<String>>(&mut self, name: N) -> &mut Self {
        let n = name.into();
        self.defs.remove(&n);
        let mut i = 0;
        let mut k = 0;
        for defs_ex in &self.defs_ex {
            let mut found = false;
            i = 0;
            for j in defs_ex.iter() {
                if j.eq(&n) { 
                    found = true;
                    break; 
                }
                i += 1;
            }
            if found { break; }
            k += 1;
        }
        self.defs_ex[k].remove(i);
        self.defs_ex_ex[k].remove(i);
        self.regexes[k].remove(i);
        self.regex_sets[k] = RegexSet::new(&self.defs_ex_ex[k]).unwrap();
        self
    }

    /// Gets a macro that may or may not be defined from a context.
    pub fn get_macro<N: Into<String>>(&self, name: N) -> Option<&String> {
        self.defs.get(&name.into())
    }

    pub fn replace_all(&self, s: &str) -> String {
        let mut res = String::from(s);
        let mut changed;
        loop {
            changed = false;
            for (i, set) in self.regex_sets.iter().enumerate() {
                for idx in set.matches(s).into_iter() {
                    let x = self.regexes[i][idx].0.replace_all(&res, &self.regexes[i][idx].1);
                    if let Cow::Owned(z) = x {
                        res = z.to_string();
                        changed = true;
                    }
                }
            }
            if !changed {
                break;
            }
        }
        res
    }

    fn skip_whitespace(&self, expr: &mut &str) {
        *expr = expr.trim_start();
    }

    fn eval_term(&self, expr: &mut &str, line: u32) -> Result<bool, Error> {
        self.skip_whitespace(expr);

        let index = expr
            .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
            .unwrap_or(expr.len());
        let term = &expr[0..index];
        *expr = &expr[index..];

        if term
            .chars()
            .next()
            .ok_or_else(|| { 
                let filename = self.current_filename.clone();
                let included_in = self.includes_stack.last().cloned();
                Error::Syntax {
                    filename, included_in, line,
                    msg: "Expected term, found nothing".to_string() }
            })?
        .is_ascii_digit()
        {
            Ok(term == "1")
        } else {
            let filename = self.current_filename.clone();
            let included_in = self.includes_stack.last().cloned();
            Err(Error::Syntax {
                filename, included_in, line,
                msg: "Undefined identifier".to_string(),
            })
        }
    }
    fn eval_unary(&self, expr: &mut &str, line: u32) -> Result<bool, Error> {
        let mut negate = false;
        self.skip_whitespace(expr);
        while expr.starts_with('!') {
            *expr = &expr[1..];
            negate = !negate;
            self.skip_whitespace(expr);
        }

        Ok(negate ^ self.eval_term(expr, line)?)
    }
    fn eval_eq(&self, expr: &mut &str, line: u32) -> Result<bool, Error> {
        let mut result = self.eval_unary(expr, line)?;
        self.skip_whitespace(expr);
        while expr.starts_with("==") {
            *expr = &expr[2..];
            result ^= !self.eval_unary(expr, line)?;
            self.skip_whitespace(expr);
        }
        Ok(result)
    }
    fn evaluate(&self, mut expr: &str, line: u32) -> Result<bool, Error> {
        let result = self.eval_eq(&mut expr, line)?;
        self.skip_whitespace(&mut expr);
        if !expr.is_empty() {
            let filename = self.current_filename.clone();
            let included_in = self.includes_stack.last().cloned();
            return Err(Error::Syntax {
                filename, included_in, line,
                msg: "Expected end-of-line".to_string(),
            });
        }
        Ok(result)
    }
}

#[derive(Eq, PartialEq, Debug, Copy, Clone)]
enum State {
    // A condition already matched, skip remaining clauses
    Skip,
    // Condition has not yet matched, evaluate remaining clauses
    Inactive,
    // Condition currently matches, pass through input
    Active,
}

/// Preprocesses a string.
///
/// This function takes a context and a string, and preprocesses it.
///
#[allow(dead_code)]
pub fn process_str(input: &str, context: &mut Context) -> Result<String, Error> {
    let mut output = Vec::new();
    process(input.as_bytes(), &mut output, context, false)?;
    Ok(String::from_utf8(output).expect("Input was utf8, so output should be too..."))
}

/// Preprocesses a generic buffer.
///
/// This function takes any generic BufRead input and Write output and preprocesses it.
///
pub fn process<I: BufRead, O: Write>(
    mut input: I,
    output: &mut O,
    context: &mut Context,
    asm: bool
) -> Result<Vec::<(std::rc::Rc::<String>,u32,Option<(std::rc::Rc::<String>,u32)>)>, Error> {
    let mut buf = String::new();
    let mut uncommented_buf = String::new();
    let mut stack = Vec::new();
    let mut state = State::Active;
    let mut lines = Vec::<(std::rc::Rc::<String>,u32,Option<(std::rc::Rc::<String>,u32)>)>::new();
    let mut line = 0;
    let filename = context.current_filename.clone();
    let filename_rc = std::rc::Rc::<String>::new(filename.clone());
    let mut in_multiline_comments = false;

    let (included_in, included_in_rc) = match context.includes_stack.last() {
        Some(s) => (Some(s.clone()), Some((std::rc::Rc::<String>::new(s.0.clone()), s.1))),
        None => (None, None),
    };

    while input.read_line(&mut buf)? > 0 {
        line += 1;

        // Process splices by removing them...
        loop {
            if buf.ends_with("\\\n") || buf.ends_with("\\\r\n") {
                if buf.ends_with("\\\r\n") {
                    buf.pop();
                }
                buf.pop();
                buf.pop();
                let mut buf2 = String::new();
                if input.read_line(&mut buf2)? > 0 {
                    buf.push_str(&buf2);
                    line += 1;
                } else {
                    break;
                }
            } else {
                break;
            }
        }

        let has_lf = buf.ends_with('\n');
        let mut remaining: &str = &buf;
        let mut insert_it = !in_multiline_comments;
        uncommented_buf.clear();
        while !remaining.is_empty() {
            if in_multiline_comments {
                let mut s = remaining.splitn(2, "*/");
                s.next().unwrap();
                match s.next() {
                    Some(string) => {
                        in_multiline_comments = false;
                        remaining = string;
                        if !remaining.is_empty() { 
                            if remaining.eq("\n") {
                                remaining = "";
                            } else {
                                insert_it = true; 
                            }
                        }
                    },
                    _ => break
                }
            } else {
                let mut s = remaining.split("//").next().unwrap().splitn(2, "/*");
                // Is there a string start before that point ?
                let s2 = s.next().unwrap();
                if !s2.starts_with("#include") && !asm {
                    if let Some((left, _)) = s2.split_once('"') {
                        // We have a string start
                        // Let's find the end of the string
                        let mut done = false;
                        let mut found = false;
                        let mut cursor = left.len() + 1;
                        while !done {
                            let s3 = &remaining[cursor..];
                            if let Some((left, _)) = s3.split_once('"') {
                                if !left.ends_with("\\") {
                                    found = true;
                                    done = true;
                                    cursor += left.len();
                                } else {
                                    // Let's check it's not an escaped backslash
                                    if left.ends_with("\\\\") {
                                        found = true;
                                        done = true;
                                        cursor += left.len();
                                    } else {
                                        cursor += left.len() + 1;
                                    }
                                }
                            } else {
                                done = true;
                            }
                        }
                        if !found {
                            // This is an unterminated string. Forbidden
                            return Err(Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: "Unterminated string".to_string() })
                        } else {
                            uncommented_buf.push_str(&format!("{}@{}@", left, context.literal_strings_number));
                            context.literal_strings_number += 1;
                            let s = remaining[left.len() + 1..cursor].to_string();
                            debug!("String literal: {:?}", &s);
                            context.literal_strings.push(s);
                            remaining = &remaining[cursor + 1..];
                        }
                    } else {
                        uncommented_buf.push_str(s2);
                        if uncommented_buf.is_empty() { insert_it = false; }
                        match s.next() {
                            Some(string) => {
                                in_multiline_comments = true;
                                remaining = string;
                            },
                            _ => break
                        }
                    }
                } else {
                    uncommented_buf.push_str(s2);
                    if uncommented_buf.is_empty() { insert_it = false; }
                    match s.next() {
                        Some(string) => {
                            in_multiline_comments = true;
                            remaining = string;
                        },
                        _ => break
                    }
                }
            }
            debug!("Line: {}, Uncommented: {:?}, Remaining: {:?}, insert it: {:?}", line, uncommented_buf, remaining, insert_it);
        }
        if insert_it {
            let substr = uncommented_buf.trim();
            // Before substitution, test the #ifdef
            if substr.starts_with("#ifdef") {
                let mut parts = substr.split("//").next().unwrap().splitn(2, ' ');
                parts.next().unwrap();
                let maybe_expr = parts.next().map(|s| s.trim()).and_then(|s| {
                    if s.is_empty() {
                        None
                    } else {
                        Some(s)
                    }
                });
                let expr = match maybe_expr {
                    Some(x) => x,
                    _ => {
                        return Err(Error::Syntax {
                            filename: filename.clone(), included_in: included_in.clone(), line,
                            msg: "Expected something after `#ifdef`".to_string() })

                    }
                };
                stack.push(state);
                if state == State::Active {
                    if context.get_macro(expr).is_none() {
                        state = State::Inactive;
                    }
                } else {
                    state = State::Skip;
                }
            } else if substr.starts_with("#ifndef") {
                let mut parts = substr.split("//").next().unwrap().splitn(2, ' ');
                parts.next().unwrap();
                let maybe_expr = parts.next().map(|s| s.trim()).and_then(|s| {
                    if s.is_empty() {
                        None
                    } else {
                        Some(s)
                    }
                });
                let expr = match maybe_expr {
                    Some(x) => x,
                    _ => {
                        return Err(Error::Syntax {
                            filename: filename.clone(), included_in: included_in.clone(), line,
                            msg: "Expected something after `#ifndef`".to_string() })
                        }
                };
                stack.push(state);
                if state == State::Active {
                    if context.get_macro(expr).is_some() {
                        state = State::Inactive;
                    }
                } else {
                    state = State::Skip;
                }
            } else if substr.starts_with("#undef") {
                if state == State::Active {
                    let mut parts = substr.split("//").next().unwrap().splitn(2, ' ');
                    parts.next().unwrap();
                    let maybe_expr = parts.next().map(|s| s.trim()).and_then(|s| {
                        if s.is_empty() {
                            None
                        } else {
                            Some(s)
                        }
                    });
                    let expr = match maybe_expr {
                        Some(x) => x,
                        _ => {
                            return Err(Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: "Expected something after `#undef`".to_string() })
                        }
                    };

                    if context.get_macro(expr).is_none() {
                        return Err(Error::Syntax {
                            filename: filename.clone(), included_in: included_in.clone(), line,
                            msg: format!("Macro {} is not defined", expr)});
                    }
                    context.undefine(expr);
                } 
            } else if substr.starts_with("#define") {
                if state == State::Active {
                    let mut parts = substr.split("//").next().unwrap().splitn(2, ' ');
                    parts.next().unwrap();
                    let maybe_expr = parts.next().map(|s| s.trim()).and_then(|s| {
                        if s.is_empty() {
                            None
                        } else {
                            Some(s)
                        }
                    });
                    let expr = maybe_expr.ok_or_else(|| Error::Syntax {
                        filename: filename.clone(), included_in: included_in.clone(), line,
                        msg: "Expected macro after `#define`".to_string() })?;
                    debug!("expr: {:?}", expr);
                    
                    let caps = context.define_regex.captures(expr).unwrap();
                    debug!("caps: {:?}", caps);
                    let mcro = &caps[1];
                    if context.get_macro(mcro).is_some() {
                        return Err(Error::Syntax {
                            filename: filename.clone(), included_in: included_in.clone(), line,
                            msg: format!("Macro {} already defined", mcro)});
                    }
                    let buf = &caps[3];
                    let mut value = context.replace_all(buf);
                    if caps.get(2).is_none() {
                        context.define(mcro, value);
                    } else {
                        let mut rex = format!("\\b{}\\(", mcro);
                        let params = caps.get(2).unwrap().as_str();
                        if params != "" {
                            for v in caps.get(2).unwrap().as_str().split(',') {
                                let vx = v.trim_start();
                                let re = Regex::new(&format!("\\b{}\\b", vx)).unwrap();
                                value = re.replace_all(&value, format!("$${}",vx)).to_string();
                                //rex += &format!("(?P<{}>[^,]*?),", vx);
                                rex += &format!(r"(?P<{}>(?:[^,)(]|\((?:[^)(]|\((?:[^)(]|\((?:[^)(]|\([^)(]*\))*\))*\))*\))*),", vx);
                            }
                            rex = rex.strip_suffix(',').unwrap().to_string();
                        }
                        rex += "\\)";
                        debug!("regex:{}", &rex);
                        context.define_ex(mcro, (rex, value));
                    }
                }
            } else { 
                let new_line = context.replace_all(&uncommented_buf);
                let substr = new_line.trim();
                if substr.starts_with('#') {
                    let mut parts = substr.split("//").next().unwrap().splitn(2, ' ');
                    let name = parts.next().unwrap();
                    let maybe_expr = parts.next().map(|s| s.trim()).and_then(|s| {
                        if s.is_empty() {
                            None
                        } else {
                            Some(s)
                        }
                    });

                    match name {
                        "#include" => {
                            if state == State::Active {
                                // Get filename
                                let expr = maybe_expr.ok_or_else(|| Error::Syntax {
                                    filename: filename.clone(), included_in: included_in.clone(), line,
                                    msg: "Expected filename after `#include`".to_string() })?;
                                let mut chars = expr.chars();
                                let separator = chars.next();
                                let end_separator = match separator {
                                    Some('<') => '>',
                                    Some('"') => '"',
                                    _ => return Err(Error::Syntax { filename: filename.clone(), included_in: included_in.clone(), line, msg: "Expected < or \" in #include filename spec".to_string() })
                                };
                                let mut fname = String::new();
                                loop {
                                    let nc = chars.next();
                                    match nc {
                                        Some(x) => if x == end_separator { break; } else { fname.push(x); }, 
                                        None => return Err(Error::Syntax { filename: filename.clone(), included_in: included_in.clone(), line, msg: "Missing end separator in #include fname".to_string() })
                                    }    
                                }

                                // Open include file
                                let mut px;
                                let mut path = Path::new(&fname);
                                if !path.exists() {
                                    let mut found = false;
                                    for p in &context.include_directories {
                                        px = p.clone() + "/" + &fname;
                                        path = Path::new(&px);
                                        if path.exists() {
                                            found = true;
                                            break;
                                        }
                                    }    
                                    if !found {
                                        return Err(Error::Syntax { 
                                            filename: filename.clone(), included_in: included_in.clone(), line, msg: format!("Included file {fname} not found")});
                                    }
                                }

                                // Process file
                                let f = File::open(path)?;
                                let assembler = fname.ends_with(".inc") || fname.ends_with(".a") || fname.ends_with(".asm");
                                if assembler {
                                    lines.push((filename_rc.clone(), line, included_in_rc.clone()));
                                    output.write_all("=== ASSEMBLER BEGIN ===\n".as_bytes())?;
                                    lines.push((filename_rc.clone(), line, included_in_rc.clone()));
                                    output.write_all(format!("; file: {}\n", fname).as_bytes())?;
                                }
                                let f = BufReader::new(f);
                                context.current_filename = fname.clone();
                                context.includes_stack.push((filename.clone(), line));
                                let mut mapped_lines = process(f, output, context, assembler)?;
                                context.includes_stack.pop();
                                context.current_filename = filename.clone();
                                lines.append(&mut mapped_lines);
                                if assembler {
                                    lines.push((filename_rc.clone(), line, included_in_rc.clone()));
                                    output.write_all("==== ASSEMBLER END ====\n".as_bytes())?;
                                }
                            } },
                        "#if" => {
                            let expr = maybe_expr.ok_or_else(|| Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: "Expected expression after `#if`".to_string() })?;
                            stack.push(state);
                            if state == State::Active {
                                if !context.evaluate(expr, line)? {
                                    state = State::Inactive;
                                }
                            } else {
                                state = State::Skip;
                            } },
                        "#elif" => {
                            let expr = maybe_expr.ok_or_else(|| Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line, 
                                msg: "Expected expression after `#elif`".to_string() })?;
                            if state == State::Inactive {
                                if context.evaluate(expr, line)? {
                                    state = State::Active;
                                }
                            } else {
                                state = State::Skip;
                            } },
                        "#else" => {
                            if maybe_expr.is_some() {
                                return Err(Error::Syntax {
                                    filename: filename.clone(), included_in: included_in.clone(), line,
                                    msg: "Unexpected expression after `#else`".to_string() });
                            }
                            if state == State::Inactive {
                                state = State::Active;
                            } else {
                                state = State::Skip;
                            } },
                        "#endif" => {
                            if maybe_expr.is_some() {
                                return Err(Error::Syntax {
                                    filename: filename.clone(), included_in: included_in.clone(), line,
                                    msg: "Unexpected expression after `#else`".to_string() });
                            }
                            state = stack.pop().ok_or_else(|| Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: "Unexpected `#endif` with no matching `#if`".to_string() })?;
                        },
                        "#error" => {
                            let expr = maybe_expr.ok_or_else(|| Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: "Expected error text after `#error`".to_string() })?;
                            return Err(Error::Compiler {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: expr.to_string() });
                        },
                        _ => {
                            return Err(Error::Syntax {
                                filename: filename.clone(), included_in: included_in.clone(), line,
                                msg: "Unrecognised preprocessor directive".to_string() });
                        }
                    }
                } else if state == State::Active {
                    lines.push((filename_rc.clone(), line, included_in_rc.clone()));
                    output.write_all(new_line.as_bytes())?;
                    if !new_line.ends_with('\n') && has_lf { output.write_all(b"\n")?; }
                }
            } 
        }
        buf.clear();
    }
    Ok(lines)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pass_through() {
        assert_eq!(
            &process_str(
                "
            some
            multiline
            text
            with # symbols
        ",
                &mut Context::new("string")
            )
            .unwrap(),
            "
            some
            multiline
            text
            with # symbols
        "
        );
    }

    #[test]
    fn variable() {
        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "1")
            )
            .unwrap(),
            "
            some
            multiline
            text
            with # symbols
        "
        );
    }

    #[test]
    fn constant() {
        assert_eq!(
            &process_str(
                "
            some
            #if 0
            multiline
            text
            #endif
            with # symbols
        ",
                &mut Context::new("string")
            )
            .unwrap(),
            "
            some
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if 1
            multiline
            text
            #endif
            with # symbols
        ",
                &mut Context::new("string")
            )
            .unwrap(),
            "
            some
            multiline
            text
            with # symbols
        "
        );
    }

    #[test]
    fn negation() {
        assert_eq!(
            &process_str(
                "
            some
            #if !FOO
            multiline
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "1")
            )
            .unwrap(),
            "
            some
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if !FOO
            multiline
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            multiline
            text
            with # symbols
        "
        );
    }

    #[test]
    fn else_() {
        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #else
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            text
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #else
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "1")
            )
            .unwrap(),
            "
            some
            multiline
            with # symbols
        "
        );
    }

    #[test]
    fn elif() {
        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #elif 1
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            text
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #elif 1
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "1")
            )
            .unwrap(),
            "
            some
            multiline
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #elif 0
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #elif 0
            text
            #else
            with # symbols
            #endif
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO
            multiline
            #elif 1
            text
            #else
            with # symbols
            #endif
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            text
        "
        );
    }

    #[test]
    fn equality() {
        assert_eq!(
            &process_str(
                "
            some
            #if FOO == 1
            multiline
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            with # symbols
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            #if FOO == 0
            multiline
            text
            #endif
            with # symbols
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            multiline
            text
            with # symbols
        "
        );
    }

    #[test]
    fn expansion() {
        assert_eq!(
            &process_str(
                "
            some
            FOO-BAR
            multiline
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            0-BAR
            multiline
        "
        );

        assert_eq!(
            &process_str(
                "
            some
            FOO_BAR
            multiline
        ",
                Context::new("string").define("FOO", "0")
            )
            .unwrap(),
            "
            some
            FOO_BAR
            multiline
        "
        );
    }
    
    #[test]
    fn multiline_comments() {
        assert_eq!(process_str("
     #if FOO
     foo text /* Bobby */
     #endif
     bar text", Context::new("string").define("FOO", "1")).unwrap(), "
     foo text 
     bar text");

    }

    #[test]
    fn define() {
    assert_eq!(process_str("#define ZOBI
     #define FOO FOO_BAR // JR
     #ifdef FOO
     foo text
     #endif
     FOO /*bar text
     Dallas
     */ Ewing", &mut Context::new("string")).unwrap(), "     foo text
     FOO_BAR 
 Ewing");
    }

    #[test]
    fn lines_mapping() {
        let mut output = Vec::new();
        let result = process("#define ZOBI
            #define FOO FOO_BAR 
            #ifdef FOO
                foo text
            #endif
            FOO bar text".as_bytes(), &mut output, &mut Context::new("string"), false);
        assert_eq!(result.unwrap().iter().map(|x| x.1).collect::<Vec::<u32>>(), &[4, 6]);
    }
    
    #[test]
    fn lines_mapping2() {
        let mut output = Vec::new();
        let result = process("/* Hello */
            world".as_bytes(), &mut output, &mut Context::new("string"), false);
        assert_eq!(result.unwrap().iter().map(|x| x.1).collect::<Vec::<u32>>(), &[2]);
    }
    
    #[test]
    fn error() {
        let mut context = Context::new("string");
        context.current_filename = "string".to_string();
        let result = process_str("#error This is an error
            foo bar", &mut context);
        assert_eq!(result.err().unwrap().to_string(), 
            "Compiler error: This is an error on line 1 of string".to_string()
            );
    }
    
    #[test]
    fn redefine() {
        let mut context = Context::new("string");
        context.current_filename = "string".to_string();
        let result = process_str("#define foobar\n#define foobar", &mut context);
        assert_eq!(result.err().unwrap().to_string(), 
            "Syntax error: Macro foobar already defined on line 2 of string".to_string()
            );
    }
    
    #[test]
    fn define_args() {
        let mut context = Context::new("string");
        context.current_filename = "string".to_string();
        let result = process_str("#define add(a,b) a+b\nadd(1,2)", &mut context);
        println!("{:?}", result);
        assert_eq!(result.unwrap(), 
            "1+2".to_string()
            );
    }
}