-
Notifications
You must be signed in to change notification settings - Fork 211
/
GroovyEngine.java
2133 lines (1983 loc) · 90 KB
/
GroovyEngine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2021, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* https://opensource.org/licenses/BSD-3-Clause
*/
package org.jline.script;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.file.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import groovy.lang.*;
import org.apache.groovy.ast.tools.ImmutablePropertyUtils;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack;
import org.codehaus.groovy.syntax.SyntaxException;
import org.jline.builtins.Nano.SyntaxHighlighter;
import org.jline.builtins.Styles;
import org.jline.console.CmdDesc;
import org.jline.console.CmdLine;
import org.jline.console.ScriptEngine;
import org.jline.console.SystemRegistry;
import org.jline.groovy.ObjectInspector;
import org.jline.groovy.Utils;
import org.jline.reader.Candidate;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.ParsedLine;
import org.jline.reader.impl.completer.AggregateCompleter;
import org.jline.reader.impl.completer.ArgumentCompleter;
import org.jline.reader.impl.completer.NullCompleter;
import org.jline.reader.impl.completer.StringsCompleter;
import org.jline.utils.AttributedString;
import org.jline.utils.Log;
import org.jline.utils.OSUtils;
import org.jline.utils.StyleResolver;
/**
* Implements Groovy ScriptEngine.
* You must be very careful when using GroovyEngine in a multithreaded environment. The Binding instance is not
* thread safe, and it is shared by all scripts.
*
* @author <a href="mailto:matti.rintanikkola@gmail.com">Matti Rinta-Nikkola</a>
*/
public class GroovyEngine implements ScriptEngine {
public enum Format {JSON, GROOVY, NONE}
public static final String CANONICAL_NAMES = "canonicalNames";
public static final String NANORC_SYNTAX = "nanorcSyntax";
public static final String NANORC_VALUE = "nanorcValue";
public static final String GROOVY_COLORS = "GROOVY_COLORS";
public static final String NO_SYNTAX_CHECK = "noSyntaxCheck";
public static final String RESTRICTED_COMPLETION = "restrictedCompletion";
public static final String ALL_FIELDS_COMPLETION = "allFieldsCompletion";
public static final String ALL_METHODS_COMPLETION = "allMethodsCompletion";
public static final String ALL_CONSTRUCTORS_COMPLETION = "allConstructorsCompletion";
public static final String ALL_CLASSES_COMPLETION = "allClassesCompletion";
public static final String IDENTIFIERS_COMPLETION = "identifiersCompletion";
public static final String META_METHODS_COMPLETION = "metaMethodsCompletion";
public static final String SYNTHETIC_METHODS_COMPLETION = "syntheticMethodsCompletion";
private static final String VAR_GROOVY_OPTIONS = "GROOVY_OPTIONS";
private static final String REGEX_SYSTEM_VAR = "[A-Z]+[A-Z_]*";
private static final String REGEX_VAR = "[a-zA-Z_]+[a-zA-Z0-9_]*";
private static final Pattern PATTERN_FUNCTION_DEF = Pattern.compile(
"^def\\s+(" + REGEX_VAR + ")\\s*\\(([a-zA-Z0-9_ ,]*)\\)\\s*\\{(.*)?}(|\n)$"
, Pattern.DOTALL);
private static final Pattern PATTERN_CLASS_DEF = Pattern.compile("^class\\s+(" + REGEX_VAR + ")\\s*(.*?\\{.*?})(|\n)$"
, Pattern.DOTALL);
private static final Pattern PATTERN_TRAIT_DEF = Pattern.compile("^trait\\s+(" + REGEX_VAR + ")\\s*(\\{.*?})(|\n)$"
, Pattern.DOTALL);
private static final String REGEX_CLASS = "(.*?)\\.([A-Z_].*)";
private static final Pattern PATTERN_CLASS = Pattern.compile(REGEX_CLASS);
private static final String REGEX_PACKAGE = "([a-z][a-z_0-9]*\\.)*";
private static final String REGEX_CLASS_NAME = "[A-Z_](\\w)*";
private static final Pattern PATTERN_LOAD_CLASS = Pattern.compile("(import\\s+|new\\s+|\\s*)?("
+ REGEX_PACKAGE + ")(" + REGEX_CLASS_NAME + ")(\\..*|\\(.*)?");
private static final List<String> DEFAULT_IMPORTS = Arrays.asList("java.lang.*", "java.util.*", "java.io.*"
, "java.net.*", "groovy.lang.*", "groovy.util.*"
, "java.math.BigInteger", "java.math.BigDecimal");
private final Map<String,Class<?>> defaultNameClass = new HashMap<>();
private final GroovyShell shell;
protected Binding sharedData;
private final Map<String,String> imports = new HashMap<>();
private final Map<String,String> methods = new HashMap<>();
private final Map<String,String> classes = new HashMap<>();
private final Map<String,String> traits = new HashMap<>();
private final Map<String,Class<?>> nameClass;
private Cloner objectCloner = new ObjectCloner();
protected final EngineClassLoader classLoader;
public interface Cloner {
Object clone(Object obj);
void markCache();
void purgeCache();
}
public GroovyEngine() {
this.sharedData = new Binding();
this.classLoader = new EngineClassLoader();
shell = new GroovyShell(classLoader, sharedData);
for (String s : DEFAULT_IMPORTS) {
addToNameClass(s, defaultNameClass);
}
nameClass = new HashMap<>(defaultNameClass);
}
@Override
public Completer getScriptCompleter() {
return compileCompleter();
}
@Override
public boolean hasVariable(String name) {
return sharedData.hasVariable(name);
}
@Override
public void put(String name, Object value) {
sharedData.setProperty(name, value);
}
@Override
public Object get(String name) {
return sharedData.hasVariable(name) ? sharedData.getVariable(name) : null;
}
@SuppressWarnings("unchecked")
@Override
public Map<String,Object> find(String name) {
Map<String, Object> out = new HashMap<>();
if (name == null) {
out = sharedData.getVariables();
} else {
for (String v : internalFind(name)) {
out.put(v, get(v));
}
}
return out;
}
@Override
public List<String> getSerializationFormats() {
return Arrays.asList(Format.JSON.toString(), Format.NONE.toString());
}
@Override
public List<String> getDeserializationFormats() {
return Arrays.asList(Format.JSON.toString(), Format.GROOVY.toString(), Format.NONE.toString());
}
@Override
public Object deserialize(String value, String formatStr) {
Object out = value;
Format format = formatStr != null && !formatStr.isEmpty() ? Format.valueOf(formatStr.toUpperCase()) : null;
if (format == Format.NONE) {
// do nothing
} else if (format == Format.JSON) {
out = Utils.toObject(value);
} else if (format == Format.GROOVY) {
try {
out = execute(value);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
} else {
value = value.trim();
boolean hasCurly = value.contains("{") && value.contains("}");
try {
if (value.startsWith("[") && value.endsWith("]")) {
try {
if (hasCurly) {
out = Utils.toObject(value); // try json
} else {
out = execute(value);
}
} catch (Exception e) {
if (hasCurly) {
try {
out = execute(value);
} catch (Exception e2) {
// ignore
}
} else {
out = Utils.toObject(value); // try json
}
}
} else if (value.startsWith("{") && value.endsWith("}")) {
out = Utils.toObject(value);
}
} catch (Exception e) {
// ignore
}
}
return out;
}
@Override
public void persist(Path file, Object object) {
persist(file, object, getSerializationFormats().get(0));
}
@Override
public void persist(Path file, Object object, String format) {
Utils.persist(file, object, Format.valueOf(format.toUpperCase()));
}
@Override
public Object execute(File script, Object[] args) throws Exception {
sharedData.setProperty("_args", args);
Script s = shell.parse(script);
return s.run();
}
private static Set<Object> classesForPackage(String pckgname, GroovyShell shell) throws ClassNotFoundException {
String name = pckgname;
Matcher matcher = PATTERN_CLASS.matcher(name);
if (matcher.matches()) {
name = matcher.group(1) + ".**";
}
Set<Object> out = new HashSet<>(PackageHelper.getClassesForPackage(name));
if (out.isEmpty()) {
out.addAll(JrtJavaBasePackages.getClassesForPackage(name));
}
if (out.isEmpty() && shell != null) {
EngineClassLoader classLoader = (EngineClassLoader)shell.getClassLoader();
if (pckgname.endsWith(".*")) {
pckgname = pckgname.substring(0, pckgname.length() - 1);
} else if (!pckgname.endsWith(".")) {
pckgname = pckgname + ".";
}
for (Class<?> c : classLoader.getLoadedClasses()) {
String cname = c.getCanonicalName();
if (cname != null && cname.startsWith(pckgname)) {
out.add(c);
}
}
Set<String> classNames = Helpers.sourcesForPackage(name);
if (name.endsWith("*")) {
for (String c : classNames) {
if (Character.isUpperCase(c.charAt(0))) {
try {
out.add(executeStatement(shell, new HashMap<>(), pckgname + c + ".class"));
} catch (Exception ignore) {
}
}
}
} else {
out.addAll(classNames);
}
out.addAll(new HashSet<>(PackageHelper.getClassesForPackage(name, shell.getClassLoader()
, n ->
{
if (n.contains("-")) {
return null;
}
Class<?> o = null;
try {
o = (Class<?>) shell.evaluate(n + ".class");
} catch (Exception | Error ignore) {
}
return o;
})));
classLoader.purgeClassCache();
}
return out;
}
private void addToNameClass(String name) {
addToNameClass(name, nameClass);
}
@SuppressWarnings("unchecked")
private void addToNameClass(String name, Map<String,Class<?>> nameClass) {
try {
if (name.endsWith(".*")) {
for (Class<?> c : (Collection<Class<?>>)(Object)classesForPackage(name, shell)) {
nameClass.put(c.getSimpleName(), c);
}
} else {
Class<?> clazz = classResolver(name, shell);
if (clazz != null) {
nameClass.put(clazz.getSimpleName(), clazz);
}
}
} catch (Exception e) {
// ignore
}
}
@Override
public Object execute(String statement) throws Exception {
Object out = null;
if (statement.matches("import\\s+(([^;\\s])+)\\s*(;)?")) {
String[] p = statement.split("\\s+");
String classname = p[1].replaceAll(";", "");
executeStatement(shell, imports, statement);
imports.put(classname, statement);
addToNameClass(classname);
} else if (statement.equals("import")) {
out = new ArrayList<>(imports.keySet());
} else if (functionDef(statement)) {
// do nothing
} else if (statement.equals("def")) {
out = methods;
} else if (statement.equals("class")) {
out = classes;
} else if (statement.equals("traits")) {
out = traits;
} else if (statement.matches("(def|class|trait)\\s+" + REGEX_VAR)) {
String name = statement.split("\\s+")[1];
if (statement.startsWith("def") && methods.containsKey(name)) {
out = "def " + name + methods.get(name);
} else if (statement.startsWith("class") && classes.containsKey(name)) {
out = "class " + name + " " + classes.get(name);
} else if (statement.startsWith("trait") && traits.containsKey(name)) {
out = "trait " + name + " " + traits.get(name);
}
} else {
out = executeStatement(shell, imports, statement);
classLoader.purgeClassCache();
if (PATTERN_CLASS_DEF.matcher(statement).matches()) {
Matcher matcher = PATTERN_CLASS_DEF.matcher(statement);
matcher.matches();
classes.put(matcher.group(1), matcher.group(2));
addToNameClass(matcher.group(1));
} else if (PATTERN_TRAIT_DEF.matcher(statement).matches()) {
Matcher matcher = PATTERN_TRAIT_DEF.matcher(statement);
matcher.matches();
traits.put(matcher.group(1), matcher.group(2));
}
}
return out;
}
private static Object executeStatement(GroovyShell shell, Map<String, String> imports, String statement) throws IOException {
int idx = statement.indexOf("=") + 1;
Matcher matcher = PATTERN_LOAD_CLASS.matcher(statement.substring(idx));
if (matcher.matches()) {
boolean importStatement = convertNull(matcher.group(1)).contains("import");
String fileName = convertNull(matcher.group(2)) + matcher.group(4);
String importClass = "import " + fileName + "; ";
fileName = fileName.replace(".", "/");
for (String type : Arrays.asList(".groovy", ".java")) {
File file = new File(fileName + type);
if (file.exists()) {
try {
shell.evaluate(file);
} catch (GroovyRuntimeException e) {
if (!(e instanceof MissingMethodExceptionNoStack) // thrown when class without main()
&& !(e.getCause() instanceof NoSuchMethodException)) { // thrown traits... no constructor
throw e;
}
}
if (importStatement) {
statement = importClass + matcher.group(4) + ".class";
} else {
statement = importClass + statement.substring(0, idx) + convertNull(matcher.group(1)) + matcher.group(4)
+ convertNull(matcher.group(6));
}
break;
}
}
}
StringBuilder e = new StringBuilder();
for (Map.Entry<String, String> entry : imports.entrySet()) {
e.append(entry.getValue()).append("\n");
}
e.append(statement);
if (classOrTraitDef(statement)) {
e.append("; null");
}
return shell.evaluate(e.toString());
}
private static String convertNull(String string) {
return string == null ? "" : string;
}
@Override
public Object execute(Object closure, Object... args) {
if (!(closure instanceof Closure)) {
throw new IllegalArgumentException();
}
return ((Closure<?>)closure).call(args);
}
@Override
public String getEngineName() {
return this.getClass().getSimpleName();
}
@Override
public List<String> getExtensions() {
return Collections.singletonList("groovy");
}
@SuppressWarnings("unchecked")
private List<String> internalFind(String var) {
List<String> out = new ArrayList<>();
if(!var.contains(".") && var.contains("*")) {
var = var.replaceAll("\\*", ".*");
}
for (String v : (Set<String>)sharedData.getVariables().keySet()) {
if (v.matches(var)) {
out.add(v);
}
}
return out;
}
private boolean functionDef(String statement) throws Exception{
boolean out = false;
Matcher m = PATTERN_FUNCTION_DEF.matcher(statement);
if (m.matches()) {
out = true;
put(m.group(1), execute("{" + m.group(2) + "->" + m.group(3) + "}"));
methods.put(m.group(1), "(" + m.group(2) + ")" + "{" + m.group(3) + "}");
}
return out;
}
private static boolean classOrTraitDef(String statement) {
return PATTERN_CLASS_DEF.matcher(statement).matches() || PATTERN_TRAIT_DEF.matcher(statement).matches();
}
private void refreshNameClass() {
nameClass.clear();
nameClass.putAll(defaultNameClass);
for (String name : imports.keySet()) {
addToNameClass(name);
}
for (String name : classes.keySet()) {
addToNameClass(name);
}
}
private void del(String var) {
if (var == null) {
return;
}
if (imports.containsKey(var)) {
imports.remove(var);
if (var.endsWith(".*")) {
refreshNameClass();
} else {
classLoader.purgeClassCache(var + "(\\$.*)?");
nameClass.remove(var.substring(var.lastIndexOf('.') + 1));
}
} else if (sharedData.hasVariable(var)) {
sharedData.getVariables().remove(var);
methods.remove(var);
} else if (classes.containsKey(var)) {
classes.remove(var);
classLoader.purgeClassCache(var + "(\\$.*)?");
} else if (traits.containsKey(var)) {
traits.remove(var);
classLoader.purgeClassCache(var + "(\\$.*)?");
} else if (!var.contains(".") && var.contains("*")) {
for (String v : internalFind(var)){
if (sharedData.hasVariable(v) && !v.equals("_") && !v.matches(REGEX_SYSTEM_VAR)) {
sharedData.getVariables().remove(v);
methods.remove(v);
}
}
}
}
@Override
public void del(String... vars) {
if (vars == null) {
return;
}
for (String s: vars) {
del(s);
}
}
@Override
public String toJson(Object obj) {
return Utils.toJson(obj);
}
@Override
public String toString(Object obj) {
return Utils.toString(obj);
}
@Override
public Map<String,Object> toMap(Object obj) {
return Utils.toMap(obj);
}
public void setObjectCloner(Cloner objectCloner) {
this.objectCloner = objectCloner;
}
public Cloner getObjectCloner() {
return objectCloner;
}
public CmdDesc scriptDescription(CmdLine line) {
return new Inspector(this).scriptDescription(line);
}
@SuppressWarnings("unchecked")
protected Map<String,Object> groovyOptions() {
return hasVariable(VAR_GROOVY_OPTIONS) ? (Map<String, Object>) get(VAR_GROOVY_OPTIONS)
: new HashMap<>();
}
protected <T>T groovyOption(String option, T defval) {
return groovyOption(groovyOptions(), option, defval);
}
@SuppressWarnings("unchecked")
protected static <T>T groovyOption(Map<String,Object> options, String option, T defval) {
T out = defval;
try {
out = (T) options.getOrDefault(option, defval);
} catch (Exception e) {
// ignore
}
return out;
}
private Completer compileCompleter() {
List<Completer> completers = new ArrayList<>();
completers.add(new ArgumentCompleter(new StringsCompleter("print", "println"), NullCompleter.INSTANCE));
completers.add(new ArgumentCompleter(new StringsCompleter("def"), new StringsCompleter(methods::keySet)
, NullCompleter.INSTANCE));
completers.add(new ArgumentCompleter(new StringsCompleter("class"), new StringsCompleter(classes::keySet)
, NullCompleter.INSTANCE));
completers.add(new ArgumentCompleter(new StringsCompleter("trait"), new StringsCompleter(traits::keySet)
, NullCompleter.INSTANCE));
completers.add(new ArgumentCompleter(new StringsCompleter("import")
, new PackageCompleter(CandidateType.PACKAGE, this), NullCompleter.INSTANCE));
completers.add(new MethodCompleter(this));
return new AggregateCompleter(completers);
}
private enum CandidateType {CONSTRUCTOR, STATIC_METHOD, PACKAGE, METHOD, FIELD, IDENTIFIER, META_METHOD, STRING, OTHER}
private static Class<?> classResolver(String classDotName, GroovyShell shell) {
Class<?> out = null;
Matcher matcher = PATTERN_CLASS.matcher(classDotName);
if (matcher.matches()) {
String classname = matcher.group(2).replaceAll("\\.", "\\$");
try {
out = Class.forName(matcher.group(1) + "." + classname);
} catch (ClassNotFoundException ex) {
try {
out = (Class<?>)executeStatement(shell, new HashMap<>(), classDotName + ".class");
} catch (Exception e) {
if (Log.isDebugEnabled()) {
ex.printStackTrace();
}
}
}
} else if (classDotName.matches(REGEX_CLASS_NAME)) {
try {
out = (Class<?>) executeStatement(shell, new HashMap<>(), classDotName + ".class");
} catch (Exception ignore) {
}
}
return out;
}
public void purgeClassCache(String regex) {
if (regex == null) {
classLoader.clearCache();
} else {
classLoader.purgeClassCache(regex);
}
//
// groovy source imports require classes to be loaded
//
Iterator<Map.Entry<String,String>> iter = imports.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
try {
executeStatement(shell, new HashMap<>(), entry.getValue());
} catch (Exception e) {
iter.remove();
}
}
classLoader.purgeClassCache();
}
public static class EngineClassLoader extends GroovyClassLoader {
public EngineClassLoader(){
super();
}
@Override
public Package[] getPackages() {
return super.getPackages();
}
public void purgeClassCache(String regex) {
for (String s : classCache.keys()) {
if (s.matches(regex)) {
removeClassCacheEntry(s);
}
}
}
public void purgeClassCache() {
for (String s : classCache.keys()) {
if (s.matches("Script\\d+(\\$.*)?")) {
removeClassCacheEntry(s);
}
}
}
}
protected static class AccessRules {
protected final boolean allMethods;
protected final boolean allFields;
protected final boolean allConstructors;
protected final boolean allClasses;
public AccessRules() {
this(new HashMap<>());
}
public AccessRules(Map<String,Object> options) {
this.allMethods = groovyOption(options, ALL_METHODS_COMPLETION, false);
this.allFields = groovyOption(options, ALL_FIELDS_COMPLETION, false);
this.allConstructors = groovyOption(options, ALL_CONSTRUCTORS_COMPLETION, false);
this.allClasses = groovyOption(options, ALL_CLASSES_COMPLETION, false);
}
}
private static class Helpers {
private static Set<String> loadedPackages(EngineClassLoader classLoader) {
Set<String> out = new HashSet<>();
for (Package p : classLoader.getPackages()) {
out.add(p.getName());
}
return out;
}
private static Set<String> names(String domain, Collection<String> packages) {
Set<String> out = new HashSet<>();
for (String p : packages) {
if (p.startsWith(domain)) {
int idx = p.indexOf('.', domain.length());
if (idx < 0) {
idx = p.length();
}
if (idx > domain.length()) {
String name = p.substring(domain.length(), idx);
if (validPackageOrClassName(name)) {
out.add(name);
}
}
}
}
return out;
}
public static Set<Method> getClassMethods(Class<?> clazz, boolean all, boolean synthetic) {
Set<Method> out = new HashSet<>();
do {
if (synthetic) {
out.addAll(Arrays.asList(clazz.getMethods()));
if (all) {
out.addAll(Arrays.asList(clazz.getDeclaredMethods()));
}
} else {
for (Method m : all ? clazz.getDeclaredMethods() : clazz.getMethods()) {
if (!m.isSynthetic()) {
out.add(m);
}
}
}
clazz = clazz.getSuperclass();
} while (clazz != null);
return out;
}
public static Set<String> getMethods(Class<?> clazz, boolean all, boolean synthetic) {
return getMethods(clazz, all, synthetic, false, false);
}
public static Set<String> getStaticMethods(Class<?> clazz, boolean all, boolean synthetic) {
return getMethods(clazz, all, synthetic, true, false);
}
public static boolean noStaticMethods(Class<?> clazz, boolean all, boolean synthetic) {
return getMethods(clazz, all, synthetic, true, true).isEmpty();
}
private static Set<String> getMethods(Class<?> clazz, boolean all, boolean synthetic, boolean statc, boolean firstOnly) {
Set<String> out = new HashSet<>();
try {
for (Method method : getClassMethods(clazz, all, synthetic)) {
if ((statc && Modifier.isStatic(method.getModifiers()))
|| (!statc && !Modifier.isStatic(method.getModifiers()))) {
out.add(method.getName());
if (firstOnly) {
break;
}
}
}
} catch (NoClassDefFoundError e) {
// ignore
}
return out;
}
public static Map<String,String> getFields(Class<?> clazz, boolean all, boolean synthetic) {
return getFields(clazz, all, synthetic, false, false);
}
public static Map<String,String> getStaticFields(Class<?> clazz, boolean all, boolean synthetic) {
return getFields(clazz, all, synthetic, true, false);
}
public static boolean noStaticFields(Class<?> clazz, boolean all, boolean synthetic) {
return getFields(clazz, all, synthetic, true, true).isEmpty();
}
private static Map<String,String> getFields(Class<?> clazz, boolean all, boolean synthetic, boolean statc, boolean firstOnly) {
Map<String,String> out = new HashMap<>();
for (Field field : all ? clazz.getDeclaredFields() : clazz.getFields()) {
if (((statc && Modifier.isStatic(field.getModifiers()))
|| (!statc && !Modifier.isStatic(field.getModifiers())))
&& (synthetic || !field.isSynthetic())) {
out.put(field.getName(), field.getType().getSimpleName());
if (firstOnly) {
break;
}
}
}
return out;
}
private static Set<String> sourcesForPackage(String domain) {
String separator = FileSystems.getDefault().getSeparator();
if (separator.equals("\\")) {
separator += separator;
}
String dom;
boolean onlyPackage = domain != null && domain.endsWith("*");
if (onlyPackage) {
domain = domain.substring(0, domain.lastIndexOf("."));
}
if (domain != null) {
dom = domain.isEmpty() ? ".*" + separator : separator + domain.replace(".", separator) + "(|.*)";
} else {
dom = separator + "(|.*)";
}
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:\\." + dom
+ "[A-Z]+[a-zA-Z]*\\.groovy");
Set<String> out = new HashSet<>();
try {
List<Path> paths = Files.walk(Paths.get(".")).filter(matcher::matches).collect(Collectors.toList());
for (Path p : paths) {
if (!p.getFileName().toString().matches("[A-Z]+[a-zA-Z]*\\.groovy")) {
continue;
}
String source = p.toString();
String className = source.substring(2, source.lastIndexOf(".")).replace(separator, ".");
if (onlyPackage) {
if (Character.isUpperCase(className.charAt(domain.length() + 1))) {
out.add(className);
}
} else {
out.add(className);
}
}
} catch(Exception ignore) {
}
return out;
}
public static Set<String> nextDomain(String domain, CandidateType type, GroovyShell shell) {
return nextDomain(domain, new AccessRules(), type, shell);
}
public static Set<String> nextDomain(String domain, AccessRules access, CandidateType type, GroovyShell shell) {
Set<String> out = new HashSet<>();
EngineClassLoader classLoader = (EngineClassLoader)shell.getClassLoader();
if (domain.isEmpty()) {
for (String p : loadedPackages(classLoader)) {
out.add(p.split("\\.")[0]);
}
out.addAll(names(domain, sourcesForPackage(null)));
} else {
try {
for (Object o : classesForPackage(domain, shell)) {
String name = null;
if (o instanceof Class<?>) {
Class<?> c = (Class<?>) o;
try {
if ((!Modifier.isPublic(c.getModifiers()) && !access.allClasses) || c.getCanonicalName() == null) {
continue;
}
if ((type == CandidateType.CONSTRUCTOR && (c.getConstructors().length == 0
|| Modifier.isAbstract(c.getModifiers())))
|| (type == CandidateType.STATIC_METHOD && noStaticMethods(c, access.allMethods, true)
&& noStaticFields(c, access.allFields, true))) {
continue;
}
name = c.getCanonicalName();
} catch (NoClassDefFoundError e) {
if (Log.isDebugEnabled()) {
e.printStackTrace();
}
}
} else if (o instanceof String) {
name = ((String)o).replace("$", ".");
}
if (name != null) {
Log.debug(name);
if (name.startsWith(domain)) {
int idx = name.indexOf('.', domain.length());
if (idx < 0) {
idx = name.length();
}
if (idx > domain.length()) {
name = name.substring(domain.length(), idx);
if (validPackageOrClassName(name)) {
out.add(name);
}
}
}
}
}
} catch (ClassNotFoundException e) {
if (Log.isDebugEnabled()) {
e.printStackTrace();
}
out.addAll(names(domain, loadedPackages(classLoader)));
out.addAll(names(domain, PackageHelper.getClassNamesForPackage(domain, classLoader)));
}
}
Log.debug("nextDomain: ", out);
return out;
}
private static boolean validPackageOrClassName(String name) {
return !(name.contains("-") || name.matches("\\d+.*"));
}
private static Map<String, String> listToMap(Collection<String> list) {
return list.stream()
.collect(Collectors.toMap(it -> it, it -> ""));
}
public static void doCandidates(List<Candidate> candidates, Collection<String> fields, String curBuf, CandidateType type) {
doCandidates(candidates, listToMap(fields), curBuf, type);
}
public static void doCandidates(List<Candidate> candidates, Map<String,String> fields, String curBuf, CandidateType type) {
if (fields == null || fields.isEmpty()) {
return;
}
for (Map.Entry<String,String> entry : fields.entrySet()) {
String group = null;
String desc = entry.getValue().isEmpty() ? null : entry.getValue();
String s = entry.getKey();
if (s == null) {
continue;
}
String postFix = "";
String preFix = "";
if (type == CandidateType.CONSTRUCTOR) {
if (s.matches("[a-z]+.*")) {
postFix = ".";
} else if (s.matches("[A-Z]+.*")) {
postFix = "(";
}
} else if (type == CandidateType.PACKAGE) {
if (s.matches("[a-z]+.*")) {
postFix = ".";
}
} else if (type == CandidateType.METHOD) {
postFix = "(";
group = "Methods";
} else if (type == CandidateType.FIELD) {
group = "Fields";
} else if (type == CandidateType.IDENTIFIER) {
group = "Identifiers";
if (s.contains("-") || s.contains("+") || s.contains(" ") || s.contains("#")
|| !s.matches("[a-zA-Z$_].*")){
continue;
}
} else if (type == CandidateType.META_METHOD) {
postFix = "(";
group = "MetaMethods";
} else if (type == CandidateType.STRING) {
String quote = s.contains("'") ? "\"" : "'";
postFix = quote;
preFix = quote;
}
candidates.add(new Candidate(AttributedString.stripAnsi(curBuf + preFix + s + postFix), s, group
, desc, null,null, false));
}
}
public static int statementBegin(String buffer) {
String buf = buffer;
while (buf.matches(".*\\)\\.\\w+$")) {
int idx = buf.lastIndexOf(".");
int openingRound = Brackets.indexOfOpeningRound(buf.substring(0,idx));
buf = buf.substring(0,openingRound);
}
return statementBegin(new Brackets(buf));
}
public static int statementBegin(String buffer, String wordbuffer, Brackets brackets) {
int out = -1;
int idx = buffer.lastIndexOf(wordbuffer);
if (idx > -1) {
out = statementBegin(brackets.lastDelim() - idx
, brackets.lastOpenRound() - idx
, brackets.lastComma() - idx
, brackets.lastOpenCurly() - idx
, brackets.lastCloseCurly() - idx
, brackets.lastSemicolon() - idx);
}
return out;
}
private static int statementBegin(Brackets brackets) {
return statementBegin(brackets.lastDelim()
, brackets.lastOpenRound()
, brackets.lastComma()
, brackets.lastOpenCurly(), brackets.lastCloseCurly(), brackets.lastSemicolon());
}
private static int statementBegin(int lastDelim, int openRound, int comma, int openCurly, int closeCurly, int semicolon) {
int out = lastDelim;
if (openRound > out) {
out = openRound;
}
if (comma > out) {
out = comma;
}
if (openCurly > out) {
out = openCurly;
}
if (closeCurly > out) {
out = closeCurly;
}
if (semicolon > out) {
out = semicolon;
}
return Math.max(out, -1);
}
public static boolean constructorStatement(String fragment) {
return fragment.matches("(.*\\s+new|.*\\(new|.*\\{new|.*=new|.*,new|new)");
}
}
private static class PackageCompleter implements Completer {
private final CandidateType type;
private final GroovyEngine groovyEngine;
public PackageCompleter(CandidateType type, GroovyEngine groovyEngine) {
this.type = type;
this.groovyEngine = groovyEngine;
}
@Override
public void complete(LineReader reader, ParsedLine commandLine, List<Candidate> candidates) {
assert commandLine != null;
assert candidates != null;
String buffer = commandLine.word().substring(0, commandLine.wordCursor());
String curBuf = "";
int lastDelim = buffer.lastIndexOf('.');
if (lastDelim > -1) {
curBuf = buffer.substring(0, lastDelim + 1);
}
Helpers.doCandidates(candidates
, Helpers.nextDomain(curBuf, new AccessRules(groovyEngine.groovyOptions()), type, groovyEngine.shell)
, curBuf, type);
}
}