moore-svlog-syntax 0.7.0

The SystemVerilog parser implementation of the moore compiler framework.
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
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
// Copyright (c) 2016-2020 Fabian Schuiki

//! A preprocessor for SystemVerilog files that takes the raw stream of
//! tokens generated by a lexer and performs include and macro
//! resolution.

use crate::cat::*;
use moore_common::errors::{DiagBuilder2, DiagResult2};
use moore_common::source::*;
use std::{collections::HashMap, fmt, path::Path, rc::Rc};

type TokenAndSpan = (CatTokenKind, Span);

pub struct Preprocessor<'a> {
    /// The stack of input files. Tokens are taken from the topmost stream until
    /// the end of input, at which point the stream is popped and the process
    /// continues with the next stream. Used to handle include files.
    stack: Vec<Stream<'a>>,
    /// References to the source contents that were touched by the preprocessor.
    /// Keeping these around ensures that all emitted tokens remain valid (and
    /// point to valid memory locations) at least until the preprocessor is
    /// dropped.
    contents: Vec<Rc<dyn SourceContent>>,
    /// The current token, or None if either the end of the stream has been
    /// encountered, or at the beginning when no token has been read yet.
    token: Option<TokenAndSpan>,
    /// The defined macros.
    macro_defs: HashMap<String, Macro>,
    /// The stack used to inject expanded macros into the token stream.
    macro_stack: Vec<TokenAndSpan>,
    /// The paths that are searched for included files, besides the current
    /// file's directory.
    include_paths: &'a [&'a Path],
    /// The define conditional stack. Whenever a `ifdef, `ifndef, `else, `elsif,
    /// or `endif directive is encountered, the stack is expanded, modified, or
    /// reduced to reflect the kind of conditional block we're in.
    defcond_stack: Vec<Defcond>,
    /// Currently enabled directives.
    dirs: Directives,
}

impl<'a> Preprocessor<'a> {
    /// Create a new preprocessor for the given source file.
    pub fn new(
        source: Source,
        include_paths: &'a [&'a Path],
        macro_defs: &'a [(&'a str, Option<&'a str>)],
    ) -> Preprocessor<'a> {
        let content = source.get_content();
        let content_unbound = unsafe { &*(content.as_ref() as *const dyn SourceContent) };
        let iter = content_unbound.iter();
        let macro_defs = macro_defs
            .into_iter()
            .map(|(name, value)| {
                let body = match value {
                    Some(value) => {
                        // Create dummy sources for each user defined macro.
                        let src = get_source_manager().add_anonymous(*value);
                        let span = Span::new(src, 0, value.len());
                        Cat::new(Box::new(value.char_indices()))
                            .map(|x| (x.0, span))
                            .collect()
                    }
                    None => Vec::new(),
                };
                (
                    name.to_string(),
                    Macro {
                        name: name.to_string(),
                        span: INVALID_SPAN,
                        args: Vec::new(),
                        body: body,
                    },
                )
            })
            .collect();
        Preprocessor {
            stack: vec![Stream {
                source: source,
                iter: Cat::new(iter),
            }],
            contents: vec![content],
            token: None,
            macro_defs,
            macro_stack: Vec::new(),
            include_paths: include_paths,
            defcond_stack: Vec::new(),
            dirs: Default::default(),
        }
    }

    /// Advance to the next token in the input stream.
    fn bump(&mut self) {
        self.token = self.macro_stack.pop();
        if self.token.is_some() {
            return;
        }
        loop {
            self.token = match self.stack.last_mut() {
                Some(stream) => stream
                    .iter
                    .next()
                    .map(|tkn| (tkn.0, Span::new(stream.source, tkn.1, tkn.2))),
                None => return,
            };
            if self.token.is_none() {
                self.stack.pop();
            } else {
                break;
            }
        }
    }

    /// Called whenever we have encountered a backtick followed by a text token.
    /// This function handles all compiler directives and performs file
    /// inclusion and macro expansion.
    fn handle_directive<S: AsRef<str>>(&mut self, dir_name: S, span: Span) -> DiagResult2<()> {
        let dir_name = dir_name.as_ref();
        let dir = DIRECTIVES_TABLE
            .with(|tbl| tbl.get(dir_name).map(|x| *x).unwrap_or(Directive::Unknown));

        match dir {
            Directive::Include => {
                if self.is_inactive() {
                    return Ok(());
                }

                // Skip leading whitespace.
                match self.token {
                    Some((Whitespace, _)) => self.bump(),
                    _ => (),
                }

                // Match the opening double quotes or angular bracket.
                let name_p;
                let name_q;
                let closing = match self.token {
                    Some((Symbol('"'), sp)) => { name_p = sp.end(); self.bump(); '"' },
                    Some((Symbol('<'), sp)) => { name_p = sp.end(); self.bump(); '>' },
                    _ => { return Err(DiagBuilder2::fatal("expected filename inside double quotes (\"...\") or angular brackets (<...>) after `include").span(span))}
                };

                // Accumulate the include path until the closing symbol.
                let mut filename = String::new();
                loop {
                    match self.token {
                        Some((Symbol(c), sp)) if c == closing => {
                            name_q = sp.begin();
                            break;
                        }
                        Some((Newline, sp)) => {
                            return Err(DiagBuilder2::fatal(
                                "expected end of included file's name before line break",
                            )
                            .span(sp));
                        }
                        Some((_, sp)) => {
                            filename.push_str(&sp.extract());
                            self.bump();
                        }
                        None => {
                            return Err(DiagBuilder2::fatal("expected filename after `include directive before the end of the input").span(span));
                        }
                    }
                }

                // Create a new lexer for the included filename and push it onto the
                // stream stack.
                // TODO: Search only system location if `include <...> is used
                let included_source = match self.open_include(&filename, &span.source.get_path()) {
                    Some(src) => src,
                    None => {
                        // TODO: Add notes to the message indicating which files have been tried.
                        return Err(DiagBuilder2::fatal(format!(
                            "cannot open included file \"{}\"",
                            filename
                        ))
                        .span(Span::union(name_p, name_q)));
                    }
                };

                let content = included_source.get_content();
                let content_unbound = unsafe { &*(content.as_ref() as *const dyn SourceContent) };
                let iter = content_unbound.iter();
                self.contents.push(content);
                self.stack.push(Stream {
                    source: included_source,
                    iter: Cat::new(iter),
                });

                self.bump();
                return Ok(());
            }

            Directive::Define => {
                if self.is_inactive() {
                    return Ok(());
                }

                // Skip leading whitespace.
                match self.token {
                    Some((Whitespace, _)) => self.bump(),
                    _ => (),
                }

                // Consume the macro name.
                let (name, name_span) = match self.try_eat_name() {
                    Some(x) => x,
                    None => {
                        return Err(
                            DiagBuilder2::fatal("expected macro name after \"`define\"").span(span)
                        );
                    }
                };
                let mut makro = Macro::new(name.clone(), name_span);

                // NOTE: No whitespace is allowed after the macro name such that
                // the preprocessor does not mistake the a in "`define FOO (a)"
                // for a macro argument.

                // Consume the macro arguments and parameters.
                match self.token {
                    Some((Symbol('('), _)) => {
                        self.bump();
                        loop {
                            // Skip whitespace.
                            match self.token {
                                Some((Whitespace, _)) => self.bump(),
                                Some((Symbol(')'), _)) => break,
                                _ => (),
                            }

                            // Consume the argument name.
                            let (name, name_span) = match self.try_eat_name() {
                                Some(x) => x,
                                _ => {
                                    return Err(DiagBuilder2::fatal(
                                        "expected macro argument name",
                                    )
                                    .span(span));
                                }
                            };
                            makro.args.push(MacroArg::new(name, name_span));
                            // TODO: Support default parameters.

                            // Skip whitespace and either consume the comma that
                            // follows or break out of the loop if a closing
                            // parenthesis is encountered.
                            match self.token {
                                Some((Whitespace, _)) => self.bump(),
                                _ => (),
                            }
                            match self.token {
                                Some((Symbol(','), _)) => self.bump(),
                                Some((Symbol(')'), _)) => break,
                                Some((_, sp)) => return Err(DiagBuilder2::fatal("expected , or ) after macro argument name").span(sp)),
                                None => return Err(DiagBuilder2::fatal("expected closing parenthesis at the end of the macro definition").span(span)),
                            }
                        }
                        self.bump();
                    }
                    _ => (),
                }

                // Skip whitespace between the macro parameters and definition.
                match self.token {
                    Some((Whitespace, _)) => self.bump(),
                    _ => (),
                }

                // Consume the macro definition up to the next newline not preceded
                // by a backslash, ignoring comments, whitespace and newlines.
                loop {
                    match self.token {
                        Some((Newline, _)) => {
                            self.bump();
                            break;
                        }
                        // Some((Whitespace, _)) => self.bump(),
                        // Some((Comment, _)) => self.bump(),
                        Some((Symbol('\\'), _)) => {
                            self.bump();
                            match self.token {
                                Some((Newline, _)) => self.bump(),
                                _ => (),
                            };
                        }
                        Some(x) => {
                            makro.body.push(x);
                            self.bump();
                        }
                        None => break,
                    }
                }

                self.macro_defs.insert(name, makro);
                return Ok(());
            }

            Directive::Undef => {
                if self.is_inactive() {
                    return Ok(());
                }

                // Skip leading whitespace.
                match self.token {
                    Some((Whitespace, _)) => self.bump(),
                    _ => (),
                }

                // Consume the macro name.
                let (name, _) = match self.try_eat_name() {
                    Some(x) => x,
                    None => {
                        return Err(
                            DiagBuilder2::fatal("expected macro name after \"`undef\"").span(span)
                        );
                    }
                };

                // Remove the macro definition.
                self.macro_defs.remove(&name);
                return Ok(());
            }

            Directive::Undefineall => {
                if self.is_inactive() {
                    return Ok(());
                }
                self.macro_defs.clear();
            }

            Directive::Ifdef | Directive::Ifndef | Directive::Elsif => {
                // Skip leading whitespace.
                match self.token {
                    Some((Whitespace, _)) => self.bump(),
                    _ => (),
                }

                // Consume the macro name.
                let name = match self.try_eat_name() {
                    Some((x, _)) => x,
                    _ => {
                        return Err(DiagBuilder2::fatal(format!(
                            "expected macro name after {}",
                            dir_name
                        ))
                        .span(span));
                    }
                };
                let exists = self.macro_defs.contains_key(&name);

                // Depending on the directive, modify the define conditional
                // stack.
                match dir {
                    Directive::Ifdef => self.defcond_stack.push(if self.is_inactive() {
                        Defcond::Done
                    } else if exists {
                        Defcond::Enabled
                    } else {
                        Defcond::Disabled
                    }),
                    Directive::Ifndef => self.defcond_stack.push(if self.is_inactive() {
                        Defcond::Done
                    } else if exists {
                        Defcond::Disabled
                    } else {
                        Defcond::Enabled
                    }),
                    Directive::Elsif => {
                        match self.defcond_stack.pop() {
                            Some(Defcond::Done) |
                            Some(Defcond::Enabled) => self.defcond_stack.push(Defcond::Done),
                            Some(Defcond::Disabled) => self.defcond_stack.push(
                                if self.is_inactive() {
                                    Defcond::Done
                                } else if exists {
                                    Defcond::Enabled
                                } else {
                                    Defcond::Disabled
                                }
                            ),
                            None => return Err(DiagBuilder2::fatal("found `elsif without any preceeding `ifdef, `ifndef, or `elsif directive").span(span))
                        };
                    }
                    _ => unreachable!(),
                }

                return Ok(());
            }

            Directive::Else => {
                match self.defcond_stack.pop() {
                    Some(Defcond::Disabled) => self.defcond_stack.push(Defcond::Enabled),
                    Some(Defcond::Enabled) | Some(Defcond::Done) => {
                        self.defcond_stack.push(Defcond::Done)
                    }
                    None => return Err(DiagBuilder2::fatal(
                        "found `else without any preceeding `ifdef, `ifndef, or `elsif directive",
                    )
                    .span(span)),
                }
                return Ok(());
            }

            Directive::Endif => {
                if self.defcond_stack.pop().is_none() {
                    return Err(DiagBuilder2::fatal("found `endif without any preceeding `ifdef, `ifndef, `else, or `elsif directive").span(span));
                }
                return Ok(());
            }

            // Perform macro substitution. If we're currently inside the
            // inactive region of a define conditional (i.e. disabled or done),
            // don't bother expanding the macro.
            Directive::Unknown => {
                if self.is_inactive() {
                    return Ok(());
                }
                if let Some(ref makro) = unsafe { &*(self as *const Preprocessor) }
                    .macro_defs
                    .get(dir_name)
                {
                    // Consume the macro parameters if the macro definition
                    // contains them.
                    let mut params = HashMap::<String, Vec<TokenAndSpan>>::new();
                    let mut args = makro.args.iter();
                    if !makro.args.is_empty() {
                        // // Skip whitespace.
                        // match self.token {
                        //  Some((Whitespace, _)) => self.bump(),
                        //  _ => ()
                        // }

                        // Consume the opening paranthesis.
                        match self.token {
                            Some((Symbol('('), _)) => self.bump(),
                            _ => {
                                return Err(DiagBuilder2::fatal(
                                    "expected macro parameters in parentheses '(...)'",
                                )
                                .span(span));
                            }
                        }

                        // Consume the macro parameters.
                        'outer: loop {
                            // // Skip whitespace and break out of the loop if the
                            // // closing parenthesis was encountered.
                            // match self.token {
                            //  Some((Whitespace, _)) => self.bump(),
                            //  _ => ()
                            // }
                            match self.token {
                                Some((Symbol(')'), _)) => break,
                                _ => (),
                            }

                            // Fetch the next argument.
                            let arg = match args.next() {
                                Some(arg) => arg,
                                None => {
                                    return Err(DiagBuilder2::fatal(
                                        "superfluous macro parameters",
                                    ));
                                }
                            };

                            // Consume the tokens that make up this argument.
                            // Take care that it is allowed to have parentheses
                            // as macro parameters, which requires bookkeeping
                            // of the parentheses nesting level. If a comma is
                            // encountered, we break out of the inner loop such
                            // that the next parameter will be read. If a
                            // closing parenthesis is encountered, we break out
                            // of the outer loop to finish parameter parsing.
                            let mut param_tokens = Vec::<TokenAndSpan>::new();
                            let mut nesting = 0;
                            loop {
                                match self.token {
                                    // Some((Whitespace, _)) => self.bump(),
                                    // Some((Newline, _)) => self.bump(),
                                    // Some((Comment, _)) => self.bump(),
                                    Some((Symbol(','), _)) if nesting == 0 => {
                                        self.bump();
                                        params.insert(arg.name.clone(), param_tokens);
                                        break;
                                    }
                                    Some((Symbol(')'), _)) if nesting == 0 => {
                                        params.insert(arg.name.clone(), param_tokens);
                                        break 'outer;
                                    }
                                    Some(x @ (Symbol('('), _)) => {
                                        param_tokens.push(x);
                                        self.bump();
                                        nesting += 1;
                                    }
                                    Some(x @ (Symbol(')'), _)) if nesting > 0 => {
                                        param_tokens.push(x);
                                        self.bump();
                                        nesting -= 1;
                                    }
                                    Some(x) => {
                                        param_tokens.push(x);
                                        self.bump();
                                    }
                                    None => {
                                        return Err(DiagBuilder2::fatal(
                                            "expected closing parenthesis after macro parameters",
                                        )
                                        .span(span));
                                    }
                                }
                            }
                        }
                        self.bump();
                    }

                    // Now we have a problem. All the tokens of the macro name
                    // have been parsed and we would like to continue by
                    // injecting the tokens of the macro body, such as to
                    // perform substitution. The token just after the macro use,
                    // e.g. the whitespace in "`foo ", is already in the buffer.
                    // However, we don't want this token to be the next, but
                    // rather have it follow after the macro expansion. To do
                    // this, we need to push the token onto the macro stack and
                    // then call `self.bump()` once the expansion has been added
                    // to the stack.
                    match self.token {
                        Some((x, sp)) => self.macro_stack.push((x, sp)),
                        None => (),
                    }

                    // Push the tokens of the macro onto the stack, potentially
                    // substituting any macro parameters as necessary.
                    if params.is_empty() {
                        self.macro_stack
                            .extend(makro.body.iter().rev().map(|&(tkn, sp)| (tkn, sp)));
                    } else {
                        let mut replacement = Vec::<TokenAndSpan>::new();
                        // TODO: Make this work for argument names that contain
                        // underscores.
                        for tkn in &makro.body {
                            match *tkn {
                                (Text, sp) => match params.get(&sp.extract()) {
                                    Some(substitute) => {
                                        replacement.extend(substitute);
                                    }
                                    None => replacement.push(*tkn),
                                },
                                x => replacement.push(x),
                            }
                        }
                        self.macro_stack
                            .extend(replacement.iter().rev().map(|&(tkn, sp)| (tkn, sp)));
                    }

                    self.bump();
                    return Ok(());
                }
            }

            // Ignore the "`timescale" directive for now.
            Directive::Timescale => {
                while let Some((tkn, _)) = self.token {
                    if tkn == Newline {
                        break;
                    }
                    self.bump();
                }
                return Ok(());
            }

            Directive::CurrentFile => {
                if !self.is_inactive() {
                    self.macro_stack.push((CatTokenKind::Text, span));
                }
                return Ok(());
            }

            Directive::CurrentLine => {
                if !self.is_inactive() {
                    self.macro_stack.push((CatTokenKind::Digits, span));
                }
                return Ok(());
            }

            Directive::Resetall => {
                if !self.is_inactive() {
                    self.dirs = Default::default();
                }
                return Ok(());
            }

            Directive::Celldefine => {
                if !self.is_inactive() {
                    self.dirs.celldefine = true;
                }
                return Ok(());
            }

            Directive::Endcelldefine => {
                if !self.is_inactive() {
                    self.dirs.celldefine = false;
                }
                return Ok(());
            }

            Directive::DefaultNettype => {
                if !self.is_inactive() {
                    // Skip leading whitespace.
                    match self.token {
                        Some((Whitespace, _)) => self.bump(),
                        _ => (),
                    }

                    // Parse the nettype.
                    let tkn = match self.token {
                        Some(tkn @ (Text, _)) => {
                            self.bump();
                            tkn
                        }
                        _ => {
                            return Err(DiagBuilder2::fatal(
                                "expected nettype after `default_nettype",
                            )
                            .span(span));
                        }
                    };

                    // Store the nettype in the directive set.
                    self.dirs.default_nettype = if tkn.1.extract() == "none" {
                        None
                    } else {
                        Some(tkn)
                    };
                    debug!(
                        "Set default_nettype to `{}`",
                        self.dirs
                            .default_nettype
                            .map(|(_, sp)| sp.extract())
                            .unwrap_or_else(|| "none".to_string())
                    );
                }
                return Ok(());
            }

            Directive::BeginKeywords => {
                if !self.is_inactive() {
                    // Skip leading whitespace.
                    match self.token {
                        Some((Whitespace, _)) => self.bump(),
                        _ => (),
                    }

                    // Consume the opening symbol.
                    match self.token {
                        Some((Symbol('"'), _)) => self.bump(),
                        _ => {
                            return Err(DiagBuilder2::fatal("expected `\"` after `begin_keywords")
                                .span(span));
                        }
                    };

                    // Consume the version specifier.
                    let mut spec = String::new();
                    while let Some(tkn) = self.token {
                        if tkn.0 == Symbol('"') {
                            break;
                        }
                        spec.push_str(&tkn.1.extract());
                        self.bump();
                    }

                    // Consume the closing symbol.
                    match self.token {
                        Some((Symbol('"'), _)) => self.bump(),
                        _ => {
                            return Err(DiagBuilder2::fatal(
                                "expected `\"` after version specifier",
                            )
                            .span(span));
                        }
                    };

                    // Parse the version.
                    let spec = match KeywordsDirective::from_str(&spec) {
                        Some(spec) => spec,
                        _ => {
                            return Err(DiagBuilder2::fatal(format!(
                                "unknown `begin_keywords version specifier `{}`",
                                spec
                            ))
                            .span(span));
                        }
                    };
                    self.dirs.keywords.push(spec);
                    debug!("Push keywords; now `{:?}`", self.dirs.keywords.last());
                }
                return Ok(());
            }

            Directive::EndKeywords => {
                if !self.is_inactive() {
                    if self.dirs.keywords.pop().is_none() {
                        return Err(DiagBuilder2::fatal(
                            "`end_keywords without earlier `begin_keywords",
                        )
                        .span(span));
                    }
                    debug!("Pop keywords; now `{:?}`", self.dirs.keywords.last());
                }
                return Ok(());
            }

            Directive::Line => {
                if !self.is_inactive() {
                    // Skip whitespace.
                    match self.token {
                        Some((Whitespace, _)) => self.bump(),
                        _ => (),
                    }

                    // Consume line number.
                    // TODO: Actually make use of this.
                    let _line = match self.token {
                        Some((Digits, sp)) => {
                            self.bump();
                            sp
                        }
                        _ => {
                            return Err(
                                DiagBuilder2::fatal("expected line number after `line").span(span)
                            );
                        }
                    };

                    // Skip whitespace.
                    match self.token {
                        Some((Whitespace, _)) => self.bump(),
                        _ => (),
                    }

                    // Consume the opening symbol.
                    match self.token {
                        Some((Symbol('"'), _)) => self.bump(),
                        _ => {
                            return Err(DiagBuilder2::fatal(
                                "expected `\"` after line number in `line",
                            )
                            .span(span));
                        }
                    };

                    // Consume the file name.
                    let mut filename = String::new();
                    while let Some(tkn) = self.token {
                        if tkn.0 == Symbol('"') {
                            break;
                        }
                        filename.push_str(&tkn.1.extract());
                        self.bump();
                    }

                    // Consume the closing symbol.
                    match self.token {
                        Some((Symbol('"'), _)) => self.bump(),
                        _ => {
                            return Err(DiagBuilder2::fatal(
                                "expected `\"` after filename in `line",
                            )
                            .span(span));
                        }
                    };

                    // Skip whitespace.
                    match self.token {
                        Some((Whitespace, _)) => self.bump(),
                        _ => (),
                    }

                    // Consume level.
                    // TODO: Actually make use of this.
                    let _level = match self.token {
                        Some((Digits, sp)) => {
                            self.bump();
                            sp
                        }
                        _ => {
                            return Err(
                                DiagBuilder2::fatal("expected level after `line").span(span)
                            );
                        }
                    };

                    debug!("Ignoring `line directive");
                }
                return Ok(());
            }

            Directive::UnconnectedDrive => {
                if !self.is_inactive() {
                    // Skip leading whitespace.
                    match self.token {
                        Some((Whitespace, _)) => self.bump(),
                        _ => (),
                    }

                    // Parse the pull type.
                    let tkn = match self.token {
                        Some((Text, _)) => self.token,
                        _ => None,
                    };
                    let pull = match tkn.map(|(_, sp)| sp.extract()).as_ref().map(|s| s.as_str()) {
                        Some("pull0") => UnconnectedDrive::Pull0,
                        Some("pull1") => UnconnectedDrive::Pull1,
                        _ => {
                            return Err(DiagBuilder2::fatal(
                                "expected `pull0` or `pull1` after `unconnected_drive",
                            )
                            .span(span));
                        }
                    };
                    self.bump(); // consume the pull

                    // Store the directive.
                    self.dirs.unconnected_drive = Some(pull);
                    debug!("Set unconnected_drive to {:?}", self.dirs.unconnected_drive);
                }
                return Ok(());
            }

            Directive::NoUnconnectedDrive => {
                if !self.is_inactive() {
                    self.dirs.unconnected_drive = None;
                    debug!("Set unconnected_drive to {:?}", self.dirs.unconnected_drive);
                }
                return Ok(());
            }
        }

        return Err(
            DiagBuilder2::fatal(format!("unknown compiler directive '`{}'", dir_name)).span(span),
        );
    }

    fn open_include(&mut self, filename: &str, current_file: &str) -> Option<Source> {
        // println!("Resolving include '{}' from '{}'", filename, current_file);
        let first = [Path::new(current_file)
            .parent()
            .expect("current file path must have a valid parent")];
        let prefices = first.iter().chain(self.include_paths.iter());
        let sm = get_source_manager();
        for prefix in prefices {
            let mut buf = prefix.to_path_buf();
            buf.push(filename);
            // println!("  trying {}", buf.to_str().unwrap());
            let src = sm.open(buf.to_str().unwrap());
            if src.is_some() {
                return src;
            }
        }
        return None;
    }

    /// Check whether we are inside a disabled define conditional. That is,
    /// whether a preceeding `ifdef, `ifndef, `else, or `elsif directive have
    /// disabled the subsequent code.
    fn is_inactive(&self) -> bool {
        match self.defcond_stack.last() {
            Some(&Defcond::Enabled) | None => false,
            _ => true,
        }
    }

    fn try_eat_name(&mut self) -> Option<(String, Span)> {
        // Eat the first token of the name, which may either be a letter or an
        // underscore.
        let (mut name, mut span) = match self.token {
            Some((Text, sp)) | Some((Symbol('_'), sp)) => (sp.extract(), sp),
            _ => return None,
        };
        self.bump();

        // Eat the remaining tokens of the name, which may be letters, digits,
        // or underscores.
        loop {
            match self.token {
                Some((Text, sp)) | Some((Digits, sp)) | Some((Symbol('_'), sp)) => {
                    name.push_str(&sp.extract());
                    span.expand(sp);
                    self.bump();
                }
                _ => break,
            }
        }

        Some((name, span))
    }
}

impl<'a> Iterator for Preprocessor<'a> {
    type Item = DiagResult2<TokenAndSpan>;

    fn next(&mut self) -> Option<DiagResult2<TokenAndSpan>> {
        // In case this is the first call to next(), the token has not been
        // populated yet. In this case we need to artificially bump the lexer.
        if self.token.is_none() {
            self.bump();
        }
        loop {
            // This is the main loop of the lexer. Upon each iteration the next
            // token is inspected and the lexer decides whether to emit it or
            // not. If no token was emitted (e.g. because it was a preprocessor
            // directive or we're inside an inactive `ifdef block), the loop
            // continues with the next token.
            match self.token {
                Some((Symbol('`'), sp_backtick)) => {
                    self.bump(); // consume the backtick
                    if let Some((name, sp)) = self.try_eat_name() {
                        // We arrive here if the sequence a backtick
                        // followed by text was encountered. In this case we
                        // call upon the handle_directive function to
                        // perform the necessary actions.
                        let dir_span = Span::union(sp_backtick, sp);
                        match self.handle_directive(name, dir_span) {
                            Err(x) => return Some(Err(x)),
                            _ => (),
                        }
                        continue;
                    } else if let Some(tkn @ (Symbol('"'), _)) = self.token {
                        // emit the '"'
                        self.bump();
                        if !self.is_inactive() {
                            return Some(Ok(tkn));
                        }
                    } else if let Some(tkn @ (Symbol('\\'), _)) = self.token {
                        // emit the '\'
                        self.bump();
                        if !self.is_inactive() {
                            return Some(Ok(tkn));
                        }
                    } else if let Some((Symbol('`'), _)) = self.token {
                        self.bump(); // consume the second backtick and ignore
                    } else {
                        return Some(Err(DiagBuilder2::fatal(
                            "expected compiler directive after '`', or '``', '`\"', or '`\\'",
                        )
                        .span(sp_backtick)));
                    }
                }
                _ => {
                    // All tokens other than preprocessor directives are
                    // emitted, unless we're currently inside a disabled define
                    // conditional.
                    if self.is_inactive() {
                        self.bump();
                    } else {
                        let tkn = self.token.map(|x| Ok(x));
                        self.bump();
                        return tkn;
                    }
                }
            }
        }
    }
}

struct Stream<'a> {
    source: Source,
    iter: Cat<'a>,
}

/// The different compiler directives recognized by the preprocessor.
#[derive(Debug, Clone, Copy)]
enum Directive {
    Include,
    Define,
    Undef,
    Undefineall,
    Ifdef,
    Ifndef,
    Else,
    Elsif,
    Endif,
    Timescale,
    CurrentFile,
    CurrentLine,
    Resetall,
    Celldefine,
    Endcelldefine,
    DefaultNettype,
    BeginKeywords,
    EndKeywords,
    Line,
    UnconnectedDrive,
    NoUnconnectedDrive,
    Unknown,
}

impl fmt::Display for Directive {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Directive::Include => write!(f, "`include"),
            Directive::Define => write!(f, "`define"),
            Directive::Undef => write!(f, "`undef"),
            Directive::Undefineall => write!(f, "`undefineall"),
            Directive::Ifdef => write!(f, "`ifdef"),
            Directive::Ifndef => write!(f, "`ifndef"),
            Directive::Else => write!(f, "`else"),
            Directive::Elsif => write!(f, "`elsif"),
            Directive::Endif => write!(f, "`endif"),
            Directive::Timescale => write!(f, "`timescale"),
            Directive::CurrentFile => write!(f, "`__FILE__"),
            Directive::CurrentLine => write!(f, "`__LINE__"),
            Directive::Resetall => write!(f, "`resetall"),
            Directive::Celldefine => write!(f, "`celldefine"),
            Directive::Endcelldefine => write!(f, "`endcelldefine"),
            Directive::DefaultNettype => write!(f, "`default_nettype"),
            Directive::BeginKeywords => write!(f, "`begin_keywords"),
            Directive::EndKeywords => write!(f, "`end_keywords"),
            Directive::Line => write!(f, "`line"),
            Directive::UnconnectedDrive => write!(f, "`unconnected_drive"),
            Directive::NoUnconnectedDrive => write!(f, "`nounconnected_drive"),
            Directive::Unknown => write!(f, "unknown"),
        }
    }
}

thread_local!(static DIRECTIVES_TABLE: HashMap<&'static str, Directive> = {
    let mut table = HashMap::new();
    table.insert("include", Directive::Include);
    table.insert("define", Directive::Define);
    table.insert("undef", Directive::Undef);
    table.insert("undefineall", Directive::Undefineall);
    table.insert("ifdef", Directive::Ifdef);
    table.insert("ifndef", Directive::Ifndef);
    table.insert("else", Directive::Else);
    table.insert("elsif", Directive::Elsif);
    table.insert("endif", Directive::Endif);
    table.insert("__FILE__", Directive::CurrentFile);
    table.insert("__LINE__", Directive::CurrentLine);
    table.insert("resetall", Directive::Resetall);
    table.insert("celldefine", Directive::Celldefine);
    table.insert("endcelldefine", Directive::Endcelldefine);
    table.insert("default_nettype", Directive::DefaultNettype);
    table.insert("begin_keywords", Directive::BeginKeywords);
    table.insert("end_keywords", Directive::EndKeywords);
    table.insert("line", Directive::Line);
    table.insert("unconnected_drive", Directive::UnconnectedDrive);
    table.insert("nounconnected_drive", Directive::NoUnconnectedDrive);
    table.insert("timescale", Directive::Timescale);
    table
});

#[derive(Debug)]
struct Macro {
    name: String,
    span: Span,
    args: Vec<MacroArg>,
    body: Vec<TokenAndSpan>,
}

impl Macro {
    fn new(name: String, span: Span) -> Macro {
        Macro {
            name: name,
            span: span,
            args: Vec::new(),
            body: Vec::new(),
        }
    }
}

#[derive(Debug)]
struct MacroArg {
    name: String,
    span: Span,
}

impl MacroArg {
    fn new(name: String, span: Span) -> MacroArg {
        MacroArg {
            name: name,
            span: span,
        }
    }
}

enum Defcond {
    Done,
    Enabled,
    Disabled,
}

#[derive(Default)]
struct Directives {
    celldefine: bool,
    default_nettype: Option<TokenAndSpan>,
    keywords: Vec<KeywordsDirective>,
    unconnected_drive: Option<UnconnectedDrive>,
}

#[allow(non_camel_case_types)]
#[derive(Debug)]
enum KeywordsDirective {
    Ieee1800_2009,
    Ieee1800_2005,
    Ieee1364_2005,
    Ieee1364_2001,
    Ieee1364_2001_Noconfig,
    Ieee1364_1995,
}

#[derive(Debug)]
enum UnconnectedDrive {
    Pull0,
    Pull1,
}

impl KeywordsDirective {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "1800-2009" => Some(Self::Ieee1800_2009),
            "1800-2005" => Some(Self::Ieee1800_2005),
            "1364-2005" => Some(Self::Ieee1364_2005),
            "1364-2001" => Some(Self::Ieee1364_2001),
            "1364-2001-noconfig" => Some(Self::Ieee1364_2001_Noconfig),
            "1364-1995" => Some(Self::Ieee1364_1995),
            _ => None,
        }
    }
}

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

    fn preproc(input: &str) -> Preprocessor {
        use std::cell::Cell;
        thread_local!(static INDEX: Cell<usize> = Cell::new(0));
        let sm = get_source_manager();
        let idx = INDEX.with(|i| {
            let v = i.get();
            i.set(v + 1);
            v
        });
        let source = sm.add(&format!("test_{}.sv", idx), input);
        Preprocessor::new(source, &[], &[])
    }

    fn check_str(input: &str, expected: &str) {
        let pp = preproc(input);
        let actual: String = pp.map(|x| x.unwrap().1.extract()).collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn include() {
        let sm = get_source_manager();
        sm.add("other.sv", "bar\n");
        sm.add("test.sv", "foo\n`include \"other.sv\"\nbaz");
        let pp = Preprocessor::new(sm.open("test.sv").unwrap(), &[], &[]);
        let actual: Vec<_> = pp.map(|x| x.unwrap().0).collect();
        assert_eq!(actual, &[Text, Newline, Text, Newline, Newline, Text,]);
    }

    #[test]
    fn include_and_define() {
        let sm = get_source_manager();
        sm.add("other.sv", "/* World */\n`define foo 42\nbar");
        sm.add(
            "test.sv",
            "// Hello\n`include \"other.sv\"\n`foo something\n",
        );
        let pp = Preprocessor::new(sm.open("test.sv").unwrap(), &[], &[]);
        let actual: String = pp
            .map(|x| {
                let x = x.unwrap();
                println!("{:?}", x);
                x.1.extract()
            })
            .collect();
        assert_eq!(actual, "// Hello\n/* World */\nbar\n42 something\n");
    }

    #[test]
    #[should_panic(expected = "unknown compiler directive")]
    fn conditional_define() {
        let sm = get_source_manager();
        let source = sm.add("test.sv", "`ifdef FOO\n`define BAR\n`endif\n`BAR");
        let mut pp = Preprocessor::new(source, &[], &[]);
        while let Some(tkn) = pp.next() {
            tkn.unwrap();
        }
    }

    #[test]
    fn macro_args() {
        check_str(
            "`define foo(x,y) {x + y _bar}\n`foo(12, foo)\n",
            "{12 +  foo _bar}\n",
        );
    }

    /// Verify that macros that take no arguments but have parantheses around
    /// their body parse properly.
    #[test]
    fn macro_noargs_parentheses() {
        check_str(
            "`define FOO 4\n`define BAR (`FOO+$clog2(2))\n`BAR",
            "(4+$clog2(2))",
        );
    }

    #[test]
    fn macro_name_with_digits_and_underscores() {
        check_str("`define AXI_BUS21_SV 42\n`AXI_BUS21_SV", "42");
    }
}