-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjavapp.java
2340 lines (1706 loc) · 73.4 KB
/
javapp.java
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
/*
* javapp.java
*
* $Id: javapp.java,v 1.302 2013/12/03 12:14:30 sjg Exp $
*
* (c) Stephen Geary, Sep 2013
*
* A general pattern matching preprocessor.
*
*/
import java.lang.* ;
import java.io.* ;
import java.util.* ;
import java.util.regex.* ;
// required for IntHolder class
import org.omg.CORBA.IntHolder ;
#define _PUBSTAT public static
public class javapp
{
_PUBSTAT String currentfilename = null ;
_PUBSTAT int filesize = 0 ;
_PUBSTAT LinkedList<Pattern> patterns = null ;
// Patterns which use identical regex strings
// do NOT match with p1.equals(p2) and so the
// matcher functions don't always return true
// when a human would expect them to.
// So we need to keep the strings.
//
_PUBSTAT LinkedList<String> patstrings = null ;
_PUBSTAT LinkedList<String> outputs = null ;
_PUBSTAT LinkedList<String> lines = null ;
_PUBSTAT Stack<Object> stack = null ;
_PUBSTAT int iflevel = 0 ;
_PUBSTAT Stack<Boolean> ifstate = null ;
// #define _LITERAL "[\\p{Alnum}_]"
#define _LITERAL "\\p{javaJavaIdentifierPart}"
#define _LITERAL_START "\\p{javaJavaIdentifierStart}"
#define _CAP_LITERAL "("+_LITERAL_START+_LITERAL+"*)"
#define _EOL_REGEX "\\s*$"
/**********************************************************
*/
/* Can turn on debuging by setting environment variable
* $DEBUG_JAVAPP ( and unset to block it )
*/
static boolean __debugme = false ;
static String DEBUG_ENV = null ;
static void checkDebug()
{
String ev = null ;
ev = System.getenv("DEBUG_JAVAPP") ;
if( ev != null )
{
__debugme = true ;
DEBUG_ENV = ev ;
}
}
#define _DEBUG() { __debugme = true ; debug("") ; __debugme = false ; }
#define debug(...) \
if( __debugme ) \
{ \
report( "At line ", __LINE__, " in ", currentfilename, " ", __VA_ARGS__ ) ; \
}
_PUBSTAT void report( Object... objs )
{
for( Object obj : objs )
{
System.err.print( obj ) ;
}
System.err.println( "" ) ;
System.err.flush() ;
}
/**********************************************************
*/
/*
* Clean a pattern string ( prior to adding it )
*
* This means removing comments and extraneous spaces.
*/
_PUBSTAT String cleanPattern( String pats )
{
int len = pats.length() ;
if( len <= 1 )
{
// can't have any comment in it
return pats.trim() ;
}
char c = pats.charAt(0) ;
if( ( c == '/' ) && ( pats.charAt(1) == '/' ) )
{
// whole thing in a comment
return "" ;
}
StringBuilder retsb = new StringBuilder() ;
boolean incomment = false ;
char lastc = (char)-1 ;
int i = 1 ;
while( i < len )
{
lastc = c ;
c = pats.charAt(i) ;
if( incomment )
{
// ignore stuff until we reach an end of comment marker
if( ( lastc == '*' ) && ( c == '/' ) )
{
incomment = false ;
}
}
else
{
if( ( lastc == '/' ) && ( c == '/' ) )
{
// end of line comment marker
// we can terminate this entire process
incomment = true ;
break ;
}
if( ( lastc == '/' ) && ( c == '*' ) )
{
incomment = true ;
// can't end a comment for at least a couple of more chars
i += 2 ;
continue ;
}
retsb.append( lastc ) ;
}
i++ ;
};
// at this point the last character (c) is not yet written to the buffer
if( ! incomment )
{
retsb.append(c) ;
}
i = 0 ;
while( retsb.charAt(i) == ' ' )
{
i++ ;
};
int j = retsb.length() - 1 ;
while( ( j > 0 ) && ( retsb.charAt(j) == ' ' ) )
{
j-- ;
};
j++ ;
return retsb.substring( i, j ) ;
}
/*
* Add a new pattern to the list
*/
_PUBSTAT void addPattern( String pats, String outs )
{
__debugme = true ;
String cleanouts = null ;
cleanouts = cleanPattern( outs ) ;
/*
if( DEBUG_ENV.equals( "addPattern" ) )
{
debug( "Adding pattern :: ", pats ) ;
debug( "Adding output :: ", outs ) ;
debug( "Cleaned output :: ", cleanouts ) ;
debug( "---------------------------------" ) ;
}
*/
patterns.add( Pattern.compile( pats, Pattern.MULTILINE ) ) ;
patstrings.add( pats ) ;
outputs.add( cleanouts ) ;
__debugme = false ;
}
/**********************************************************
*/
#define __CATCH_IOE \
catch( IOException ioe ) \
{ \
}
#define __IOE( statement ) \
try \
{ \
statement ; \
} \
__CATCH_IOE
public static void closeStream( Closeable st )
{
try
{
if( st != null )
{
if( st instanceof Flushable )
{
( (Flushable)st ).flush() ;
}
st.close() ;
}
}
__CATCH_IOE
}
/*
* Process an external command from lines at the given position,
*
* Stops when a line matches the regex "^#\\s*end-command\\s*(?://.*)?$"
*
* This code may have to insert lines into the line list.
*/
_PUBSTAT void processCommand( String cmd, int startingline )
{
// create a process
ProcessBuilder pb = new ProcessBuilder( cmd.split(" ") ) ;
if( pb == null )
{
// cannot create the process
return ;
}
pb.redirectError( ProcessBuilder.Redirect.INHERIT ) ;
Process proc = null ;
__IOE( proc = pb.start() ) ;
if( proc == null )
{
report( "Could not start process from ", cmd, " on line ", startingline, " in ", currentfilename ) ;
return ;
}
InputStreamReader pisr = new InputStreamReader( proc.getInputStream() ) ;
OutputStreamWriter posw = new OutputStreamWriter( proc.getOutputStream() ) ;
if( ( pisr == null ) || ( posw == null ) )
{
debug( "Could not get process streams." ) ;
closeStream( pisr ) ;
closeStream( posw ) ;
return ;
}
// send input to the process
int k = 0 ;
int numlines = lines.size() ;
LinkedList<String> outlines = new LinkedList<String>() ;
String t = null ;
Pattern p = Pattern.compile( "^#\\s*end-command\\s*$" ) ;
boolean endcommandfound = false;
for( k = startingline+1 ; k < numlines ; k++ )
{
t = lines.get(k) ;
if( p.matcher(t).matches() )
{
// found end of command input
endcommandfound = true ;
break ;
}
// feed that line to the output process
__IOE( posw.write( t ) ) ;
__IOE( posw.write( (int)'\n' ) ) ;
}
// NOTE : we use k later on !
// Note that we could check for an "end-command" before
// we run out of input lines, but in a practical sense
// this would just force a developer to add a useless
// end-command to the end of a file.
//
// we do need to at least warn about a missing directive
if( ! endcommandfound )
{
report( "WARNING :: Did not find \"#end-command\" before end of file to match \"#command\" at line ", startingline, " in ", currentfilename ) ;
}
__IOE( posw.flush() ) ;
closeStream( posw ) ;
// fetch the output of the command into lines
StringBuilder sb = new StringBuilder() ;
int c = 0 ;
while( c != -1 )
{
__IOE( c = pisr.read() ) ;
if( ( c != -1 ) && ( c != (int)'\n' ) )
{
sb.append( (char)c ) ;
}
/*
if( __debugme && ( c != -1 ) )
{
System.err.printf( "char = [%04x] %c\n", c, (char)c ) ;
}
*/
if( c == (int)'\n' )
{
// write the output
outlines.add( sb.toString() ) ;
// reset the string builder
sb.setLength( 0 ) ;
}
}
closeStream( pisr ) ;
// now replace input lines with output lines
// which lets the preprocessor process them further
// remove all the lines from k to startingline inclusive
// note the order we remove which is easier
while( k >= startingline )
{
lines.remove( k ) ;
k-- ;
};
// now add the new lines from starting line
// note the order we add which is easier
int i = outlines.size() ;
while( i > 0 )
{
i-- ;
lines.add( startingline, outlines.get(i) ) ;
// debug( outlines.get(i) ) ;
};
}
/**********************************************************
*/
_PUBSTAT boolean evaluate( String expr )
{
boolean errorhappened = false ;
StringBuilder sb = new StringBuilder() ;
// this routine builds a sting without spaces and with
// the tokens replaced by true or false values
// This simplifies parsing the expression, although it's
// not the most efficient way to do it.
boolean notpending = false ;
int len = expr.length() ;
int i = 0 ;
char c = 0 ;
// check for symbols and resolve them, removing spaces as we go
for( i = 0 ; i < len ; i++ )
{
c = expr.charAt(i) ;
if( Character.isJavaIdentifierStart(c) )
{
// read the identifier and determine if it
// exists, output 't' or 'f' for that result.
StringBuilder sb2 = new StringBuilder() ;
sb2.append( c ) ;
i++ ;
while( i < len )
{
c = expr.charAt(i) ;
if( ! Character.isJavaIdentifierPart(c) )
{
// end of identifer.
// because identifiers are the first thing checked we
// can proceed with this new character on the rest of
// the checks in the main loop
break ;
}
sb2.append(c) ;
i++ ;
};
// at this point we have an identifier in sb2
// TODO :
//
// Test for a string equality sequence.
// There are two possible forms :
// (1) x = y
// (2) y = "stuff"
//
// We use the ~ operator for case ignoring matches,
// and the = operator for case sensitive matches.
//
// Note that we don't allow "stuff" == y
while( ( i < len ) && Character.isWhitespace(c) )
{
i++ ;
c = expr.charAt(i) ;
};
boolean b = false ;
if( ( c == '=' ) || ( c == '~' ) )
{
boolean ignorecase = false ;
if( c == '~' )
{
ignorecase = true ;
}
// found a string equality test
// read the next identifier
i++ ;
// check for double symbols i.e. we accept '=' or '=='
// as well as '~' and '~~'
if( i < len )
{
char c2 = expr.charAt(i) ;
if( c2 == c )
{
// consume the character
i++ ;
}
}
while( ( i < len ) && Character.isWhitespace( c = expr.charAt(i) ) )
{
i++ ;
};
if( ! ( Character.isJavaIdentifierStart(c) || ( c == '"' ) ) )
{
report( "Expecting identifier start or quote after '=' in expression." ) ;
report( "\tExpression was [", expr, "]" ) ;
report( "\tProblem encountered at character number [", i, "] which is [", c, "]" ) ;
return false ;
}
StringBuilder sb3 = new StringBuilder() ;
int j1 = 0 ;
int j2 = 0 ;
j1 = patstrings.indexOf( makeToken( sb2.toString() ) ) ;
String lefts = null ;
String rights = null ;
lefts = outputs.get(j1) ;
i++ ;
// could be a string literal or a symbol next
if( c == '"' )
{
while( ( i < len ) && ( ( c = expr.charAt(i) ) != '"' ) )
{
sb3.append( c ) ;
i++ ;
}
// move past the quote
i++ ;
j2 = 0 ;
rights = sb3.toString() ;
}
else
{
sb3.append(c) ;
while( ( i < len ) && Character.isJavaIdentifierPart( c = expr.charAt(i) ) )
{
sb3.append( c ) ;
i++ ;
};
j2 = patstrings.indexOf( makeToken( sb3.toString() ) ) ;
if( j2 != -1 )
{
rights = outputs.get(j2) ;
}
}
if( ( j1 == -1 ) || ( j2 == -1 ) )
{
b = false ;
}
else
{
if( ignorecase )
{
b = lefts.equalsIgnoreCase( rights ) ;
}
else
{
b = lefts.equals( rights ) ;
}
}
}
else
{
// Just a simple identifier existence test.
b = tokenExists( sb2.toString() ) ;
}
b = b ^ notpending ;
notpending = false ;
if( b )
{
sb.append('t') ;
}
else
{
sb.append('f') ;
}
if( i == len )
{
// reached the end of the expression
// so force the end of the main loop
break ;
}
}
if( Character.isWhitespace(c) )
{
// ignore whitespace
continue ;
}
switch( c )
{
case '(' :
if( notpending )
{
sb.append( '!' ) ;
notpending = false ;
}
sb.append( '(' ) ;
break ;
case ')' :
case '&' :
case '|' :
case '^' :
if( notpending )
{
report( "Not operation preceeded '",c,"' character, which is illegal." ) ;
return false ;
}
sb.append(c) ;
break ;
case '!' :
notpending = notpending ^ true ;
break ;
default :
// an illegal character in a boolean expression
report( "Illegal character in boolean expression [", c, "] in expression [", expr, "]" ) ;
errorhappened = true ;
break ;
}
if( errorhappened )
{
return false ;
}
}
return eval( sb.toString(), new IntHolder(0), sb.length(), false ) ;
}
_PUBSTAT boolean eval( String expr, IntHolder frompos, int topos, boolean bracketoutstanding )
{
// evaluate the boolean expression given
boolean forcereturn = false ;
boolean result = false ;
boolean not_pending = false ;
char c = 0 ;
int i = frompos.value ;
boolean operand = false ;
boolean op_pending = false ;
char operation = 0 ;
// read chars and try to match them
while( i < topos )
{
c = expr.charAt(i) ;
switch( c )
{
case 't' :
case 'f' :
if( c == 't' )
{
operand = true ;
}
else
{
operand = false ;
}
if( op_pending )
{
if( operation == '&' )
{
result = result & operand ;
}
else if( operation == '|' )
{
result = result | operand ;
}
else if( operation == '^' )
{
result = result ^ operand ;
}
else
{
report( "Illegal operation in expression." ) ;
return false ;
}
}
else
{
result = operand ;
}
break ;
case '(' :
// evaluate sub-expression
boolean subresult = false ;
// The ONLY standard Java class that is a container
// for a mutable integer is the IntHolder class from
// org.omg.CORBA. The standard Integer class is
// immutable which means we cannot use it to recieve
// a return value from the function we call.
IntHolder ih = new IntHolder( i+1 ) ;
subresult = not_pending ^ eval( expr, ih, topos, true ) ;
i = ih.value ;
if( op_pending )
{
if( operation == '&' )
{
result = result & subresult ;
}
else if( operation == '|' )
{
result = result | subresult ;
}
else if( operation == '^' )
{
result = result ^ subresult ;
}
}
else
{
result = subresult ;
}
break ;
case ')' :
// a sub-expression must be ending
// inform the calling code of the current position
// we are parsing
frompos.value = i ;
if( bracketoutstanding )
{
// end of sub-expression
result = not_pending ^ result ;
}
else
{
// this is an error in the expression as
// we have no opening bracket matching
report( "Opening bracket does not match opening bracket in expression." ) ;
result = false ;
}
forcereturn = true ;
break ;
case '!' :
// we have preparsed so that a not operation here
// can only happen if we are opening a bracketted
// expression
not_pending = not_pending ^ true ;
break ;
case '&' :
if( op_pending )
{
report( "Two operations not separated by operands in expression." ) ;
return false ;
}
op_pending = true ;
operation = '&' ;
break ;
case '|' :
if( op_pending )
{
report( "Two operations not separated by operands in expression." ) ;
return false ;
}
op_pending = true ;
operation = '|' ;
break ;
case '^' :
if( op_pending )
{
report( "Two operations not separated by operands in expression." ) ;
return false ;
}
op_pending = true ;
operation = '^' ;
break ;
default :
report( "Illegal character found during parsing of boolean expression." ) ;
forcereturn = true ;
result = false ;
break ;
}
if( forcereturn )
{
return result ;
}
i++ ;
}
return result ;
}
/**********************************************************
*/
/* Literal defined - e.g. #define WIBBLE 1234
* need to have some extra regex stuff in the pattern string
* in order to avoid false matches.
* This ensures a consistent treatment of that extra regex stuff
* in the application.
*
* Note that this method also calls the method that removes
* extraneous whitespace and comments.
*/
static String makeToken( String s )
{
String rets = null ;
rets = "(?<!" + _LITERAL + ")" + cleanPattern(s) + "(?![" + _LITERAL + "\\(])" ;
return rets ;
}
static int __pretokenlen = ( "(?<!" + _LITERAL + ")" ).length() ;
static int __posttokenlen = ( "(?![" + _LITERAL + "\\(])" ).length() ;
static String detokenize( String s )
{
String rets = null ;
int len = s.length() ;
rets = s.substring( __pretokenlen, len - __posttokenlen ) ;
return rets ;
}
static boolean tokenExists( String s )
{
String t = makeToken(s) ;
// debug( "Checking token ", t ) ;
int pos = -1 ;
pos = patstrings.indexOf(t) ;
if( pos < 0 )
{
/*
for( String st : patstrings )
{
debug( "\t\t", st ) ;
}
*/
return false ;
}
return true ;
}
#define _IF_MATCH_GROUPS \
\
Matcher m = p.matcher( s ) ; \
\
if( ! m.find() ) \
{ \
debug( ">>> WEIRD : matcher failed :: " ) ; \
debug( "\t", m ) ; \
debug( "\t[", s, "]" ) ; \
\
break ; \
} \
else
#ifdef _DEBUG_IFSTACK
# define _DUMP_IFSTACK \
\
debug( "IFSTACK DUMP ::\t\t", i, "\t", j,"\t", k ) ; \
\
for( Boolean _bb : ifstate ) \
{ \
debug( "\t", _bb ) ; \
} \
debug( "IFSTACK ENDS ::" ) ;
#else
# define _DUMP_IFSTACK
#endif
#define _LINE_CHANGED \
{ \
linechanged = true ; \
\
s = sb.toString() ; \
\
sb = new StringBuilder() ; \
}
static int outputlinecount = 0 ;
#define _OUTPUT_LINES \