-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAST.java
More file actions
874 lines (791 loc) · 30.1 KB
/
AST.java
File metadata and controls
874 lines (791 loc) · 30.1 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
import java.io.InputStream;
import java.util.List;
import java.util.function.Function;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;
/* ANBF Grammar:
* whitespace = ?any whitespace character?
* alphabet = ALPHA / "_"
* unary = "+" / "-"
* binary = "+" / "-" / "*" / "/" / "^" / "%" / "#"
* string = ALPHA *(alphabet / digit)
* separator = ";"
*
* Number = 1*digit ["." *(digit)]
* Name = string ["(" [string *("," string)] ")"]
*
* argument = string / Expression
* Call = string ["(" [argument *("," argument)] ")"] ; same as Name's, besides that it can be a string or an Expression
* Expression = ["("] *unary (Number / Call) *(binary Expression) [")"]
*
* TopLevelExpression = Expression separator
* Def = "def" whitespace Name whitespace Expression separator
*
* Program = *(TopLevelExpression / Def) [EOF]
*/
public class AST {
public enum TokenType {
SEPARATOR(-1),
EOF(-2),
NUMBER(-3),
NAME(-4),
DEF(-5),
OPERATOR(-6);
private int value;
TokenType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private InputStream inputStream;
private String currentToken;
private double currentNumber;
private int currentTokenType;
public AST(InputStream inputStream) {
this.inputStream = inputStream;
}
private int lastChar = ' ';
private int getToken() {
try {
while (Character.isWhitespace(lastChar)) {
lastChar = inputStream.read();
}
if (Character.isLetter(lastChar) || lastChar == '_') {
currentToken = String.valueOf((char) lastChar);
while (Character.isLetterOrDigit(lastChar = inputStream.read()) || lastChar == '_') {
currentToken += (char) lastChar;
}
if (currentToken.equals("def")) {
return TokenType.DEF.getValue();
}
return TokenType.NAME.getValue();
}
if (Character.isDigit(lastChar)) {
currentToken = String.valueOf((char) lastChar);
while (Character.isDigit(lastChar = inputStream.read()) || lastChar == '.') {
currentToken += (char) lastChar;
}
String powerToken = "";
if (lastChar == 'E' || lastChar == 'e') {
powerToken += (char)lastChar;
while (Character.isDigit(lastChar = inputStream.read()) || lastChar == '-') {
powerToken += (char)lastChar;
}
}
try {
currentNumber = Double.parseDouble(currentToken);
if (powerToken.length() > 0)
currentNumber *= Math.pow(10, Double.parseDouble(powerToken.substring(1)));
} catch (NumberFormatException e) {
logError("Invalid number format: " + currentToken + powerToken);
}
return TokenType.NUMBER.getValue();
}
if (lastChar == -1) {
return TokenType.EOF.getValue();
}
if (lastChar == '+' || lastChar == '-' || lastChar == '*' || lastChar == '/' || lastChar == '%' || lastChar == '^' || lastChar == '#' || lastChar == '=') {
int token = lastChar;
currentToken = String.valueOf((char) token);
lastChar = inputStream.read();
return TokenType.OPERATOR.getValue();
}
if (lastChar == '<' || lastChar == '>') {
currentToken = String.valueOf((char) lastChar);
lastChar = inputStream.read();
if (lastChar == '=') {
currentToken += (char) lastChar;
lastChar = inputStream.read();
}
return TokenType.OPERATOR.getValue();
}
if (lastChar == '=' || lastChar == '!') {
currentToken = String.valueOf((char) lastChar);
lastChar = inputStream.read();
if (lastChar == '=') {
currentToken += (char) lastChar;
lastChar = inputStream.read();
} else {
logError("Expected '=', found: " + currentToken);
}
return TokenType.OPERATOR.getValue();
}
if (lastChar == '(' || lastChar == ')' || lastChar == ',' || lastChar == '?' || lastChar == ':') {
int token = lastChar;
currentToken = String.valueOf((char) token);
lastChar = inputStream.read();
return token;
}
lastChar = inputStream.read();
return TokenType.SEPARATOR.getValue();
} catch (Exception e) {
logError("Error reading input: " + e.getMessage());
return TokenType.EOF.getValue();
}
}
public int getNextToken() {
return currentTokenType = getToken();
}
public Expression logError(String message) {
System.err.println("Error: " + message);
return null;
}
public Name logErrorName(String message) {
System.err.println("Error: " + message);
return null;
}
public NumberExpression parseNumber() {
NumberExpression number = new NumberExpression(currentNumber);
getNextToken();
return number;
}
public Expression parseParenExpression() {
getNextToken();
Expression expression = parseExpression();
if (expression == null) {
return null;
}
if (currentTokenType != ')') {
return logError("Expected ')', found: " + currentToken);
}
getNextToken();
return expression;
}
public Expression parseCallExpression() {
String name = currentToken;
getNextToken();
if (currentTokenType != '(')
return new NameExpression(name);
getNextToken();
List<Expression> arguments = new ArrayList<>();
if (currentTokenType != ')') {
do {
Expression argument = parseExpression();
if (argument == null) {
return null;
}
arguments.add(argument);
} while (currentTokenType == ',' && getNextToken() != ')');
}
getNextToken();
return new CallExpression(name, arguments.toArray(new Expression[arguments.size()]));
}
public Expression parsePrimaryExpression() {
if (currentTokenType == TokenType.NUMBER.getValue()) {
return parseNumber();
}
if (currentTokenType == TokenType.NAME.getValue()) {
return parseCallExpression();
}
if (currentTokenType == '(') {
return parseParenExpression();
}
return logError("Expected number, name or '(', found: " + currentToken);
}
public Expression parseUnaryExpression() {
if (currentToken.equals("+") || currentToken.equals("-")) {
String operator = currentToken;
getNextToken();
Expression expression = parseUnaryExpression();
if (expression == null) {
return null;
}
return new UnaryExpression(operator, expression);
}
return parsePrimaryExpression();
}
public HashMap<String, Integer> precedences = new HashMap<>() {
{
put("+", 1);
put("-", 1);
put("*", 2);
put("/", 2);
put("%", 2);
put("^", 3);
put("#", 3);
put("<", 11);
put("<=", 11);
put(">", 11);
put(">=", 11);
put("=", 11);
put("!=", 11);
}
};
public int getOperatorPrecedence() {
if (currentTokenType == TokenType.OPERATOR.getValue() && precedences.containsKey(currentToken)) {
return precedences.get(currentToken);
}
return -1;
}
public Expression parseExpression() {
Expression first = parseUnaryExpression();
if (first == null) {
return null;
}
if (currentTokenType == '?') {
getNextToken();
Expression trueExpression = parseExpression();
if (trueExpression == null) {
return null;
}
if (currentTokenType != ':') {
return logError("Expected ':', found: " + currentToken);
}
getNextToken();
Expression falseExpression = parseExpression();
if (falseExpression == null) {
return logError(currentToken + " is not a valid expression.");
}
return new CondExpression(first, trueExpression, falseExpression);
}
return parseBinaryExpress(first, 0);
}
public Expression parseBinaryExpress(Expression left, int precedence) {
while (true) {
int tokenPrecedence = getOperatorPrecedence();
if (tokenPrecedence <= precedence) {
return left;
}
String operator = new String(currentToken);
getNextToken();
Expression right = parseUnaryExpression();
if (right == null) {
return null;
}
if (currentTokenType == '?') {
getNextToken();
Expression trueExpression = parseExpression();
if (trueExpression == null) {
return null;
}
if (currentTokenType != ':') {
return logError("Expected ':', found: " + currentToken);
}
getNextToken();
Expression falseExpression = parseExpression();
if (falseExpression == null) {
return logError(currentToken + " is not a valid expression.");
}
return new CondExpression(new BinaryExpression(operator, left, right), trueExpression, falseExpression);
}
int nextPrecedence = getOperatorPrecedence();
if (tokenPrecedence <= nextPrecedence) {
right = parseBinaryExpress(right, tokenPrecedence);
if (right == null) {
return null;
}
}
left = new BinaryExpression(operator, left, right);
}
}
public Name parseName() {
if (currentTokenType != TokenType.NAME.getValue()) {
return logErrorName("Expected name, found: " + currentToken);
}
String name = currentToken;
getNextToken();
if (currentTokenType != '(') {
return new Name(name, null);
}
List<String> arguments = new ArrayList<>();
while (true) {
getNextToken();
if (currentTokenType == ',') {
getNextToken();
if (currentTokenType != TokenType.NAME.getValue()) {
return logErrorName("Expected name, found: " + currentToken);
}
}
if (currentTokenType != TokenType.NAME.getValue()) {
if (currentTokenType != ')') {
return logErrorName("Expected name or ')', found: " + currentToken);
}
break;
}
arguments.add(currentToken);
}
getNextToken();
return new Name(name, arguments.toArray(new String[arguments.size()]));
}
public Def parseDef() {
getNextToken();
Name name = parseName();
if (name == null) {
return null;
}
Expression expressions = parseExpression();
if (expressions == null) {
return null;
}
return new Def(name, expressions);
}
public Def parseTopLevelExpression() {
Expression expression = parseExpression();
if (expression == null) {
return null;
}
Name name = new Name("", null);
Def def = new Def(name, expression);
return def;
}
private Def quickUnaryDef(String name, Function<Double, Double> f) {
return new Def(new Name("abs", new String[] { "x" }), null) {
public String toString() {
return "def " + name + "(x) internal;";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
Def def = definitions.get("x");
if (def == null) {
return null;
}
return new NumberExpression(f.apply(def.evaluate(definitions).getValue()));
}
};
}
private HashMap<String, Def> definitions = new HashMap<>() {
{
put("pi", new Def(new Name("pi", null), null) {
public String toString() {
return "def pi() internal;";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
return new NumberExpression(Math.PI);
}
});
put("e", new Def(new Name("e", null), null) {
public String toString() {
return "def e() internal;";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
return new NumberExpression(Math.E);
}
});
put("random", new Def(new Name("random", null), null) {
public String toString() {
return "def random() internal;";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
return new NumberExpression(Math.random());
}
});
put("exit", new ExitDef());
put("pow", new PowDef());
put("sqrt", quickUnaryDef("sqrt", x -> Math.sqrt(x)));
put("abs", quickUnaryDef("abs", x -> Math.abs(x)));
put("pow2", quickUnaryDef("abs", x -> Math.pow(x, 2)));
put("fact", new GammaDef());
put("exp", quickUnaryDef("exp", x -> Math.exp(x)));
put("floor", quickUnaryDef("floor", x -> Math.floor(x)));
put("ceil", quickUnaryDef("ceil", x -> Math.ceil(x)));
put("gamma", new GammaDef());
put("sin", quickUnaryDef("sin", x -> Math.sin(x)));
put("cos", quickUnaryDef("cos", x -> Math.cos(x)));
put("tan", quickUnaryDef("tan", x -> Math.tan(x)));
put("asin", quickUnaryDef("asin", x -> Math.asin(x)));
put("acos", quickUnaryDef("acos", x -> Math.acos(x)));
put("atan", quickUnaryDef("atan", x -> Math.atan(x)));
put("sinh", quickUnaryDef("sinh", x -> Math.sinh(x)));
put("cosh", quickUnaryDef("cosh", x -> Math.cosh(x)));
put("tanh", quickUnaryDef("tanh", x -> Math.tanh(x)));
put("asinh", quickUnaryDef("asinh", x -> Math.log(x + Math.sqrt(x * x + 1))));
put("acosh", quickUnaryDef("acosh", x -> Math.log(x + Math.sqrt(x * x - 1))));
put("atanh", quickUnaryDef("atanh", x -> 0.5 * Math.log((1 + x) / (1 - x))));
}
};
public void console() {
try {
while (true) {
while (inputStream.available() > 0) {
if (!Character.isWhitespace(lastChar)) {
break;
}
lastChar = inputStream.read();
}
if (inputStream.available() == 0) {
System.err.print("Input>");
}
getNextToken();
if (currentTokenType == TokenType.EOF.getValue()) {
break;
}
if (currentTokenType == TokenType.SEPARATOR.getValue()) {
getNextToken();
continue;
}
if (currentTokenType == TokenType.DEF.getValue()) {
Def def = parseDef();
if (def != null) {
System.out.println("Parsed def: " + def.toString());
definitions.put(def.getName(), def);
continue;
}
} else {
Def def = parseTopLevelExpression();
if (def != null) {
System.out.println("Parsed top-level expression: " + def.toString());
NumberExpression result = def.evaluate(definitions);
if (result != null) {
System.out.println("Evaluated: " + def.evaluate(new HashMap<>(definitions)).getValue());
}
continue;
}
}
inputStream.skip(inputStream.available());
continue;
}
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
}
}
public String parse() {
try {
while (true) {
while (inputStream.available() > 0) {
if (!Character.isWhitespace(lastChar)) {
break;
}
lastChar = inputStream.read();
}
if (inputStream.available() == 0) {
System.err.print("Input>");
}
getNextToken();
if (currentTokenType == TokenType.EOF.getValue()) {
break;
}
if (currentTokenType == TokenType.SEPARATOR.getValue()) {
getNextToken();
continue;
}
if (currentTokenType == TokenType.DEF.getValue()) {
Def def = parseDef();
if (def != null) {
System.out.println("Parsed def: " + def.toString());
definitions.put(def.getName(), def);
continue;
}
} else {
Def def = parseTopLevelExpression();
if (def != null) {
System.out.println("Parsed top-level expression: " + def.toString());
NumberExpression result = def.evaluate(definitions);
if (result != null) {
return String.valueOf(def.evaluate(new HashMap<>(definitions)).getValue());
//System.out.println("Evaluated: " + def.evaluate(new HashMap<>(definitions)).getValue());
}
continue;
}
}
inputStream.skip(inputStream.available());
continue;
}
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
}
return null;
}
}
interface Expression {
String toString();
NumberExpression evaluate(HashMap<String, Def> definitions);
default NumberExpression logError(String message) {
System.err.println("Evaluate Error: " + message);
return null;
}
}
class NumberExpression implements Expression {
private double value;
public NumberExpression(double value) {
this.value = value;
}
public String toString() {
return String.valueOf(value);
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
return this;
}
public double getValue() {
return value;
}
}
class UnaryExpression implements Expression {
private String operator;
private Expression operand;
public UnaryExpression(String operator, Expression operand) {
this.operator = operator;
this.operand = operand;
}
public String toString() {
return operator + operand.toString();
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
NumberExpression value = operand.evaluate(definitions);
if (value == null) {
return null;
}
switch (operator) {
case "+":
return new NumberExpression(+value.getValue());
case "-":
return new NumberExpression(-value.getValue());
default:
return logError(operator + " is not a valid unary operator.");
}
}
}
class BinaryExpression implements Expression {
private String operator;
private Expression left;
private Expression right;
public BinaryExpression(String operator, Expression left, Expression right) {
this.operator = operator;
this.left = left;
this.right = right;
}
public String toString() {
return "(" + left.toString() + " " + operator + " " + right.toString() + ")";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
NumberExpression leftValue = left.evaluate(definitions);
NumberExpression rightValue = right.evaluate(definitions);
if (leftValue == null || rightValue == null) {
return null;
}
switch (operator) {
case "+":
return new NumberExpression(leftValue.getValue() + rightValue.getValue());
case "-":
return new NumberExpression(leftValue.getValue() - rightValue.getValue());
case "*":
return new NumberExpression(leftValue.getValue() * rightValue.getValue());
case "/":
return new NumberExpression(leftValue.getValue() / rightValue.getValue());
case "%":
return new NumberExpression(leftValue.getValue() % rightValue.getValue());
case "^":
return new NumberExpression(Math.pow(leftValue.getValue(), rightValue.getValue()));
case "#":
return new NumberExpression(Math.log(leftValue.getValue()) / Math.log(rightValue.getValue()));
case "<":
return new NumberExpression(leftValue.getValue() < rightValue.getValue() ? 1 : 0);
case "<=":
return new NumberExpression(leftValue.getValue() <= rightValue.getValue() ? 1 : 0);
case ">":
return new NumberExpression(leftValue.getValue() > rightValue.getValue() ? 1 : 0);
case ">=":
return new NumberExpression(leftValue.getValue() >= rightValue.getValue() ? 1 : 0);
case "=":
return new NumberExpression(leftValue.getValue() == rightValue.getValue() ? 1 : 0);
case "!=":
return new NumberExpression(leftValue.getValue() != rightValue.getValue() ? 1 : 0);
default:
return logError(operator + " is not a valid binary operator.");
}
}
}
class CondExpression implements Expression {
private Expression condition;
private Expression trueExpression;
private Expression falseExpression;
public CondExpression(Expression condition, Expression trueExpression, Expression falseExpression) {
this.condition = condition;
this.trueExpression = trueExpression;
this.falseExpression = falseExpression;
}
public String toString() {
return "( " + condition.toString() + " ? " + trueExpression.toString() + " : " + falseExpression.toString()
+ " )";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
NumberExpression condValue = condition.evaluate(definitions);
if (condValue == null) {
return null;
}
if (condValue.getValue() != 0) {
return trueExpression.evaluate(definitions);
} else {
return falseExpression.evaluate(definitions);
}
}
}
class CallExpression implements Expression {
private String name;
private Expression[] arguments;
public CallExpression(String name, Expression[] arguments) {
this.name = name;
this.arguments = arguments;
}
public String toString() {
StringBuilder sb = new StringBuilder(name);
if (arguments != null && arguments.length > 0) {
sb.append("(");
for (int i = 0; i < arguments.length; i++) {
sb.append(arguments[i].toString());
if (i < arguments.length - 1) {
sb.append(", ");
}
}
sb.append(")");
}
return sb.toString();
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
Def def = definitions.get(name);
if (def == null) {
return logError("Name/Function " + name + " is not defined.");
}
int defArgCount = (def == null || def.arguments == null ? 0 : def.arguments.length);
int argCount = (arguments == null ? 0 : arguments.length);
if (defArgCount != argCount) {
return logError("Function " + name + " expects " + defArgCount + " arguments, but got " + argCount);
}
HashMap<String, Def> args = new HashMap<>(definitions);
for (int i = 0; i < argCount; i++) {
if (arguments[i] == null) {
return null;
}
if (arguments[i] instanceof CallExpression)
args.put(def.getArgumentName(i), new Def(new Name(def.getArgumentName(i), null), arguments[i].evaluate(definitions)));
else if (arguments[i] instanceof NameExpression)
args.put(def.getArgumentName(i), definitions.get(((NameExpression)arguments[i]).toString()));
else {
NumberExpression argValue = arguments[i].evaluate(definitions);
if (argValue == null) {
return null;
}
args.put(def.getArgumentName(i), new Def(new Name(def.getArgumentName(i), null), argValue));
}
}
return def.evaluate(args);
}
}
class NameExpression implements Expression {
private String name;
public NameExpression(String name) {
this.name = name;
}
public String toString() {
return name;
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
Def def = definitions.get(name);
if (def == null) {
return logError("Name/Function " + name + " is not defined.");
}
return def.evaluate(definitions);
}
}
class Name {
protected String name;
protected String[] arguments;
public Name(String name, String[] arguments) {
this.name = name;
this.arguments = arguments;
}
public Name(Name name) {
this.name = name.name;
this.arguments = name.arguments;
}
public String toString() {
StringBuilder sb = new StringBuilder(name);
if (arguments != null && arguments.length > 0) {
sb.append("(");
for (int i = 0; i < arguments.length; i++) {
sb.append(arguments[i]);
if (i < arguments.length - 1) {
sb.append(", ");
}
}
sb.append(")");
}
return sb.toString();
}
public String getName() {
return name;
}
public String getArgumentName(int index) {
return arguments[index];
}
}
class Def extends Name {
protected Expression expression;
public Def(Name name, Expression expression) {
super(name);
this.expression = expression;
}
public String toString() {
String nameString = super.toString();
if (nameString.isEmpty()) {
return expression.toString();
}
return "def " + nameString + " " + expression.toString();
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
return expression == null ? null : expression.evaluate(definitions);
}
}
class PowDef extends Def {
public PowDef() {
super(new Name("pow", new String[] { "x", "y" }), null);
}
public String toString() {
return "def pow(x, y) internal;";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
Def defX = definitions.get("x");
Def defY = definitions.get("y");
if (defX == null || defY == null) {
return null;
}
return new NumberExpression(
Math.pow(defX.evaluate(definitions).getValue(), defY.evaluate(definitions).getValue()));
}
}
class ExitDef extends Def {
public ExitDef() {
super(new Name("exit", null), null);
}
public String toString() {
return "def exit() internal;";
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
System.exit(0);
return null;
}
}
class GammaDef extends Def {
public GammaDef() {
super(new Name("gamma", new String[]{"x"}), null);
}
public String toString() {
return "def gamma() internal;";
}
private static final double[] LANCZOS_COEFFS = {
0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7
};
private static final double SQRT_2PI = Math.sqrt(2 * Math.PI);
private static final int G = 7;
public static double gamma(double x) {
// 处理负数和零(Gamma 函数未定义)
if (x <= 0) {
if (x % 1 == 0) throw new IllegalArgumentException("Gamma undefined for non-positive integers");
// 反射公式:Γ(z) = π / [Γ(1−z) * sin(πz)]
return Math.PI / (Math.sin(Math.PI * x) * gamma(1 - x));
}
x -= 1; // 平移值
double a = LANCZOS_COEFFS[0];
for (int i = 1; i < G + 2; i++) {
a += LANCZOS_COEFFS[i] / (x + i);
}
double t = x + G + 0.5;
return SQRT_2PI * Math.pow(t, x + 0.5) * Math.exp(-t) * a;
}
public NumberExpression evaluate(HashMap<String, Def> definitions) {
return new NumberExpression(gamma(definitions.get("x").evaluate(definitions).getValue() + 1));
}
}