-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathInterpreter.java
More file actions
1331 lines (1244 loc) · 49.5 KB
/
Interpreter.java
File metadata and controls
1331 lines (1244 loc) · 49.5 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
package com.laytonsmith.tools;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery;
import com.laytonsmith.PureUtilities.CommandExecutor;
import com.laytonsmith.PureUtilities.Common.FileUtil;
import com.laytonsmith.PureUtilities.Common.FileWriteMode;
import com.laytonsmith.PureUtilities.Common.HTMLUtils;
import com.laytonsmith.PureUtilities.Common.MutableObject;
import com.laytonsmith.PureUtilities.Common.OSUtils;
import com.laytonsmith.PureUtilities.Common.ReflectionUtils;
import com.laytonsmith.PureUtilities.Common.StreamUtils;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.PureUtilities.Common.WinRegistry;
import com.laytonsmith.PureUtilities.LimitedQueue;
import com.laytonsmith.PureUtilities.RunnableQueue;
import com.laytonsmith.PureUtilities.SignalHandler;
import com.laytonsmith.PureUtilities.SignalType;
import com.laytonsmith.PureUtilities.Signals;
import com.laytonsmith.PureUtilities.TermColors;
import com.laytonsmith.abstraction.AbstractConvertor;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.MCAttributeModifier;
import com.laytonsmith.abstraction.MCColor;
import com.laytonsmith.abstraction.MCEnchantment;
import com.laytonsmith.abstraction.MCEntity;
import com.laytonsmith.abstraction.MCFireworkBuilder;
import com.laytonsmith.abstraction.MCInventory;
import com.laytonsmith.abstraction.MCInventoryHolder;
import com.laytonsmith.abstraction.MCItemMeta;
import com.laytonsmith.abstraction.MCItemStack;
import com.laytonsmith.abstraction.MCLocation;
import com.laytonsmith.abstraction.MCMetadataValue;
import com.laytonsmith.abstraction.MCNote;
import com.laytonsmith.abstraction.MCPattern;
import com.laytonsmith.abstraction.MCPlugin;
import com.laytonsmith.abstraction.MCPluginMeta;
import com.laytonsmith.abstraction.MCPotionData;
import com.laytonsmith.abstraction.MCRecipe;
import com.laytonsmith.abstraction.MCServer;
import com.laytonsmith.abstraction.MCWorld;
import com.laytonsmith.abstraction.blocks.MCMaterial;
import com.laytonsmith.abstraction.enums.MCAttribute;
import com.laytonsmith.abstraction.enums.MCDyeColor;
import com.laytonsmith.abstraction.enums.MCEquipmentSlot;
import com.laytonsmith.abstraction.enums.MCPatternShape;
import com.laytonsmith.abstraction.enums.MCPotionType;
import com.laytonsmith.abstraction.enums.MCRecipeType;
import com.laytonsmith.abstraction.enums.MCTone;
import com.laytonsmith.annotations.api;
import com.laytonsmith.annotations.convert;
import com.laytonsmith.annotations.seealso;
import com.laytonsmith.annotations.typeof;
import com.laytonsmith.commandhelper.CommandHelperPlugin;
import com.laytonsmith.core.Documentation;
import com.laytonsmith.core.Installer;
import com.laytonsmith.core.LogLevel;
import com.laytonsmith.core.MethodScriptCompiler;
import com.laytonsmith.core.MethodScriptComplete;
import com.laytonsmith.core.MethodScriptFileLocations;
import com.laytonsmith.core.ParseTree;
import com.laytonsmith.core.Prefs;
import com.laytonsmith.core.Profiles;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.compiler.TokenStream;
import com.laytonsmith.core.compiler.analysis.Declaration;
import com.laytonsmith.core.compiler.analysis.Namespace;
import com.laytonsmith.core.compiler.analysis.StaticAnalysis;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CBoolean;
import com.laytonsmith.core.constructs.CClosure;
import com.laytonsmith.core.constructs.CInt;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.IVariable;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.constructs.Variable;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.environments.InvalidEnvironmentException;
import com.laytonsmith.core.environments.RuntimeMode;
import com.laytonsmith.core.environments.StaticRuntimeEnv;
import com.laytonsmith.core.events.Driver;
import com.laytonsmith.core.events.EventUtils;
import com.laytonsmith.core.events.drivers.CmdlineEvents;
import com.laytonsmith.core.exceptions.CRE.CREFormatException;
import com.laytonsmith.core.exceptions.CRE.CREIOException;
import com.laytonsmith.core.exceptions.CRE.CREThrowable;
import com.laytonsmith.core.exceptions.AbstractCompileException;
import com.laytonsmith.core.exceptions.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigCompileGroupException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.functions.Cmdline;
import com.laytonsmith.core.functions.Cmdline.prompt_char;
import com.laytonsmith.core.functions.Echoes;
import com.laytonsmith.core.functions.ExampleScript;
import com.laytonsmith.core.functions.Function;
import com.laytonsmith.core.functions.FunctionBase;
import com.laytonsmith.core.functions.FunctionList;
import com.laytonsmith.core.profiler.ProfilePoint;
import com.laytonsmith.persistence.DataSourceException;
import com.laytonsmith.tools.docgen.DocGen;
import com.laytonsmith.tools.docgen.DocGenTemplates;
import jline.console.ConsoleReader;
import jline.console.completer.ArgumentCompleter;
import jline.console.completer.StringsCompleter;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.laytonsmith.PureUtilities.TermColors.BLUE;
import static com.laytonsmith.PureUtilities.TermColors.RED;
import static com.laytonsmith.PureUtilities.TermColors.YELLOW;
import static com.laytonsmith.PureUtilities.TermColors.p;
import static com.laytonsmith.PureUtilities.TermColors.pl;
import static com.laytonsmith.PureUtilities.TermColors.reset;
/**
* This is a command line implementation of the in game interpreter mode. This should only be run while the server is
* stopped, as it has full access to filesystem resources. Many things won't work as intended, but pure abstract
* functions should still work fine.
*/
public final class Interpreter {
/**
* THIS MUST NEVER EVER EVER EVER EVER EVER EVER CHANGE. EVER.
*
* BAD THINGS WILL HAPPEN TO EVERYBODY YOU LOVE IF THIS IS CHANGED!
*/
private static final String UNIX_INTERPRETER_INSTALLATION_LOCATION = "/usr/local/bin/";
/**
* Be sure to update this if the powershell.psm1 file changes.
*/
private static final String POWERSHELL_MODULE_VERSION = "1.0.0";
private boolean inTTYMode = false;
private boolean multilineMode = false;
private boolean inShellMode = false;
private String script = "";
private Environment env;
private StaticAnalysis staticAnalysis;
private Thread scriptThread = null;
private volatile boolean isExecuting = false;
private final Queue<String> commandHistory = new LimitedQueue<>(MAX_COMMAND_HISTORY);
/**
* If they mash ctrlC a bunch, they probably really want to quit, so we'll keep track of this, and reset it only if
* they then run an actual command.
*/
private volatile int ctrlCcount = 0;
/**
* After this many mashes of Ctrl+C, clearly they want to exit, so we'll exit the shell.
*/
private static final int MAX_CTRL_C_MASHES = 5;
/**
* Max commands that are tracked.
*/
private static final int MAX_COMMAND_HISTORY = 100;
public static void startWithTTY(File file, List<String> args, boolean systemExitOnFailure) throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
startWithTTY(file.getCanonicalPath(), args, systemExitOnFailure);
}
public static void startWithTTY(String file, List<String> args) throws Profiles.InvalidProfileException, IOException, DataSourceException, URISyntaxException {
startWithTTY(file, args, true);
}
public static void startWithTTY(String file, List<String> args, boolean systemExitOnFailure) throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
File fromFile = new File(file).getCanonicalFile();
Interpreter interpreter = new Interpreter(args, fromFile.getParentFile().getPath(), true);
try {
interpreter.execute(FileUtil.read(fromFile), args, fromFile);
} catch (ConfigCompileException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null, null);
StreamUtils.GetSystemOut().println(TermColors.reset());
if(systemExitOnFailure) {
System.exit(1);
}
} catch (ConfigCompileGroupException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null);
StreamUtils.GetSystemOut().println(TermColors.reset());
if(systemExitOnFailure) {
System.exit(1);
}
}
}
private String getHelpMsg() {
String msg = YELLOW + "You are now in cmdline interpreter mode.\n"
+ "- on a line by itself (outside of mulitline mode), or the exit() command exits the shell.\n"
+ ">>> on a line by itself starts multiline mode, where multiple lines can be written, but not yet executed.\n"
+ "<<< on a line by itself ends multiline mode, and executes the buffered script.\n"
+ "- on a line by itself while in multiline mode cancels multiline mode, and clears the buffer, without executing the buffered script.\n"
+ "If the line starts with $$, then the rest of the line is taken to be a shell command. The command is taken as a string, wrapped\n"
+ "in shell_adv(), (where system out and system err are piped to the corresponding outputs).\n"
+ "If $$ is on a line by itself, it puts the shell in shell_adv mode, and each line is taken as if it started\n"
+ "with $$. Use - on a line by itself to exit this mode as well.\n\n"
+ "For more information about a specific function, type \"help function\"\n"
+ "and for documentation plus examples, type \"examples function\". See the api tool\n"
+ "for more information about this feature.";
try {
msg += "\nYour current working directory is: " + env.getEnv(GlobalEnv.class).GetRootFolder().getCanonicalPath();
} catch (IOException ex) {
//
}
return msg;
}
/**
* Creates a new Interpreter object. This object can then be manipulated via the cmdline interactively, or
* standalone, via the execute method.
*
* @param args Any arguments passed in to the script. They are set as $vars
* @param cwd The initial working directory.
* @throws IOException
* @throws DataSourceException
* @throws URISyntaxException
*/
public Interpreter(List<String> args, String cwd) throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
this(args, cwd, false);
}
private Interpreter(List<String> args, String cwd, boolean inTTYMode) throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
doStartup();
env.getEnv(GlobalEnv.class).SetRootFolder(new File(cwd));
if(inTTYMode) {
//Ok, done. They'll have to execute from here.
return;
}
//We have two modes here, piped input, or interactive console.
if(System.console() == null) {
Scanner scanner = new Scanner(System.in);
//We need to read in everything, it's basically in multiline mode
StringBuilder script = new StringBuilder();
String line;
try {
while((line = scanner.nextLine()) != null) {
script.append(line).append("\n");
}
} catch (NoSuchElementException e) {
//Done
}
try {
execute(script.toString(), args);
StreamUtils.GetSystemOut().print(TermColors.reset());
System.exit(0);
} catch (ConfigCompileException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null, null);
StreamUtils.GetSystemOut().print(TermColors.reset());
System.exit(1);
} catch (ConfigCompileGroupException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null);
StreamUtils.GetSystemOut().println(TermColors.reset());
System.exit(1);
}
} else {
final ConsoleReader reader = new ConsoleReader();
reader.setExpandEvents(false);
//Get a list of all the function names. This will be provided to the auto completer.
Set<FunctionBase> functions = FunctionList.getFunctionList(api.Platforms.INTERPRETER_JAVA,
env.getEnvClasses());
List<String> names = new ArrayList<>();
for(FunctionBase f : functions) {
if(f.appearInDocumentation()) {
names.add(f.getName());
}
}
reader.addCompleter(new ArgumentCompleter(new ArgumentCompleter.AbstractArgumentDelimiter() {
@Override
public boolean isDelimiterChar(CharSequence buffer, int pos) {
char c = buffer.charAt(pos);
return !Character.isLetter(c) && c != '_';
}
}, new StringsCompleter(names) {
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
//The autocomplete can be improved a bit, instead of putting a space after it,
//let's put a parenthesis.
int ret = super.complete(buffer, cursor, candidates);
if(candidates.size() == 1) {
String functionName = candidates.get(0).toString().trim();
candidates.set(0, functionName + "()");
}
return ret;
}
}));
while(true) {
String prompt;
if(multilineMode) {
prompt = TermColors.WHITE + ">" + reset();
} else {
prompt = getPrompt();
}
String line = reader.readLine(prompt);
if(line == null || !textLine(line)) {
break;
}
}
//TODO: Add syntax highlighting, function keys, etc, but in order
//to do that, history, command completion, etc, will all have to be re-implemented,
//and implemented around readCharacter, which is a lot of work.
}
}
private String getPrompt() {
CClosure c = (CClosure) env.getEnv(GlobalEnv.class).GetCustom("cmdline_prompt");
if(c != null) {
try {
String val = c.executeCallable(CBoolean.get(inShellMode)).val();
return Static.MCToANSIColors(val) + TermColors.RESET;
} catch (ConfigRuntimeException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, env);
}
}
return BLUE + ":" + TermColors.RESET;
}
private void doStartup() throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
Installer.Install(MethodScriptFileLocations.getDefault().getConfigDirectory());
Installer.InstallCmdlineInterpreter();
env = Static.GenerateStandaloneEnvironment(false, EnumSet.of(RuntimeMode.CMDLINE, RuntimeMode.INTERPRETER));
staticAnalysis = new StaticAnalysis(true);
if(Prefs.UseColors()) {
TermColors.EnableColors();
} else {
TermColors.DisableColors();
}
String autoInclude = FileUtil.read(MethodScriptFileLocations.getDefault().getCmdlineInterpreterAutoIncludeFile());
try {
MethodScriptCompiler.execute(autoInclude, MethodScriptFileLocations.getDefault()
.getCmdlineInterpreterAutoIncludeFile(), true, env, env.getEnvClasses(), null, null, null);
} catch (ConfigCompileException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, "Interpreter will continue to run, however.", null);
} catch (ConfigCompileGroupException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null);
}
//Install our signal handlers.
SignalHandler.SignalCallback signalHandler = new SignalHandler.SignalCallback() {
@Override
public boolean handle(SignalType type) {
if(isExecuting) {
env.getEnv(GlobalEnv.class).SetInterrupt(true);
if(scriptThread != null) {
scriptThread.interrupt();
}
for(Thread t : env.getEnv(StaticRuntimeEnv.class).GetDaemonManager().getActiveThreads()) {
t.interrupt();
}
} else {
ctrlCcount++;
if(ctrlCcount > MAX_CTRL_C_MASHES) {
//Ok, ok, we get the hint.
StreamUtils.GetSystemOut().println();
StreamUtils.GetSystemOut().flush();
System.exit(130); //Standard Ctrl+C exit code
}
pl(YELLOW + "\nUse exit() to exit the shell." + reset());
p(getPrompt());
}
return true;
}
};
try {
SignalHandler.addHandler(Signals.SIGTERM, signalHandler);
} catch (IllegalArgumentException ex) {
// Oh well.
}
try {
SignalHandler.addHandler(Signals.SIGINT, signalHandler);
} catch (IllegalArgumentException ex) {
// Oh well again.
}
}
/**
* This evaluates each line of text
*
* @param line
* @return
* @throws IOException
*/
private boolean textLine(String line) throws IOException {
switch(line) {
case "-":
//Exit interpreter mode
if(multilineMode) {
script = "";
} else if(inShellMode) {
inShellMode = false;
} else {
return false;
}
break;
case ">>>":
//Start multiline mode
if(multilineMode) {
pl(RED + "You are already in multiline mode!");
} else {
multilineMode = true;
pl(YELLOW + "You are now in multiline mode. Type <<< on a line by itself to execute.");
}
break;
case "<<<":
//Execute multiline
multilineMode = false;
try {
execute(script, null);
script = "";
} catch (ConfigCompileException e) {
ConfigRuntimeException.HandleUncaughtException(e, null, null);
} catch (ConfigCompileGroupException e) {
ConfigRuntimeException.HandleUncaughtException(e, null);
}
break;
case "$$":
inShellMode = true;
break;
default: {
Pattern p = Pattern.compile("(help|examples) (.*)");
Matcher m;
if((m = p.matcher(line)).find()) {
String helpCommand = m.group(2);
try {
List<FunctionBase> fl = new ArrayList<>();
for(FunctionBase fb : FunctionList.getFunctionList(api.Platforms.INTERPRETER_JAVA,
env.getEnvClasses())) {
if(fb.getName().matches("^" + helpCommand + "$")) {
fl.add(fb);
}
}
if(fl.isEmpty()) {
StreamUtils.GetSystemErr().println("Could not find function of name " + helpCommand);
} else if(fl.size() == 1) {
StreamUtils.GetSystemOut().println(formatDocsForCmdline(helpCommand,
m.group(1).equals("examples")));
} else {
StreamUtils.GetSystemOut().println("Multiple function matches found:");
for(FunctionBase fb : fl) {
StreamUtils.GetSystemOut().println(fb.getName());
}
}
} catch (IOException | DataSourceException | URISyntaxException
| DocGenTemplates.Generator.GenerateException | ConfigCompileException e) {
e.printStackTrace(StreamUtils.GetSystemErr());
}
break;
}
if(multilineMode) {
//Queue multiline
script = script + line + "\n";
} else {
try {
//Execute single line
execute(line, null);
} catch (ConfigCompileException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null, null);
} catch (ConfigCompileGroupException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null);
}
}
break;
}
}
return true;
}
/**
* Given a function name, returns a string that is suitable for printing to the command line. This mechanism
* is standardized, so that the display of this information is standardized across different methods. The returned
* string will contain usages of {@link TermColors}.
* @param function
* @param showExamples
* @return
* @throws ConfigCompileException
* @throws IOException
* @throws DataSourceException
* @throws URISyntaxException
* @throws com.laytonsmith.tools.docgen.DocGenTemplates.Generator.GenerateException
*/
public static String formatDocsForCmdline(String function, boolean showExamples) throws ConfigCompileException,
IOException, DataSourceException, URISyntaxException, DocGenTemplates.Generator.GenerateException {
StringBuilder b = new StringBuilder();
FunctionBase f = FunctionList.getFunction(function, null, Target.UNKNOWN);
DocGen.DocInfo d = new DocGen.DocInfo(f.docs());
b.append(TermColors.CYAN).append(d.ret).append(" ");
b.append(TermColors.RESET).append(f.getName()).append("(")
.append(TermColors.MAGENTA).append(d.originalArgs).append(TermColors.RESET).append(")\n");
if(f instanceof Function) {
Class<? extends CREThrowable>[] thrown = ((Function) f).thrown();
if(thrown != null && thrown.length > 0) {
b.append("Throws: ");
Set<String> th = new HashSet<>();
for(Class<? extends CREThrowable> c : thrown) {
if(ClassDiscovery.GetClassAnnotation(c, typeof.class) != null) {
typeof t = ClassDiscovery.GetClassAnnotation(c, typeof.class);
th.add(t.value());
}
}
b.append(TermColors.RED).append(StringUtils.Join(th, ", ")).append(TermColors.RESET).append("\n");
}
}
b.append("\n");
{
String desc = reverseHTML(d.desc);
b.append(TermColors.WHITE).append(desc).append("\n");
}
if(d.extendedDesc != null) {
String desc = reverseHTML(d.extendedDesc);
b.append(TermColors.WHITE).append(desc).append("\n");
}
if(f instanceof Function) {
if(f.getClass().getAnnotation(seealso.class) != null) {
List<String> seeAlso = new ArrayList<>();
for(Class c : ((Function) f).seeAlso()) {
Object i = ReflectionUtils.newInstance(c);
if(i instanceof Documentation) {
Documentation seeAlsoDocumentation = (Documentation) i;
String color = TermColors.YELLOW;
if(i instanceof Function) {
if(((Function) f).isRestricted()) {
color = TermColors.CYAN;
} else {
color = TermColors.GREEN;
}
}
seeAlso.add(color + seeAlsoDocumentation.getName() + TermColors.RESET);
}
// TODO: also support Templates at some point, though this method will have to also be able
// to support the display of them, which it currently is unable to do.
}
if(!seeAlso.isEmpty()) {
b.append("See also: ");
b.append(StringUtils.Join(seeAlso, ", ")).append("\n");
}
}
}
if(f instanceof Function && showExamples) {
ExampleScript[] examples = ((Function) f).examples();
if(examples != null && examples.length > 0) {
b.append(TermColors.BOLD).append("\nExamples").append(TermColors.RESET).append("\n");
b.append("----------------------------------------------\n\n");
for(int i = 0; i < examples.length; i++) {
b.append(TermColors.BRIGHT_WHITE).append(TermColors.BOLD).append(TermColors.UNDERLINE)
.append("Example ").append(i + 1).append(TermColors.RESET).append("\n");
if(i > 0) {
b.append("\n\n");
}
ExampleScript e = examples[i];
b.append(e.getDescription()).append("\n\n");
b.append(TermColors.UNDERLINE).append("Code").append(TermColors.RESET).append("\n")
.append(reverseHTML(DocGenTemplates.CODE.generate(e.getScript()))).append("\n\n");
b.append(TermColors.UNDERLINE).append("Output").append(TermColors.RESET).append("\n")
.append(e.getOutput()).append("\n\n");
}
}
}
b.append(TermColors.RESET).append("\n");
return b.toString();
}
public static String reverseHTML(String input) {
input = input
.replaceAll("\\<br(.*?)>", "\n")
.replaceAll("</div>", "\n")
.replaceAll("\\<.*?>", "")
.replaceAll("(?s)\\<!--.*?-->", "");
input = HTMLUtils.unescapeHTML(input);
input = input.replaceAll("\\{\\{keyword\\|(.*?)\\}\\}", TermColors.BLUE + "$1" + TermColors.RESET);
input = input.replaceAll("\\{\\{object\\|(.*?)\\}\\}", TermColors.BRIGHT_BLUE + "$1" + TermColors.RESET);
input = input.replaceAll("\\\\\n", "\n");
input = input.replaceAll("(?s)\\{\\{Warning\\|text=(.*?)\\}\\}", TermColors.RED + "$1" + TermColors.RESET);
while(true) {
Matcher functionMatcher = Pattern.compile("\\{\\{function\\|(.*?)\\}\\}").matcher(input);
if(functionMatcher.find()) {
String function = functionMatcher.group(1);
String color;
try {
FunctionBase f = FunctionList.getFunction(function, null, Target.UNKNOWN);
if(f instanceof Function) {
if(((Function) f).isRestricted()) {
color = TermColors.CYAN;
} else {
color = TermColors.GREEN;
}
} else {
color = TermColors.YELLOW;
}
} catch (ConfigCompileException ex) {
color = TermColors.YELLOW;
}
input = input.replaceAll("\\{\\{function\\|" + function + "\\}\\}", color + function
+ TermColors.RESET);
} else {
break;
}
}
{
StringBuilder b = new StringBuilder();
StringBuilder headerLine = new StringBuilder();
boolean inTable = false;
boolean inTableHeader = false;
boolean inTableHeaderField = false;
for(int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
char c2 = '\0';
char c3 = '\0';
if(i < input.length() - 1) {
c2 = input.charAt(i + 1);
}
if(i < input.length() - 2) {
c3 = input.charAt(i + 2);
}
if(c == '{' && c2 == '|') {
inTable = true;
inTableHeader = true;
b.append("\n");
i++;
continue;
}
if(c == '|' && c2 == '}') {
inTable = false;
i++;
b.append('\n');
continue;
}
if(inTable) {
if(inTableHeader) {
if(c == '|' && c2 == '-') {
b.append("\n");
i++;
continue;
}
if(c == '\n') {
inTableHeader = false;
}
continue;
}
if(inTableHeaderField) {
if(c == '|') {
inTableHeaderField = false;
b.append(TermColors.RESET).append("\n|").append(TermColors.MAGENTA);
} else if(c == '\n') {
b.append(TermColors.RESET).append("| ").append(TermColors.MAGENTA)
.append(headerLine.toString()).append(TermColors.RESET)
.append("\n");
if(c2 != '!') {
inTableHeaderField = false;
} else {
headerLine = new StringBuilder();
i++;
}
continue;
}
headerLine.append(c);
continue;
}
if(c == '\n' && c2 == '!') {
headerLine = new StringBuilder();
inTableHeaderField = true;
i++;
continue;
}
if((c == '\n' && c2 == '|' && c3 == '-') || (c == '|' && c2 == '-')) {
b.append(TermColors.RESET).append("\n").append(StringUtils.stringMultiply(80, "-"));
if(c == '\n') {
i += 2;
} else {
i++;
b.append("\n");
}
continue;
}
}
b.append(c);
}
input = b.toString() + "\n";
}
return input;
}
/**
* This executes a script
*
* @param script
* @param args
* @throws ConfigCompileException
* @throws IOException
*/
public void execute(String script, List<String> args) throws ConfigCompileException, IOException, ConfigCompileGroupException {
execute(script, args, null);
}
/**
* This executes an entire script. The cmdline_prompt_event is first triggered (if used) and if the event is
* cancelled, nothing happens.
*
* @param script
* @param args
* @param fromFile
* @throws ConfigCompileException
* @throws IOException
*/
public void execute(String script, List<String> args, File fromFile) throws ConfigCompileException, IOException, ConfigCompileGroupException {
CmdlineEvents.cmdline_prompt_input.CmdlinePromptInput input = new CmdlineEvents.cmdline_prompt_input.CmdlinePromptInput(script, inShellMode);
EventUtils.TriggerListener(Driver.CMDLINE_PROMPT_INPUT, "cmdline_prompt_input", input);
if(input.isCancelled()) {
return;
}
ctrlCcount = 0;
if("exit".equals(script)) {
if(inShellMode) {
inShellMode = false;
return;
}
pl(YELLOW + "Use exit() if you wish to exit.");
return;
}
if("help".equals(script)) {
pl(getHelpMsg());
return;
}
if(fromFile == null) {
fromFile = new File("Interpreter");
}
boolean localShellMode = false;
if(!inShellMode && script.startsWith("$$")) {
localShellMode = true;
script = script.substring(2);
}
if(inShellMode || localShellMode) {
// Wrap this in shell_adv
if(doBuiltin(script)) {
return;
}
List<String> shellArgs = StringUtils.ArgParser(script);
List<String> escapedArgs = new ArrayList<>();
for(String arg : shellArgs) {
escapedArgs.add(new CString(arg, Target.UNKNOWN).getQuote());
}
script = "shell_adv("
+ "array("
+ StringUtils.Join(escapedArgs, ",")
+ "),"
+ "array("
+ "'stdout':closure(@l){sys_out(@l);},"
+ "'stderr':closure(@l){sys_err(@l);})"
+ ");";
}
isExecuting = true;
if(args != null) {
staticAnalysis.getStartScope().addDeclaration(
new Declaration(Namespace.IVARIABLE, "@arguments", CArray.TYPE, null, Target.UNKNOWN));
}
ProfilePoint compile = env.getEnv(StaticRuntimeEnv.class).GetProfiler().start("Compilation", LogLevel.VERBOSE);
final ParseTree tree;
try {
TokenStream stream = MethodScriptCompiler.lex(script, env, fromFile, true);
try {
tree = MethodScriptCompiler.compile(stream, env, env.getEnvClasses(), staticAnalysis);
} catch (AbstractCompileException e) {
// Pause on script exception in cmdline mode if set in the file options.
if(env.getEnv(GlobalEnv.class).inCmdlineMode()
&& System.console() != null && stream.getFileOptions().isCmdlinePauseOnException()) {
compile.stop();
if(e instanceof ConfigCompileException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null, null);
} else if(e instanceof ConfigCompileGroupException ex) {
ConfigRuntimeException.HandleUncaughtException(ex, null);
} else {
throw e;
}
StreamUtils.GetSystemOut().println(TermColors.reset());
prompt_char.promptChar("Press any key to continue...");
return;
}
// Pass exception to caller.
throw e;
}
staticAnalysis = new StaticAnalysis(staticAnalysis.getEndScope(), true); // Continue analysis in end scope.
} finally {
compile.stop();
}
//Environment env = Environment.createEnvironment(this.env.getEnv(GlobalEnv.class));
final List<Variable> vars = new ArrayList<>();
if(args != null) {
//Build the @arguments variable, the $ vars, and $ itself. Note that
//we have special handling for $0, that is the script name, like bash.
//However, it doesn't get added to either $ or @arguments, due to the
//uncommon use of it.
StringBuilder finalArgument = new StringBuilder();
CArray arguments = new CArray(Target.UNKNOWN);
{
//Set the $0 argument
Variable v = new Variable("$0", "", Target.UNKNOWN);
v.setVal(fromFile.toString());
v.setDefault(fromFile.toString());
vars.add(v);
}
for(int i = 0; i < args.size(); i++) {
String arg = args.get(i);
if(i > 0) {
finalArgument.append(" ");
}
Variable v = new Variable("$" + Integer.toString(i + 1), "", Target.UNKNOWN);
v.setVal(new CString(arg, Target.UNKNOWN));
v.setDefault(arg);
vars.add(v);
finalArgument.append(arg);
arguments.push(new CString(arg, Target.UNKNOWN), Target.UNKNOWN);
}
Variable v = new Variable("$", "", false, true, Target.UNKNOWN);
v.setVal(new CString(finalArgument.toString(), Target.UNKNOWN));
v.setDefault(finalArgument.toString());
vars.add(v);
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments,
Target.UNKNOWN));
}
try {
ProfilePoint p = this.env.getEnv(StaticRuntimeEnv.class)
.GetProfiler().start("Interpreter Script", LogLevel.ERROR);
try {
final MutableObject<Throwable> wasThrown = new MutableObject<>();
scriptThread = new Thread(new Runnable() {
@Override
public void run() {
try {
MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {
@Override
public void done(String output) {
if(System.console() != null && !"".equals(output.trim())) {
StreamUtils.GetSystemOut().println(output);
}
}
}, null, vars);
env.getEnv(StaticRuntimeEnv.class).GetDaemonManager().waitForThreads();
} catch (CancelCommandException | InterruptedException e) {
// Nothing, though we could have been Ctrl+C cancelled, so we need to reset
// the interrupt flag. But we do that unconditionally below, in the finally,
// in the other thread.
// However, interrupt all the underlying threads
for(Thread t : env.getEnv(StaticRuntimeEnv.class).GetDaemonManager().getActiveThreads()) {
t.interrupt();
}
} catch (ConfigRuntimeException e) {
ConfigRuntimeException.HandleUncaughtException(e, env);
// No need for the full stack trace.
if(System.console() == null) {
System.exit(1);
}
// Pause on script exception in cmdline mode if set in the file options.
if(env.getEnv(GlobalEnv.class).inCmdlineMode()
&& tree.getFileOptions().isCmdlinePauseOnException()) {
try {
prompt_char.promptChar("Press any key to continue...");
} catch (IOException e1) {
// Ignore.
}
}
} catch (NoClassDefFoundError e) {
StreamUtils.GetSystemErr().println(RED + Static.getNoClassDefFoundErrorMessage(e) + reset());
StreamUtils.GetSystemErr().println("Since you're running from standalone interpreter mode, this is not a fatal error, but one of the functions you just used required"
+ " an actual backing engine that isn't currently loaded. (It still might fail even if you load the engine though.) You simply won't be"
+ " able to use that function here.");
if(System.console() == null) {
System.exit(1);
}
} catch (InvalidEnvironmentException ex) {
StreamUtils.GetSystemErr().println(RED + ex.getMessage() + " " + ex.getData() + "() cannot be used in this context.");
if(System.console() == null) {
System.exit(1);
}
} catch (RuntimeException e) {
pl(RED + e.toString());
e.printStackTrace(StreamUtils.GetSystemErr());
if(System.console() == null) {
System.exit(1);
}
}
}
}, "MethodScript-Main");
scriptThread.start();
try {
scriptThread.join();
} catch (InterruptedException ex) {
//
}
} finally {
p.stop();
}
} finally {
env.getEnv(GlobalEnv.class).SetInterrupt(false);
isExecuting = false;
}
}
/**
* Works like {@link #execute(String, List, File)} but reads the file in for you.
*
* @param script Path the the file
* @param args Arguments to be passed to the script
* @throws ConfigCompileException If there is a compile error in the script
* @throws IOException
*/
public void execute(File script, List<String> args) throws ConfigCompileException, IOException, ConfigCompileGroupException {
String scriptString = FileUtil.read(script);
execute(scriptString, args, script);
}
public boolean doBuiltin(String script) {
List<String> args = StringUtils.ArgParser(script);
if(args.size() > 0) {
String command = args.get(0);
args.remove(0);
command = command.toLowerCase(Locale.ENGLISH);
switch(command) {
case "help":
pl(getHelpMsg());
pl("Shell builtins:");
pl("cd <dir> - Runs cd() with the provided argument.");
pl("s - equivalent to cd('..').");
pl("echo - Prints the arguments. If -e is set as the first argument, arguments are sent to colorize() first.");
pl("exit - Exits shellMode, and returns back to normal mscript mode.");
pl("logout - Exits the shell entirely with a return code of 0.");
pl("pwd - Runs pwd()");
pl("help - Prints this message.");
return true;
case "cd":
case "s":
if("s".equals(command)) {
args.add("..");
}
if(args.size() > 1) {
pl(RED + "Too many arguments passed to cd");
return true;
}
Construct[] a = new Construct[0];
if(args.size() == 1) {
a = new Construct[]{new CString(args.get(0), Target.UNKNOWN)};
}
try {
new Cmdline.cd().exec(Target.UNKNOWN, env, a);
} catch (CREIOException ex) {
pl(RED + ex.getMessage());
}
return true;
case "pwd":
pl(new Cmdline.pwd().exec(Target.UNKNOWN, env).val());
return true;
case "exit":
// We need previous code to intercept, we cannot do this here.
throw new Error("I should not run");
case "logout":
new Cmdline.exit().exec(Target.UNKNOWN, env, new CInt(0, Target.UNKNOWN));
return true; // won't actually run
case "echo":
// TODO Probably need some variable interpolation maybe? Otherwise, I don't think this command
// is actually useful as is, because this is not supposed to be a scripting environment.. that's
// what the normal shell is for.
boolean colorize = false;
if(args.size() > 0 && "-e".equals(args.get(0))) {
colorize = true;
args.remove(0);
}