-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathBoaAstIntrinsics.java
More file actions
900 lines (815 loc) · 30.1 KB
/
Copy pathBoaAstIntrinsics.java
File metadata and controls
900 lines (815 loc) · 30.1 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
/*
* Copyright 2017, Hridesh Rajan, Robert Dyer, Jingyi Su
* Iowa State University of Science and Technology
* and Bowling Green State University
*
* 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 boa.functions;
import java.io.IOException;
import java.util.HashMap;
import java.util.Stack;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.InvalidProtocolBufferException;
import boa.datagen.DefaultProperties;
import boa.types.Ast.*;
import boa.types.Code.CodeRepository;
import boa.types.Code.Revision;
import boa.types.Diff.ChangedFile;
import boa.types.Issues.IssueRepository;
import boa.types.Issues.IssuesRoot;
import boa.types.Shared.ChangeKind;
import boa.types.Shared.Person;
import boa.types.Toplevel.Project;
/**
* Boa functions for working with ASTs.
*
* @author rdyer
* @author jsu
*/
public class BoaAstIntrinsics {
@SuppressWarnings("rawtypes")
private static Context context;
private static MapFile.Reader map, commentsMap, issuesMap, specMap;
public static enum ASTCOUNTER {
GETS_ATTEMPTED,
GETS_SUCCEED,
GETS_FAILED,
GETS_FAIL_MISSING,
GETS_FAIL_BADPROTOBUF,
GETS_FAIL_BADLOC,
};
@FunctionSpec(name = "url", returnType = "string", formalParameters = { "ChangedFile" })
public static String changedfileToString(final ChangedFile f) {
return f.getKey() + "!!" + f.getName();
}
private static final ASTRoot emptyAst = ASTRoot.newBuilder().build();
private static final CommentsRoot emptyComments = CommentsRoot.newBuilder().build();
private static final IssuesRoot emptyIssues = IssuesRoot.newBuilder().build();
private static final SpecDeclaration emptySpecDeclaration = SpecDeclaration.newBuilder().build();
private static final SpecMethod emptySpecMethod = SpecMethod.newBuilder().build();
private static final SpecStatement emptySpecStatement = SpecStatement.newBuilder().build();
private static final SpecVariable emptySpecVariable = SpecVariable.newBuilder().build();
/**
* Given a ChangedFile, return the AST for that file at that revision.
*
* @param f the ChangedFile to get a snapshot of the AST for
* @return the AST, or an empty AST on any sort of error
*/
@SuppressWarnings("unchecked")
@FunctionSpec(name = "getast", returnType = "ASTRoot", formalParameters = { "ChangedFile" })
public static ASTRoot getast(final ChangedFile f) {
// since we know only certain kinds have ASTs, filter before looking up
final ChangedFile.FileKind kind = f.getKind();
if (kind != ChangedFile.FileKind.SOURCE_JAVA_ERROR
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS2
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS3
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS4
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS8)
return emptyAst;
context.getCounter(ASTCOUNTER.GETS_ATTEMPTED).increment(1);
final String rowName = f.getKey() + "!!" + f.getName();
if (map == null)
openMap();
try {
final BytesWritable value = new BytesWritable();
if (map.get(new Text(rowName), value) == null) {
context.getCounter(ASTCOUNTER.GETS_FAIL_MISSING).increment(1);
} else {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
// defaults to 64, really big ASTs require more
_stream.setRecursionLimit(Integer.MAX_VALUE);
final ASTRoot root = ASTRoot.parseFrom(_stream);
context.getCounter(ASTCOUNTER.GETS_SUCCEED).increment(1);
return root;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
context.getCounter(ASTCOUNTER.GETS_FAIL_BADPROTOBUF).increment(1);
} catch (final IOException e) {
e.printStackTrace();
context.getCounter(ASTCOUNTER.GETS_FAIL_MISSING).increment(1);
} catch (final RuntimeException e) {
e.printStackTrace();
context.getCounter(ASTCOUNTER.GETS_FAIL_MISSING).increment(1);
} catch (final Error e) {
e.printStackTrace();
context.getCounter(ASTCOUNTER.GETS_FAIL_BADPROTOBUF).increment(1);
}
System.err.println("error with ast: " + rowName);
context.getCounter(ASTCOUNTER.GETS_FAILED).increment(1);
return emptyAst;
}
/**
* Given a ChangedFile, return the comments for that file at that revision.
*
* @param f the ChangedFile to get a snapshot of the comments for
* @return the comments list, or an empty list on any sort of error
*/
@FunctionSpec(name = "getcomments", returnType = "CommentsRoot", formalParameters = { "ChangedFile" })
public static CommentsRoot getcomments(final ChangedFile f) {
// since we know only certain kinds have comments, filter before looking up
final ChangedFile.FileKind kind = f.getKind();
if (kind != ChangedFile.FileKind.SOURCE_JAVA_ERROR
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS2
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS3
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS4
&& kind != ChangedFile.FileKind.SOURCE_JAVA_JLS8)
return emptyComments;
final String rowName = f.getKey() + "!!" + f.getName();
if (commentsMap == null)
openCommentMap();
try {
final BytesWritable value = new BytesWritable();
if (commentsMap.get(new Text(rowName), value) != null) {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
final CommentsRoot root = CommentsRoot.parseFrom(_stream);
return root;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final RuntimeException e) {
e.printStackTrace();
} catch (final Error e) {
e.printStackTrace();
}
System.err.println("error with comments: " + rowName);
return emptyComments;
}
/**
* Given an IssueRepository, return the issues.
*
* @param f the IssueRepository to get issues for
* @return the issues list, or an empty list on any sort of error
*/
@FunctionSpec(name = "getissues", returnType = "IssuesRoot", formalParameters = { "IssueRepository" })
public static IssuesRoot getissues(final IssueRepository f) {
if (issuesMap == null)
openIssuesMap();
try {
final BytesWritable value = new BytesWritable();
if (issuesMap.get(new Text(f.getKey()), value) != null) {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
final IssuesRoot root = IssuesRoot.parseFrom(_stream);
return root;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final RuntimeException e) {
e.printStackTrace();
} catch (final Error e) {
e.printStackTrace();
}
System.err.println("error with issues: " + f.getKey());
return emptyIssues;
}
@SuppressWarnings("unchecked")
@FunctionSpec(name = "getspec", returnType = "SpecDeclaration", formalParameters = { "Declaration" })
public static SpecDeclaration getspec(final Declaration f) {
if (!f.hasKey())
return emptySpecDeclaration;
final String rowName = f.getKey() + "!!" + f.getName();
if (specMap == null)
openSpecMap();
try {
final BytesWritable value = new BytesWritable();
if (specMap.get(new Text(rowName), value) == null) {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
final SpecDeclaration specdeclaration = SpecDeclaration.parseFrom(_stream);
return specdeclaration;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final RuntimeException e) {
e.printStackTrace();
} catch (final Error e) {
e.printStackTrace();
}
System.err.println("error with SpecDeclaration: " + rowName);
return emptySpecDeclaration;
}
@SuppressWarnings("unchecked")
@FunctionSpec(name = "getspec", returnType = "SpecMethod", formalParameters = { "Method" })
public static SpecMethod getspec(final Method f) {
if (!f.hasKey())
return emptySpecMethod;
final String rowName = f.getKey() + "!!" + f.getName();
if (specMap == null)
openSpecMap();
try {
final BytesWritable value = new BytesWritable();
if (specMap.get(new Text(rowName), value) == null) {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
final SpecMethod specmethod = SpecMethod.parseFrom(_stream);
return specmethod;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final RuntimeException e) {
e.printStackTrace();
} catch (final Error e) {
e.printStackTrace();
}
System.err.println("error with SpecMethod: " + rowName);
return emptySpecMethod;
}
@SuppressWarnings("unchecked")
@FunctionSpec(name = "getspec", returnType = "SpecStatement", formalParameters = { "Statement" })
public static SpecStatement getspec(final Statement f) {
if (!f.hasKey())
return emptySpecStatement;
final String rowName = f.getKey();
if (specMap == null)
openSpecMap();
try {
final BytesWritable value = new BytesWritable();
if (specMap.get(new Text(rowName), value) == null) {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
final SpecStatement specstatement = SpecStatement.parseFrom(_stream);
return specstatement;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final RuntimeException e) {
e.printStackTrace();
} catch (final Error e) {
e.printStackTrace();
}
System.err.println("error with SpecStatement: " + rowName);
return emptySpecStatement;
}
@SuppressWarnings("unchecked")
@FunctionSpec(name = "getspec", returnType = "SpecVariable", formalParameters = { "Variable" })
public static SpecVariable getspec(final Variable f) {
if (!f.hasKey())
return emptySpecVariable;
final String rowName = f.getKey() + "!!" + f.getName();
if (specMap == null)
openSpecMap();
try {
final BytesWritable value = new BytesWritable();
if (specMap.get(new Text(rowName), value) == null) {
final CodedInputStream _stream = CodedInputStream.newInstance(value.getBytes(), 0, value.getLength());
final SpecVariable specvariable = SpecVariable.parseFrom(_stream);
return specvariable;
}
} catch (final InvalidProtocolBufferException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final RuntimeException e) {
e.printStackTrace();
} catch (final Error e) {
e.printStackTrace();
}
System.err.println("error with SpecVariable: " + rowName);
return emptySpecVariable;
}
@SuppressWarnings("rawtypes")
public static void setup(final Context context) {
BoaAstIntrinsics.context = context;
}
private static void openMap() {
try {
final Configuration conf = context.getConfiguration();
final FileSystem fs;
final Path p;
if (DefaultProperties.localDataPath != null) {
p = new Path(DefaultProperties.localDataPath);
fs = FileSystem.getLocal(conf);
} else {
p = new Path(
context.getConfiguration().get("fs.default.name", "hdfs://boa-njt/"),
new Path(
conf.get("boa.ast.dir", conf.get("boa.input.dir", "repcache/live")),
new Path("ast")
)
);
fs = FileSystem.get(conf);
}
map = new MapFile.Reader(fs, p.toString(), conf);
} catch (final Exception e) {
e.printStackTrace();
}
}
private static void openCommentMap() {
try {
final Configuration conf = context.getConfiguration();
final FileSystem fs;
final Path p;
if (DefaultProperties.localDataPath != null) {
p = new Path(DefaultProperties.localCommentPath);
fs = FileSystem.getLocal(conf);
} else {
p = new Path(
context.getConfiguration().get("fs.default.name", "hdfs://boa-njt/"),
new Path(
conf.get("boa.comments.dir", conf.get("boa.input.dir", "repcache/live")),
new Path("comments")
)
);
fs = FileSystem.get(conf);
}
commentsMap = new MapFile.Reader(fs, p.toString(), conf);
} catch (final Exception e) {
e.printStackTrace();
}
}
private static void openIssuesMap() {
try {
final Configuration conf = context.getConfiguration();
final FileSystem fs;
final Path p;
if (DefaultProperties.localDataPath != null) {
p = new Path(DefaultProperties.localIssuePath);
fs = FileSystem.getLocal(conf);
} else {
p = new Path(
context.getConfiguration().get("fs.default.name", "hdfs://boa-njt/"),
new Path(
conf.get("boa.issues.dir", conf.get("boa.input.dir", "repcache/live")),
new Path("issues")
)
);
fs = FileSystem.get(conf);
}
issuesMap = new MapFile.Reader(fs, p.toString(), conf);
} catch (final Exception e) {
e.printStackTrace();
}
}
private static void openSpecMap() {
try {
final Configuration conf = context.getConfiguration();
final FileSystem fs;
final Path p;
if (DefaultProperties.localDataPath != null) {
p = new Path(DefaultProperties.localIssuePath);
fs = FileSystem.getLocal(conf);
} else {
p = new Path(
context.getConfiguration().get("fs.default.name", "hdfs://boa-njt/"),
new Path(
conf.get("boa.spec.dir", conf.get("boa.input.dir", "repcache/live")),
new Path("specs")
)
);
fs = FileSystem.get(conf);
}
issuesMap = new MapFile.Reader(fs, p.toString(), conf);
} catch (final Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
public static void cleanup(final Context context) {
closeMap();
closeCommentMap();
closeIssuesMap();
closeSpecMap();
}
private static void closeMap() {
if (map != null)
try {
map.close();
} catch (final IOException e) {
e.printStackTrace();
}
map = null;
}
private static void closeCommentMap() {
if (commentsMap != null)
try {
commentsMap.close();
} catch (final IOException e) {
e.printStackTrace();
}
commentsMap = null;
}
private static void closeIssuesMap() {
if (issuesMap != null)
try {
issuesMap.close();
} catch (final IOException e) {
e.printStackTrace();
}
issuesMap = null;
}
private static void closeSpecMap() {
if (specMap != null)
try {
specMap.close();
} catch (final IOException e) {
e.printStackTrace();
}
specMap = null;
}
@FunctionSpec(name = "type_name", returnType = "string", formalParameters = { "string" })
public static String type_name(final String s) {
// first, normalize the string
final String t = s.replaceAll("<\\s+", "<")
.replaceAll(",\\s+", ", ")
.replaceAll("\\s*>\\s*", ">")
.replaceAll("\\s*&\\s*", " & ")
.replaceAll("\\s*\\|\\s*", " | ");
if (!t.contains("."))
return t;
/*
* Remove qualifiers from anywhere in the string...
*
* SomeType => SomeType
* foo.SomeType => SomeType
* foo.bar.SomeType => SomeType
* SomeType<T> => SomeType<T>
* SomeType<T, S> => SomeType<T, S>
* SomeType<foo.bar.T, S> => SomeType<T, S>
* SomeType<T, foo.bar.S> => SomeType<T, S>
* foo.bar.SomeType<T, foo.bar.S<bar.Q>> => SomeType<T, S<Q>>
* SomeType|foo.Bar => SomeType|Bar
* foo<T>.bar<T> => foo<T>.bar<T>
*/
return t.replaceAll("[^\\s,<>|]+\\.([^\\s\\[.,><|]+)", "$1");
}
/**
* A visitor that returns the total number of AST nodes.
*/
public final static BoaCountingVisitor lenVisitor = new BoaCountingVisitor() {
/** {@inheritDoc} */
@Override
protected boolean defaultPreVisit() {
count++;
return true;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final Project node) throws Exception {
return true;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final CodeRepository node) throws Exception {
return true;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final Revision node) throws Exception {
return true;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final ChangedFile node) throws Exception {
return true;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final ASTRoot node) throws Exception {
return true;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final Person node) throws Exception {
return true;
}
};
/**
*
*/
public static class SnapshotVisitor extends BoaCollectingVisitor<String, ChangedFile> {
private long timestamp;
private String[] kinds;
public SnapshotVisitor initialize(final long timestamp, final String... kinds) {
initialize(new HashMap<String, ChangedFile>());
this.timestamp = timestamp;
this.kinds = kinds;
return this;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final Revision node) throws Exception {
return node.getCommitDate() <= timestamp;
}
/** {@inheritDoc} */
@Override
protected boolean preVisit(final ChangedFile node) throws Exception {
if (node.getChange() == ChangeKind.DELETED) {
map.remove(node.getName());
return false;
}
boolean filter = kinds.length > 0;
if (filter) {
final String kindName = node.getKind().name();
for (final String kind : kinds)
if (kindName.startsWith(kind)) {
filter = false;
break;
}
}
if (!filter)
map.put(node.getName(), node);
return false;
}
}
public final static SnapshotVisitor snapshot = new SnapshotVisitor();
@FunctionSpec(name = "getsnapshot", returnType = "array of ChangedFile", formalParameters = { "CodeRepository", "time", "string..." })
public static ChangedFile[] getSnapshot(final CodeRepository cr, final long timestamp, final String... kinds) throws Exception {
snapshot.initialize(timestamp, kinds).visit(cr);
return snapshot.map.values().toArray(new ChangedFile[0]);
}
@FunctionSpec(name = "getsnapshot", returnType = "array of ChangedFile", formalParameters = { "CodeRepository", "string..." })
public static ChangedFile[] getSnapshot(final CodeRepository cr, final String... kinds) throws Exception {
return getSnapshot(cr, Long.MAX_VALUE, kinds);
}
@FunctionSpec(name = "getsnapshot", returnType = "array of ChangedFile", formalParameters = { "CodeRepository", "time" })
public static ChangedFile[] getSnapshot(final CodeRepository cr, final long timestamp) throws Exception {
return getSnapshot(cr, timestamp, new String[0]);
}
@FunctionSpec(name = "getsnapshot", returnType = "array of ChangedFile", formalParameters = { "CodeRepository" })
public static ChangedFile[] getSnapshot(final CodeRepository cr) throws Exception {
return getSnapshot(cr, Long.MAX_VALUE, new String[0]);
}
///////////////////////////////
// Literal testing functions */
///////////////////////////////
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is an integer literal.
*
* The test is a simplified grammar, based on the one from:
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10
*
* DecimalNumeral:
* [0-9] [lL]?
* [1-9] [0-9] ([0-9_]* [0-9])? [lL]?
* [1-9] [_]+ [0-9] ([0-9_]* [0-9])? [lL]?
*
* HexNumeral:
* 0 [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?
*
* OctalNumeral:
* 0 [_]* [0-7] ([0-7_]* [0-7])? [lL]?
*
* BinaryNumeral:
* 0 [bB] [01] ([01_]* [01])? [lL]?
*
* If any of these match, it returns <code>true</code>. Otherwise it
* returns <code>false</code>.
*
* @param e the expression to test
* @return true if the expression is an integer literal, otherwise false
*/
@FunctionSpec(name = "isintlit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isIntLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
if (e.getLiteral().matches("^[0-9][lL]?$")) return true;
if (e.getLiteral().matches("^[1-9][0-9]([0-9_]*[0-9])?[lL]?$")) return true;
if (e.getLiteral().matches("^[1-9][_]+[0-9]([0-9_]*[0-9])?[lL]?$")) return true;
if (e.getLiteral().matches("^0[xX][0-9a-fA-F]([0-9a-fA-F_]*[0-9a-fA-F])?[lL]?$")) return true;
if (e.getLiteral().matches("^0[_]*[0-7]([0-7_]*[0-7])?[lL]?$")) return true;
return e.getLiteral().matches("^0[bB][01]([01_]*[01])?[lL]?$");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is a float literal.
*
* The test is a simplified grammar, based on the one from:
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10
*
* DecimalFloatingPointLiteral:
* [0-9] ([0-9_]* [0-9])? \\. ([0-9] ([0-9_]* [0-9])?)? ([eE] [+-]? [0-9] ([0-9_]* [0-9])?)? [fFdD]?
* \\. [0-9] ([0-9_]* [0-9])? ([eE] [+-]? [0-9] ([0-9_]* [0-9])?)? [fFdD]?
* [0-9] ([0-9_]* [0-9])? [eE] [+-]? [0-9] ([0-9_]* [0-9])? [fFdD]?
* [0-9] ([0-9_]* [0-9])? ([eE] [+-]? [0-9] ([0-9_]* [0-9])?)? [fFdD]
*
* HexadecimalFloatingPointLiteral:
* 0 [Xx] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? \\.? [pP] [+-]? [0-9] ([0-9_]* [0-9])? [fFdD]?
* 0 [Xx] ([0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])?)? \\. [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [pP] [+-]? [0-9] ([0-9_]* [0-9])? [fFdD]?
*
* @param e the expression to test
* @return true if the expression is a char literal, otherwise false
*/
@FunctionSpec(name = "isfloatlit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isFloatLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
if (e.getLiteral().matches("^[0-9]([0-9_]*[0-9])?\\.([0-9]([0-9_]*[0-9])?)?([eE][+-]?[0-9]([0-9_]*[0-9])?)?[fFdD]?$")) return true;
if (e.getLiteral().matches("^\\.[0-9]([0-9_]*[0-9])?([eE][+-]?[0-9]([0-9_]*[0-9])?)?[fFdD]?$")) return true;
if (e.getLiteral().matches("^[0-9]([0-9_]*[0-9])?[eE][+-]?[0-9]([0-9_]*[0-9])?[fFdD]?$")) return true;
if (e.getLiteral().matches("^[0-9]([0-9_]*[0-9])?([eE][+-]?[0-9]([0-9_]*[0-9])?)?[fFdD]$")) return true;
if (e.getLiteral().matches("^0[Xx][0-9a-fA-F]([0-9a-fA-F_]*[0-9a-fA-F])?\\.?[pP][+-]?[0-9]([0-9_]*[0-9])?[fFdD]?$")) return true;
return e.getLiteral().matches("^0[Xx]([0-9a-fA-F]([0-9a-fA-F_]*[0-9a-fA-F])?)?\\.[0-9a-fA-F]([0-9a-fA-F_]*[0-9a-fA-F])?[pP][+-]?[0-9]([0-9_]*[0-9])?[fFdD]?$");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is a char literal.
*
* @param e the expression to test
* @return true if the expression is a char literal, otherwise false
*/
@FunctionSpec(name = "ischarlit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isCharLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
return e.getLiteral().startsWith("'");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is a string literal.
*
* @param e the expression to test
* @return true if the expression is a string literal, otherwise false
*/
@FunctionSpec(name = "isstringlit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isStringLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
return e.getLiteral().startsWith("\"");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is a type literal.
*
* @param e the expression to test
* @return true if the expression is a type literal, otherwise false
*/
@FunctionSpec(name = "istypelit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isTypeLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
return e.getLiteral().endsWith(".class");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is a bool literal.
*
* @param e the expression to test
* @return true if the expression is a bool literal, otherwise false
*/
@FunctionSpec(name = "isboollit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isBoolLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
return e.getLiteral().equals("true") || e.getLiteral().equals("false");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and is a null literal.
*
* @param e the expression to test
* @return true if the expression is a null literal, otherwise false
*/
@FunctionSpec(name = "isnulllit", returnType = "bool", formalParameters = { "Expression" })
public static boolean isNullLit(final Expression e) throws Exception {
if (e.getKind() != Expression.ExpressionKind.LITERAL) return false;
if (!e.hasLiteral()) return false;
return e.getLiteral().equals("null");
}
/**
* Returns <code>true</code> if the expression <code>e</code> is of kind
* <code>LITERAL</code> and the literal matches the string <code>lit</code>.
*
* @param e the expression to test
* @return true if the expression is a string literal, otherwise false
*/
@FunctionSpec(name = "isliteral", returnType = "bool", formalParameters = { "Expression", "string" })
public static boolean isLiteral(final Expression e, final String lit) throws Exception {
return e.getKind() == Expression.ExpressionKind.LITERAL && e.hasLiteral() && e.getLiteral().equals(lit);
}
//////////////////////////////
// Collect Annotations Used //
//////////////////////////////
private static class AnnotationCollectingVisitor extends BoaCollectingVisitor<String,Long> {
@Override
protected boolean preVisit(Modifier node) {
if (node.getKind() == Modifier.ModifierKind.ANNOTATION) {
final String name = BoaAstIntrinsics.type_name(node.getAnnotationName());
final long count = map.containsKey(name) ? map.get(name) : 0;
map.put(name, count + 1);
}
return true;
}
}
private static AnnotationCollectingVisitor annotationCollectingVisitor = new AnnotationCollectingVisitor();
@FunctionSpec(name = "collect_annotations", returnType = "map[string] of int", formalParameters = { "ASTRoot", "map[string] of int" })
public static HashMap<String,Long> collect_annotations(final ASTRoot f, final HashMap<String,Long> map) throws Exception {
annotationCollectingVisitor.initialize(map).visit(f);
return annotationCollectingVisitor.map;
}
///////////////////////////
// Collect Generics Used //
///////////////////////////
private static class GenericsCollectingVisitor extends BoaCollectingVisitor<String,Long> {
@Override
protected boolean preVisit(Type node) {
// FIXME
/*
try {
parseGenericType(BoaAstIntrinsics.type_name(node.getName()).trim(), map);
} catch (final StackOverflowError e) {
System.err.println("STACK ERR: " + node.getName() + " -> " + BoaAstIntrinsics.type_name(node.getName()).trim());
}
*/
return true;
}
}
private static GenericsCollectingVisitor genericsCollectingVisitor = new GenericsCollectingVisitor();
@FunctionSpec(name = "collect_generic_types", returnType = "map[string] of int", formalParameters = { "ASTRoot", "map[string] of int" })
public static HashMap<String,Long> collect_generic_types(final ASTRoot f, final HashMap<String,Long> map) throws Exception {
genericsCollectingVisitor.initialize(map).visit(f);
return genericsCollectingVisitor.map;
}
private static void parseGenericType(final String name, final HashMap<String,Long> counts) {
if (!name.contains("<") || name.startsWith("<"))
return;
if (name.contains("|")) {
for (final String s : name.split("\\|"))
parseGenericType(s.trim(), counts);
return;
}
if (name.contains("&")) {
int count = 0;
int last = 0;
for (int i = 0; i < name.length(); i++)
switch (name.charAt(i)) {
case '<':
count++;
break;
case '>':
count--;
break;
case '&':
if (count == 0) {
parseGenericType(name.substring(last, i).trim(), counts);
last = i + 1;
}
break;
default:
break;
}
parseGenericType(name.substring(last).trim(), counts);
return;
}
foundType(name, counts);
int start = name.indexOf("<");
final Stack<Integer> starts = new Stack<Integer>();
int lastStart = start + 1;
for (int i = lastStart; i < name.lastIndexOf(">"); i++)
switch (name.charAt(i)) {
case '<':
starts.push(lastStart);
lastStart = i + 1;
break;
case '>':
if (!starts.empty())
foundType(name.substring(starts.pop(), i + 1).trim(), counts);
break;
case '&':
case '|':
case ',':
case ' ':
case '.':
case '\t':
lastStart = i + 1;
break;
default:
break;
}
}
private static void foundType(final String name, final HashMap<String,Long> counts) {
final String type = name.endsWith("...") ? name.substring(0, name.length() - 3).trim() : name.trim();
final long count = counts.containsKey(type) ? counts.get(type) : 0;
counts.put(type, count + 1);
String rawType = type.substring(0, type.indexOf("<")).trim();
if (!type.endsWith(">"))
rawType += type.substring(type.lastIndexOf(">") + 1).trim();
final long rawCount = counts.containsKey(rawType) ? counts.get(rawType) : 0;
counts.put(rawType, rawCount + 1);
}
}