|
| 1 | +package com.lexicalscope.svm.j.instruction.symbolic.ops.natives; |
| 2 | + |
| 3 | +import static com.lexicalscope.svm.j.statementBuilder.StatementBuilder.statements; |
| 4 | +import static com.lexicalscope.svm.partition.trace.TraceMetaKey.TRACE; |
| 5 | + |
| 6 | +import com.lexicalscope.svm.j.instruction.factory.InstructionSource; |
| 7 | +import com.lexicalscope.svm.j.natives.AbstractNativeMethodDef; |
| 8 | +import com.lexicalscope.svm.partition.trace.HashTrace; |
| 9 | +import com.lexicalscope.svm.partition.trace.Trace; |
| 10 | +import com.lexicalscope.svm.vm.j.InstructionQuery; |
| 11 | +import com.lexicalscope.svm.vm.j.JState; |
| 12 | +import com.lexicalscope.svm.vm.j.MethodBody; |
| 13 | +import com.lexicalscope.svm.vm.j.Vop; |
| 14 | +import com.lexicalscope.svm.vm.j.klass.SMethodDescriptor; |
| 15 | + |
| 16 | +/** |
| 17 | + * Method which chooses a number randomly between 0 and (count - 1) creating n choices. |
| 18 | + */ |
| 19 | +public class Symbolic_selectState extends AbstractNativeMethodDef { |
| 20 | + public Symbolic_selectState() { |
| 21 | + super("com/lexicalscope/svm/j/instruction/symbolic/symbols/SymbolFactory", "selectState", "(I)I"); |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public MethodBody instructions(InstructionSource instructions) { |
| 26 | + return statements(instructions) |
| 27 | + .maxStack(1) |
| 28 | + .maxLocals(1) |
| 29 | + .linearOp(new SelectStateOp()) |
| 30 | + .return1(name()).build(); |
| 31 | + } |
| 32 | + |
| 33 | + public static void pushValues(JState ctx, Object[] values) { |
| 34 | + SMethodDescriptor context = (SMethodDescriptor) ctx.currentFrame().context(); |
| 35 | + Trace trace = ctx.getMeta(TRACE); |
| 36 | + trace = trace.extend(context, HashTrace.CallReturn.CALL, 0); |
| 37 | + ctx.setMeta(TRACE, trace); |
| 38 | + |
| 39 | + JState[] forks = new JState[values.length]; |
| 40 | + for (int i = 0; i < values.length; i++) { |
| 41 | + forks[i] = ctx.snapshot(); |
| 42 | + forks[i].push(values[i]); |
| 43 | + |
| 44 | + Trace forkTrace = trace.extend(context, HashTrace.CallReturn.RETURN, 0, i); |
| 45 | + forks[i].setMeta(TRACE, forkTrace); |
| 46 | + } |
| 47 | + |
| 48 | + ctx.forkDisjoined(forks); |
| 49 | + } |
| 50 | + |
| 51 | + private class SelectStateOp implements Vop { |
| 52 | + @Override |
| 53 | + public void eval(JState ctx) { |
| 54 | + int count = (int) ctx.pop(); |
| 55 | + assert count > 0: "Cannot select one from 0 states."; |
| 56 | + Object[] values = new Object[count]; |
| 57 | + for (int i = 0; i < count; i++) { |
| 58 | + values[i] = i; |
| 59 | + } |
| 60 | + |
| 61 | + pushValues(ctx, values); |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public <T> T query(InstructionQuery<T> instructionQuery) { |
| 66 | + return instructionQuery.nativ3(); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments