Debian Codegraph @

src/pp_tests.rs

raw symbols SCIP
1 use super::lexer::{self, Token as LexerToken, TokenValue as LexerTokenValue};
2 use super::pp::{convert_lexer_token, Preprocessor, PreprocessorItem};
3 use super::token::{Float, Integer, Location, PreprocessorError, Punct, Token, TokenValue};
4
5 struct NoopPreprocessor<'a> {
6 lexer: lexer::Lexer<'a>,
7 }
8
9 impl<'a> NoopPreprocessor<'a> {
10 pub fn new(input: &'a str) -> NoopPreprocessor {
11 NoopPreprocessor {
12 lexer: lexer::Lexer::new(input),
13 }
14 }
15 }
16
17 impl<'a> Iterator for NoopPreprocessor<'a> {
18 type Item = Result<Token, (PreprocessorError, Location)>;
19
20 fn next(&mut self) -> Option<Self::Item> {
21 loop {
22 match self.lexer.next() {
23 Some(Ok(LexerToken {
24 value: LexerTokenValue::NewLine,
25 ..
26 })) => continue,
27 Some(Ok(token)) => return Some(Ok(convert_lexer_token(token).unwrap())),
28 None => return None,
29 Some(Err(err)) => return Some(Err(err)),
30 }
31 }
32 }
33 }
34
35 #[track_caller]
36 fn check_preprocessed_result(input: &str, expected: &str) {
37 let pp_items: Vec<PreprocessorItem> = Preprocessor::new(input).collect();
38 let noop_items: Vec<PreprocessorItem> = NoopPreprocessor::new(expected).collect();
39
40 assert_eq!(pp_items.len(), noop_items.len());
41 for (pp_item, noop_item) in pp_items.iter().zip(noop_items) {
42 if let (Ok(pp_tok), Ok(ref noop_tok)) = (pp_item, noop_item) {
43 assert_eq!(pp_tok.value, noop_tok.value);
44 } else {
45 unreachable!();
46 }
47 }
48 }
49
50 #[track_caller]
51 fn check_preprocessing_error(input: &str, expected_err: PreprocessorError) {
52 for item in Preprocessor::new(input) {
53 if let Err((err, _)) = item {
54 assert_eq!(err, expected_err);
55 return;
56 }
57 }
58 unreachable!();
59 }
60
61 #[test]
62 fn parse_directive() {
63 // Test parsing a simple directive
64 check_preprocessed_result("#define A B", "");
65
66 // Test parsing a simple directive with comment right after the hash
67 check_preprocessed_result("# /**/ \tdefine A B", "");
68
69 // Test preprocessing directive can only come after a newline
70 check_preprocessing_error("42 #define A B", PreprocessorError::UnexpectedHash);
71
72 // Test not an identifier after the hash
73 check_preprocessing_error(
74 "# ; A B",
75 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Semicolon)),
76 );
77
78 // Test a fake directive
79 check_preprocessing_error("#CoucouLeChat", PreprocessorError::UnknownDirective);
80 }
81
82 #[test]
83 fn parse_error() {
84 // Test preprocessing directive can only come after a newline
85 check_preprocessing_error("#error", PreprocessorError::ErrorDirective);
86 }
87
88 #[test]
89 fn parse_define() {
90 // Test the define name must be an identifier
91 check_preprocessing_error(
92 "#define [",
93 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::LeftBracket)),
94 );
95 check_preprocessing_error(
96 "#define 1.0",
97 PreprocessorError::UnexpectedToken(TokenValue::Float(Float {
98 value: 1.0,
99 width: 32,
100 })),
101 );
102
103 // Test that there must be a name before the new line
104 check_preprocessing_error(
105 "#define
106 A",
107 PreprocessorError::UnexpectedNewLine,
108 );
109
110 // Test putting a garbage character for the define name
111 check_preprocessing_error("#@", PreprocessorError::UnexpectedCharacter);
112 }
113
114 #[test]
115 fn parse_undef() {
116 // Test the define name must be an identifier
117 check_preprocessing_error(
118 "#undef !",
119 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Bang)),
120 );
121
122 // Test that there must be a name before the new line
123 check_preprocessing_error(
124 "#undef
125 A",
126 PreprocessorError::UnexpectedNewLine,
127 );
128 }
129
130 #[test]
131 fn argument_less_define() {
132 // Test a simple case
133 check_preprocessed_result(
134 "#define A B
135 A",
136 "B",
137 );
138
139 // Test an empty define
140 check_preprocessed_result(
141 "#define A
142 A something",
143 "something",
144 );
145
146 // Test a define containing a token that's itself
147 check_preprocessed_result(
148 "#define A A B C
149 A",
150 "A B C",
151 );
152
153 // Test a define invocation followed by () doesn't remove them
154 check_preprocessed_result(
155 "#define A foo
156 A()",
157 "foo()",
158 );
159
160 // Test nesting define
161 check_preprocessed_result(
162 "#define B C
163 #define A B
164 A",
165 "C",
166 );
167
168 // Test nesting with a bunch of empty tokens
169 check_preprocessed_result(
170 "#define D
171 #define C D D
172 #define B C C D D
173 #define A B B C C D D
174 A truc",
175 "truc",
176 );
177
178 // Test line continuation doesn't break the define
179 check_preprocessed_result(
180 "#define C A \\
181 B
182 C",
183 "A B",
184 );
185
186 // Test that multiline comments don't break the define
187 check_preprocessed_result(
188 "#define C A /*
189 */ B
190 C",
191 "A B",
192 );
193
194 // Test that substitution in defines happens at invocation time
195 // Checks both when undefined a ident found in A and redefining it.
196 check_preprocessed_result(
197 "#define B stuff
198 #define C stuffy stuff
199 #define A B C
200 #undef B
201 #undef C
202 #define C :)
203 A",
204 "B :)",
205 );
206
207 // The first token of the define can be a ( if it has whitespace after
208 // the identifier
209 check_preprocessed_result(
210 "#define A ()
211 #define B\t(!
212 #define C/**/(a, b)
213 A B C",
214 "() (! (a, b)",
215 );
216
217 // Check that hashes are disallowed in defines
218 check_preprocessing_error("#define A #", PreprocessorError::UnexpectedHash);
219 }
220
221 #[test]
222 fn function_like_define() {
223 // Test calling a define with 1 argument
224 check_preprocessed_result(
225 "#define A(a) +a+
226 A(1)",
227 "+1+",
228 );
229
230 // Test calling a define with 0 arguments
231 check_preprocessed_result(
232 "#define A() foo
233 A()",
234 "foo",
235 );
236
237 // Test called a define with multiple arguments
238 check_preprocessed_result(
239 "#define A(a, b) b a
240 A(1, 2)",
241 "2 1",
242 );
243
244 // Test not calling a function-like macro just returns the identifier
245 check_preprocessed_result(
246 "#define A(a) foobar
247 A + B",
248 "A + B",
249 );
250
251 // Test that duplicate argument names are disallowed
252 check_preprocessing_error("#define A(a, a) foo", PreprocessorError::DuplicateParameter);
253
254 // Test that non ident or , are disallowed in the parameter list
255 check_preprocessing_error(
256 "#define A(%) foo",
257 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Percent)),
258 );
259 check_preprocessing_error(
260 "#define A(a, %) foo",
261 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Percent)),
262 );
263
264 // Test that starting the param list with a comma is disallowed
265 check_preprocessing_error(
266 "#define A(,a) foo",
267 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Comma)),
268 );
269
270 // Test that two identifier in a row is disallowed
271 check_preprocessing_error(
272 "#define A(a b) foo",
273 PreprocessorError::UnexpectedToken(TokenValue::Ident("b".to_string())),
274 );
275 check_preprocessing_error(
276 "#define A(a, b c) foo",
277 PreprocessorError::UnexpectedToken(TokenValue::Ident("c".to_string())),
278 );
279
280 // Test passing too many arguments is disallowed
281 check_preprocessing_error(
282 "#define A(a, b) foo
283 A(1, 2, 3)",
284 PreprocessorError::TooManyDefineArguments,
285 );
286
287 // Test passing too few arguments is disallowed
288 check_preprocessing_error(
289 "#define A(a, b) foo
290 A(1)",
291 PreprocessorError::TooFewDefineArguments,
292 );
293
294 // Test passing no argument to a define with one parameter.
295 check_preprocessed_result(
296 "#define A(a) foo a
297 A()",
298 "foo",
299 );
300
301 // Test EOF while parsing define arguments
302 check_preprocessing_error(
303 "#define A(a, b) foo
304 A(",
305 PreprocessorError::UnexpectedEndOfInput,
306 );
307
308 // Test unknown token while parsing define arguments
309 check_preprocessing_error(
310 "#define A(a) foo
311 A($)",
312 PreprocessorError::UnexpectedCharacter,
313 );
314
315 // Test #error while parsing arguments
316 check_preprocessing_error(
317 "#define A(a) foo
318 A(
319 #error
320 )",
321 PreprocessorError::ErrorDirective,
322 );
323
324 // Test that commas inside () are not used to split parameters
325 check_preprocessed_result(
326 "#define STUFF(a, b) a + b
327 STUFF((1, 2), 3)",
328 "(1, 2) + 3",
329 );
330
331 // Test that commas inside more nesting
332 check_preprocessed_result(
333 "#define STUFF(a, b) a + b
334 STUFF((((()1, 2))), 3)",
335 "(((()1, 2))) + 3",
336 );
337
338 // Test that a macro can be used in its own arguments
339 check_preprocessed_result(
340 "#define B(foo) (foo)
341 B(1 B(2))",
342 "(1 (2))",
343 );
344
345 // Test that define expansion doesn't happen while parsing define call arguments. If it
346 // were, the COMMA would make a third argument to A appear, which would be an error.
347 check_preprocessed_result(
348 "#define A(x, y) x + y
349 #define COMMA ,
350 A(1 COMMA 2, 3)",
351 "1, 2 + 3",
352 );
353
354 // Test that define expansion of arguments happens before giving tokens in the define
355 // call. If it weren't the COMMA wouldn't make a second argument to A appear, which would
356 // be an error.
357 check_preprocessed_result(
358 "#define A(x, y) x + y
359 #define COMMA ,
360 #define B(foo) A(foo)
361 B(1 COMMA 2)",
362 "1 + 2",
363 );
364
365 // Same but checking args are fully expanded by doing some weird nesting. The inner B's
366 // call to A will create the token that will cause the outer B to call A with two arguments
367 check_preprocessed_result(
368 "#define A(a, b) ,(a + b)
369 #define B(foo) A(foo)
370 #define COMMA ,
371 B(1 B(2 COMMA 3))",
372 ",(1 + (2 + 3))",
373 );
374
375 // Test that the ( , and ) can come from the expansion of an argument.
376 check_preprocessed_result(
377 "#define LPAREN (
378 #define COMMA ,
379 #define RPAREN )
380 #define A(a, b) (a + b)
381 #define B(a) a
382 B(A LPAREN 1 COMMA 2 RPAREN)",
383 "(1 + 2)",
384 );
385
386 // Test that a define being expanded cannot be re-expanded inside an argument to an inner
387 // define call.
388 check_preprocessed_result(
389 "#define LPAREN (
390 #define COMMA ,
391 #define RPAREN )
392 #define A(a) a
393 #define B(a) a
394 #define C B(A(C))
395 C",
396 "C",
397 );
398
399 // Test that an error during define argument expansion gets surfaced properly.
400 check_preprocessing_error(
401 "#define A(x, y) x + y
402 #define COMMA ,
403 #define B(foo) A(1, foo)
404 B(2 COMMA 3)",
405 PreprocessorError::TooManyDefineArguments,
406 );
407
408 // Test putting comments inside the arguments to a function-like macro
409 check_preprocessed_result(
410 "#define A(x, y) x + y
411 A(/*this is a 2*/ 2,
412 // And below is a 3!
413 3
414 )",
415 "2 + 3",
416 );
417 }
418
419 #[test]
420 fn define_redefinition() {
421 // Test that it is valid to redefine a define with the same tokens.
422 // Function-like case.
423 check_preprocessed_result(
424 "#define A(x, y) (x + y)
425 #define A(x, y) (x + y)",
426 "",
427 );
428 // Not function-like case.
429 check_preprocessed_result(
430 "#define A (x, y)
431 #define A (x, y)",
432 "",
433 );
434
435 // Oh no a token is different!
436 check_preprocessing_error(
437 "#define A (a, y)
438 #define A (x, y)",
439 PreprocessorError::DefineRedefined,
440 );
441
442 // Oh no, one has more tokens!
443 check_preprocessing_error(
444 "#define A a b
445 #define A a",
446 PreprocessorError::DefineRedefined,
447 );
448
449 // Oh no, one is function-like and not the other
450 check_preprocessing_error(
451 "#define A a
452 #define A() a",
453 PreprocessorError::DefineRedefined,
454 );
455
456 // Oh no, a parameter name is different!
457 check_preprocessing_error(
458 "#define A(b) a
459 #define A(c) a",
460 PreprocessorError::DefineRedefined,
461 );
462
463 // Oh no, the parameter count is different!
464 check_preprocessing_error(
465 "#define A(b, d) a
466 #define A(c) a",
467 PreprocessorError::DefineRedefined,
468 );
469
470 // Oh no, the parameter order is different!
471 check_preprocessing_error(
472 "#define A(b, d) a
473 #define A(d, b) a",
474 PreprocessorError::DefineRedefined,
475 );
476 }
477
478 #[test]
479 fn define_undef() {
480 // Basic test
481 check_preprocessed_result(
482 "#define A B
483 #undef A
484 A",
485 "A",
486 );
487
488 // It is ok to undef a non-existent define
489 check_preprocessed_result(
490 "#undef A
491 A",
492 "A",
493 );
494
495 // It is ok to undef a define twice
496 check_preprocessed_result(
497 "#define A B
498 #undef A
499 #undef A
500 A",
501 "A",
502 );
503 }
504
505 #[test]
506 fn parse_if() {
507 // Basic test of parsing and operations.
508 check_preprocessed_result(
509 "#if 0
510 1
511 #endif
512 #if 1
513 2
514 #endif",
515 "2",
516 );
517
518 // Check that garbage tokens are allowed if we are skipping.
519 check_preprocessed_result(
520 "#if 0
521 #if % ^ * )
522 #endif
523 #endif",
524 "",
525 );
526
527 // Check a couple simple expressions
528 check_preprocessed_result(
529 "#define FOO
530 #if defined(FOO)
531 A
532 #endif",
533 "A",
534 );
535 check_preprocessed_result(
536 "#if defined FOO
537 A
538 #endif",
539 "",
540 );
541 check_preprocessed_result(
542 "#define FOO 0
543 #if FOO
544 A
545 #endif",
546 "",
547 );
548
549 check_preprocessed_result(
550 "#define FOO FOO
551 #if FOO
552 #endif",
553 "",
554 );
555
556 check_preprocessed_result(
557 "#define FOO 1
558 #define BAR 1
559 #if (FOO & BAR) == 1
560 2
561 #endif",
562 "2",
563 );
564
565 check_preprocessed_result(
566 "#if 1 + -2 * 3 == -5
567 2
568 #endif",
569 "2",
570 );
571
572 check_preprocessed_result(
573 "#if 4 % 3 == 1
574 2
575 #endif",
576 "2",
577 );
578
579 check_preprocessed_result(
580 "#if 4 / 3 == 1
581 2
582 #endif",
583 "2",
584 );
585
586 // TODO test that the if_parse gives back the unused tokens
587 // TODO test expressions?
588 }
589
590 #[test]
591 fn parse_ifdef() {
592 // Basic test of parsing and operations.
593 check_preprocessed_result(
594 "#define A
595 #ifdef B
596 1
597 #endif
598 #ifdef A
599 2
600 #endif",
601 "2",
602 );
603
604 // Check that extra tokens after the identifier are disallowed.
605 check_preprocessing_error(
606 "#ifdef B ;
607 #endif",
608 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Semicolon)),
609 );
610
611 // Check that the identifier is required.
612 check_preprocessing_error(
613 "#ifdef
614 #endif",
615 PreprocessorError::UnexpectedNewLine,
616 );
617
618 // Check that extra tokens are allowed if we are skipping.
619 check_preprocessed_result(
620 "#if 0
621 #ifdef B ;
622 #endif
623 #endif",
624 "",
625 );
626
627 // Check that having no identifier is allowed if we are skipping.
628 check_preprocessed_result(
629 "#if 0
630 #ifdef
631 #endif
632 #endif",
633 "",
634 );
635 }
636
637 #[test]
638 fn parse_ifndef() {
639 // Basic test of parsing and operations.
640 check_preprocessed_result(
641 "#define A
642 #ifndef B
643 1
644 #endif
645 #ifndef A
646 2
647 #endif",
648 "1",
649 );
650
651 // Check that extra tokens after the identifier are disallowed.
652 check_preprocessing_error(
653 "#ifndef B ;
654 #endif",
655 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Semicolon)),
656 );
657
658 // Check that the identifier is required.
659 check_preprocessing_error(
660 "#ifndef
661 #endif",
662 PreprocessorError::UnexpectedNewLine,
663 );
664
665 // Check that extra tokens are allowed if we are skipping.
666 check_preprocessed_result(
667 "#if 0
668 #ifndef B ;
669 #endif
670 #endif",
671 "",
672 );
673
674 // Check that having no identifier is allowed if we are skipping.
675 check_preprocessed_result(
676 "#if 0
677 #ifndef
678 #endif
679 #endif",
680 "",
681 );
682 }
683
684 #[test]
685 fn parse_elif() {
686 // Basic test of using elif
687 check_preprocessed_result(
688 "#if 1
689 1
690 #elif 1
691 2
692 #endif
693 #if 0
694 3
695 #elif 1
696 4
697 #elif 0
698 5
699 #endif",
700 "1 4",
701 );
702
703 // Check that #elif must appear in a block
704 check_preprocessing_error(
705 "#elif
706 aaa",
707 PreprocessorError::ElifOutsideOfBlock,
708 );
709
710 // Check that #elif must appear before the #else
711 check_preprocessing_error(
712 "#if 0
713 #else
714 #elif 1
715 #endif",
716 PreprocessorError::ElifAfterElse,
717 );
718
719 // Check that #elif must appear before the #else even when skipping
720 check_preprocessing_error(
721 "#if 0
722 #if 0
723 #else
724 #elif 1
725 #endif
726 #endif",
727 PreprocessorError::ElifAfterElse,
728 );
729
730 // Check that the condition isn't processed if the block is skipped.
731 check_preprocessed_result(
732 "#if 0
733 #if 1
734 #elif # !
735 #endif
736 #endif",
737 "",
738 );
739
740 // Check that the condition isn't processed if a previous segment was used.
741 check_preprocessed_result(
742 "#if !defined(FOO)
743 #elif # !
744 #endif
745
746 #if 0
747 #elif 1
748 #elif # %
749 #endif",
750 "",
751 );
752
753 // Check that elif isn't taken if at least one block was taken.
754 check_preprocessed_result(
755 "#if 1
756 A
757 #elif 1
758 B
759 #endif
760
761 #if 0
762 C
763 #elif 1
764 D
765 #elif 1
766 E
767 #endif",
768 "A D",
769 );
770 }
771
772 #[test]
773 fn parse_else() {
774 // Basic test of using else with if and elif
775 check_preprocessed_result(
776 "#if 0
777 1
778 #else
779 2
780 #endif
781 #if 0
782 3
783 #elif 0
784 4
785 #else
786 5
787 #endif",
788 "2 5",
789 );
790
791 // Check that #else must appear in a block
792 check_preprocessing_error(
793 "#else
794 aaa",
795 PreprocessorError::ElseOutsideOfBlock,
796 );
797
798 // Check that else can only appear once in a block, when skipping or not.
799 check_preprocessing_error(
800 "#if 0
801 #else
802 #else
803 #endif",
804 PreprocessorError::MoreThanOneElse,
805 );
806 check_preprocessing_error(
807 "#if 0
808 #if 0
809 #else
810 #else
811 #endif
812 #endif",
813 PreprocessorError::MoreThanOneElse,
814 );
815
816 // Check that else isn't taken if at least one block was taken.
817 check_preprocessed_result(
818 "#if 1
819 A
820 #else
821 B
822 #endif
823 #if 0
824 C
825 #elif 1
826 D
827 #else
828 E
829 #endif",
830 "A D",
831 );
832
833 // Check that else isn't taken if it's skipped from the outside.
834 check_preprocessed_result(
835 "#if 0
836 #if 0
837 #else
838 FOO
839 #endif
840 #endif",
841 "",
842 );
843 }
844
845 #[test]
846 fn parse_endif() {
847 // Basic test of using endif
848 check_preprocessed_result(
849 "#if 0
850 a
851 #endif
852 b",
853 "b",
854 );
855
856 // Check that extra tokens are disallowed.
857 check_preprocessing_error(
858 "#if 1
859 #endif %",
860 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Percent)),
861 );
862
863 // Check that extra tokens are disallowed even for an inner_skipped block.
864 check_preprocessing_error(
865 "#if 0
866 #endif %",
867 PreprocessorError::UnexpectedToken(TokenValue::Punct(Punct::Percent)),
868 );
869
870 // Check that extra tokens are allowed if we are skipping.
871 check_preprocessed_result(
872 "#if 0
873 #if 0
874 #endif %
875 #endif",
876 "",
877 );
878
879 // Check that a missing endif triggers an error, nest and unnested case.
880 check_preprocessing_error("#if 0", PreprocessorError::UnfinishedBlock);
881 check_preprocessing_error(
882 "#if 1
883 #if 0
884 #endif",
885 PreprocessorError::UnfinishedBlock,
886 );
887
888 // Check that endif must be well nested with ifs.
889 check_preprocessing_error("#endif", PreprocessorError::EndifOutsideOfBlock);
890 check_preprocessing_error(
891 "#if 1
892 #endif
893 #endif",
894 PreprocessorError::EndifOutsideOfBlock,
895 );
896 }
897
898 #[test]
899 fn skipping_behavior() {
900 // Check regular tokens are skipped
901 check_preprocessed_result(
902 "#if 0
903 a b % 1 2u
904 #endif",
905 "",
906 );
907 // Check random hash is allowed while skipping
908 check_preprocessed_result(
909 "#if 0
910 a # b
911 #endif",
912 "",
913 );
914
915 // Check that a hash at the start of the line and nothing else if valid while skipping
916 check_preprocessed_result(
917 "#if 0
918 #
919 #endif",
920 "",
921 );
922
923 // Check invalid directives are allowed while skipping
924 check_preprocessed_result(
925 "#if 0
926 #CestlafauteaNandi
927 #endif",
928 "",
929 );
930
931 // Check that defines skipped (otherwise there would be a redefinition error)
932 check_preprocessed_result(
933 "#if 0
934 #define A 1
935 #endif
936 #define A 2",
937 "",
938 );
939
940 // Check that undefs are skipped.
941 check_preprocessed_result(
942 "#define A 1
943 #if 0
944 #undef A
945 #endif
946 A",
947 "1",
948 );
949
950 // Check that #error is skipped.
951 check_preprocessed_result(
952 "#if 0
953 #error
954 #endif",
955 "",
956 );
957
958 // Check that #line directives are skipped.
959 check_preprocessed_result(
960 "#if 0
961 #line 1000
962 #endif
963 __LINE__",
964 "4u",
965 );
966
967 // Check that #version/extension/pragma are skipped.
968 check_preprocessed_result(
969 "#if 0
970 #version a b c
971 #extension 1 2 3
972 #pragma tic
973 #endif",
974 "",
975 );
976 }
977
978 #[test]
979 fn parse_line() {
980 // Test that #line with a uint and int is allowed.
981 check_preprocessed_result(
982 "#line 4u
983 #line 3
984 #line 0xF00
985 __LINE__",
986 "0xF01u",
987 );
988
989 // Test with something other than a number after #line (including a newline)
990 check_preprocessing_error("#line !", PreprocessorError::UnexpectedEndOfInput);
991 check_preprocessing_error("#line", PreprocessorError::UnexpectedEndOfInput);
992 check_preprocessing_error(
993 "#line foo",
994 PreprocessorError::UnexpectedToken(TokenValue::Ident("foo".into())),
995 );
996
997 // Test that an invalid #line directive is allowed if skipping
998 check_preprocessed_result(
999 "#if 0
1000 #line !
1001 #endif
1002 __LINE__",
1003 "4u",
1004 );
1005 // Test that #line must have a newline after the integer (this will change when #line
1006 // supports constant expressions)
1007 check_preprocessing_error("#line 1 #", PreprocessorError::UnexpectedHash);
1008
1009 // test that the integer must fit in a u32
1010 check_preprocessing_error("#line 4294967296u", PreprocessorError::LineOverflow);
1011 // test that the integer must fit in a u32
1012 check_preprocessed_result("#line 4294967295u", "");
1013 check_preprocessing_error("#line -1", PreprocessorError::LineOverflow);
1014
1015 // Test some expression
1016 check_preprocessed_result(
1017 "#line 20 << 2 + 1
1018 __LINE__",
1019 "161u",
1020 );
1021 check_preprocessed_result(
1022 "#line 20 * 0 -2 + 100
1023 __LINE__",
1024 "99u",
1025 );
1026 check_preprocessed_result(
1027 "#line 0 (1 << 1 * (10)) % 2
1028 __LINE__",
1029 "1u",
1030 );
1031
1032 // Test passing both a line and file id is allowed.
1033 check_preprocessed_result("#line 0 1", "");
1034
1035 // Test passing more numbers is invalid.
1036 check_preprocessing_error(
1037 "#line 0 1 2",
1038 PreprocessorError::UnexpectedToken(TokenValue::Integer(Integer {
1039 value: 2,
1040 signed: true,
1041 width: 32,
1042 })),
1043 );
1044 }
1045
1046 #[test]
1047 fn line_define() {
1048 // Test that the __LINE__ define gives the number of the line.
1049 check_preprocessed_result(
1050 "__LINE__
1051 __LINE__
1052
1053 __LINE__",
1054 "1u 2u 4u",
1055 );
1056
1057 // Test that __LINE__ split over multiple lines gives the first line.
1058 check_preprocessed_result("__L\\\nINE__", "1u");
1059
1060 // Test that the __LINE__ define used in define gives the invocation's line
1061 check_preprocessed_result(
1062 "#define MY_DEFINE __LINE__
1063 MY_DEFINE
1064 MY\\\n_DEFINE",
1065 "2u 3u",
1066 );
1067
1068 // Test a corner case where the __LINE__ is a peeked token for function-like
1069 // define parsing.
1070 check_preprocessed_result(
1071 "#define A(foo) Bleh
1072 A __LINE__ B",
1073 "A 2u B",
1074 );
1075
1076 // Test that __LINE__ inside function like defines is the position of the closing )
1077 check_preprocessed_result(
1078 "#define B + __LINE__ +
1079 #define A(X, Y) X __LINE__ Y B
1080 A(-, -)
1081 A(-, -
1082 )",
1083 "- 3u - + 3u +
1084 - 5u - + 5u +",
1085 );
1086
1087 // Test that the __LINE__ inside a define's argument get the correct value.
1088 check_preprocessed_result(
1089 "#define A(X) X
1090 A(__LINE__
1091 __LINE__)",
1092 "2u 3u",
1093 );
1094 check_preprocessed_result(
1095 "#define B(X) X
1096 #define A(X) B(X) + __LINE__
1097 A(__LINE__)",
1098 "3u + 3u",
1099 );
1100
1101 // Check that #line is taken into account and can modify the line number in both directions.
1102 check_preprocessed_result(
1103 "#line 1000
1104 __LINE__
1105 __LINE__
1106
1107 #line 0
1108 __LINE__
1109 __LINE__",
1110 "1001u 1002u 1u 2u",
1111 );
1112
1113 // Check that line computations are not allowed to overflow an u32
1114 check_preprocessed_result(
1115 "#line 4294967294
1116 __LINE__",
1117 "4294967295u",
1118 );
1119 check_preprocessing_error(
1120 "#line 4294967295
1121 __LINE__",
1122 PreprocessorError::LineOverflow,
1123 );
1124
1125 // Check that line directives don't allow floats
1126 check_preprocessing_error(
1127 "#line 1.0",
1128 PreprocessorError::UnexpectedToken(TokenValue::Float(Float {
1129 value: 1.0,
1130 width: 32,
1131 })),
1132 )
1133 }
1134
1135 #[test]
1136 fn parse_version() {
1137 // Check that the #version directive is recognized and gets all the tokens until the newline
1138 let tokens: Vec<PreprocessorItem> = Preprocessor::new("#version 1 ; (").collect();
1139 assert_eq!(tokens.len(), 1);
1140 match &tokens[0] {
1141 Ok(Token {
1142 value: TokenValue::Version(version),
1143 ..
1144 }) => {
1145 assert!(!version.has_comments_before);
1146 assert!(version.is_first_directive);
1147 assert_eq!(version.tokens.len(), 3);
1148 assert_eq!(
1149 version.tokens[0].value,
1150 TokenValue::Integer(Integer {
1151 value: 1,
1152 signed: true,
1153 width: 32
1154 })
1155 );
1156 assert_eq!(version.tokens[1].value, TokenValue::Punct(Punct::Semicolon));
1157 assert_eq!(version.tokens[2].value, TokenValue::Punct(Punct::LeftParen));
1158 }
1159 _ => {
1160 unreachable!();
1161 }
1162 };
1163
1164 // Check that we correctly detect comments before the #version directive.
1165 let tokens: Vec<PreprocessorItem> = Preprocessor::new("/**/#version (").collect();
1166 assert_eq!(tokens.len(), 1);
1167 match &tokens[0] {
1168 Ok(Token {
1169 value: TokenValue::Version(version),
1170 ..
1171 }) => {
1172 assert!(version.has_comments_before);
1173 assert!(version.is_first_directive);
1174 assert_eq!(version.tokens.len(), 1);
1175 assert_eq!(version.tokens[0].value, TokenValue::Punct(Punct::LeftParen));
1176 }
1177 _ => {
1178 unreachable!();
1179 }
1180 };
1181
1182 // Check that we properly detect tokens before the #version directive.
1183 let tokens: Vec<PreprocessorItem> = Preprocessor::new("4 \n #version (").collect();
1184 assert_eq!(tokens.len(), 2);
1185 match &tokens[1] {
1186 Ok(Token {
1187 value: TokenValue::Version(version),
1188 ..
1189 }) => {
1190 assert!(!version.has_comments_before);
1191 assert!(!version.is_first_directive);
1192 assert_eq!(version.tokens.len(), 1);
1193 assert_eq!(version.tokens[0].value, TokenValue::Punct(Punct::LeftParen));
1194 }
1195 _ => {
1196 unreachable!();
1197 }
1198 };
1199
1200 // Same thing but with another preprocessor directive.
1201 let tokens: Vec<PreprocessorItem> = Preprocessor::new("#line 1\n #version (").collect();
1202 assert_eq!(tokens.len(), 1);
1203 match &tokens[0] {
1204 Ok(Token {
1205 value: TokenValue::Version(version),
1206 ..
1207 }) => {
1208 assert!(!version.has_comments_before);
1209 assert!(!version.is_first_directive);
1210 assert_eq!(version.tokens.len(), 1);
1211 assert_eq!(version.tokens[0].value, TokenValue::Punct(Punct::LeftParen));
1212 }
1213 _ => {
1214 unreachable!();
1215 }
1216 };
1217 }
1218
1219 #[test]
1220 fn parse_extension() {
1221 // Check that the #extension directive is recognized and gets all the tokens until the newline
1222 let tokens: Vec<PreprocessorItem> =
1223 Preprocessor::new("#extension USE_WEBGPU_INSTEAD_OF_GL : required").collect();
1224 assert_eq!(tokens.len(), 1);
1225 match &tokens[0] {
1226 Ok(Token {
1227 value: TokenValue::Extension(extension),
1228 ..
1229 }) => {
1230 assert!(!extension.has_non_directive_before);
1231 assert_eq!(extension.tokens.len(), 3);
1232 assert_eq!(
1233 extension.tokens[0].value,
1234 TokenValue::Ident("USE_WEBGPU_INSTEAD_OF_GL".into())
1235 );
1236 assert_eq!(extension.tokens[1].value, TokenValue::Punct(Punct::Colon));
1237 assert_eq!(
1238 extension.tokens[2].value,
1239 TokenValue::Ident("required".into())
1240 );
1241 }
1242 _ => {
1243 unreachable!();
1244 }
1245 };
1246
1247 // Check that we correctly detect non directive tokens before the #extension
1248 let tokens: Vec<PreprocessorItem> = Preprocessor::new("miaou\n#extension").collect();
1249 assert_eq!(tokens.len(), 2);
1250 match &tokens[1] {
1251 Ok(Token {
1252 value: TokenValue::Extension(extension),
1253 ..
1254 }) => {
1255 assert!(extension.has_non_directive_before);
1256 assert_eq!(extension.tokens.len(), 0);
1257 }
1258 _ => {
1259 unreachable!();
1260 }
1261 };
1262 }
1263
1264 #[test]
1265 fn parse_pragma() {
1266 // Check that the #extension directive is recognized and gets all the tokens until the newline
1267 let tokens: Vec<PreprocessorItem> = Preprocessor::new("#pragma stuff").collect();
1268 assert_eq!(tokens.len(), 1);
1269 match &tokens[0] {
1270 Ok(Token {
1271 value: TokenValue::Pragma(pragma),
1272 ..
1273 }) => {
1274 assert_eq!(pragma.tokens.len(), 1);
1275 assert_eq!(pragma.tokens[0].value, TokenValue::Ident("stuff".into()));
1276 }
1277 _ => {
1278 unreachable!();
1279 }
1280 };
1281 }
1282
1283 #[test]
1284 fn add_define() {
1285 // Test adding multiple defines at the start.
1286 let mut pp = Preprocessor::new("A B");
1287 pp.add_define("A", "bat").unwrap();
1288 pp.add_define("B", "man").unwrap();
1289
1290 match pp.next() {
1291 Some(Ok(Token {
1292 value: TokenValue::Ident(ident),
1293 ..
1294 })) => {
1295 assert_eq!(ident, "bat");
1296 }
1297 _ => {
1298 unreachable!();
1299 }
1300 }
1301 match pp.next() {
1302 Some(Ok(Token {
1303 value: TokenValue::Ident(ident),
1304 ..
1305 })) => {
1306 assert_eq!(ident, "man");
1307 }
1308 _ => {
1309 unreachable!();
1310 }
1311 }
1312
1313 // Test that a multiline define works.
1314 let mut pp = Preprocessor::new("A");
1315 pp.add_define("A", "bat\nman").unwrap();
1316
1317 match pp.next() {
1318 Some(Ok(Token {
1319 value: TokenValue::Ident(ident),
1320 ..
1321 })) => {
1322 assert_eq!(ident, "bat");
1323 }
1324 _ => {
1325 unreachable!();
1326 }
1327 }
1328 match pp.next() {
1329 Some(Ok(Token {
1330 value: TokenValue::Ident(ident),
1331 ..
1332 })) => {
1333 assert_eq!(ident, "man");
1334 }
1335 _ => {
1336 unreachable!();
1337 }
1338 }
1339
1340 // Test adding defines in the middle without overwriting.
1341 let mut pp = Preprocessor::new("A A");
1342 match pp.next() {
1343 Some(Ok(Token {
1344 value: TokenValue::Ident(ident),
1345 ..
1346 })) => {
1347 assert_eq!(ident, "A");
1348 }
1349 _ => {
1350 unreachable!();
1351 }
1352 }
1353
1354 pp.add_define("A", "foo").unwrap();
1355 match pp.next() {
1356 Some(Ok(Token {
1357 value: TokenValue::Ident(ident),
1358 ..
1359 })) => {
1360 assert_eq!(ident, "foo");
1361 }
1362 _ => {
1363 unreachable!();
1364 }
1365 }
1366
1367 // Test adding defines in the middle with overwriting.
1368 let mut pp = Preprocessor::new(
1369 "#define A bat
1370 A A",
1371 );
1372 match pp.next() {
1373 Some(Ok(Token {
1374 value: TokenValue::Ident(ident),
1375 ..
1376 })) => {
1377 assert_eq!(ident, "bat");
1378 }
1379 _ => {
1380 unreachable!();
1381 }
1382 }
1383
1384 pp.add_define("A", "foo").unwrap();
1385 match pp.next() {
1386 Some(Ok(Token {
1387 value: TokenValue::Ident(ident),
1388 ..
1389 })) => {
1390 assert_eq!(ident, "foo");
1391 }
1392 _ => {
1393 unreachable!();
1394 }
1395 }
1396
1397 // Test a parsing error.
1398 let mut pp = Preprocessor::new("A");
1399 assert_eq!(
1400 pp.add_define("A", "@").unwrap_err().0,
1401 PreprocessorError::UnexpectedCharacter
1402 );
1403
1404 // Test some crashes detected by fuzzing
1405 let mut pp = Preprocessor::new("#if G/fp");
1406 while let Some(_) = pp.next() {}
1407
1408 let mut pp = Preprocessor::new("\n#if~O%t");
1409 while let Some(_) = pp.next() {}
1410
1411 let mut pp = Preprocessor::new("#if~f>>~f");
1412 while let Some(_) = pp.next() {}
1413 }