-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathPreprocessor.java
More file actions
2227 lines (2021 loc) · 72.4 KB
/
Preprocessor.java
File metadata and controls
2227 lines (2021 loc) · 72.4 KB
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
/*
* Anarres C Preprocessor
* Copyright (c) 2007-2015, Shevek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.anarres.cpp;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.anarres.cpp.PreprocessorCommand.*;
import org.anarres.cpp.PreprocessorListener.SourceChangeEvent;
import static org.anarres.cpp.Token.*;
/**
* A C Preprocessor.
* The Preprocessor outputs a token stream which does not need
* re-lexing for C or C++. Alternatively, the output text may be
* reconstructed by concatenating the {@link Token#getText() text}
* values of the returned {@link Token Tokens}. (See
* {@link CppReader}, which does this.)
*/
/*
* Source file name and line number information is conveyed by lines of the form
*
* # linenum filename flags
*
* These are called linemarkers. They are inserted as needed into
* the output (but never within a string or character constant). They
* mean that the following line originated in file filename at line
* linenum. filename will never contain any non-printing characters;
* they are replaced with octal escape sequences.
*
* After the file name comes zero or more flags, which are `1', `2',
* `3', or `4'. If there are multiple flags, spaces separate them. Here
* is what the flags mean:
*
* `1'
* This indicates the start of a new file.
* `2'
* This indicates returning to a file (after having included another
* file).
* `3'
* This indicates that the following text comes from a system header
* file, so certain warnings should be suppressed.
* `4'
* This indicates that the following text should be treated as being
* wrapped in an implicit extern "C" block.
*/
public class Preprocessor implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(Preprocessor.class);
private static final Source INTERNAL = new Source() {
@Override
public Token token()
throws IOException,
LexerException {
throw new LexerException("Cannot read from " + getName());
}
@Override
public String getPath() {
return "<internal-data>";
}
@Override
public String getName() {
return "internal data";
}
};
private static final Macro __LINE__ = new Macro(INTERNAL, "__LINE__");
private static final Macro __FILE__ = new Macro(INTERNAL, "__FILE__");
private static final Macro __COUNTER__ = new Macro(INTERNAL, "__COUNTER__");
private final List<Source> inputs;
/* The fundamental engine. */
private final Map<String, Macro> macros;
private final Stack<State> states;
private Source source;
/* Miscellaneous support. */
private int counter;
private final Set<String> onceseenpaths = new HashSet<String>();
private final List<VirtualFile> includes = new ArrayList<VirtualFile>();
/* Support junk to make it work like cpp */
private List<String> quoteincludepath; /* -iquote */
private List<String> sysincludepath; /* -I */
private List<String> frameworkspath;
private final Set<Feature> features;
private final Set<Warning> warnings;
private VirtualFileSystem filesystem;
private PreprocessorListener listener;
public Preprocessor() {
this.inputs = new ArrayList<Source>();
this.macros = new HashMap<String, Macro>();
macros.put(__LINE__.getName(), __LINE__);
macros.put(__FILE__.getName(), __FILE__);
macros.put(__COUNTER__.getName(), __COUNTER__);
this.states = new Stack<State>();
states.push(new State());
this.source = null;
this.counter = 0;
this.quoteincludepath = new ArrayList<String>();
this.sysincludepath = new ArrayList<String>();
this.frameworkspath = new ArrayList<String>();
this.features = EnumSet.noneOf(Feature.class);
this.warnings = EnumSet.noneOf(Warning.class);
this.filesystem = new JavaFileSystem();
this.listener = new DefaultPreprocessorListener();
}
public Preprocessor(@Nonnull Source initial) {
this();
addInput(initial);
}
/** Equivalent to
* 'new Preprocessor(new {@link FileLexerSource}(file))'
*/
public Preprocessor(@Nonnull File file)
throws IOException {
this(new FileLexerSource(file));
}
/**
* Sets the VirtualFileSystem used by this Preprocessor.
*/
public void setFileSystem(@Nonnull VirtualFileSystem filesystem) {
this.filesystem = filesystem;
}
/**
* Returns the VirtualFileSystem used by this Preprocessor.
*/
@Nonnull
public VirtualFileSystem getFileSystem() {
return filesystem;
}
/**
* Sets the PreprocessorListener which handles events for
* this Preprocessor.
*
* The listener is notified of warnings, errors and source
* changes, amongst other things.
*/
public void setListener(@Nonnull PreprocessorListener listener) {
this.listener = listener;
Source s = source;
while (s != null) {
// s.setListener(listener);
s.init(this);
s = s.getParent();
}
// Make sure that any input sources know about this feature
for (Source source: inputs) {
source.init(this);
}
}
/**
* Returns the PreprocessorListener which handles events for
* this Preprocessor.
*/
@Nonnull
public PreprocessorListener getListener() {
return listener;
}
/**
* Returns the feature-set for this Preprocessor.
*
* This set may be freely modified by user code.
*/
@Nonnull
public Set<Feature> getFeatures() {
return features;
}
/**
* Adds a feature to the feature-set of this Preprocessor.
*/
public void addFeature(@Nonnull Feature f) {
features.add(f);
// Make sure that any input sources know about this feature
for (Source source: inputs) {
source.init(this);
}
}
/**
* Adds features to the feature-set of this Preprocessor.
*/
public void addFeatures(@Nonnull Collection<Feature> f) {
features.addAll(f);
}
/**
* Adds features to the feature-set of this Preprocessor.
*/
public void addFeatures(Feature... f) {
addFeatures(Arrays.asList(f));
}
/**
* Returns true if the given feature is in
* the feature-set of this Preprocessor.
*/
public boolean getFeature(@Nonnull Feature f) {
return features.contains(f);
}
/**
* Returns the warning-set for this Preprocessor.
*
* This set may be freely modified by user code.
*/
@Nonnull
public Set<Warning> getWarnings() {
return warnings;
}
/**
* Adds a warning to the warning-set of this Preprocessor.
*/
public void addWarning(@Nonnull Warning w) {
warnings.add(w);
}
/**
* Adds warnings to the warning-set of this Preprocessor.
*/
public void addWarnings(@Nonnull Collection<Warning> w) {
warnings.addAll(w);
}
/**
* Returns true if the given warning is in
* the warning-set of this Preprocessor.
*/
public boolean getWarning(@Nonnull Warning w) {
return warnings.contains(w);
}
/**
* Adds input for the Preprocessor.
*
* Inputs are processed in the order in which they are added.
*/
public void addInput(@Nonnull Source source) {
source.init(this);
inputs.add(source);
}
/**
* Adds input for the Preprocessor.
*
* @see #addInput(Source)
*/
public void addInput(@Nonnull File file)
throws IOException {
addInput(new FileLexerSource(file));
}
/**
* Handles an error.
*
* If a PreprocessorListener is installed, it receives the
* error. Otherwise, an exception is thrown.
*/
protected void error(int line, int column, @Nonnull String msg)
throws LexerException {
if (listener != null)
listener.handleError(source, line, column, msg);
else
throw new LexerException("Error at " + line + ":" + column + ": " + msg);
}
/**
* Handles an error.
*
* If a PreprocessorListener is installed, it receives the
* error. Otherwise, an exception is thrown.
*
* @see #error(int, int, String)
*/
protected void error(@Nonnull Token tok, @Nonnull String msg)
throws LexerException {
error(tok.getLine(), tok.getColumn(), msg);
}
/**
* Handles a warning.
*
* If a PreprocessorListener is installed, it receives the
* warning. Otherwise, an exception is thrown.
*/
protected void warning(int line, int column, @Nonnull String msg)
throws LexerException {
if (warnings.contains(Warning.ERROR))
error(line, column, msg);
else if (listener != null)
listener.handleWarning(source, line, column, msg);
else
throw new LexerException("Warning at " + line + ":" + column + ": " + msg);
}
/**
* Handles a warning.
*
* If a PreprocessorListener is installed, it receives the
* warning. Otherwise, an exception is thrown.
*
* @see #warning(int, int, String)
*/
protected void warning(@Nonnull Token tok, @Nonnull String msg)
throws LexerException {
warning(tok.getLine(), tok.getColumn(), msg);
}
/**
* Adds a Macro to this Preprocessor.
*
* The given {@link Macro} object encapsulates both the name
* and the expansion.
*
* @throws LexerException if the definition fails or is otherwise illegal.
*/
public void addMacro(@Nonnull Macro m) throws LexerException {
// System.out.println("Macro " + m);
String name = m.getName();
/* Already handled as a source error in macro(). */
if ("defined".equals(name))
throw new LexerException("Cannot redefine name 'defined'");
macros.put(m.getName(), m);
}
/**
* Defines the given name as a macro.
*
* The String value is lexed into a token stream, which is
* used as the macro expansion.
*
* @throws LexerException if the definition fails or is otherwise illegal.
*/
public void addMacro(@Nonnull String name, @Nonnull String value)
throws LexerException {
try {
Macro m = new Macro(name);
StringLexerSource s = new StringLexerSource(value);
// In order to make sure that the source honors all the features of this preprocessor, we have to init it
s.init(this);
for (;;) {
Token tok = s.token();
if (tok.getType() == EOF)
break;
m.addToken(tok);
}
addMacro(m);
} catch (IOException e) {
throw new LexerException(e);
}
}
/**
* Defines the given name as a macro, with the value <code>1</code>.
*
* This is a convnience method, and is equivalent to
* <code>addMacro(name, "1")</code>.
*
* @throws LexerException if the definition fails or is otherwise illegal.
*/
public void addMacro(@Nonnull String name)
throws LexerException {
addMacro(name, "1");
}
/**
* Sets the user include path used by this Preprocessor.
*/
/* Note for future: Create an IncludeHandler? */
public void setQuoteIncludePath(@Nonnull List<String> path) {
this.quoteincludepath = path;
}
/**
* Returns the user include-path of this Preprocessor.
*
* This list may be freely modified by user code.
*/
@Nonnull
public List<String> getQuoteIncludePath() {
return quoteincludepath;
}
/**
* Sets the system include path used by this Preprocessor.
*/
/* Note for future: Create an IncludeHandler? */
public void setSystemIncludePath(@Nonnull List<String> path) {
this.sysincludepath = path;
}
/**
* Returns the system include-path of this Preprocessor.
*
* This list may be freely modified by user code.
*/
@Nonnull
public List<String> getSystemIncludePath() {
return sysincludepath;
}
/**
* Sets the Objective-C frameworks path used by this Preprocessor.
*/
/* Note for future: Create an IncludeHandler? */
public void setFrameworksPath(@Nonnull List<String> path) {
this.frameworkspath = path;
}
/**
* Returns the Objective-C frameworks path used by this
* Preprocessor.
*
* This list may be freely modified by user code.
*/
@Nonnull
public List<String> getFrameworksPath() {
return frameworkspath;
}
/**
* Returns the Map of Macros parsed during the run of this
* Preprocessor.
*
* @return The {@link Map} of macros currently defined.
*/
@Nonnull
public Map<String, Macro> getMacros() {
return macros;
}
/**
* Returns the named macro.
*
* While you can modify the returned object, unexpected things
* might happen if you do.
*
* @return the Macro object, or null if not found.
*/
@CheckForNull
public Macro getMacro(@Nonnull String name) {
return macros.get(name);
}
/**
* Returns the list of {@link VirtualFile VirtualFiles} which have been
* included by this Preprocessor.
*
* This does not include any {@link Source} provided to the constructor
* or {@link #addInput(java.io.File)} or {@link #addInput(Source)}.
*/
@Nonnull
public List<? extends VirtualFile> getIncludes() {
return includes;
}
/* States */
private void push_state() {
State top = states.peek();
states.push(new State(top));
}
private void pop_state()
throws LexerException {
State s = states.pop();
if (states.isEmpty()) {
error(0, 0, "#" + "endif without #" + "if");
states.push(s);
}
}
private boolean isActive() {
State state = states.peek();
return state.isParentActive() && state.isActive();
}
/* Sources */
/**
* Returns the top Source on the input stack.
*
* @see Source
* @see #push_source(Source,boolean)
* @see #pop_source()
*
* @return the top Source on the input stack.
*/
// @CheckForNull
protected Source getSource() {
return source;
}
/**
* Pushes a Source onto the input stack.
*
* @param source the new Source to push onto the top of the input stack.
* @param autopop if true, the Source is automatically removed from the input stack at EOF.
* @see #getSource()
* @see #pop_source()
*/
protected void push_source(@Nonnull Source source, boolean autopop) {
source.init(this);
source.setParent(this.source, autopop);
// source.setListener(listener);
if (listener != null)
listener.handleSourceChange(this.source, SourceChangeEvent.SUSPEND);
this.source = source;
if (listener != null)
listener.handleSourceChange(this.source, SourceChangeEvent.PUSH);
}
/**
* Pops a Source from the input stack.
*
* @see #getSource()
* @see #push_source(Source,boolean)
*
* @param linemarker TODO: currently ignored, might be a bug?
* @throws IOException if an I/O error occurs.
*/
@CheckForNull
protected Token pop_source(boolean linemarker)
throws IOException {
if (listener != null)
listener.handleSourceChange(this.source, SourceChangeEvent.POP);
Source s = this.source;
this.source = s.getParent();
/* Always a noop unless called externally. */
s.close();
if (listener != null && this.source != null)
listener.handleSourceChange(this.source, SourceChangeEvent.RESUME);
Source t = getSource();
if (getFeature(Feature.LINEMARKERS)
&& s.isNumbered()
&& t != null) {
/* We actually want 'did the nested source
* contain a newline token', which isNumbered()
* approximates. This is not perfect, but works. */
return line_token(t.getLine(), t.getName(), " 2");
}
return null;
}
protected void pop_source()
throws IOException {
pop_source(false);
}
@Nonnull
private Token next_source() {
if (inputs.isEmpty())
return new Token(EOF);
Source s = inputs.remove(0);
push_source(s, true);
return line_token(s.getLine(), s.getName(), " 1");
}
/* Source tokens */
private Token source_token;
/* XXX Make this include the NL, and make all cpp directives eat
* their own NL. */
@Nonnull
private Token line_token(int line, @CheckForNull String name, @Nonnull String extra) {
StringBuilder buf = new StringBuilder();
buf.append("#line ").append(line)
.append(" \"");
/* XXX This call to escape(name) is correct but ugly. */
if (name == null)
buf.append("<no file>");
else
MacroTokenSource.escape(buf, name);
buf.append("\"").append(extra).append("\n");
return new Token(P_LINE, line, 0, buf.toString(), null);
}
@Nonnull
private Token source_token()
throws IOException,
LexerException {
if (source_token != null) {
Token tok = source_token;
source_token = null;
if (getFeature(Feature.DEBUG))
LOG.debug("Returning unget token " + tok);
return tok;
}
for (;;) {
Source s = getSource();
if (s == null) {
Token t = next_source();
if (t.getType() == P_LINE && !getFeature(Feature.LINEMARKERS))
continue;
return t;
}
Token tok = s.token();
/* XXX Refactor with skipline() */
if (tok.getType() == EOF && s.isAutopop()) {
// System.out.println("Autopop " + s);
Token mark = pop_source(true);
if (mark != null)
return mark;
continue;
}
if (getFeature(Feature.DEBUG))
LOG.debug("Returning fresh token " + tok);
return tok;
}
}
private void source_untoken(Token tok) {
if (this.source_token != null)
throw new IllegalStateException("Cannot return two tokens");
this.source_token = tok;
}
private boolean isWhite(Token tok) {
int type = tok.getType();
return (type == WHITESPACE)
|| (type == CCOMMENT)
|| (type == CPPCOMMENT);
}
private Token source_token_nonwhite()
throws IOException,
LexerException {
Token tok;
do {
tok = source_token();
} while (isWhite(tok));
return tok;
}
/**
* Returns an NL or an EOF token.
*
* The metadata on the token will be correct, which is better
* than generating a new one.
*
* This method can, as of recent patches, return a P_LINE token.
*/
private Token source_skipline(boolean white)
throws IOException,
LexerException {
// (new Exception("skipping line")).printStackTrace(System.out);
Source s = getSource();
Token tok = s.skipline(white);
/* XXX Refactor with source_token() */
if (tok.getType() == EOF && s.isAutopop()) {
// System.out.println("Autopop " + s);
Token mark = pop_source(true);
if (mark != null)
return mark;
}
return tok;
}
/* processes and expands a macro. */
private boolean macro(Macro m, Token orig)
throws IOException,
LexerException {
Token tok;
List<Argument> args = new ArrayList<Argument>();
//System.out.println("pp: expanding " + m);
if (m.isFunctionLike()) {
OPEN:
for (;;) {
tok = source_token();
// System.out.println("pp: open: token is " + tok);
switch (tok.getType()) {
case WHITESPACE: /* XXX Really? */
case CCOMMENT:
case CPPCOMMENT:
case NL:
break; /* continue */
case '(':
break OPEN;
default:
source_untoken(tok);
return false;
}
}
// tok = expanded_token_nonwhite();
tok = source_token_nonwhite();
/* We either have, or we should have args.
* This deals elegantly with the case that we have
* one empty arg. */
if (tok.getType() != ')' || m.getArgs() > 0) {
Argument arg = new Argument();
int depth = 0;
boolean space = false;
ARGS:
for (;;) {
// System.out.println("pp: arg: token is " + tok);
switch (tok.getType()) {
case EOF:
error(tok, "EOF in macro args");
return false;
case ',':
if (depth == 0) {
if (m.isVariadic()
&& /* We are building the last arg. */ args.size() == m.getArgs() - 1) {
/* Just add the comma. */
arg.addToken(tok);
} else {
args.add(arg);
arg = new Argument();
}
} else {
arg.addToken(tok);
}
space = false;
break;
case ')':
if (depth == 0) {
args.add(arg);
break ARGS;
} else {
depth--;
arg.addToken(tok);
}
space = false;
break;
case '(':
depth++;
arg.addToken(tok);
space = false;
break;
case WHITESPACE:
case CCOMMENT:
case CPPCOMMENT:
case NL:
/* Avoid duplicating spaces. */
space = true;
break;
default:
/* Do not put space on the beginning of
* an argument token. */
if (space && !arg.isEmpty())
arg.addToken(Token.space);
arg.addToken(tok);
space = false;
break;
}
// tok = expanded_token();
tok = source_token();
}
/* space may still be true here, thus trailing space
* is stripped from arguments. */
if (args.size() != m.getArgs()) {
if (m.isVariadic()) {
if (args.size() == m.getArgs() - 1) {
args.add(new Argument());
} else {
error(tok,
"variadic macro " + m.getName()
+ " has at least " + (m.getArgs() - 1) + " parameters "
+ "but given " + args.size() + " args");
return false;
}
} else {
error(tok,
"macro " + m.getName()
+ " has " + m.getArgs() + " parameters "
+ "but given " + args.size() + " args");
/* We could replay the arg tokens, but I
* note that GNU cpp does exactly what we do,
* i.e. output the macro name and chew the args.
*/
return false;
}
}
for (Argument a : args) {
a.expand(this);
}
// System.out.println("Macro " + m + " args " + args);
} else {
/* nargs == 0 and we (correctly) got () */
}
} else {
/* Macro without args. */
}
if (m == __LINE__) {
push_source(new FixedTokenSource(
new Token[]{new Token(NUMBER,
orig.getLine(), orig.getColumn(),
Integer.toString(orig.getLine()),
new NumericValue(10, Integer.toString(orig.getLine())))}
), true);
} else if (m == __FILE__) {
StringBuilder buf = new StringBuilder("\"");
String name = getSource().getName();
if (name == null)
name = "<no file>";
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '\\':
buf.append("\\\\");
break;
case '"':
buf.append("\\\"");
break;
default:
buf.append(c);
break;
}
}
buf.append("\"");
String text = buf.toString();
push_source(new FixedTokenSource(
new Token[]{new Token(STRING,
orig.getLine(), orig.getColumn(),
text, text)}
), true);
} else if (m == __COUNTER__) {
/* This could equivalently have been done by adding
* a special Macro subclass which overrides getTokens(). */
int value = this.counter++;
push_source(new FixedTokenSource(
new Token[]{new Token(NUMBER,
orig.getLine(), orig.getColumn(),
Integer.toString(value),
new NumericValue(10, Integer.toString(value)))}
), true);
} else {
push_source(new MacroTokenSource(m, args), true);
}
return true;
}
/**
* Expands an argument.
*/
/* I'd rather this were done lazily, but doing so breaks spec. */
@Nonnull
/* pp */ List<Token> expand(@Nonnull List<Token> arg)
throws IOException,
LexerException {
List<Token> expansion = new ArrayList<Token>();
boolean space = false;
push_source(new FixedTokenSource(arg), false);
EXPANSION:
for (;;) {
Token tok = expanded_token();
switch (tok.getType()) {
case EOF:
break EXPANSION;
case WHITESPACE:
case CCOMMENT:
case CPPCOMMENT:
space = true;
break;
default:
if (space && !expansion.isEmpty())
expansion.add(Token.space);
expansion.add(tok);
space = false;
break;
}
}
// Always returns null.
pop_source(false);
return expansion;
}
/* processes a #define directive */
private Token define()
throws IOException,
LexerException {
Token tok = source_token_nonwhite();
if (tok.getType() != IDENTIFIER) {
error(tok, "Expected identifier");
return source_skipline(false);
}
/* if predefined */
String name = tok.getText();
if ("defined".equals(name)) {
error(tok, "Cannot redefine name 'defined'");
return source_skipline(false);
}
Macro m = new Macro(getSource(), name);
List<String> args;
tok = source_token();
if (tok.getType() == '(') {
tok = source_token_nonwhite();
if (tok.getType() != ')') {
args = new ArrayList<String>();
ARGS:
for (;;) {
switch (tok.getType()) {
case IDENTIFIER:
args.add(tok.getText());
break;
case ELLIPSIS:
// Unnamed Variadic macro
args.add("__VA_ARGS__");
// We just named the ellipsis, but we unget the token
// to allow the ELLIPSIS handling below to process it.
source_untoken(tok);
break;
case NL:
case EOF:
error(tok,
"Unterminated macro parameter list");
return tok;
default:
error(tok,
"error in macro parameters: "
+ tok.getText());
return source_skipline(false);
}
tok = source_token_nonwhite();
switch (tok.getType()) {
case ',':
break;
case ELLIPSIS:
tok = source_token_nonwhite();