/
Main.java
383 lines (358 loc) · 14 KB
/
Main.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
package APL;
import APL.errors.*;
import APL.tokenizer.*;
import APL.tokenizer.types.*;
import APL.types.*;
import APL.types.arrs.*;
import APL.types.functions.VarArr;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("WeakerAccess") // for use as a library
public class Main {
public static final String CODEPAGE = "\0\0\0\0\0\0\0\0\0\t\n\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~÷×↑↓⌈⌊≠∊⍺⍴⍵⍳∍⋾⎕⍞⌸⌺⍇⍁⍂⌻⌼⍃⍄⍈⍌⍍⍐⍓⍔⍗⍯⍰⍠⌹⊆⊇⍶⍸⍹⍘⍚⍛⍜⍊≤≥⍮ϼ⍷⍉⌽⊖⊙⌾○∘⍟⊗¨⍨⍡⍥⍩⍣⍢⍤⊂⊃∩∪⊥⊤∆∇⍒⍋⍫⍱⍲∨∧⍬⊣⊢⌷⍕⍎←→⍅⍆⍏⍖⌿⍀⍪≡≢⍦⍧⍭‽⍑∞…√ᑈᐵ";
public static boolean debug = false;
public static boolean vind = false; // vector indexing
public static boolean noBoxing = false;
public static boolean quotestrings = false;
public static boolean enclosePrimitives = false;
public static boolean colorful = true;
static final ChrArr alphabet = toAPL("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
static final ChrArr lowercaseAlphabet = toAPL("abcdefghijklmnopqrstuvwxyz");
public static final ChrArr digits = toAPL("0123456789");
static int printlvl = 0;
public static final Error up = null;//new Error("A problem has been detected and APL has been shut down to prevent damage to your computer.");
static final long startingMillis = System.currentTimeMillis();
public static Scanner console;
public static Tokenable faulty;
private static Throwable lastError = null;
public static void main(String[] args) {
colorful = System.console() != null && System.getenv().get("TERM") != null;
console = new Scanner(System.in);
Scope global = new Scope();
boolean REPL = false;
boolean silentREPL = false;
if (args.length > 0) {
try {
for (int i = 0; i < args.length; i++) {
String p = args[i];
if (p.length() >= 2 && p.charAt(0) == '-') {
if (p.charAt(1) == '-') {
switch (p) {
case "--help":
println("Usage: APL [options]");
println("Options:");
println("-f file: execute the contents of the file");
println("-e code: execute the argument as APL");
println("-p code: execute the argument as APL and print its result");
println("-i : execute STDIN as APL");
println("-r : start the REPL after everything else");
println("-s : start the REPL without \">\" after everything else");
println("-d : enable debug mode");
println("-q : enable quoting of strings");
println("-b : disable boxing");
println("-c : disable colorful printing");
println("-q : define quads in the next argument");
println("-D file: run the file as SBCS");
println("-E a b : encode the file A in the SBCS, save as B");
println("If given no arguments, an implicit -r will be added");
System.exit(0);
break;
default:
throw new DomainError("Unknown command-line argument " + p);
}
} else {
for (char c : p.substring(1).toCharArray()) {
switch (c) {
case 'f':
String name = args[++i];
exec(readFile(name), global);
break;
case 'e':
String code = args[++i];
exec(code, global);
break;
case 'p':
code = args[++i];
println(exec(code, global).toString());
break;
case 'i':
StringBuilder s = new StringBuilder();
while (console.hasNext()) {
s.append(console.nextLine()).append('\n');
}
exec(s.toString(), global);
break;
case 'r':
REPL = true;
break;
case 's':
REPL = true;
silentREPL^= true;
break;
case 'd':
debug = true;
break;
case 'q':
quotestrings = true;
break;
case 'b':
noBoxing = true;
break;
case 'c':
colorful = false;
break;
case 'E': {
String origS = readFile(args[++i]);
byte[] res = new byte[origS.length()];
for (int j = 0; j < origS.length(); j++) {
char chr = origS.charAt(j);
int index = CODEPAGE.indexOf(chr);
if (index == -1) throw new DomainError("error encoding character " + chr + " (" + (+chr) + ")");
res[j] = (byte) index;
}
String conv = args[++i];
try (FileOutputStream stream = new FileOutputStream(conv)) {
stream.write(res);
} catch (IOException e) {
e.printStackTrace();
throw new DomainError("couldn't write file");
}
break;
}
case 'D':
try {
byte[] bytes = Files.readAllBytes(new File(args[++i]).toPath());
StringBuilder res = new StringBuilder();
for (byte b : bytes) {
res.append(CODEPAGE.charAt(b & 0xff));
}
exec(res.toString(), global);
} catch (IOException e) {
e.printStackTrace();
throw new DomainError("couldn't read file");
}
break;
default:
throw new DomainError("Unknown command-line argument -" + c);
}
}
}
} else {
throw new DomainError("Unknown command-line argument " + p);
}
}
} catch (APLError e) {
e.print();
throw e;
} catch (Throwable e) {
e.printStackTrace();
colorprint(e + ": " + e.getMessage(), 246);
throw e;
}
}
if (args.length == 0 || REPL) {
if (!silentREPL) print("> ");
while (console.hasNext()) {
faulty = null;
try {
String cr = console.nextLine();
if (cr.equals("exit")) break;
if (cr.startsWith(")")) {
if (")OFF".equals(cr) || ")EXIT".equals(cr) || ")STOP".equals(cr)) break /* REPL */;
ucmd(global, cr.substring(1));
} else {
Obj r = exec(cr, global);
if (r!=null) println(r.toString());
}
} catch (APLError e) {
lastError = e;
e.print();
} catch (Throwable e) {
lastError = e;
colorprint(e + ": " + e.getMessage(), 246);
if (faulty != null && faulty.getToken() != null) {
String s = IntStream.range(0, faulty.getToken().spos).mapToObj(i -> " ").collect(Collectors.joining());
colorprint(faulty.getToken().raw, 217);
colorprint(s + "^", 217);
}
e.printStackTrace();
}
if (!silentREPL) print("> ");
}
}
}
public static void ucmd(Scope sc, String cr) {
String[] parts = cr.split(" ");
String t = parts[0].toUpperCase();
String rest = parts.length==1? "" : cr.substring(t.length()+1);
switch (t) {
case "EX":
exec(readFile(parts[1]), sc);
break;
case "DEBUG":
debug = !debug;
break;
case "QUOTE":
quotestrings = !quotestrings;
break;
case "ONELINE":
noBoxing = !noBoxing;
break;
case "TOKENIZE" : println(Tokenizer.tokenize(rest).toTree("")); break;
case "TOKENIZEREPR": println(Tokenizer.tokenize(rest).toRepr()); break;
case "CLASS" : var r = exec(rest, sc); println(r == null? "nothing" : r.getClass().getCanonicalName()); break;
case "UOPT" : var e = (Arr)sc.get(rest); sc.set(rest, new HArr(e.values(), e.shape)); break;
case "ATYPE" : println(exec(rest, sc).humanType(false)); break;
case "STACK":
if (lastError != null) {
lastError.printStackTrace();
}
break;
default:
throw new SyntaxError("Undefined user command");
}
}
public static void print(String s) {
System.out.print(s);
}
public static void println(String s) {
System.out.println(s);
}
public static String formatAPL (int[] ia) {
return Arrays.stream(ia).mapToObj(String::valueOf).collect(Collectors.joining(" "));
}
static String readFile(String path) {
try {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new DomainError("File "+path+" not found");
}
}
public static Obj exec(String s, Scope sc) {
BasicLines t = Tokenizer.tokenize(s);
printdbg(t);
return execLines(t, sc);
}
static public void printdbg(Object... args) {
if (!debug) return;
if (args.length > 0) print(args[0] == null? "null" : args[0].toString());
for (int i = 1; i < args.length; i++) {
print(" ");
print(args[i] == null? "null" : args[i].toString());
}
print("\n");
}
public static String explain(Token tok) {
return tok.toRepr();
}
enum EType {
all
}
public static Obj exec(LineTok s, Scope sc) {
return new Exec(s, sc).exec();
}
public static Obj oexec(LineTok s, Scope sc) {
Obj val = Main.exec(s, sc);
if (val instanceof VarArr) val = ((VarArr) val).get();
if (val instanceof Settable) val = ((Settable) val).get();
return val;
}
public static Obj vexec(LineTok s, Scope sc) {
Obj val = Main.exec(s, sc);
if (val instanceof VarArr) val = ((VarArr) val).get();
if (val instanceof Settable) val = ((Settable) val).get();
if (val instanceof Value) return val;
throw new SyntaxError("expected array, got " + val.humanType(true));
}
static public Obj execLines(TokArr<LineTok> lines, Scope sc) {
Obj res = null;
HashMap<EType, LineTok> eGuards = new HashMap<>();
try {
for (LineTok ln : lines.tokens) {
List<Token> tokens = ln.tokens;
int guardPos = ln.colonPos();
int eguardPos = ln.eguardPos();
if (guardPos != -1 && eguardPos != -1) throw new SyntaxError("both : and :: found in line");
boolean endAfter = tokens.size() > 1 && tokens.get(0) instanceof SetTok;
if (endAfter) tokens = tokens.subList(1, tokens.size());
else if (guardPos != -1) {
if (guardPos == tokens.size()-1) throw new SyntaxError("Guard without success expression");
if (tokens.get(guardPos+1) instanceof SetTok) endAfter = true;
} else if (eguardPos != -1) {
if (eguardPos == tokens.size()-1) throw new SyntaxError("Error guard without success expression");
}
if (guardPos != -1) {
var guard = LineTok.inherit(tokens.subList(0, guardPos));
if (bool(norm(exec(guard, sc)))) {
var expr = LineTok.inherit(tokens.subList(guardPos+(endAfter? 2 : 1), tokens.size()));
res = exec(expr, sc);
if (endAfter) return res;
}
} else if (eguardPos != -1) {
var guard = LineTok.inherit(tokens.subList(0, eguardPos));
Value r = norm(exec(guard, sc));
EType t;
if (r.equals(Num.ZERO)) t = EType.all;
else throw new DomainError("guard "+r+" not supported");
var expr = LineTok.inherit(tokens.subList(eguardPos+(endAfter? 2 : 1), tokens.size()));
eGuards.put(t, expr);
} else {
res = exec(endAfter? LineTok.inherit(tokens) : ln, sc);
if (endAfter) return res;
}
}
if (res instanceof Settable) return ((Settable) res).get();
} catch (Throwable e) {
for (Map.Entry<EType, LineTok> entry : eGuards.entrySet()) {
EType t = entry.getKey();
if (t == EType.all) return norm(exec(entry.getValue(), sc));
}
throw e;
}
return res;
}
public static boolean bool(double d) {
if (d == 1) return true;
if (d == 0) return false;
throw new DomainError("Expected boolean, got "+d);
}
public static boolean bool(Obj v) {
if (v instanceof Num) {
double num = ((Num) v).num;
if (num == 1) return true;
if (num == 0) return false;
}
throw new DomainError("Expected boolean, got "+v);
}
public static void colorprint(String s, int col) {
if (colorful) println("\u001b[38;5;" + col + "m" + s + "\u001b[0m");
else println(s);
}
public static DoubleArr toAPL(int[] arr) {
var da = new double[arr.length];
for (int i = 0; i < arr.length; i++) {
da[i] = arr[i];
}
return new DoubleArr(da);
}
public static DoubleArr toAPL(int[] arr, int[] sh) {
var da = new double[arr.length];
for (int i = 0; i < arr.length; i++) {
da[i] = arr[i];
}
return new DoubleArr(da, sh);
}
private static Value norm(Obj o) {
if (o instanceof VarArr) return ((VarArr) o).get();
if (o instanceof Settable) return (Value) ((Settable) o).get();
if (!(o instanceof Value)) throw new DomainError("Trying to use "+o.humanType(true)+" as array");
return (Value) o;
}
public static ChrArr toAPL(String s) {
return new ChrArr(s);
}
}