forked from processing/processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASTGenerator.java
More file actions
3779 lines (3413 loc) · 140 KB
/
ASTGenerator.java
File metadata and controls
3779 lines (3413 loc) · 140 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.pdex;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.PlainDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import org.eclipse.jdt.core.JavaCore;
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.Comment;
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.NodeFinder;
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.Base;
import processing.app.Library;
import processing.app.SketchCode;
import processing.app.Toolkit;
import processing.app.syntax.JEditTextArea;
import processing.mode.java.JavaEditor;
import processing.mode.java.JavaMode;
import processing.mode.java.preproc.PdePreprocessor;
import com.google.classpath.ClassPath;
import com.google.classpath.ClassPathFactory;
import com.google.classpath.RegExpResourceFilter;
@SuppressWarnings({ "deprecation", "unchecked" })
public class ASTGenerator {
protected ErrorCheckerService errorCheckerService;
protected JavaEditor editor;
public DefaultMutableTreeNode codeTree = new DefaultMutableTreeNode();
protected DefaultMutableTreeNode currentParent = null;
/**
* AST Window
*/
protected JFrame frmASTView;
protected JFrame frameAutoComp;
/**
* Swing component wrapper for AST, used for internal testing
*/
protected JTree jtree;
/**
* JTree used for testing refactoring operations
*/
protected JTree treeRename;
protected CompilationUnit compilationUnit;
protected JTable tableAuto;
protected JEditorPane javadocPane;
protected JScrollPane scrollPane;
protected JFrame frmRename;
protected JButton btnRename;
protected JButton btnListOccurrence;
protected JTextField txtRenameField;
protected JFrame frmOccurenceList;
protected JLabel lblRefactorOldName;
public ASTGenerator(ErrorCheckerService ecs) {
this.errorCheckerService = ecs;
this.editor = ecs.getEditor();
setupGUI();
//addCompletionPopupListner();
addListeners();
//loadJavaDoc();
predictionOngoing = new AtomicBoolean(false);
}
protected void setupGUI(){
frmASTView = new JFrame();
jtree = new JTree();
frmASTView.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmASTView.setBounds(new Rectangle(680, 100, 460, 620));
frmASTView.setTitle("AST View - " + editor.getSketch().getName());
JScrollPane sp = new JScrollPane();
sp.setViewportView(jtree);
frmASTView.add(sp);
btnRename = new JButton("Rename");
btnListOccurrence = new JButton("Show Usage");
frmRename = new JFrame();
frmRename.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmRename.setSize(250, 130);
frmRename.setLayout(new BoxLayout(frmRename.getContentPane(), BoxLayout.Y_AXIS));
Toolkit.setIcon(frmRename);
JPanel panelTop = new JPanel(), panelBottom = new JPanel();
panelTop.setLayout(new BoxLayout(panelTop, BoxLayout.Y_AXIS));
panelTop.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelBottom.setLayout(new BoxLayout(panelBottom, BoxLayout.X_AXIS));
panelBottom.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelBottom.add(Box.createHorizontalGlue());
panelBottom.add(btnListOccurrence);
panelBottom.add(Box.createRigidArea(new Dimension(15, 0)));
panelBottom.add(btnRename);
frmRename.setTitle("Enter new name:");
txtRenameField = new JTextField();
txtRenameField.setPreferredSize(new Dimension(150, 60));
panelTop.add(txtRenameField);
//renameWindow.setVisible(true);
lblRefactorOldName = new JLabel();
lblRefactorOldName.setText("Old Name: ");
panelTop.add(Box.createRigidArea(new Dimension(0, 10)));
panelTop.add(lblRefactorOldName);
frmRename.add(panelTop);
frmRename.add(panelBottom);
frmRename.setMinimumSize(frmRename.getSize());
frmRename.setLocation(editor.getX()
+ (editor.getWidth() - frmRename.getWidth()) / 2,
editor.getY()
+ (editor.getHeight() - frmRename.getHeight())
/ 2);
frmOccurenceList = new JFrame();
frmOccurenceList.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmOccurenceList.setSize(300, 400);
Toolkit.setIcon(frmOccurenceList);
JScrollPane sp2 = new JScrollPane();
treeRename = new JTree();
sp2.setViewportView(treeRename);
frmOccurenceList.add(sp2);
//occurenceListFrame.setVisible(true);
// frameAutoComp = new JFrame();
// frameAutoComp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// frameAutoComp.setBounds(new Rectangle(1280, 100, 460, 620));
// Toolkit.setIcon(frameAutoComp);
// tableAuto = new JTable();
// JScrollPane sp3 = new JScrollPane();
// sp3.setViewportView(tableAuto);
// frameAutoComp.add(sp3);
// frmJavaDoc = new JFrame();
// frmJavaDoc.setTitle("P5 InstaHelp");
// //jdocWindow.setUndecorated(true);
// frmJavaDoc.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// javadocPane = new JEditorPane();
// javadocPane.setContentType("text/html");
// javadocPane.setText("<html> </html>");
// javadocPane.setEditable(false);
// scrollPane = new JScrollPane();
// scrollPane.setViewportView(javadocPane);
// frmJavaDoc.add(scrollPane);
//frmJavaDoc.setUndecorated(true);
}
/**
* Toggle AST View window
*/
public static final boolean SHOWAST = !true;
protected DefaultMutableTreeNode buildAST(String source, CompilationUnit cu) {
if (cu == null) {
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(source.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);
parser.setCompilerOptions(options);
compilationUnit = (CompilationUnit) parser.createAST(null);
} else {
compilationUnit = cu;
//log("Other cu");
}
// OutlineVisitor visitor = new OutlineVisitor();
// compilationUnit.accept(visitor);
getCodeComments();
codeTree = new DefaultMutableTreeNode(new ASTNodeWrapper((ASTNode) compilationUnit
.types().get(0)));
//log("Total CU " + compilationUnit.types().size());
if(compilationUnit.types() == null || compilationUnit.types().isEmpty()){
Base.loge("No CU found!");
}
visitRecur((ASTNode) compilationUnit.types().get(0), codeTree);
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
if (codeTree != null) {
if(SHOWAST){
if (jtree.hasFocus() || frmASTView.hasFocus())
return;
jtree.setModel(new DefaultTreeModel(codeTree));
((DefaultTreeModel) jtree.getModel()).reload();
jtree.validate();
if (!frmASTView.isVisible()) {
frmASTView.setVisible(true);
}
}
// if (!frameAutoComp.isVisible()) {
//
// frameAutoComp.setVisible(true);
//
// }
// if (!frmJavaDoc.isVisible()) {
// long t = System.currentTimeMillis();
// loadJavaDoc();
// log("Time taken: "
// + (System.currentTimeMillis() - t));
// frmJavaDoc.setBounds(new Rectangle(errorCheckerService.getEditor()
// .getX() + errorCheckerService.getEditor().getWidth(),
// errorCheckerService.getEditor()
// .getY(), 450, 600));
// frmJavaDoc.setVisible(true);
// }
}
}
};
worker.execute();
// Base.loge("++>" + System.getProperty("java.class.path"));
// log(System.getProperty("java.class.path"));
// log("-------------------------------");
return codeTree;
}
protected ClassPathFactory factory;
/**
* Used for searching for package declaration of a class
*/
protected ClassPath classPath;
//protected JFrame frmJavaDoc;
/**
* Loads up .jar files and classes defined in it for completion lookup
*/
protected void loadJars() {
// SwingWorker worker = new SwingWorker() {
// protected void done(){
// }
// protected Object doInBackground() throws Exception {
// return null;
// }
// };
// worker.execute();
Thread t = new Thread(new Runnable() {
public void run() {
try {
factory = new ClassPathFactory();
StringBuilder tehPath = new StringBuilder(System
.getProperty("java.class.path"));
// Starting with JDK 1.7, no longer using Apple's Java, so
// rt.jar has the same path on all OSes
tehPath.append(File.pathSeparatorChar
+ System.getProperty("java.home") + File.separator + "lib"
+ File.separator + "rt.jar" + File.pathSeparatorChar);
if (errorCheckerService.classpathJars != null) {
synchronized (errorCheckerService.classpathJars) {
for (URL jarPath : errorCheckerService.classpathJars) {
//log(jarPath.getPath());
tehPath.append(jarPath.getPath() + File.pathSeparatorChar);
}
}
}
// String paths[] = tehPath.toString().split(File.separatorChar +"");
// StringTokenizer st = new StringTokenizer(tehPath.toString(),
// File.pathSeparatorChar + "");
// while (st.hasMoreElements()) {
// String sstr = (String) st.nextElement();
// log(sstr);
// }
classPath = factory.createFromPath(tehPath.toString());
log("Classpath created " + (classPath != null));
// for (String packageName : classPath.listPackages("")) {
// log(packageName);
// }
// RegExpResourceFilter regExpResourceFilter = new RegExpResourceFilter(
// ".*",
// "ArrayList.class");
// String[] resources = classPath.findResources("", regExpResourceFilter);
// for (String className : resources) {
// log("-> " + className);
// }
log("Sketch classpath jars loaded.");
if (Base.isMacOS()) {
File f = new File(System.getProperty("java.home") + File.separator + "bundle"
+ File.separator + "Classes" + File.separator + "classes.jar");
log(f.getAbsolutePath() + " | classes.jar found?"
+ f.exists());
} else {
File f = new File(System.getProperty("java.home") + File.separator
+ "lib" + File.separator + "rt.jar" + File.separator);
log(f.getAbsolutePath() + " | rt.jar found?"
+ f.exists());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
protected TreeMap<String, String> jdocMap;
protected void loadJavaDoc() {
jdocMap = new TreeMap<String, String>();
// presently loading only p5 reference for PApplet
Thread t = new Thread(new Runnable() {
@Override
public void run() {
JavadocHelper.loadJavaDoc(jdocMap, editor.getMode().getReferenceFolder());
}
});
t.start();
}
public DefaultMutableTreeNode buildAST(CompilationUnit cu) {
return buildAST(errorCheckerService.sourceCode, cu);
}
public static 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(params.get(i).toString(), "", "",
// CompletionCandidate.LOCAL_VAR);
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 ret[] = new CompletionCandidate[vdfs.size()];
int i = 0;
for (VariableDeclarationFragment vdf : vdfs) {
// ret[i++] = new CompletionCandidate(getNodeAsString2(vdf), "", "",
// CompletionCandidate.LOCAL_VAR);
ret[i++] = new CompletionCandidate(vdf);
}
return ret;
}
return null;
}
/**
* Find the parent of the expression in a().b, this would give me the return
* type of a(), so that we can find all children of a() begininng with b
*
* @param nearestNode
* @param expression
* @return
*/
public static ASTNode resolveExpression(ASTNode nearestNode,
ASTNode expression, boolean noCompare) {
log("Resolving " + getNodeAsString(expression) + " noComp "
+ noCompare);
if (expression instanceof SimpleName) {
return findDeclaration2(((SimpleName) expression), nearestNode);
} else if (expression instanceof MethodInvocation) {
log("3. Method Invo "
+ ((MethodInvocation) expression).getName());
return findDeclaration2(((MethodInvocation) expression).getName(),
nearestNode);
} else if (expression instanceof FieldAccess) {
log("2. Field access "
+ getNodeAsString(((FieldAccess) expression).getExpression()) + "|||"
+ getNodeAsString(((FieldAccess) expression).getName()));
if (noCompare) {
/*
* ASTNode ret = findDeclaration2(((FieldAccess) expression).getName(),
* nearestNode); log("Found as ->"+getNodeAsString(ret));
* return ret;
*/
return findDeclaration2(((FieldAccess) expression).getName(),
nearestNode);
} else {
/*
* Note how for the next recursion, noCompare is reversed. Let's say
* I've typed getABC().quark.nin where nin is incomplete(ninja being the
* field), when execution first enters here, it calls resolveExpr again
* for "getABC().quark" where we know that quark field must be complete,
* so we toggle noCompare. And kaboom.
*/
return resolveExpression(nearestNode,
((FieldAccess) expression).getExpression(),
!noCompare);
}
//return findDeclaration2(((FieldAccess) expression).getExpression(), nearestNode);
} else if (expression instanceof QualifiedName) {
log("1. Resolving "
+ ((QualifiedName) expression).getQualifier() + " ||| "
+ ((QualifiedName) expression).getName());
if (noCompare) { // no compare, as in "abc.hello." need to resolve hello here
return findDeclaration2(((QualifiedName) expression).getName(),
nearestNode);
} else {
//User typed "abc.hello.by" (bye being complete), so need to resolve "abc.hello." only
return findDeclaration2(((QualifiedName) expression).getQualifier(),
nearestNode);
}
}
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()
* @param nearestNode
* @param astNode
* @return
*/
public ClassMember resolveExpression3rdParty(ASTNode nearestNode,
ASTNode astNode, boolean noCompare) {
log("Resolve 3rdParty expr-- " + getNodeAsString(astNode)
+ " nearest node " + getNodeAsString(nearestNode));
if(astNode == null) return null;
ClassMember scopeParent = null;
SimpleType stp = null;
if(astNode instanceof SimpleName){
ASTNode decl = findDeclaration2(((SimpleName)astNode),nearestNode);
if(decl != null){
// see if locally defined
log(getNodeAsString(astNode)+" found decl -> " + getNodeAsString(decl));
return new ClassMember(extracTypeInfo(decl));
}
else {
// or in a predefined class?
Class<?> tehClass = findClassIfExists(((SimpleName) 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(((SimpleName)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(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(stp.getName().toString(), "THIS");
} else {
scopeParent = resolveExpression3rdParty(nearestNode,
fa.getExpression(), noCompare);
}
log("FA, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(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)));
return new ClassMember(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) {
stp = extracTypeInfo(findDeclaration2((SimpleName) mi.getExpression(),
nearestNode));
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(((SimpleName)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(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(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(new ClassMember(tehClass), mi
.getName().toString());
}
//return new ClassMember(findClassIfExists(stp.getName().toString()));
}
//scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
return definedIn3rdPartyClass(new ClassMember(typeDec), mi
.getName().toString());
} else {
log("MI EXP.."+getNodeAsString(mi.getExpression()));
// return null;
scopeParent = resolveExpression3rdParty(nearestNode,
mi.getExpression(), noCompare);
log("MI, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(scopeParent, mi.getName().toString());
}
}
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(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(qn.getQualifier().toString());
if (tehClass != null) {
// note how similar thing is called on line 690. Check check.
return definedIn3rdPartyClass(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(stp.getName().toString());
if (tehClass != null) {
// note how similar thing is called on line 690. Check check.
return definedIn3rdPartyClass(new ClassMember(tehClass), qn
.getName().toString());
}
log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
return null;
}
return definedIn3rdPartyClass(new ClassMember(typeDec), qn
.getName().toString());
} else {
scopeParent = resolveExpression3rdParty(nearestNode,
qn.getQualifier(), noCompare);
log("QN, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(scopeParent, qn.getName().toString());
}
}
case ASTNode.ARRAY_ACCESS:
ArrayAccess arac = (ArrayAccess)astNode;
return resolveExpression3rdParty(nearestNode, arac.getArray(), noCompare);
default:
log("Unaccounted type " + getNodeAsString(astNode));
break;
}
return null;
}
/**
* For a().abc.a123 this would return a123
*
* @param expression
* @return
*/
public static ASTNode getChildExpression(ASTNode expression) {
// ASTNode anode = null;
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;
}
public static ASTNode getParentExpression(ASTNode expression) {
// ASTNode anode = null;
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;
}
protected void trimCandidates(String newWord){
ArrayList<CompletionCandidate> newCandidate = new ArrayList<CompletionCandidate>();
newWord = newWord.toLowerCase();
for (CompletionCandidate comp : candidates) {
if(comp.getNoHtmlLabel().toLowerCase().startsWith(newWord)){
newCandidate.add(comp);
}
}
candidates = newCandidate;
}
/**
* List of CompletionCandidates
*/
protected ArrayList<CompletionCandidate> candidates;
protected String lastPredictedWord = " ";
//protected AtomicBoolean predictionsEnabled;
protected int predictionMinLength = 2;
private AtomicBoolean predictionOngoing;
/**
* The main function that calculates possible code completion candidates
*
* @param word
* @param line
* @param lineStartNonWSOffset
*/
public void preparePredictions(final String word, final int line, final int lineStartNonWSOffset) {
if(predictionOngoing.get()) return;
if (!JavaMode.codeCompletionsEnabled) return;
if (word.length() < predictionMinLength) return;
predictionOngoing.set(true);
// This method is called from TextArea.fetchPhrase, which is called via a SwingWorker instance
// in TextArea.processKeyEvent
if(caretWithinLineComment()){
log("No predictions.");
predictionOngoing.set(false);
return;
}
// SwingWorker worker = new SwingWorker() {
//
// @Override
// protected Object doInBackground() throws Exception {
// return null;
// }
//
// protected void done() {
// If the parsed code contains pde enhancements, take 'em out.
String word2 = ASTNodeWrapper.getJavaCode(word);
//After typing 'arg.' all members of arg type are to be listed. This one is a flag for it
boolean noCompare = false;
if (word2.endsWith(".")) {
// return all matches
word2 = word2.substring(0, word2.length() - 1);
noCompare = true;
}
if (word2.length() >= predictionMinLength && !noCompare
&& word2.length() > lastPredictedWord.length()) {
if (word2.startsWith(lastPredictedWord)) {
log(word + " starts with " + lastPredictedWord);
log("Don't recalc");
if (word2.contains(".")) {
int x = word2.lastIndexOf('.');
trimCandidates(word2.substring(x + 1));
} else {
trimCandidates(word2);
}
showPredictions(word);
lastPredictedWord = word2;
predictionOngoing.set(false);
return;
}
}
int lineNumber = line;
// Adjust line number for tabbed sketches
if (errorCheckerService != null) {
editor = errorCheckerService.getEditor();
int codeIndex = editor.getSketch().getCodeIndex(editor
.getCurrentTab());
if (codeIndex > 0)
for (int i = 0; i < codeIndex; i++) {
SketchCode sc = editor.getSketch().getCode(i);
int len = Base.countLines(sc.getProgram()) + 1;
lineNumber += len;
}
}
// Ensure that we're not inside a comment. TODO: Binary search
/*for (Comment comm : getCodeComments()) {
int commLineNo = PdeToJavaLineNumber(compilationUnit
.getLineNumber(comm.getStartPosition()));
if(commLineNo == lineNumber){
log("Found a comment line " + comm);
log("Comment LSO "
+ javaCodeOffsetToLineStartOffset(compilationUnit
.getLineNumber(comm.getStartPosition()),
comm.getStartPosition()));
break;
}
}*/
// Now parse the expression into an ASTNode object
ASTNode nearestNode = null;
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setKind(ASTParser.K_EXPRESSION);
parser.setSource(word2.toCharArray());
ASTNode testnode = parser.createAST(null);
//Base.loge("PREDICTION PARSER PROBLEMS: " + parser);
// Find closest ASTNode of the document to this word
Base.loge("Typed: " + word2 + "|" + " temp Node type: " + testnode.getClass().getSimpleName());
if(testnode instanceof MethodInvocation){
MethodInvocation mi = (MethodInvocation)testnode;
log(mi.getName() + "," + mi.getExpression() + "," + mi.typeArguments().size());
}
// find nearest ASTNode
nearestNode = findClosestNode(lineNumber, (ASTNode) errorCheckerService.getLastCorrectCU().types()
.get(0));
if (nearestNode == null) {
// Make sure nearestNode is not NULL if couldn't find a closeset node
nearestNode = (ASTNode) errorCheckerService.getLastCorrectCU().types().get(0);
}
Base.loge(lineNumber + " Nearest ASTNode to PRED "
+ getNodeAsString(nearestNode));
candidates = new ArrayList<CompletionCandidate>();
lastPredictedWord = word2;
// Determine the expression typed
if (testnode instanceof SimpleName && !noCompare) {
Base.loge("One word expression " + getNodeAsString(testnode));
//==> Simple one word exprssion - so is just an identifier
// Bottom up traversal of the AST to look for possible definitions at
// higher levels.
//nearestNode = nearestNode.getParent();
while (nearestNode != null) {
// If the current class has a super class, look inside it for
// definitions.
if (nearestNode instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) nearestNode;
if (td
.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) != null) {
SimpleType st = (SimpleType) td
.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY);
log("Superclass " + st.getName());
for (CompletionCandidate can : getMembersForType(st.getName()
.toString(), word2, noCompare, false)) {
candidates.add(can);
}
//findDeclaration(st.getName())
}
}
List<StructuralPropertyDescriptor> sprops = nearestNode
.structuralPropertiesForType();
for (StructuralPropertyDescriptor sprop : sprops) {
ASTNode cnode = null;
if (!sprop.isChildListProperty()) {
if (nearestNode.getStructuralProperty(sprop) instanceof ASTNode) {
cnode = (ASTNode) nearestNode.getStructuralProperty(sprop);
CompletionCandidate[] types = checkForTypes(cnode);
if (types != null) {
for (int i = 0; i < types.length; i++) {
if (types[i].getElementName().toLowerCase().startsWith(word2.toLowerCase()))
candidates.add(types[i]);
}
}
}
} else {
// Childlist prop
List<ASTNode> nodelist = (List<ASTNode>) nearestNode
.getStructuralProperty(sprop);
for (ASTNode clnode : nodelist) {
CompletionCandidate[] types = checkForTypes(clnode);
if (types != null) {
for (int i = 0; i < types.length; i++) {
if (types[i].getElementName().toLowerCase().startsWith(word2.toLowerCase()))
candidates.add(types[i]);
}
}
}
}
}
nearestNode = nearestNode.getParent();
}
// We're seeing a simple name that's not defined locally or in
// the parent class. So most probably a pre-defined type.
log("Empty can. " + word2);
if (classPath != null) {
RegExpResourceFilter regExpResourceFilter;
regExpResourceFilter = new RegExpResourceFilter(
Pattern
.compile(".*"),
Pattern
.compile(word2
+ "[a-zA-Z_0-9]*.class",
Pattern.CASE_INSENSITIVE));
String[] resources = classPath.findResources("",