-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expression.java
2122 lines (1820 loc) · 66.4 KB
/
Expression.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package arb.expressions;
import static arb.expressions.Compiler.*;
import static arb.expressions.Parser.*;
import static java.lang.String.format;
import static java.lang.System.err;
import static org.objectweb.asm.Opcodes.*;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.objectweb.asm.*;
import org.objectweb.asm.signature.SignatureWriter;
import org.objectweb.asm.util.TraceClassVisitor;
import arb.*;
import arb.Integer;
import arb.documentation.BusinessSourceLicenseVersionOnePointOne;
import arb.documentation.TheArb4jLibrary;
import arb.exceptions.CompilerException;
import arb.expressions.nodes.*;
import arb.expressions.nodes.binary.*;
import arb.expressions.nodes.nary.NAryOperationNode;
import arb.expressions.nodes.nary.ProductNode;
import arb.expressions.nodes.nary.SumNode;
import arb.expressions.nodes.unary.*;
import arb.functions.Function;
import arb.functions.NullaryFunction;
import arb.functions.integer.Sequence;
import arb.utensils.Utensils;
import arb.utensils.text.trees.TextTree;
import arb.utensils.text.trees.TreeModel;
import arb.viz.ArbShellExecutionController;
/**
* The {@link Expression} class represents mathematical expressions in infix and
* postfix notation flexibily depending upon the context in which the characters
* are encountered. It uses {@link Character}s and {@link String}s to represent
* symbols and operations within these expressions. This class is part of the
* {@code arb.expressions} package and serves as a dynamic compiler that
* translates these expressions into high-performance Java bytecode, leveraging
* the ASM library for bytecode manipulation and generation.
*
* <p>
* Internally, the {@link Expression} class parses the input string to construct
* an Abstract Syntax Tree (AST), where each {@link Node} represents a
* {@link BinaryOperationNode}, {@link UnaryOperationNode},
* {@link NAryOperationNode}, such as {@link AdditionNode} ,
* {@link SubtractionNode}, {@link MultiplicationNode}, and {@link DivisionNode}
* or its operands like {@link VariableNode} and {@link LiteralConstantNode},
* etc. This {@link TreeModel} structure allows the class to correctly manage
* operator precedence and associativity rules inherent in mathematical
* expressions and also naturally facilitate their printing via the
* {@link TextTree} interface. The AST is then traversed by the
* {@link #generate()} method to produce the corresponding Java bytecodes that
* which when executed produce the result of the evaluation of the the
* expression.
*
* <h2>Key Features:</h2>
* <ul>
* <li>Dynamically compiles mathematical expressions into executable Java
* bytecode, allowing for efficient evaluation.</li>
* <li>Supports {@link VariableNode}, {@link LiteralConstantNode}, and
* {@link FunctionNode}s within {@link Expression}, providing an extensive set
* of features for constructing elaborate expressions, linked together via a
* shared {@link Context} in which variables and other functions are registered
* for mutual accessibility..</li>
* <li>Effectively manages {@link IntermediateVariable} and
* {@link LiteralConstantNode}, optimizing memory usage and performance.</li>
* <li>Automatically injects {@link VariableReference}s to {@link VariableNode}
* and {@link FunctionNode}s into the compiled bytecode, facilitating dynamic
* execution.</li>
* <li>The {@link Parser} provides comprehensive methods for parsing
* expressions, evaluating them, and generating the necessary bytecode, all
* while handling mathematical precedence and associativity.</li>
* </ul>
*
* <h2>System Properties:</h2>
* <ul>
* <li>{@code arb4j.compiler.traceGeneration=true|false}: Print detail
* information related to the generation process. Default is {@code false}.</li>
*
* <li>{@code arb4j.compiler.saveClasses=true|false}: Specifies whether the
* compiled classes should be saved to disk (the current directory). Default is
* {@code true}.</li>
* </ul>
*
* <pre>
* Note: Why we don't manually compute stackmap frames: Using `COMPUTE_FRAMES`
* is the pragmatic choice in most situations, especially for a tool like the
* `Expression` compiler, which is typically used during application
* initialization or setup rather than in performance-critical paths.
*
* The additional time taken by `COMPUTE_FRAMES` to automatically compute stack
* map frames is usually negligible in the grand scheme of things. It's a small
* price to pay for the convenience, reliability, and maintainability it
* provides.
*
* Moreover, the `Expression` compiler is designed to generate bytecode for
* individual expressions, which are then executed repeatedly. The compilation
* overhead is incurred only once, while the benefits of the generated bytecode,
* such as improved performance and type safety, are enjoyed throughout the
* lifetime of the application.
*
* Attempting to optimize the compilation process by manually computing frames
* would be a case of premature optimization, adding unnecessary complexity and
* maintenance burden without providing any tangible benefits in most real-world
* scenarios.
*
* Therefore, sticking with `COMPUTE_FRAMES` is a sensible choice for the
* `Expression` compiler, as it strikes a good balance between development
* effort, correctness, and overall performance.
* </pre>
*
* @param <D> The domain type over which the expression operates, such as
* {@link Integer}, {@link Real}, {@link Complex},
* {@link RealPolynomial}, etc
* @param <C> The codomain type that the expression evaluates to, representing
* the result of the expression.
* @param <F> The function type of the expression, extending the
* {@link Function} interface, encapsulating the compiled expression
* as an evaluatable function in the sense of Java
*
* @author Stephen Andrew Crowley ©2024
*
* @see BusinessSourceLicenseVersionOnePointOne#gett for the terms of use of the
* {@link TheArb4jLibrary}
*/
public class Expression<D, C, F extends Function<? extends D, ? extends C>> implements
Typesettable
{
private static final String ASSERTION_ERROR_METHOD_DESCRIPTOR = Compiler.getMethodDescriptor(Void.class,
Object.class);
public static final String evaluationMethodDescriptor =
"(Ljava/lang/Object;IILjava/lang/Object;)Ljava/lang/Object;";
public static final Class<?>[] implementedInterfaces = new Class[]
{ Typesettable.class, AutoCloseable.class, Initializable.class };
public static final String IS_INITIALIZED = "isInitialized";
public static final String nameOfInitializerFunction = "initialize";
public static boolean saveClasses =
Boolean.valueOf(System.getProperty("arb4j.compiler.saveClasses", "true"));
public static boolean trace =
Boolean.valueOf(System.getProperty("arb4j.compiler.trace", "false"));
public static final String VOID_METHOD_DESCRIPTOR = Compiler.getMethodDescriptor(Void.class);
static
{
assert arb.functions.integer.Sequence.class.equals(Sequence.class) : "you forgot to import arb.functions.sequences.Sequence or imported a class named sequence in another package";
}
public Expression<?, ?, ?> ascendentExpression;
public char character = 0;
public String className;
public final String coDomainClassDescriptor;
public final String coDomainClassInternalName;
public final Class<? extends C> coDomainType;
public Class<F> compiledClass;
int constantCount = 1;
public Context context;
public final String domainClassDescriptor;
public final String domainClassInternalName;
public final Class<? extends D> domainType;
public final String evaluateMethodSignature;
public String expression;
public Class<? extends F> functionClass;
public String functionClassDescriptor;
public String functionName;
public final String genericFunctionClassInternalName;
public boolean inAbsoluteValue = false;
public VariableNode<D, C, F> independentVariable;
public VariableNode<D, C, F> indeterminateVariable;
public LinkedList<Consumer<MethodVisitor>> initializers = new LinkedList<>();
public F instance;
public byte[] instructionByteCodes;
public HashMap<String, IntermediateVariable<D, C, F>> intermediateVariables = new HashMap<>();
public HashMap<String, LiteralConstantNode<D, C, F>> literalConstants = new HashMap<>();
public FunctionMapping<D, C, F> mapping;
public int position = -1;
public char previousCharacter;
public boolean recursive = false;
public HashMap<String, FunctionMapping<?, ?, ?>> referencedFunctions = new HashMap<>();
public HashMap<String, VariableNode<D, C, F>> referencedVariables = new HashMap<>();
public Node<D, C, F> rootNode;
public Variables variables;
public boolean variablesDeclared = false;
boolean verboseTrace = false;
public boolean insideInitializer = false;
public Expression(String className,
Class<? extends D> domainClass,
Class<? extends C> coDomainClass,
Class<? extends F> functionClass,
String expressionString,
Context context)
{
this(className,
domainClass,
coDomainClass,
functionClass,
expressionString,
context,
null,
null);
}
public Expression(String className,
Class<? extends D> domain,
Class<? extends C> codomain,
Class<? extends F> function,
String expression,
Context context,
String functionName,
Expression<?, ?, ?> parentExpression)
{
assert className != null : "className needs to be specified";
this.ascendentExpression = parentExpression;
this.coDomainClassDescriptor = codomain.descriptorString();
this.domainClassDescriptor = domain.descriptorString();
this.className = className;
this.domainType = domain;
this.coDomainType = codomain;
this.functionClass = function;
this.coDomainClassInternalName = Type.getInternalName(codomain);
this.domainClassInternalName = Type.getInternalName(domain);
this.genericFunctionClassInternalName = Type.getInternalName(function);
this.functionClassDescriptor = function.descriptorString();
this.expression = Parser.replaceArrowsEllipsesAndSuperscriptAlphabeticalExponents(expression);
this.context = context;
this.variables = context != null ? context.variables : null;
this.functionName = functionName;
evaluateMethodSignature = String.format("(L%s;IIL%s;)L%s;",
domainClassInternalName,
coDomainClassInternalName,
coDomainClassInternalName);
if (context != null && context.saveClasses)
{
saveClasses = true;
}
}
public Node<D, C, F> addAndSubtract(Node<D, C, F> node)
{
while (true)
{
if (nextCharacterIs('+', '₊'))
{
node = new AdditionNode<>(this,
node,
exponentiateMultiplyAndDivide());
}
else if (nextCharacterIs('-', '₋', '−'))
{
Node<D, C, F> rhs = exponentiateMultiplyAndDivide();
node = node == null ? new NegationNode<>(this,
rhs)
: new SubtractionNode<>(this,
node,
rhs);
}
else
{
return node;
}
}
}
protected boolean hasScalarCodomain(Expression<D, C, F> expression)
{
return coDomainType.equals(Real.class) || coDomainType.equals(Complex.class) || coDomainType.equals(Fraction.class)
|| coDomainType.equals(Integer.class) || coDomainType.equals(ComplexFraction.class)
|| coDomainType.equals(GaussianInteger.class);
}
public void addCheckForNullField(MethodVisitor mv, String varName, boolean variable)
{
Class<?> fieldClass;
if (variable)
{
Object field = context.getVariable(varName);
fieldClass = field != null ? field.getClass() : null;
}
else
{
fieldClass = context.functions.get(varName).type();
}
if (fieldClass != null)
{
String fieldDesc = fieldClass.descriptorString();
addNullCheckForField(mv, className, varName, fieldDesc);
}
}
public void addChecksForNullVariableReferences(MethodVisitor mv)
{
if (context != null)
{
context.variableClassStream()
.forEach(entry -> addCheckForNullField(loadThisOntoStack(mv), entry.getLeft(), true));
}
}
/**
* Calls this{@link #newIntermediateVariable(Class)} followed by
* this{@link #loadThisFieldOntoStack(MethodVisitor, String, Class)} with the
* newly assigned intermediate variable
*
* @param methodVisitor
* @param type
* @return
*/
public String allocateIntermediateVariable(MethodVisitor methodVisitor, Class<?> type)
{
String intermediateVariableName = newIntermediateVariable(type);
loadThisFieldOntoStack(methodVisitor, intermediateVariableName, type);
return intermediateVariableName;
}
public String allocateIntermediateVariable(MethodVisitor methodVisitor, String prefix, Class<?> type)
{
String intermediateVariableName = newIntermediateVariable(prefix, type);
loadFieldOntoStack(loadThisOntoStack(methodVisitor), intermediateVariableName, type.descriptorString());
return intermediateVariableName;
}
public MethodVisitor annotateWith(MethodVisitor methodVisitor, Class<? extends Annotation> annotation)
{
AnnotationVisitor av = methodVisitor.visitAnnotation(annotation.descriptorString(), true);
av.visitEnd();
return methodVisitor;
}
public MethodVisitor annotateWithOverride(MethodVisitor methodVisitor)
{
return annotateWith(methodVisitor, Override.class);
}
public boolean anyAscendentIndependentVariableIsEqualTo(String name)
{
if (independentVariable != null && independentVariable.getName().equals(name))
{
return true;
}
if (ascendentExpression != null)
{
if (ascendentExpression.anyAscendentIndependentVariableIsEqualTo(name))
{
return true;
}
}
return false;
}
public static ClassVisitor constructClassVisitor()
{
// ClassVisitor cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
return cw;
}
public ClassVisitor declareConstants(ClassVisitor classVisitor)
{
for (var constant : literalConstants.values())
{
constant.declareField(classVisitor);
}
return classVisitor;
}
public MethodVisitor
declareEvaluateMethodsLocalVariableArguments(MethodVisitor methodVisitor, Label startLabel, Label endLabel)
{
methodVisitor.visitLocalVariable("this", "L" + className + ";", null, startLabel, endLabel, 0);
methodVisitor.visitLocalVariable(independentVariable != null ? independentVariable.getName() : "in",
domainType.descriptorString(),
null,
startLabel,
endLabel,
1);
methodVisitor.visitLocalVariable("order", "I", null, startLabel, endLabel, 2);
methodVisitor.visitLocalVariable("bits", "I", null, startLabel, endLabel, 3);
methodVisitor.visitLocalVariable("result", coDomainType.descriptorString(), null, startLabel, endLabel, 4);
return methodVisitor;
}
public void declareFields(ClassVisitor cw)
{
cw.visitField(Opcodes.ACC_PUBLIC, IS_INITIALIZED, "Z", null, null);
declareConstants(cw);
declareFunctionReferences(cw);
declareVariables(cw);
declareIntermediateVariables(cw);
}
public ClassVisitor declareFunctionReferences(ClassVisitor classVisitor)
{
if (context != null)
{
referencedFunctions.forEach((name, function) -> function.declare(classVisitor, name));
}
return classVisitor;
}
public void declareIntermediateVariables(ClassVisitor classVisitor)
{
for (var variable : intermediateVariables.values())
{
if (!declaredIntermediateVariables.contains(variable.name))
{
if (trace)
{
System.out.format("Declaring IntermediateVariable of %s: %s %s\n", className, variable.type, variable.name);
}
variable.declareField(classVisitor);
declaredIntermediateVariables.add(variable.name);
}
}
}
HashSet<String> declaredIntermediateVariables = new HashSet<>();
public void declareVariableEntry(ClassVisitor classVisitor, Entry<String, Named> variable)
{
if (trace)
{
System.out.println("Declaring variable of " + className + ": " + variable);
}
if (variable.getValue() != null)
{
classVisitor.visitField(ACC_PUBLIC,
variable.getKey(),
variable.getValue().getClass().descriptorString(),
null,
null);
}
else
{
if (trace)
{
System.out.println("Skipping null variable of " + className + ": " + variable);
}
}
}
public void declareVariables(ClassVisitor classVisitor)
{
// assert !variablesDeclared : "variables have already been declared";
if (ascendentExpression != null)
{
var parentIndependentVariableNode = ascendentExpression.independentVariable;
if (parentIndependentVariableNode != null && !parentIndependentVariableNode.type().equals(Object.class))
{
classVisitor.visitField(ACC_PUBLIC,
parentIndependentVariableNode.reference.name,
parentIndependentVariableNode.type().descriptorString(),
null,
null);
}
}
if (context != null)
{
if (trace)
{
String vars = context.variables.map.entrySet().stream().map(x -> x.toString()).collect(Collectors.joining(","));
System.out.println("declareVariables: " + vars);
}
for (var variable : context.variables.map.entrySet()
.stream()
.sorted((a, b) -> a.getKey().compareTo(b.getKey()))
.toList())
{
declareVariableEntry(classVisitor, variable);
}
}
variablesDeclared = true;
}
public Class<F> defineClass()
{
if (compiledClass != null)
{
return compiledClass;
}
if (trace)
{
System.err.format("\nExpression(#%s).defineClass(expression=%s\n,className=%s\n, context=%s)\n\n",
System.identityHashCode(this),
expression,
className,
context);
}
if (instructionByteCodes == null)
{
generate();
}
return compiledClass = loadFunctionClass(className, instructionByteCodes, context);
}
/**
* @return a parenthetical {@link Node}, a {@link ProductNode}, a
* {@link LiteralConstantNode},a {@link Function}, a
* {@link VariableNode} or null if for instance "-t" is encountered, as
* a 0 is implied by the absence of a node before the
* {@link SubtractionNode} operator is encountered, also handles
* {@link ProductNode} also known as the product operator and
* {@link SumNode}
*
* @throws CompilerException
*/
public Node<D, C, F> evaluate() throws CompilerException
{
Node<D, C, F> node = null;
if (nextCharacterIs('['))
{
node = new VectorNode<>(this);
}
else if (nextCharacterIs('('))
{
node = resolve();
require(')');
}
else if (nextCharacterIs('∂'))
{
node = new DerivativeNode<D, C, F>(this);
}
else if (nextCharacterIs('∫'))
{
node = new IntegralNode<>(this);
}
else if (nextCharacterIs('Π', '∏'))
{
node = new ProductNode<>(this);
}
else if (nextCharacterIs('∑', 'Σ'))
{
node = new SumNode<>(this);
}
else if (isNumeric(character))
{
node = evaluateNumber();
}
else if (isIdentifierCharacter())
{
node = resolveIdentifier();
}
return resolvePostfixOperators(node);
}
public Node<D, C, F> evaluateIndex()
{
var index = evaluateSquareBracketedIndex();
return index == null ? index = evaluateSubscriptedIndex() : index;
}
public VariableReference<D, C, F> evaluateName(int startPos)
{
String identifier = parseName(startPos);
var index = evaluateIndex();
return new VariableReference<D, C, F>(identifier,
index);
}
public Node<D, C, F> evaluateNumber()
{
int startingPosition = position;
while (isNumeric(character))
{
nextCharacter();
}
assert position > startingPosition : "didn't read any digits";
return new LiteralConstantNode<>(this,
expression.substring(startingPosition, position));
}
public Expression<D, C, F> evaluateOptionalIndependentVariableSpecification()
{
int rightArrowIndex =
(expression =
replaceArrowsEllipsesAndSuperscriptAlphabeticalExponents(expression)).indexOf('➔');
if (rightArrowIndex != -1)
{
String inputVariableName = expression.substring(0, rightArrowIndex);
boolean isInputVariableSpecified = true;
for (int i = 0; i < inputVariableName.length(); i++)
{
if (!isAlphabetical(inputVariableName.charAt(i)))
{
isInputVariableSpecified = false;
}
}
if (isInputVariableSpecified)
{
if (context != null)
{
if (context.getVariable(inputVariableName) != null)
{
throw new CompilerException(inputVariableName
+ " cannot be declared as the input since it is already registered as a context variable in "
+ context);
}
}
var variable = new VariableNode<>(this,
new VariableReference<>(inputVariableName,
null,
domainType),
position,
false);
if (hasIndeterminateVariable())
{
indeterminateVariable = variable;
indeterminateVariable.isIndeterminate = true;
}
else
{
independentVariable = variable;
independentVariable.isIndependent = true;
}
position = rightArrowIndex;
}
}
return this;
}
public Node<D, C, F> evaluateSquareBracketedIndex()
{
Node<D, C, F> index = null;
if (nextCharacterIs('['))
{
index = resolve();
require(']');
}
return index;
}
public Node<D, C, F> evaluateSubscriptedIndex()
{
int startPos = position;
if (nextCharacterIs(Parser.SUBSCRIPT_DIGITS_ARRAY))
{
while (nextCharacterIs(Parser.SUBSCRIPT_DIGITS_ARRAY));
return new LiteralConstantNode<>(this,
expression.substring(startPos, position));
}
else if (isIdentifierCharacter())
{
return resolveIdentifier();
}
return null;
}
public Node<D, C, F> exponentiate() throws CompilerException
{
return exponentiate(evaluate());
}
public Node<D, C, F> exponentiate(Node<D, C, F> node) throws CompilerException
{
if (nextCharacterIs('^'))
{
final boolean parenthetical = nextCharacterIs('(');
node = new ExponentiationNode<>(this,
node,
parenthetical ? resolve() : evaluate());
if (parenthetical)
{
require(')');
}
return node;
}
else
{
return parseSuperscripts(node);
}
}
/**
* @return the result of passing this{@link #exponentiate()} to
* this{@link #multiplyAndDivide(Node)}
*/
public Node<D, C, F> exponentiateMultiplyAndDivide()
{
var node = exponentiate();
return multiplyAndDivide(node);
}
/**
* Generate the implementation of the function after this{@link #parseRoot()}
* has been invoked
*
* @return this
* @throws CompilerException
*/
public Expression<D, C, F> generate() throws CompilerException
{
if (trace)
{
System.err.format("Expression(#%s).generate() className=%s\n\n", System.identityHashCode(this), className);
}
ClassVisitor classVisitor = constructClassVisitor();
try
{
generateFunctionInterface(this, className, classVisitor);
generateCoDomainTypeMethod(classVisitor);
generateEvaluationMethod(classVisitor);
declareFields(classVisitor);
generateInitializationMethod(classVisitor);
generateConstructor(classVisitor);
declareIntermediateVariables(classVisitor);
if (needsCloseMethod())
{
generateCloseMethod(classVisitor);
}
generateToStringMethod(classVisitor);
generateTypesetMethod(classVisitor);
}
finally
{
classVisitor.visitEnd();
}
return storeInstructions(classVisitor);
}
public MethodVisitor generateCloseFieldCall(MethodVisitor methodVisitor, String fieldName, Class<?> fieldType)
{
getFieldFromThis(methodVisitor, className, fieldName, fieldType);
return invokeCloseMethod(methodVisitor, fieldType);
}
public ClassVisitor generateCloseMethod(ClassVisitor classVisitor)
{
var methodVisitor = defineMethod(classVisitor, "close", VOID_METHOD_DESCRIPTOR);
methodVisitor.visitCode();
literalConstants.values()
.forEach(constant -> generateCloseFieldCall(loadThisOntoStack(methodVisitor),
constant.fieldName,
constant.type()));
intermediateVariables.values()
.forEach(intermediateVariable -> generateCloseFieldCall(loadThisOntoStack(methodVisitor),
intermediateVariable.name,
intermediateVariable.type));
referencedFunctions.forEach((name, mapping) -> generateCloseFieldCall(loadThisOntoStack(methodVisitor),
name,
mapping.type()));
methodVisitor.visitInsn(Opcodes.RETURN);
methodVisitor.visitMaxs(10, 10);
methodVisitor.visitEnd();
return classVisitor;
}
public void generateCodeToSetIsInitializedToTrue(MethodVisitor methodVisitor)
{
loadThisOntoStack(methodVisitor).visitInsn(Opcodes.ICONST_1);
methodVisitor.visitFieldInsn(PUTFIELD, className, IS_INITIALIZED, "Z");
}
public void generateCodeToThrowErrorIfAlreadyInitialized(MethodVisitor mv)
{
loadThisOntoStack(mv);
mv.visitFieldInsn(GETFIELD, className, IS_INITIALIZED, "Z");
var alreadyInitializedLabel = new Label();
mv.visitJumpInsn(IFEQ, alreadyInitializedLabel);
mv.visitTypeInsn(NEW, "java/lang/AssertionError");
duplicateTopOfTheStack(mv).visitLdcInsn("Already initialized");
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/AssertionError", "<init>", ASSERTION_ERROR_METHOD_DESCRIPTOR, false);
mv.visitInsn(ATHROW);
mv.visitLabel(alreadyInitializedLabel);
}
public ClassVisitor generateCoDomainTypeMethod(ClassVisitor classVisitor) throws CompilerException
{
MethodVisitor mv = classVisitor.visitMethod(Opcodes.ACC_PUBLIC,
"coDomainType",
Compiler.getMethodDescriptor(Class.class),
getCoDomainTypeMethodSignature(),
null);
annotateWithOverride(mv);
mv.visitCode();
mv.visitLdcInsn(Type.getType(coDomainType));
mv.visitInsn(Opcodes.ARETURN);
mv.visitMaxs(1, 0);
mv.visitEnd();
return classVisitor;
}
public void generateConditionalInitializater(MethodVisitor mv)
{
loadThisOntoStack(mv);
mv.visitFieldInsn(GETFIELD, className, IS_INITIALIZED, "Z");
var alreadyInitialized = new Label();
mv.visitJumpInsn(Opcodes.IFNE, alreadyInitialized);
loadThisOntoStack(mv);
mv.visitMethodInsn(INVOKEVIRTUAL, className, nameOfInitializerFunction, "()V", false);
mv.visitLabel(alreadyInitialized);
}
public ClassVisitor generateConstructor(ClassVisitor classVisitor)
{
MethodVisitor mv = classVisitor.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
generateInvocationOfDefaultNoArgConstructor(mv, true);
if (trace)
{
System.err.println("referencedFunctions=" + referencedFunctions);
}
referencedFunctions.values()
.stream()
.filter(func -> func.functionName == null || functionName == null
|| !functionName.equals(func.functionName))
.filter(func -> func.expression != null)
.forEach(mapping -> generateFunctionInstance(mv, mapping));
generateLiteralConstantInitializers(mv);
generateIntermediateVariableInitializers(mv);
mv.visitInsn(RETURN);
mv.visitMaxs(10, 10);
mv.visitEnd();
return classVisitor;
}
public ClassVisitor generateEvaluationMethod(ClassVisitor classVisitor) throws CompilerException
{
if (rootNode == null)
{
parseRoot();
}
Label startLabel = new Label();
Label endLabel = new Label();
MethodVisitor mv = classVisitor.visitMethod(Opcodes.ACC_PUBLIC,
"evaluate",
evaluationMethodDescriptor,
evaluateMethodSignature,
null);
mv.visitCode();
mv.visitLabel(startLabel);
annotateWithOverride(mv);
generateConditionalInitializater(mv);
if (trace)
{
System.out.format("Expression(#%s) Generating %s\n\n", System.identityHashCode(this), expression);
}
rootNode.generate(mv, coDomainType);
mv.visitInsn(Opcodes.ARETURN);
mv.visitLabel(endLabel);
declareEvaluateMethodsLocalVariableArguments(mv, startLabel, endLabel);
mv.visitMaxs(10, 10);
mv.visitEnd();
return classVisitor;
}
public MethodVisitor generateFunctionInitializer(MethodVisitor mv, FunctionMapping<?, ?, ?> nestedFunction)
{
if (trace)
{
err.format("Expression.generateFunctionInitializer( nestedFunction=%s )\n\n", nestedFunction);
}
if (nestedFunction.instance != null)
{
initializeNestedFunctionVariableReferences(loadThisOntoStack(mv),
className,
Type.getInternalName(nestedFunction.type()),
nestedFunction.functionName,
context.variableClassStream());
}
else
{
referencedFunctions.put(nestedFunction.functionName, nestedFunction);
// if (!nestedFunction.functionName.equals(functionName))
// {
// throw new CompilerException("nestedFunction.func should not be null if its"
// + " not the recursive function referring to itself, "
// + String.format("nestedFunction.name=%s, name=%s\n",
// nestedFunction.functionName,
// functionName));
//
// }
}
return mv;
}
public void generateFunctionInstance(MethodVisitor mv, FunctionMapping<?, ?, ?> mapping)
{
Class<?> type = mapping.type();
if (type == null)
{