-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShell.java
More file actions
1425 lines (1263 loc) · 42.7 KB
/
Shell.java
File metadata and controls
1425 lines (1263 loc) · 42.7 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.csse3200.game.ui.terminal;
import java.io.PrintStream;
import java.lang.reflect.*;
import java.util.*;
/**
* Shell: A simple, single-file, dependency-free scripting language interpreter
* written in vanilla Java.
*/
@SuppressWarnings("ALL") // Because the unused and exposed classes here are used in reflection.
public class Shell {
/** A reference to the Range class for internal use. */
final public static Class<?> RangeClass = Range.class;
/** A reference to the ShellMap class */
final public static Class<?> ShellMapClass = ShellMap.class;
/** A reference to the ReturnValue class for internal use. */
final public static Class<?> ReturnValueClass = ReturnValue.class;
/**
* An interface for abstracting read/write operations, allowing the Shell to
* work with different input/output sources, such as a standard console or a
* network socket.
*/
public interface Console {
/**
* Prints any generic object to the output.
*
* @param obj The object to print.
* NOTE: It is assumed that calls to the print method are cheap,
* Therefore, this should probably be buffered
*/
void print(Object obj);
/**
* Reads a line / block to be Interpreter from the input.
*
* @return The line read from the input source.
*/
String next();
/**
* Checks if there is another chunk to be read.
*
* @return true if there is a next line, false otherwise.
*/
boolean hasNext();
/**
* Closes the console's underlying resources.
*/
void close();
}
/** The console used for input and output operations. */
final private Console console;
/** The execution environment, holding global variables and the call stack. */
public Environment env;
/**
* Constructs a new Shell with a given console and a new default environment.
*
* @param console The console interface for I/O.
*/
public Shell(Console console) {
this(console, new Environment());
}
/**
* Constructs a new Shell with a specified console and a pre-existing
* environment.
*
* @param console The console interface for I/O.
* @param env The execution environment to use.
*/
public Shell(Console console, Environment env) {
this.console = console;
this.env = env;
this.env.put("globalThis", this);
}
/**
* Runs the shell's read-evaluation loop.
*/
public void run() {
while (console.hasNext()) {
try {
final Object result = eval(console.next());
if (result != null) {
console.print(result);
console.print("\n");
}
} catch (ShellException e) {
console.print("Error: ");
console.print(e.getMessage());
console.print("\n");
} catch (Exception e) {
console.print("Runtime Error: ");
console.print(e.getClass().getSimpleName());
console.print(" - ");
console.print(e.getMessage());
console.print("\n");
}
}
}
/**
* Cleanup the resources used by the shell.
*/
public void close() {
console.close();
}
/**
* Evaluates a given string of source code.
*
* @param source The source code to evaluate.
* @return The result of the last evaluated statement.
*/
public Object eval(String source) {
if (source.trim().isEmpty()) return null;
Parser parser = new Parser(source);
ArrayList<Evaluable> statements = new ArrayList<>();
// Parse all statements
while (!parser.isAtEnd()) statements.add(parser.parseStatement());
Object lastResult = null;
// Execute all statements
for (Evaluable s : statements) lastResult = s.evaluate(env);
return lastResult;
}
/**
* The main function.
* This is for testing purposes only.
*/
public static void main(String[] args) {
new Shell(new Console() {
final Scanner scanner = new Scanner(System.in);
final PrintStream out = System.out;
@Override
public void print(Object obj) {
out.print(obj);
}
@Override
public String next() {
out.print("> ");
StringBuilder inputBuffer = new StringBuilder();
while (true) {
final String line = scanner.nextLine();
inputBuffer.append(line);
if (!line.trim().endsWith("!") && scanner.hasNextLine()) {
inputBuffer.append("\n");
continue;
}
String source = inputBuffer.toString().trim();
source = source.substring(0, source.length() - 1);
inputBuffer.setLength(0);
return source;
}
}
@Override
public boolean hasNext() {
return scanner.hasNextLine();
}
@Override
public void close() {
scanner.close();
}
}).run();
}
/**
* Provides a string representation of the Shell instance, including its
* environment.
*
* @return A string representation of the shell.
*/
@Override
public String toString() {
return "Shell{.env = " + env + "}";
}
/**
* Performs a logical AND operation.
*
* @param l The left-hand side operand.
* @param r The right-hand side operand.
* @return The result of the logical AND.
*/
public static Object and(Object l, Object r) {
return isTruthy(l) && isTruthy(r);
}
/**
* Performs a logical OR operation.
*
* @param l The left-hand side operand.
* @param r The right-hand side operand.
* @return The result of the logical OR.
*/
public static Object or(Object l, Object r) {
return isTruthy(l) || isTruthy(r);
}
/**
* Performs a logical NOT operation.
*
* @param x The operand.
* @return The result of the logical NOT.
*/
public static Object not(Object x) {
return !isTruthy(x);
}
/**
* Determines the "truthiness" of an object, similar to languages like
* JavaScript or Python. Used to coerce objects to booleans.
*
* @param obj The object to evaluate.
* @return false if the object is null, a zero number, an empty string/collection,
* or Boolean false. Returns true otherwise.
*/
public static boolean isTruthy(Object obj) {
switch (obj) {
case null -> {
return false;
}
case Boolean b -> {
return b;
}
case Number number -> {
return number.doubleValue() != 0.0;
}
case String s -> {
return !s.isEmpty();
}
case Character c -> {
return c != '\0';
}
case Collection<?> collection -> {
return !collection.isEmpty();
}
case Map<?, ?> map -> {
return !map.isEmpty();
}
default -> {
}
}
if (obj.getClass().isArray()) return Array.getLength(obj) != 0;
return true;
}
/**
* Implements an if-then construct. Executes the function if the condition is
* truthy.
*
* @param condition The condition to check.
* @param function The function to execute if the condition is true.
* @return The result of the function, or null if the condition was false.
*/
public Object ifThen(Object condition, EvaluableFunction function) {
if (isTruthy(condition)) {
return function.evaluate(env, new ArrayList<>());
}
return null;
}
/**
* Implements an if-else construct.
*
* @param condition The condition to check.
* @param ifFunction The function to execute if the condition is true.
* @param elseFunction The function to execute if the condition is false.
* @return The result of the executed function.
*/
public Object ifElse(Object condition, EvaluableFunction ifFunction, EvaluableFunction elseFunction) {
if (isTruthy(condition)) {
return ifFunction.evaluate(env, new ArrayList<>());
}
return elseFunction.evaluate(env, new ArrayList<>());
}
/**
* Represents a numerical range that can be iterated over.
* This is intended for shell use only
*/
public static class Range implements Iterator<Long> {
private long start;
private final long end;
private final long step;
/**
* Creates a range with a step of 1.
*
* @param start The starting value (inclusive).
* @param end The ending value (inclusive).
*/
public Range(long start, long end) {
this(start, end, 1);
}
/**
* Creates a range with a specified step.
*
* @param start The starting value (inclusive).
* @param end The ending value (inclusive).
* @param step The increment value.
*/
public Range(long start, long end, long step) {
this.start = start;
this.end = end;
this.step = step;
}
/**
* Checks if the iteration has more elements.
*
* @return true if the current value is less than or equal to the end.
*/
public boolean hasNext() {
return start <= end;
}
/**
* Returns the next element in the iteration.
*
* @return The next long value in the range.
*/
public Long next() {
long currentValue = start;
start += step;
return currentValue;
}
}
/**
* Implements a for-each loop construct that iterates over various iterable types.
*
* @param obj The object to iterate over (can be an Iterator, Collection, Array, or Map).
* @param function The function to execute for each item.
* @return null after the loop completes.
* @throws ShellException if the object is not iterable.
*/
public Object forEach(Object obj, EvaluableFunction function) {
if (obj == null) return null;
if (obj.getClass().isArray()) {
int length = Array.getLength(obj);
for (int i = 0; i < length; i++) {
final Object result = function.evaluate(env, new ArrayList<>(List.of(Array.get(obj, i))));
if (result instanceof ReturnValue) return result;
}
} else if (obj instanceof Iterator<?> iterator) {
while (iterator.hasNext()) {
final Object result = function.evaluate(env, new ArrayList<>(List.of(iterator.next())));
if (result instanceof ReturnValue) return result;
}
} else if (obj instanceof Iterable<?> iterable) {
for (Object item : iterable) {
final Object result = function.evaluate(env, new ArrayList<>(List.of(item)));
if (result instanceof ReturnValue) return result;
}
} else if (obj instanceof Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
final Object result = function.evaluate(env, new ArrayList<>(List.of(entry.getKey(), entry.getValue())));
if (result instanceof ReturnValue) return result;
}
} else {
throw new ShellException("Cannot iterate over " + obj.getClass().getSimpleName());
}
return null;
}
/**
* Implements a while loop construct.
*
* @param condition The condition to evaluate before each iteration.
* @param function The function to execute in the loop body.
* @return The result of the last executed statement in the loop.
*/
public Object whileLoop(EvaluableFunction condition, EvaluableFunction function) {
while (isTruthy(condition.evaluate(env, new ArrayList<>()))) {
final Object result = function.evaluate(env, new ArrayList<>());
if (result instanceof ReturnValue) return ((ReturnValue) result).value;
}
return null;
}
/**
* Implements a try-catch construct for error handling.
*
* @param tryBlock The function containing code that might throw an exception.
* @param catchBlock The function to execute if a ShellException is caught.
* @return The result of the try block, or the result of the catch block if an exception occurred.
*/
public Object tryCatch(EvaluableFunction tryBlock, EvaluableFunction catchBlock) {
try {
return tryBlock.evaluate(env, new ArrayList<>());
} catch (ShellException e) {
return catchBlock.evaluate(env, new ArrayList<>(List.of(e)));
}
}
/**
* Sets a value in the global environment scope.
*
* @param name The name of the global variable.
* @param value The value to set.
* @return The value that was set.
*/
public Object setGlobal(String name, Object value) {
env.global.put(name, value);
return value;
}
/**
* Gets a value from the global environment scope.
*
* @param name The name of the global variable.
* @return The value of the global variable.
*/
public Object getGlobal(String name) {
return env.global.get(name);
}
/**
* Returns true if the give object is actually a class type
*
* @param obj the object to be tested
* @return true if obj is a class, false otherwise
*/
public boolean isClass(Object obj) {
return obj instanceof Class<?>;
}
/**
* Returns true if a given object exists in the current scope
*
* @param name the name to look for in the environment
* @return true if the object exists
*/
public boolean exists(String name) {
return env.get(name) != null;
}
}
/**
* A specialized HashMap used for environment frames in the shell.
* It provides a safe toString() implementation to prevent infinite recursion
* when printing environments that reference themselves.
*/
class ShellMap {
private final HashMap<String, Object> map = new HashMap<>();
/**
* A static accessor for the underlying map.
*
* @param self The ShellMap instance.
* @return The map itself.
*/
public static HashMap<String, Object> getMap(ShellMap self) {
return self.map;
}
public Object put(String key, Object val) {
return map.put(key, val);
}
public Object get(String key) {
return map.get(key);
}
/**
* Thread unsafe recursion guard.
*/
private boolean inToStringCall = false;
/**
* Provides a string representation of the map, with a guard against recursive calls.
*
* @return A string representation of the map, or "..." if a recursive call is detected.
*/
@Override
public String toString() {
if (inToStringCall) return "...";
inToStringCall = true;
final String returnValue = getMap(this).toString();
inToStringCall = false;
return returnValue;
}
}
/**
* Represents the state of our shell environment, including global variables and a stack frames
*/
class Environment {
/** The global scope, accessible from anywhere. */
public final ShellMap global = new ShellMap();
/** The stack of function frames */
public ArrayList<ShellMap> frames = new ArrayList<>();
/**
* Thread unsafe recursion guard.
*/
private boolean inToStringCall = false;
public Environment() {
}
/**
* Pushes a new frame onto the stack for a new local scope.
*
* @return The newly created frame.
*/
public ShellMap pushFrame() {
final ShellMap frame = new ShellMap();
frames.add(frame);
return frame;
}
/**
* Pops the current frame from the stack when a scope is exited.
*/
public void popFrame() {
frames.removeLast();
}
/**
* Retrieves a variable by name, searches from the innermost frame and the global scope.
*
* @param name The name of the variable to look up.
* @return The value of the variable, or null if not found.
*/
public Object get(String name) {
if (!frames.isEmpty()) { // Only need to check the last frame
final Object returnValue = frames.getLast().get(name);
if (returnValue != null) return returnValue;
}
return global.get(name);
}
/**
* Puts a variable in the current scope (function or global scope).
*
* @param name The name of the variable.
* @param value The value to assign.
*/
public void put(String name, Object value) {
if (!frames.isEmpty()) {
frames.getLast().put(name, value);
} else {
global.put(name, value);
}
}
/**
* Provides a string representation of the Environment, with a guard for recursive calls.
*
* @return A string representation of the environment.
*/
@Override
@SuppressWarnings("ALL") // LSP does not recognise recursion smh!
public String toString() {
if (inToStringCall) return "...";
inToStringCall = true;
final String returnValue = "Environment{.global = " + global + ".frames = " + frames + "}";
inToStringCall = false;
return returnValue;
}
}
/**
* A custom exception class for user-level errors that occur during script execution.
*/
final class ShellException extends RuntimeException {
public ShellException(String message) {
super(message);
}
}
/**
* A wrapper class to signify a return value from a function. This is used to
* unwind the call stack during a return statement.
*/
class ReturnValue {
public Object value;
public ReturnValue(Object value) {
this.value = value;
}
@Override
public String toString() {
return "ReturnValue(" + value + ")";
}
}
/**
* An interface representing any piece of code that can be evaluated.
*/
interface Evaluable {
/**
* Evaluates the code fragment in context of a given environment.
*
* @param env The environment to use for evaluation.
* @return The result of the evaluation.
*/
Object evaluate(Environment env);
}
/**
* An interface representing a callable function.
*/
interface EvaluableFunction {
/**
* Evaluates the function with a given set of parameters.
*
* @param env The environment to use for evaluation.
* @param parameters The arguments passed to the function.
* @return The return value of the function.
*/
Object evaluate(Environment env, ArrayList<Object> parameters);
}
/**
* Represents a constant literal value in the code, such as a number or a string.
*/
record ConstantStatement(Object value) implements Evaluable {
/**
* Returns the held constant value.
*
* @param env The environment (unused).
* @return The constant value.
*/
@Override
public Object evaluate(Environment env) {
return value;
}
@Override
public String toString() {
return "Constant(" + value + ")";
}
}
/**
* A utility class for accessing properties on objects, maps, and classes using
* Java Reflection. This allows the script to interact with Java objects.
*/
final class Accessor {
/**
* Accesses a property on the environment.
*
* @param env The environment for the initial variable lookup.
* @param path The path of properties to access (e.g., ["myObject", "myField"]).
* @param accessMethods True if method resolution should be attempted for the last element.
* @return The final value or a MaybeMethodStatement if a method was found.
* @throws ShellException if access is invalid (e.g., property on null).
*/
public static Object access(Environment env, List<String> path, boolean accessMethods) {
assert (!path.isEmpty());
Object current = env.get(path.getFirst());
return accessObj(current, path.subList(1, path.size()), accessMethods);
}
/**
* Accesses a property on an object through a given path.
*
* @param current The object on which the lookup will be done.
* @param path The path of properties to access (e.g., ["myObject", "myField"]).
* @param accessMethods True if method resolution should be attempted for the last element.
* @return The final value or a MaybeMethodStatement if a method was found.
* @throws ShellException if access is invalid (e.g., property on null).
*/
public static Object accessObj(Object current, List<String> path, boolean accessMethods) {
for (int i = 0; i < path.size(); i++) {
if (current == null) {
throw new ShellException("Cannot access property '" + path.get(i) + "' on a null value.");
}
String propertyName = path.get(i);
if (current instanceof ShellMap) {
current = ((ShellMap) current).get(propertyName);
continue;
}
Class<?> targetClass = (current instanceof Class) ? (Class<?>) current : current.getClass();
Object instance = (current instanceof Class) ? null : current;
try {
Field field = targetClass.getField(propertyName);
current = field.get(instance);
continue;
} catch (NoSuchFieldException e) {
// Maybe a private field / method!
} catch (Exception e) {
throw new ShellException("Cannot access field '" + propertyName + "' on " + targetClass.getSimpleName());
}
if (i == path.size() - 1 && accessMethods) {
for (Method method : targetClass.getMethods()) {
if (method.getName().equals(propertyName)) {
return new MaybeMethodStatement(current, propertyName);
}
}
}
boolean found = false;
for (Class<?> currentClass = targetClass; currentClass != null; currentClass = currentClass.getSuperclass()) {
try {
for (Class<?> c : currentClass.getDeclaredClasses()) {
if (c.getSimpleName().equals(propertyName)) {
current = c;
found = true;
break;
}
}
if (found) break;
} catch (Exception e) {
throw new ShellException("Error accessing class '" + propertyName + "': " + e.getMessage());
}
try {
Field field = currentClass.getDeclaredField(propertyName);
if (instance == null && !Modifier.isStatic(field.getModifiers())) {
throw new ShellException("Cannot access instance field '" + propertyName + "' from a static context on class " + targetClass.getSimpleName());
}
field.setAccessible(true);
current = field.get(instance);
found = true;
break;
} catch (NoSuchFieldException e) {
// might be a method
} catch (Exception e) {
throw new ShellException("Error accessing field '" + propertyName + "': " + e.getMessage());
}
if (i == path.size() - 1 && accessMethods) {
for (Method method : targetClass.getDeclaredMethods()) {
if (method.getName().equals(propertyName)) {
return new MaybeMethodStatement(current, propertyName);
}
}
if (current instanceof Class) {
try {
Class.class.getDeclaredMethod(propertyName);
return new MaybeMethodStatement(currentClass, propertyName);
} catch (NoSuchMethodException e) {
System.err.println("Error accessing class '" + propertyName + "': " + e.getMessage());
// Ignore
}
}
}
}
if (i == path.size() - 1 && !found) {
throw new ShellException("Cannot access property '" + path.get(i) + "' on " + targetClass.getSimpleName());
}
}
return current;
}
}
/**
* Represents a variable access statement, which can be a simple variable name
* or a chain of property accesses.
* e.g. `x` or `x.y`
*/
record AccessStatement(String[] path) implements Evaluable {
AccessStatement {
if (path.length == 0) throw new IllegalArgumentException("Access path cannot be empty.");
}
/**
* Evaluates the access path to retrieve the final value.
*
* @param env The environment in which to evaluate.
* @return The retrieved value.
* @throws ShellException if the variable is not found.
*/
@Override
public Object evaluate(Environment env) {
if (path.length == 1) {
Object current = env.get(path[0]);
if (current == null) {
throw new ShellException("Variable '" + path[0] + "' not found.");
}
return current;
}
return Accessor.access(env, Arrays.asList(path), true);
}
@Override
public String toString() {
return "Access(" + String.join(".", path) + ")";
}
}
/**
* Represents an assignment statement, supports traversing
* e.g. `x = 0;` or `x.y = 0;`
*/
record AssignmentStatement(AccessStatement left, Evaluable right) implements Evaluable {
/**
* Evaluates the right-hand side and assigns the result to the left-hand side.
*
* @param env The environment in which to evaluate.
* @return The value that was assigned.
* @throws ShellException if the assignment target is invalid.
*/
@Override
public Object evaluate(Environment env) {
Object valueToAssign = right.evaluate(env);
String[] path = left.path();
if (path.length == 1) {
env.put(path[0], valueToAssign);
return valueToAssign;
}
Object toSet = Accessor.access(env, Arrays.asList(path).subList(0, path.length - 1), false);
switch (toSet) {
case null ->
throw new ShellException("Cannot access property '" + path[path.length - 1] + "' on a null container.");
case ShellMap shellMap -> {
shellMap.put(path[path.length - 1], valueToAssign);
return valueToAssign;
}
case Environment environment -> {
environment.put(path[path.length - 1], valueToAssign);
return valueToAssign;
}
default -> {
}
}
Class<?> targetClass = (toSet instanceof Class) ? (Class<?>) toSet : toSet.getClass();
for (Class<?> currentClass = targetClass; currentClass != null; currentClass = currentClass.getSuperclass()) {
try {
Field field = currentClass.getDeclaredField(path[path.length - 1]);
field.setAccessible(true);
field.set(toSet, valueToAssign);
return valueToAssign;
} catch (NoSuchFieldException ignored) {
} catch (Exception e) {
throw new ShellException("Error setting field '" + path[path.length - 1] + "': " + e.getMessage());
}
}
throw new ShellException("Cannot set field '" + path[path.length - 1] + "' on " + targetClass.getSimpleName());
}
@Override
public String toString() {
return "Assignment(" + left + " = " + right + ")";
}
}
/**
* Represents what could be a callable method / function statement.
* Uses reflection to find the best matching overload.
*/
final class MaybeMethodStatement implements EvaluableFunction {
Object instance;
String methodName;
MaybeMethodStatement(Object object, String methodName) {
this.instance = object;
this.methodName = methodName;
}
private boolean isInvocable(Method method, Object targetInstance, Object[] args) {
if (!method.getName().equals(methodName) || method.getParameterCount() != args.length) return false;
boolean isStatic = Modifier.isStatic(method.getModifiers());
if (!isStatic && targetInstance == null) return false;
Class<?>[] paramTypes = method.getParameterTypes();
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
if (paramTypes[i].isPrimitive()) return false;
} else if (!isAssignable(paramTypes[i], args[i].getClass())) {
return false;
}
}
return true;
}
private Object tryInvoke(Method method, Object targetInstance, Object[] args) {
try {
method.setAccessible(true);
return method.invoke(targetInstance, args);
} catch (Exception e) {
throw new ShellException("Error invoking method '" + methodName + "': " + e + e.getCause() + "\nArgs: " + Arrays.toString(args));
}
}
/**
* Evaluates the method call by finding a suitable method overload for the
* given parameters and invoking it.
*
* @param env The environment (unused).
* @param parameters The arguments for the method call.
* @return The result of the method invocation.
* @throws ShellException if no suitable method is found or if invocation fails.
*/
@Override
public Object evaluate(Environment env, ArrayList<Object> parameters) {
Object targetInstance = (instance instanceof Class) ? null : instance;
Class<?> targetClass = (instance instanceof Class) ? (Class<?>) instance : instance.getClass();
Object[] args = parameters.toArray();
for (Class<?> currentClass = targetClass; currentClass != null; currentClass = currentClass.getSuperclass()) {
for (Method method : currentClass.getDeclaredMethods()) {
if (isInvocable(method, targetInstance, args)) return tryInvoke(method, targetInstance, args);
}
}
if (instance instanceof Class) {
for (Method method : Class.class.getDeclaredMethods()) {
if (isInvocable(method, instance, args)) return tryInvoke(method, instance, args);
}
}
throw new ShellException("No matching method '" + methodName + "' found for the given arguments in " + targetClass.getSimpleName());
}
/** Map of primitive types to their corresponding wrapper classes. */
static final Map<Class<?>, Class<?>> WRAPPER_TYPES = Map.of(
boolean.class, Boolean.class, byte.class, Byte.class, char.class, Character.class,
double.class, Double.class, float.class, Float.class, int.class, Integer.class,
long.class, Long.class, short.class, Short.class);
/**
* Checks if a value from a source type can be assigned to a target type,
* handling primitive-to-wrapper conversions.
*
* @param targetType The type of the parameter.
* @param sourceType The type of the argument.
* @return true if assignment is possible.
*/
private boolean isAssignable(Class<?> targetType, Class<?> sourceType) {
if (targetType.isAssignableFrom(sourceType)) return true;
if (targetType.isPrimitive()) {
return WRAPPER_TYPES.get(targetType).equals(sourceType);
}
return false;
}
}
/**
* Represents a user-defined function in the shell script.
* // e.g. `(x, y) { return(.java.lang.Math.pow(x, y)); }`
*/
record FunctionStatement(Evaluable[] instructions, String[] parameter_names,
int variadicIndex) implements EvaluableFunction {
/**
* Executes the function call statement
*
* @param env The parent environment.
* @param parameters The arguments passed to the function.
* @return The function's return value, or null if no return statement is executed.
* @throws ShellException if the wrong number of arguments is provided.
*/
@Override
public Object evaluate(Environment env, ArrayList<Object> parameters) {
final ShellMap frame = env.pushFrame();
if (variadicIndex == -1) {
if (parameter_names.length != parameters.size()) {
throw new ShellException("Expected " + parameter_names.length + " arguments, got " + parameters.size());
}
}
for (int i = 0; i < (variadicIndex == -1 ? parameter_names.length : parameter_names.length - 1); i++) {
frame.put(parameter_names[i], parameters.get(i));
}
if (variadicIndex != -1) {