-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathCompletionGenerator.java
More file actions
1814 lines (1640 loc) · 70.1 KB
/
Copy pathCompletionGenerator.java
File metadata and controls
1814 lines (1640 loc) · 70.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
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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package processing.mode.java;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.swing.DefaultListModel;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ArrayAccess;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationExpression;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import processing.app.Messages;
import com.google.classpath.ClassPath;
import com.google.classpath.RegExpResourceFilter;
import processing.mode.java.preproc.ImportStatement;
import processing.mode.java.preproc.SourceUtil;
import processing.mode.java.preproc.TextTransform;
@SuppressWarnings({ "unchecked" })
public class CompletionGenerator {
JavaMode mode;
public CompletionGenerator(JavaMode mode) {
this.mode = mode;
}
static private CompletionCandidate[] checkForTypes(ASTNode node) {
List<VariableDeclarationFragment> vdfs = null;
switch (node.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
return new CompletionCandidate[]{new CompletionCandidate((TypeDeclaration) node)};
case ASTNode.METHOD_DECLARATION:
MethodDeclaration md = (MethodDeclaration) node;
log(getNodeAsString(md));
List<ASTNode> params = (List<ASTNode>) md
.getStructuralProperty(MethodDeclaration.PARAMETERS_PROPERTY);
CompletionCandidate[] cand = new CompletionCandidate[params.size() + 1];
cand[0] = new CompletionCandidate(md);
for (int i = 0; i < params.size(); i++) {
cand[i + 1] = new CompletionCandidate((SingleVariableDeclaration) params.get(i));
}
return cand;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
return new CompletionCandidate[]{new CompletionCandidate((SingleVariableDeclaration) node)};
case ASTNode.FIELD_DECLARATION:
vdfs = ((FieldDeclaration) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
vdfs = ((VariableDeclarationStatement) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
vdfs = ((VariableDeclarationExpression) node).fragments();
break;
default:
break;
}
if (vdfs != null) {
CompletionCandidate[] outgoing = new CompletionCandidate[vdfs.size()];
int i = 0;
for (VariableDeclarationFragment vdf : vdfs) {
// ret[i++] = new CompletionCandidate(getNodeAsString2(vdf), "", "",
// CompletionCandidate.LOCAL_VAR);
outgoing[i++] = new CompletionCandidate(vdf);
}
return outgoing;
}
return null;
}
/**
* Finds the type of the expression in foo.bar().a().b, this would give me the
* type of b if it exists in return type of a(). If noCompare is true,
* it'll return type of a()
*/
static private ClassMember resolveExpression3rdParty(PreprocSketch ps, ASTNode nearestNode,
ASTNode astNode, boolean noCompare) {
log("Resolve 3rdParty expr-- " + getNodeAsString(astNode)
+ " nearest node " + getNodeAsString(nearestNode));
if (astNode == null) return null;
ClassMember scopeParent;
SimpleType stp;
if (astNode instanceof SimpleName){
ASTNode decl = findDeclaration2(((SimpleName)astNode),nearestNode);
if (decl != null) {
// see if locally defined
log(getNodeAsString(astNode)+" found decl -> " + getNodeAsString(decl));
{
if (decl.getNodeType() == ASTNode.TYPE_DECLARATION) {
TypeDeclaration td = (TypeDeclaration) decl;
return new ClassMember(ps, td);
}
}
{ // Handle "array." x "array[1]."
Type type = extracTypeInfo2(decl);
if (type != null && type.isArrayType() &&
astNode.getParent().getNodeType() != ASTNode.ARRAY_ACCESS) {
// No array access, we want members of the array itself
Type elementType = ((ArrayType) type).getElementType();
// Get name of the element class
String name = "";
if (elementType.isSimpleType()) {
Class<?> c = findClassIfExists(ps, elementType.toString());
if (c != null) name = c.getName();
} else if (elementType.isPrimitiveType()) {
name = ((PrimitiveType) elementType).getPrimitiveTypeCode().toString();
}
// Convert element class to array class
Class<?> arrayClass = getArrayClass(name, ps.classLoader);
return arrayClass == null ? null : new ClassMember(arrayClass);
}
}
return new ClassMember(ps, extracTypeInfo(decl));
} else {
// or in a predefined class?
Class<?> tehClass = findClassIfExists(ps, astNode.toString());
if (tehClass != null) {
return new ClassMember(tehClass);
}
}
astNode = astNode.getParent();
}
switch (astNode.getNodeType()) {
//TODO: Notice the redundancy in the 3 cases, you can simplify things even more.
case ASTNode.FIELD_ACCESS:
FieldAccess fa = (FieldAccess) astNode;
if (fa.getExpression() == null) {
// TODO: Check for existence of 'new' keyword. Could be a ClassInstanceCreation
// Local code or belongs to super class
log("FA,Not implemented.");
return null;
} else {
if (fa.getExpression() instanceof SimpleName) {
stp = extracTypeInfo(findDeclaration2((SimpleName) fa.getExpression(),
nearestNode));
if(stp == null){
/*The type wasn't found in local code, so it might be something like
* log(), or maybe belonging to super class, etc.
*/
Class<?> tehClass = findClassIfExists(ps, fa.getExpression().toString());
if (tehClass != null) {
// Method Expression is a simple name and wasn't located locally, but found in a class
// so look for method in this class.
return definedIn3rdPartyClass(ps, new ClassMember(tehClass), fa
.getName().toString());
}
log("FA resolve 3rd par, Can't resolve " + fa.getExpression());
return null;
}
log("FA, SN Type " + getNodeAsString(stp));
scopeParent = definedIn3rdPartyClass(ps, stp.getName().toString(), "THIS");
} else {
scopeParent = resolveExpression3rdParty(ps, nearestNode,
fa.getExpression(), noCompare);
}
log("FA, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(ps, scopeParent, fa.getName().toString());
}
case ASTNode.METHOD_INVOCATION:
MethodInvocation mi = (MethodInvocation) astNode;
ASTNode temp = findDeclaration2(mi.getName(), nearestNode);
if(temp instanceof MethodDeclaration){
// method is locally defined
log(mi.getName() + " was found locally," + getNodeAsString(extracTypeInfo(temp)));
{ // Handle "array." x "array[1]."
Type type = extracTypeInfo2(temp);
if (type != null && type.isArrayType() &&
astNode.getParent().getNodeType() != ASTNode.ARRAY_ACCESS) {
// No array access, we want members of the array itself
Type elementType = ((ArrayType) type).getElementType();
// Get name of the element class
String name = "";
if (elementType.isSimpleType()) {
Class<?> c = findClassIfExists(ps, elementType.toString());
if (c != null) name = c.getName();
} else if (elementType.isPrimitiveType()) {
name = ((PrimitiveType) elementType).getPrimitiveTypeCode().toString();
}
// Convert element class to array class
Class<?> arrayClass = getArrayClass(name, ps.classLoader);
return arrayClass == null ? null : new ClassMember(arrayClass);
}
}
return new ClassMember(ps, extracTypeInfo(temp));
}
if (mi.getExpression() == null) {
// if()
//Local code or belongs to super class
log("MI,Not implemented.");
return null;
} else {
if (mi.getExpression() instanceof SimpleName) {
ASTNode decl = findDeclaration2((SimpleName) mi.getExpression(),
nearestNode);
if (decl != null) {
if (decl.getNodeType() == ASTNode.TYPE_DECLARATION) {
TypeDeclaration td = (TypeDeclaration) decl;
return new ClassMember(ps, td);
}
stp = extracTypeInfo(decl);
if(stp == null){
/*The type wasn't found in local code, so it might be something like
* System.console()., or maybe belonging to super class, etc.
*/
Class<?> tehClass = findClassIfExists(ps, mi.getExpression().toString());
if (tehClass != null) {
// Method Expression is a simple name and wasn't located locally, but found in a class
// so look for method in this class.
return definedIn3rdPartyClass(ps, new ClassMember(tehClass), mi
.getName().toString());
}
log("MI resolve 3rd par, Can't resolve " + mi.getExpression());
return null;
}
log("MI, SN Type " + getNodeAsString(stp));
ASTNode typeDec = findDeclaration2(stp.getName(),nearestNode);
if(typeDec == null){
log(stp.getName() + " couldn't be found locally..");
Class<?> tehClass = findClassIfExists(ps, stp.getName().toString());
if (tehClass != null) {
// Method Expression is a simple name and wasn't located locally, but found in a class
// so look for method in this class.
return definedIn3rdPartyClass(ps, new ClassMember(tehClass), mi
.getName().toString());
}
//return new ClassMember(findClassIfExists(stp.getName().toString()));
}
//scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
return definedIn3rdPartyClass(ps, new ClassMember(ps, typeDec), mi
.getName().toString());
}
} else {
log("MI EXP.."+getNodeAsString(mi.getExpression()));
// return null;
scopeParent = resolveExpression3rdParty(ps, nearestNode,
mi.getExpression(), noCompare);
log("MI, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(ps, scopeParent, mi.getName().toString());
}
}
break;
case ASTNode.QUALIFIED_NAME:
QualifiedName qn = (QualifiedName) astNode;
ASTNode temp2 = findDeclaration2(qn.getName(), nearestNode);
if(temp2 instanceof FieldDeclaration){
// field is locally defined
log(qn.getName() + " was found locally," + getNodeAsString(extracTypeInfo(temp2)));
return new ClassMember(ps, extracTypeInfo(temp2));
}
if (qn.getQualifier() == null) {
log("QN,Not implemented.");
return null;
} else {
if (qn.getQualifier() instanceof SimpleName) {
stp = extracTypeInfo(findDeclaration2(qn.getQualifier(), nearestNode));
if(stp == null){
/*The type wasn't found in local code, so it might be something like
* log(), or maybe belonging to super class, etc.
*/
Class<?> tehClass = findClassIfExists(ps, qn.getQualifier().toString());
if (tehClass != null) {
// note how similar thing is called on line 690. Check check.
return definedIn3rdPartyClass(ps, new ClassMember(tehClass), qn
.getName().toString());
}
log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
return null;
}
log("QN, SN Local Type " + getNodeAsString(stp));
//scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
ASTNode typeDec = findDeclaration2(stp.getName(),nearestNode);
if(typeDec == null){
log(stp.getName() + " couldn't be found locally..");
Class<?> tehClass = findClassIfExists(ps, stp.getName().toString());
if (tehClass != null) {
// note how similar thing is called on line 690. Check check.
return definedIn3rdPartyClass(ps, new ClassMember(tehClass), qn
.getName().toString());
}
log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
return null;
}
return definedIn3rdPartyClass(ps, new ClassMember(ps, typeDec), qn
.getName().toString());
} else {
scopeParent = resolveExpression3rdParty(ps, nearestNode,
qn.getQualifier(), noCompare);
log("QN, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(ps, scopeParent, qn.getName().toString());
}
}
case ASTNode.ARRAY_ACCESS:
ArrayAccess arac = (ArrayAccess)astNode;
return resolveExpression3rdParty(ps, nearestNode, arac.getArray(), noCompare);
default:
log("Unaccounted type " + getNodeAsString(astNode));
break;
}
return null;
}
static private Class<?> getArrayClass(String elementClass, ClassLoader classLoader) {
String name;
if (elementClass.startsWith("[")) {
// just add a leading "["
name = "[" + elementClass;
} else if (elementClass.equals("boolean")) {
name = "[Z";
} else if (elementClass.equals("byte")) {
name = "[B";
} else if (elementClass.equals("char")) {
name = "[C";
} else if (elementClass.equals("double")) {
name = "[D";
} else if (elementClass.equals("float")) {
name = "[F";
} else if (elementClass.equals("int")) {
name = "[I";
} else if (elementClass.equals("long")) {
name = "[J";
} else if (elementClass.equals("short")) {
name = "[S";
} else {
// must be an object non-array class
name = "[L" + elementClass + ";";
}
return loadClass(name, classLoader);
}
/**
* For a().abc.a123 this would return a123
*/
static private ASTNode getChildExpression(ASTNode expression) {
if (expression instanceof SimpleName) {
return expression;
} else if (expression instanceof FieldAccess) {
return ((FieldAccess) expression).getName();
} else if (expression instanceof QualifiedName) {
return ((QualifiedName) expression).getName();
}else if (expression instanceof MethodInvocation) {
return ((MethodInvocation) expression).getName();
}else if(expression instanceof ArrayAccess){
return ((ArrayAccess)expression).getArray();
}
log(" getChildExpression returning NULL for "
+ getNodeAsString(expression));
return null;
}
static private ASTNode getParentExpression(ASTNode expression) {
if (expression instanceof SimpleName) {
return expression;
} else if (expression instanceof FieldAccess) {
return ((FieldAccess) expression).getExpression();
} else if (expression instanceof QualifiedName) {
return ((QualifiedName) expression).getQualifier();
} else if (expression instanceof MethodInvocation) {
return ((MethodInvocation) expression).getExpression();
} else if (expression instanceof ArrayAccess) {
return ((ArrayAccess) expression).getArray();
}
log("getParentExpression returning NULL for "
+ getNodeAsString(expression));
return null;
}
/**
* Loads classes from .jar files in sketch classpath
*/
static public List<CompletionCandidate> getMembersForType(PreprocSketch ps,
String typeName,
String child,
boolean noCompare,
boolean staticOnly) {
List<CompletionCandidate> candidates = new ArrayList<>();
log("In GMFT(), Looking for match " + child
+ " in class " + typeName + " noCompare " + noCompare + " staticOnly "
+ staticOnly);
Class<?> probableClass = findClassIfExists(ps, typeName);
if (probableClass == null) {
log("In GMFT(), class not found.");
return candidates;
}
return getMembersForType(ps, new ClassMember(probableClass), child, noCompare, staticOnly);
}
static public ArrayList<CompletionCandidate> getMembersForType(PreprocSketch ps,
ClassMember tehClass,
String childToLookFor,
boolean noCompare,
boolean staticOnly) {
String child = childToLookFor.toLowerCase();
ArrayList<CompletionCandidate> candidates = new ArrayList<>();
log("getMemFoType-> Looking for match " + child
+ " inside " + tehClass + " noCompare " + noCompare + " staticOnly "
+ staticOnly);
if(tehClass == null){
return candidates;
}
// tehClass will either be a TypeDecl defined locally
if(tehClass.getDeclaringNode() instanceof TypeDeclaration){
TypeDeclaration td = (TypeDeclaration) tehClass.getDeclaringNode();
{
FieldDeclaration[] fields = td.getFields();
for (FieldDeclaration field : fields) {
if (staticOnly && notStatic(field.modifiers())) {
continue;
}
List<VariableDeclarationFragment> vdfs = field.fragments();
for (VariableDeclarationFragment vdf : vdfs) {
if (noCompare) {
candidates.add(new CompletionCandidate(vdf));
} else if (vdf.getName().toString().toLowerCase().startsWith(child))
candidates.add(new CompletionCandidate(vdf));
}
}
}
{
MethodDeclaration[] methods = td.getMethods();
for (MethodDeclaration method : methods) {
if (staticOnly && notStatic(method.modifiers())) {
continue;
}
if (noCompare) {
candidates.add(new CompletionCandidate(method));
} else if (method.getName().toString().toLowerCase()
.startsWith(child))
candidates.add(new CompletionCandidate(method));
}
}
ArrayList<CompletionCandidate> superClassCandidates;
if (td.getSuperclassType() != null) {
log(getNodeAsString(td.getSuperclassType()) + " <-Looking into superclass of " + tehClass);
ClassMember cm = new ClassMember(ps, td.getSuperclassType());
superClassCandidates =
getMembersForType(ps, cm, childToLookFor, noCompare, staticOnly);
} else {
superClassCandidates = getMembersForType(ps, new ClassMember(Object.class),
childToLookFor, noCompare, staticOnly);
}
candidates.addAll(superClassCandidates);
return candidates;
}
// Or tehClass will be a predefined class
Class<?> probableClass;
if (tehClass.getClass_() != null) {
probableClass = tehClass.getClass_();
} else {
probableClass = findClassIfExists(ps, tehClass.getTypeAsString());
if (probableClass == null) {
log("Couldn't find class " + tehClass.getTypeAsString());
return candidates;
}
log("Loaded " + probableClass);
}
for (Method method : probableClass.getMethods()) {
if (!Modifier.isStatic(method.getModifiers()) && staticOnly) {
continue;
}
StringBuilder label = new StringBuilder(method.getName() + "(");
for (int i = 0; i < method.getParameterTypes().length; i++) {
label.append(method.getParameterTypes()[i].getSimpleName());
if (i < method.getParameterTypes().length - 1)
label.append(",");
}
label.append(")");
if (noCompare) {
candidates.add(new CompletionCandidate(method));
} else if (label.toString().toLowerCase().startsWith(child)) {
candidates.add(new CompletionCandidate(method));
}
}
for (Field field : probableClass.getFields()) {
if (!Modifier.isStatic(field.getModifiers()) && staticOnly) {
continue;
}
if (noCompare) {
candidates.add(new CompletionCandidate(field));
} else if (field.getName().toLowerCase().startsWith(child)) {
candidates.add(new CompletionCandidate(field));
}
}
if (probableClass.isArray() && !staticOnly) {
// add array members manually, they can't be fetched through code
String className = probableClass.getSimpleName();
if (noCompare || "clone()".startsWith(child)) {
String methodLabel = "<html>clone() : " + className +
" - <font color=#777777>" + className + "</font></html>";
candidates.add(new CompletionCandidate("clone()", methodLabel, "clone()",
CompletionCandidate.PREDEF_METHOD));
}
if ("length".startsWith(child)) {
String fieldLabel = "<html>length : int - <font color=#777777>" +
className + "</font></html>";
candidates.add(new CompletionCandidate("length", fieldLabel, "length",
CompletionCandidate.PREDEF_FIELD));
}
}
return candidates;
}
static private boolean notStatic(List<org.eclipse.jdt.core.dom.Modifier> modifiers) {
for (org.eclipse.jdt.core.dom.Modifier m : modifiers) {
if (m.isStatic()) return false;
}
return true;
}
/**
* Searches for the particular class in the default list of imports as well as
* the Sketch classpath
*/
static private Class<?> findClassIfExists(PreprocSketch ps, String className){
if (className == null){
return null;
}
if (className.indexOf('.') >= 0) {
// Figure out what is package and what is class
String[] parts = className.split("\\.");
StringBuilder newClassName = new StringBuilder(parts[0]);
int i = 1;
while (i < parts.length &&
ps.classPath.isPackage(newClassName.toString())) {
newClassName.append('/').append(parts[i++]);
}
while (i < parts.length) {
newClassName.append('$').append(parts[i++]);
}
className = newClassName.toString().replace('/', '.');
}
// First, see if the classname is a fully qualified name and loads straightaway
Class<?> tehClass = loadClass(className, ps.classLoader);
if (tehClass != null) {
//log(tehClass.getName() + " located straightaway");
return tehClass;
}
// This name is qualified and it already had its chance
if (className.indexOf('.') >= 0) {
return null;
}
log("Looking in the classloader for " + className);
// Using ClassPath and RegExResourceFilter to find a matching class
// and then loading the thing might be simpler and faster
// These can be preprocessed during error check for performance
// (collect, split into starred and not starred)
List<ImportStatement> programImports = ps.programImports;
List<ImportStatement> codeFolderImports = ps.codeFolderImports;
List<ImportStatement> coreAndDefaultImports = ps.coreAndDefaultImports;
ImportStatement javaLang = ImportStatement.wholePackage("java.lang");
Stream<List<ImportStatement>> importListStream =
Stream.of(Collections.singletonList(javaLang), coreAndDefaultImports,
programImports, codeFolderImports);
final String finalClassName = className;
// These streams can be made unordered parallel if it helps performance
return importListStream
.map(list -> list.stream()
.map(is -> {
if (is.getMemberName().equals(finalClassName)) {
return is.getFullMemberName();
} else if (is.isStarredImport()) {
return is.getPackageName() + "." + finalClassName;
}
return null;
})
.filter(Objects::nonNull)
.map(name -> loadClass(name, ps.classLoader))
.filter(Objects::nonNull)
.findAny())
.filter(Optional::isPresent)
.map(Optional::get)
.findAny()
.orElse(null);
}
static private Class<?> loadClass(String className, ClassLoader classLoader){
Class<?> tehClass = null;
if (className != null) {
try {
tehClass = Class.forName(className, false, classLoader);
} catch (ClassNotFoundException e) {
//log("Doesn't exist in package: ");
}
}
return tehClass;
}
static ClassMember definedIn3rdPartyClass(PreprocSketch ps, String className, String memberName){
Class<?> probableClass = findClassIfExists(ps, className);
if (probableClass == null) {
log("Couldn't load " + className);
return null;
}
if (memberName.equals("THIS")) {
return new ClassMember(probableClass);
} else {
return definedIn3rdPartyClass(ps, new ClassMember(probableClass), memberName);
}
}
static ClassMember definedIn3rdPartyClass(PreprocSketch ps, ClassMember tehClass,String memberName){
if(tehClass == null)
return null;
log("definedIn3rdPartyClass-> Looking for " + memberName
+ " in " + tehClass);
String memberNameL = memberName.toLowerCase();
if (tehClass.getDeclaringNode() instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) tehClass.getDeclaringNode();
for (int i = 0; i < td.getFields().length; i++) {
List<VariableDeclarationFragment> vdfs =
td.getFields()[i].fragments();
for (VariableDeclarationFragment vdf : vdfs) {
if (vdf.getName().toString().toLowerCase()
.startsWith(memberNameL))
return new ClassMember(ps, vdf);
}
}
for (int i = 0; i < td.getMethods().length; i++) {
if (td.getMethods()[i].getName().toString().toLowerCase()
.startsWith(memberNameL))
return new ClassMember(ps, td.getMethods()[i]);
}
if (td.getSuperclassType() != null) {
log(getNodeAsString(td.getSuperclassType()) + " <-Looking into superclass of " + tehClass);
return definedIn3rdPartyClass(ps, new ClassMember(ps, td
.getSuperclassType()),memberName);
} else {
return definedIn3rdPartyClass(ps, new ClassMember(Object.class),memberName);
}
}
Class<?> probableClass;
if (tehClass.getClass_() != null) {
probableClass = tehClass.getClass_();
} else {
probableClass = findClassIfExists(ps, tehClass.getTypeAsString());
log("Loaded " + probableClass.toString());
}
for (Method method : probableClass.getMethods()) {
if (method.getName().equalsIgnoreCase(memberName)) {
return new ClassMember(method);
}
}
for (Field field : probableClass.getFields()) {
if (field.getName().equalsIgnoreCase(memberName)) {
return new ClassMember(field);
}
}
return null;
}
static private ASTNode findClosestParentNode(int lineNumber, ASTNode node) {
// Base.loge("Props of " + node.getClass().getName());
for (StructuralPropertyDescriptor prop : (Iterable<StructuralPropertyDescriptor>) node
.structuralPropertiesForType()) {
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) != null) {
// System.out
// .println(node.getStructuralProperty(prop) + " -> " + (prop));
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode cnode = (ASTNode) node.getStructuralProperty(prop);
// log("Looking at " + getNodeAsString(cnode)+ " for line num " + lineNumber);
int cLineNum = ((CompilationUnit) cnode.getRoot())
.getLineNumber(cnode.getStartPosition() + cnode.getLength());
if (getLineNumber(cnode) <= lineNumber && lineNumber <= cLineNum) {
return findClosestParentNode(lineNumber, cnode);
}
}
}
} else if (prop.isChildListProperty()) {
List<ASTNode> nodelist = (List<ASTNode>) node
.getStructuralProperty(prop);
for (ASTNode cnode : nodelist) {
int cLineNum = ((CompilationUnit) cnode.getRoot())
.getLineNumber(cnode.getStartPosition() + cnode.getLength());
// log("Looking at " + getNodeAsString(cnode)+ " for line num " + lineNumber);
if (getLineNumber(cnode) <= lineNumber && lineNumber <= cLineNum) {
return findClosestParentNode(lineNumber, cnode);
}
}
}
}
return node;
}
static private ASTNode findClosestNode(int lineNumber, ASTNode node) {
log("findClosestNode to line " + lineNumber);
ASTNode parent = findClosestParentNode(lineNumber, node);
log("findClosestParentNode returned " + getNodeAsString(parent));
if (parent == null)
return null;
if (getLineNumber(parent) == lineNumber){
log(parent + "|PNode " + getLineNumber(parent) + ", lfor " + lineNumber );
return parent;
}
List<ASTNode> nodes;
if (parent instanceof TypeDeclaration) {
nodes = ((TypeDeclaration) parent).bodyDeclarations();
} else if (parent instanceof Block) {
nodes = ((Block) parent).statements();
} else {
log("findClosestNode() found " + getNodeAsString(parent));
return null;
}
if (nodes.size() > 0) {
ASTNode retNode = parent;
for (ASTNode cNode : nodes) {
log(cNode + "|cNode " + getLineNumber(cNode) + ", lfor " + lineNumber);
if (getLineNumber(cNode) <= lineNumber)
retNode = cNode;
}
return retNode;
}
return parent;
}
/**
* Fetches line number of the node in its CompilationUnit.
*/
static public int getLineNumber(ASTNode node) {
CompilationUnit cu = (CompilationUnit) node.getRoot();
return cu.getLineNumber(node.getStartPosition());
}
/**
* Give this thing a {@link Name} instance - a {@link SimpleName} from the
* ASTNode for ex, and it tries its level best to locate its declaration in
* the AST. It really does.
*/
static private ASTNode findDeclaration(Name findMe) {
// WARNING: You're entering the Rube Goldberg territory of Experimental Mode.
// To debug this code, thou must take the Recursive Leap of Faith.
// log("entering --findDeclaration1 -- " + findMe.toString());
ASTNode declaringClass;
ASTNode parent = findMe.getParent();
ASTNode ret;
ArrayList<Integer> constrains = new ArrayList<>();
if (parent.getNodeType() == ASTNode.METHOD_INVOCATION) {
Expression exp = (Expression) parent.getStructuralProperty(MethodInvocation.EXPRESSION_PROPERTY);
//TODO: Note the imbalance of constrains.add(ASTNode.METHOD_DECLARATION);
// Possibly a bug here. Investigate later.
if (((MethodInvocation) parent).getName().toString()
.equals(findMe.toString())) {
constrains.add(ASTNode.METHOD_DECLARATION);
if (exp != null) {
constrains.add(ASTNode.TYPE_DECLARATION);
// log("MI EXP: " + exp.toString() + " of type "
// + exp.getClass().getName() + " parent: " + exp.getParent());
if (exp instanceof MethodInvocation) {
SimpleType stp = extracTypeInfo(findDeclaration(((MethodInvocation) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains);
} else if (exp instanceof FieldAccess) {
SimpleType stp = extracTypeInfo(findDeclaration(((FieldAccess) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration((stp.getName()));
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains);
}
if (exp instanceof SimpleName) {
SimpleType stp = extracTypeInfo(findDeclaration(((SimpleName) exp)));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
// log("MI.SN " + getNodeAsString(declaringClass));
constrains.add(ASTNode.METHOD_DECLARATION);
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains);
}
}
} else {
parent = parent.getParent(); // Move one up the AST. Very important.
}
} else if (parent.getNodeType() == ASTNode.FIELD_ACCESS) {
FieldAccess fa = (FieldAccess) parent;
Expression exp = fa.getExpression();
if (fa.getName().toString().equals(findMe.toString())) {
constrains.add(ASTNode.FIELD_DECLARATION);
if (exp != null) {
constrains.add(ASTNode.TYPE_DECLARATION);
// log("FA EXP: " + exp.toString() + " of type "
// + exp.getClass().getName() + " parent: " + exp.getParent());
if (exp instanceof MethodInvocation) {
SimpleType stp = extracTypeInfo(findDeclaration(((MethodInvocation) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
return definedIn(declaringClass, fa.getName().toString(),
constrains);
} else if (exp instanceof FieldAccess) {
SimpleType stp = extracTypeInfo(findDeclaration(((FieldAccess) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration((stp.getName()));
constrains.add(ASTNode.TYPE_DECLARATION);
return definedIn(declaringClass, fa.getName().toString(),
constrains);
}
if (exp instanceof SimpleName) {
SimpleType stp = extracTypeInfo(findDeclaration(((SimpleName) exp)));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
// log("FA.SN " + getNodeAsString(declaringClass));
constrains.add(ASTNode.METHOD_DECLARATION);
return definedIn(declaringClass, fa.getName().toString(),
constrains);
}
}
} else {
parent = parent.getParent(); // Move one up the ast. V V IMP!!
}
} else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME) {
QualifiedName qn = (QualifiedName) parent;
if (!findMe.toString().equals(qn.getQualifier().toString())) {
SimpleType stp = extracTypeInfo(findDeclaration((qn.getQualifier())));
// log(qn.getQualifier() + "->" + qn.getName());
if (stp == null) {
return null;
}
declaringClass = findDeclaration(stp.getName());
// log("QN decl class: " + getNodeAsString(declaringClass));
constrains.clear();
constrains.add(ASTNode.TYPE_DECLARATION);
constrains.add(ASTNode.FIELD_DECLARATION);
return definedIn(declaringClass, qn.getName().toString(), constrains);
}
else{
if(findMe instanceof QualifiedName){
QualifiedName qnn = (QualifiedName) findMe;
// log("findMe is a QN, "
// + (qnn.getQualifier().toString() + " other " + qnn.getName()
// .toString()));
SimpleType stp = extracTypeInfo(findDeclaration((qnn.getQualifier())));
if (stp == null) {
return null;
}
declaringClass = findDeclaration(stp.getName());
constrains.clear();
constrains.add(ASTNode.TYPE_DECLARATION);
constrains.add(ASTNode.FIELD_DECLARATION);
return definedIn(declaringClass, qnn.getName().toString(),
constrains);
}
}
} else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE) {
constrains.add(ASTNode.TYPE_DECLARATION);
if (parent.getParent().getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
constrains.add(ASTNode.CLASS_INSTANCE_CREATION);
}
} else if (parent.getNodeType() == ASTNode.TYPE_DECLARATION) {
// The condition where we look up the name of a class decl
TypeDeclaration td = (TypeDeclaration) parent;
if (findMe.equals(td.getName())) {
return parent;
}
} else if (parent instanceof Expression) {
// constrains.add(ASTNode.TYPE_DECLARATION);
// constrains.add(ASTNode.METHOD_DECLARATION);
// constrains.add(ASTNode.FIELD_DECLARATION);
}
// else if(findMe instanceof QualifiedName){
// QualifiedName qn = (QualifiedName) findMe;
// System.out
// .println("findMe is a QN, "
// + (qn.getQualifier().toString() + " other " + qn.getName()
// .toString()));
// }
while (parent != null) {
// log("findDeclaration1 -> " + getNodeAsString(parent));
for (Object oprop : parent.structuralPropertiesForType()) {
StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (parent.getStructuralProperty(prop) instanceof ASTNode) {
// log(prop + " C/S Prop of -> "
// + getNodeAsString(parent));