use of gov.sandia.n2a.language.Visitor in project n2a by frothga.
the class JobC method generateStatic.
public void generateStatic(final EquationSet s, final StringBuilder result) {
for (EquationSet p : s.parts) generateStatic(p, result);
// Generate static definitions
final BackendDataC bed = (BackendDataC) s.backendData;
class CheckStatic extends Visitor {
public boolean global;
public boolean visit(Operator op) {
if (op instanceof Constant) {
Type m = ((Constant) op).value;
if (m instanceof Matrix) {
Matrix A = (Matrix) m;
int rows = A.rows();
int cols = A.columns();
String matrixName = "Matrix" + matrixNames.size();
matrixNames.put(op, matrixName);
if (rows == 3 && cols == 1)
result.append("Vector3 " + matrixName + " = Matrix<float>");
else
result.append("Matrix<float> " + matrixName);
result.append(" (\"" + A + "\");\n");
}
// Don't try to descend tree from here
return false;
}
if (op instanceof Function) {
Function f = (Function) op;
if (// We need to auto-generate the column name.
f instanceof Output && f.operands.length < 3) {
String stringName = "columnName" + stringNames.size();
stringNames.put(op, stringName);
if (global) {
bed.setGlobalNeedPath(s);
bed.globalColumns.add(stringName);
} else {
bed.setLocalNeedPath(s);
bed.localColumns.add(stringName);
}
}
// Detect functions that need static handles
if (f.operands.length > 0) {
Operator operand0 = f.operands[0];
if (operand0 instanceof Constant) {
Constant c = (Constant) operand0;
Type o = c.value;
if (o instanceof Text) {
String fileName = ((Text) o).value;
if (op instanceof ReadMatrix) {
if (!matrixNames.containsKey(fileName)) {
String matrixName = "Matrix" + matrixNames.size();
matrixNames.put(fileName, matrixName);
result.append("MatrixInput * " + matrixName + " = matrixHelper (\"" + fileName + "\");\n");
}
} else if (f instanceof Input) {
if (!inputNames.containsKey(fileName)) {
String inputName = "Input" + inputNames.size();
inputNames.put(fileName, inputName);
result.append("InputHolder * " + inputName + " = inputHelper (\"" + fileName + "\");\n");
}
} else if (f instanceof Output) {
if (!outputNames.containsKey(fileName)) {
String outputName = "Output" + outputNames.size();
outputNames.put(fileName, outputName);
result.append("OutputHolder * " + outputName + " = outputHelper (\"" + fileName + "\");\n");
}
}
}
} else // Dynamic file name (no static handle)
{
if (f instanceof ReadMatrix) {
matrixNames.put(op, "Matrix" + matrixNames.size());
stringNames.put(operand0, "fileName" + stringNames.size());
} else if (f instanceof Input) {
inputNames.put(op, "Input" + inputNames.size());
stringNames.put(operand0, "fileName" + stringNames.size());
} else if (f instanceof Output) {
outputNames.put(op, "Output" + outputNames.size());
stringNames.put(operand0, "fileName" + stringNames.size());
}
}
}
// Functions could be nested, so continue descent.
return true;
}
return true;
}
}
CheckStatic checkStatic = new CheckStatic();
for (Variable v : s.ordered) {
checkStatic.global = v.hasAttribute("global");
v.visit(checkStatic);
}
}
use of gov.sandia.n2a.language.Visitor in project n2a by frothga.
the class InternalBackendData method analyze.
public void analyze(final EquationSet s) {
System.out.println(s.name);
if (s.connectionBindings != null) {
// Note that populations have already been allocated in the constructor.
endpoints = countLocalObject;
countLocalObject += s.connectionBindings.size();
}
for (// we want the sub-lists to be ordered correctly
Variable v : // we want the sub-lists to be ordered correctly
s.ordered) {
String className = "null";
if (v.type != null)
className = v.type.getClass().getSimpleName();
System.out.println(" " + v.nameString() + " " + v.attributeString() + " " + className);
if (v.name.equals("$index"))
index = v;
else if (v.name.equals("$init"))
init = v;
else if (v.name.equals("$live"))
live = v;
else if (v.name.equals("$n") && v.order == 0)
n = v;
else if (v.name.equals("$p") && v.order == 0)
p = v;
else if (v.name.equals("$type"))
type = v;
else if (v.name.equals("$xyz") && v.order == 0)
xyz = v;
else if (v.name.equals("$t")) {
if (v.order == 0)
t = v;
else if (v.order == 1)
dt = v;
}
if (v.hasAttribute("global")) {
v.global = true;
v.visit(new Visitor() {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
if (av.reference.resolution.size() > 0)
addReferenceGlobal(av.reference, s);
return false;
}
if (op instanceof Output) {
Output o = (Output) op;
if (o.operands.length < 3) {
o.index = countGlobalObject++;
namesGlobalObject.add("columnName" + o.index);
}
// Continue descent, because parameters of output() may contain variable references
return true;
}
return true;
}
});
if (// eliminate non-computed values, unless they refer to a variable outside the immediate equation set
!v.hasAny(new String[] { "constant", "accessor", "readOnly" }) || v.hasAll(new String[] { "constant", "reference" })) {
boolean initOnly = v.hasAttribute("initOnly");
boolean updates = !initOnly && v.equations.size() > 0 && (v.derivative == null || v.hasAttribute("updates"));
if (updates)
globalUpdate.add(v);
if (v.hasAttribute("reference")) {
addReferenceGlobal(v.reference, s);
} else {
boolean temporary = v.hasAttribute("temporary");
if (!temporary || v.hasUsers())
globalInit.add(v);
if (!temporary && !v.hasAttribute("dummy")) {
if (!v.hasAttribute("preexistent"))
globalMembers.add(v);
boolean external = false;
if (v.hasAttribute("externalWrite") || v.assignment != Variable.REPLACE) {
external = true;
globalBufferedExternalWrite.add(v);
}
if (external || (v.hasAttribute("externalRead") && updates)) {
external = true;
globalBufferedExternal.add(v);
}
if (external || v.hasAttribute("cycle")) {
globalBuffered.add(v);
if (!external) {
globalBufferedInternal.add(v);
if (!initOnly)
globalBufferedInternalUpdate.add(v);
}
}
}
}
}
} else // local
{
v.visit(new Visitor() {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
if (av.reference.resolution.size() > 0)
addReferenceLocal(av.reference, s);
return false;
}
if (op instanceof Output) {
Output o = (Output) op;
if (o.operands.length < 3) {
o.index = countLocalObject++;
namesLocalObject.add("columnName" + o.index);
}
// Continue descent, because parameters of output() may contain variable references
return true;
}
return true;
}
});
if (!v.hasAny(new String[] { "constant", "accessor", "readOnly" }) || v.hasAll(new String[] { "constant", "reference" })) {
boolean initOnly = v.hasAttribute("initOnly");
boolean updates = !initOnly && v.equations.size() > 0 && (v.derivative == null || v.hasAttribute("updates"));
if (updates)
localUpdate.add(v);
if (v.hasAttribute("reference")) {
addReferenceLocal(v.reference, s);
} else {
boolean temporary = v.hasAttribute("temporary");
if (!temporary || v.hasUsers()) {
if (v.name.startsWith("$") || (temporary && v.neededBySpecial())) {
if (!v.name.equals("$index") && !v.name.equals("$live"))
localInitSpecial.add(v);
} else {
localInitRegular.add(v);
}
}
if (!temporary && !v.hasAttribute("dummy")) {
if (!v.hasAttribute("preexistent"))
localMembers.add(v);
boolean external = false;
if (v.hasAttribute("externalWrite") || v.assignment != Variable.REPLACE) {
external = true;
localBufferedExternalWrite.add(v);
}
if (external || (v.hasAttribute("externalRead") && updates)) {
external = true;
localBufferedExternal.add(v);
}
if (external || v.hasAttribute("cycle")) {
if (v.name.startsWith("$"))
localBufferedSpecial.add(v);
else
localBufferedRegular.add(v);
if (// v got here only by being a "cycle", not "externalRead" or "externalWrite"
!external) {
localBufferedInternal.add(v);
if (!initOnly)
localBufferedInternalUpdate.add(v);
}
}
}
}
}
}
}
for (// we need these to be in order by differential level, not by dependency
Variable v : // we need these to be in order by differential level, not by dependency
s.variables) {
if (v.derivative != null && !v.hasAny(new String[] { "constant", "initOnly" })) {
if (v.hasAttribute("global"))
globalIntegrated.add(v);
else
localIntegrated.add(v);
}
}
populationCanGrowOrDie = s.lethalP || s.lethalType || s.canGrow();
if (n != null) {
populationCanResize = globalMembers.contains(n);
// See EquationSet.forceTemporaryStorageForSpecials() for a related issue.
if (!populationCanResize && populationCanGrowOrDie && n.hasUsers()) {
Backend.err.get().println("WARNING: $n can change (due to structural dynamics) but it was detected as a constant. Equations that depend on $n may give incorrect results.");
}
}
if (index != null) {
indexNext = countGlobalFloat++;
namesGlobalFloat.add("indexNext");
indexAvailable = countGlobalObject++;
namesGlobalObject.add("indexAvailable");
}
if (// track instances
s.connected || s.needInstanceTracking || populationCanResize) {
// The reason populationCanResize forces use of the instances array is to enable pruning of parts when $n decreases.
instances = countGlobalObject++;
namesGlobalObject.add("instances");
if (// in addition, track newly created instances
s.connected) {
firstborn = countGlobalFloat++;
namesGlobalFloat.add("firstborn");
newborn = countLocalFloat++;
namesLocalFloat.add("newborn");
}
}
if (p != null) {
Pdependencies = new ArrayList<Variable>();
for (Variable t : s.ordered) {
if (t.hasAttribute("temporary") && p.dependsOn(t) != null) {
Pdependencies.add(t);
}
}
}
populationIndex = 0;
if (// check for null specifically to guard against the Wrapper equation set (which is not fully constructed)
s.container != null && s.container.parts != null) {
for (EquationSet p : s.container.parts) {
if (p == s)
break;
populationIndex++;
}
}
if (// connection-specific stuff
s.connectionBindings != null) {
int size = s.connectionBindings.size();
// endpoints is allocated at the top of this function, because it is needed for reference handling in the variable analysis loop
projectDependencies = new Object[size];
projectReferences = new Object[size];
count = new int[size];
k = new Variable[size];
max = new Variable[size];
min = new Variable[size];
project = new Variable[size];
radius = new Variable[size];
for (int i = 0; i < s.connectionBindings.size(); i++) {
ConnectionBinding c = s.connectionBindings.get(i);
count[i] = -1;
k[i] = s.find(new Variable(c.alias + ".$k"));
max[i] = s.find(new Variable(c.alias + ".$max"));
min[i] = s.find(new Variable(c.alias + ".$min"));
project[i] = s.find(new Variable(c.alias + ".$project"));
radius[i] = s.find(new Variable(c.alias + ".$radius"));
if (c.endpoint.accountableConnections != null) {
AccountableConnection query = new AccountableConnection(s, c.alias);
AccountableConnection ac = c.endpoint.accountableConnections.floor(query);
if (// Only true if this endpoint is accountable.
ac.equals(query)) {
// Allocate space for counter in target part
InternalBackendData endpointBed = (InternalBackendData) c.endpoint.backendData;
count[i] = endpointBed.countLocalFloat++;
endpointBed.namesLocalFloat.add(s.prefix() + ".$count");
if (// $count is referenced explicitly, so need to finish setting it up
ac.count != null) {
ac.count.readIndex = ac.count.writeIndex = count[i];
}
}
}
// Note that countLocalObject has already been incremented above
namesLocalObject.add(c.alias);
if (project[i] != null) {
ArrayList<Variable> dependencies = new ArrayList<Variable>();
// Always assign, even if empty.
projectDependencies[i] = dependencies;
for (Variable t : s.ordered) {
if (t.hasAttribute("temporary") && project[i].dependsOn(t) != null) {
dependencies.add(t);
}
}
final TreeSet<VariableReference> references = new TreeSet<VariableReference>(referenceComparator);
class ProjectVisitor extends Visitor {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
if (av.reference.resolution.size() > 0)
references.add(av.reference);
return false;
}
return true;
}
}
ProjectVisitor visitor = new ProjectVisitor();
project[i].visit(visitor);
for (Variable v : dependencies) v.visit(visitor);
if (references.size() > 0)
projectReferences[i] = references;
}
c.resolution = translateResolution(c.resolution, s);
}
}
// Locals
for (Variable v : localMembers) {
// in the type array rather than the float array.
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = countLocalFloat++;
namesLocalFloat.add(v.nameString());
} else {
v.readIndex = v.writeIndex = countLocalObject++;
namesLocalObject.add(v.nameString());
}
}
for (Variable v : localBufferedExternal) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = countLocalFloat++;
namesLocalFloat.add("next_" + v.nameString());
} else {
v.writeIndex = countLocalObject++;
namesLocalObject.add("next_" + v.nameString());
}
}
for (Variable v : localBufferedInternal) {
v.writeTemp = true;
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = countLocalTempFloat++;
namesLocalTempFloat.add("next_" + v.nameString());
} else {
v.writeIndex = countLocalTempObject++;
namesLocalTempObject.add("next_" + v.nameString());
}
}
// Globals
for (Variable v : globalMembers) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = countGlobalFloat++;
namesGlobalFloat.add(v.nameString());
} else {
v.readIndex = v.writeIndex = countGlobalObject++;
namesGlobalObject.add(v.nameString());
}
}
for (Variable v : globalBufferedExternal) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = countGlobalFloat++;
namesGlobalFloat.add("next_" + v.nameString());
} else {
v.writeIndex = countGlobalObject++;
namesGlobalObject.add("next_" + v.nameString());
}
}
for (Variable v : globalBufferedInternal) {
v.writeTemp = true;
if (v.type instanceof Scalar && v.reference.variable == v) {
v.writeIndex = countGlobalTempFloat++;
namesGlobalTempFloat.add("next_" + v.nameString());
} else {
v.writeIndex = countGlobalTempObject++;
namesGlobalTempObject.add("next_" + v.nameString());
}
}
// fully temporary values
for (Variable v : s.variables) {
if (!v.hasAttribute("temporary"))
continue;
v.readTemp = v.writeTemp = true;
if (v.hasAttribute("global")) {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = countGlobalTempFloat++;
namesGlobalTempFloat.add(v.nameString());
} else {
v.readIndex = v.writeIndex = countGlobalTempObject++;
namesGlobalTempObject.add(v.nameString());
}
} else {
if (v.type instanceof Scalar && v.reference.variable == v) {
v.readIndex = v.writeIndex = countLocalTempFloat++;
namesLocalTempFloat.add(v.nameString());
} else {
v.readIndex = v.writeIndex = countLocalTempObject++;
namesLocalTempObject.add(v.nameString());
}
}
}
if (live.hasAttribute("constant"))
liveStorage = LIVE_CONSTANT;
else if (live.hasAttribute("accessor"))
liveStorage = LIVE_ACCESSOR;
else
// $live is "initOnly"
liveStorage = LIVE_STORED;
for (VariableReference r : localReference) r.resolution = translateResolution(r.resolution, s);
for (VariableReference r : globalReference) r.resolution = translateResolution(r.resolution, s);
// Type conversions
String[] forbiddenAttributes = new String[] { "global", "constant", "accessor", "reference", "temporary", "dummy", "preexistent" };
for (EquationSet target : s.getConversionTargets()) {
if (s.connectionBindings == null) {
if (target.connectionBindings != null)
throw new EvaluationException("Can't change $type from compartment to connection.");
} else {
if (target.connectionBindings == null)
throw new EvaluationException("Can't change $type from connection to compartment.");
}
Conversion conversion = new Conversion();
conversions.put(target, conversion);
// Match variables
for (Variable v : target.variables) {
if (v.name.equals("$type"))
continue;
if (v.hasAny(forbiddenAttributes))
continue;
Variable v2 = s.find(v);
if (v2 != null && v2.equals(v)) {
conversion.to.add(v);
conversion.from.add(v2);
}
}
// Match connection bindings
if (// Since we checked above, we know that target is also a connection.
s.connectionBindings != null) {
conversion.bindings = new int[s.connectionBindings.size()];
int i = 0;
for (ConnectionBinding c : s.connectionBindings) {
conversion.bindings[i] = -1;
int j = 0;
for (ConnectionBinding d : target.connectionBindings) {
if (c.alias.equals(d.alias)) {
conversion.bindings[i] = j;
break;
}
j++;
}
// Note: ALL bindings must match. There is no other mechanism for initializing the endpoints.
if (conversion.bindings[i] < 0)
throw new EvaluationException("Unfulfilled connection binding during $type change.");
i++;
}
}
// TODO: Match populations?
// Currently, any contained populations do not carry over to new instance. Instead, it must create them from scratch.
}
}
use of gov.sandia.n2a.language.Visitor in project n2a by frothga.
the class InternalBackendData method analyzeEvents.
public static void analyzeEvents(final EquationSet s, final List<EventTarget> eventTargets, final List<Variable> eventReferences) {
class EventVisitor extends Visitor {
public boolean found;
public boolean visit(Operator op) {
if (op instanceof Event) {
found = true;
Event de = (Event) op;
if (// this event has not yet been analyzed
de.eventType == null) {
final EventTarget et = new EventTarget(de);
int targetIndex = eventTargets.indexOf(et);
if (// event target already exists
targetIndex >= 0) {
de.eventType = eventTargets.get(targetIndex);
} else // we must create a new event target, or more properly, fill in the event target we just used as a query object
{
// Create an entry and save the index
targetIndex = eventTargets.size();
eventTargets.add(et);
de.eventType = et;
et.container = s;
// Determine edge type
if (de.operands.length < 3) {
et.edge = EventTarget.RISE;
} else if (de.operands[2] instanceof Constant) {
Constant c = (Constant) de.operands[2];
if (c.value instanceof Text) {
Text t = (Text) c.value;
if (t.value.equalsIgnoreCase("nonzero"))
et.edge = EventTarget.NONZERO;
else if (t.value.equalsIgnoreCase("change"))
et.edge = EventTarget.CHANGE;
else if (t.value.equalsIgnoreCase("fall"))
et.edge = EventTarget.FALL;
else
et.edge = EventTarget.RISE;
} else {
Backend.err.get().println("ERROR: event() edge type must be a string.");
throw new Backend.AbortRun();
}
} else {
Backend.err.get().println("ERROR: event() edge type must be constant.");
throw new Backend.AbortRun();
}
// Allocate auxiliary variable
if (de.operands[0] instanceof AccessVariable) {
AccessVariable av = (AccessVariable) de.operands[0];
VariableReference reference = av.reference;
Variable v = reference.variable;
// then the user has broken the rule that we can't see temporaries in other parts.
if (v.hasAttribute("temporary") && v.container != s) {
Backend.err.get().println("WARNING: Cannot be temporary due to event monitor: " + v.container.name + "." + v.nameString() + " from " + s.name);
v.removeAttribute("temporary");
}
// so fall through to the !trackOne case below.
if (!v.hasAttribute("temporary")) {
// ensure it's buffered, so we can detect change
v.addAttribute("externalRead");
et.trackOne = true;
// just a holder for the reference
et.track = new Variable();
et.track.reference = reference;
}
}
if (// Expression, so create auxiliary variable. Aux not needed for NONZERO, because no change detection.
!et.trackOne && et.edge != EventTarget.NONZERO) {
et.track = new Variable("eventAux" + targetIndex, 0);
et.track.type = new Scalar(0);
et.track.reference = new VariableReference();
et.track.reference.variable = et.track;
}
// Locate any temporaries for evaluation. TODO: for more efficiency, we could have separate lists of temporaries for the condition and delay operands
// Tie into the dependency graph using a phantom variable (which can go away afterward without damaging the graph).
final Variable phantom = new Variable("event");
phantom.uses = new IdentityHashMap<Variable, Integer>();
for (int i = 0; i < et.event.operands.length; i++) et.event.operands[i].visit(new Visitor() {
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
Variable v = av.reference.variable;
if (!phantom.uses.containsKey(v))
phantom.uses.put(v, 1);
return false;
}
return true;
}
});
// Scan all variables in equation set to see if we need them
for (Variable t : s.variables) {
if (t.hasAttribute("temporary") && phantom.dependsOn(t) != null)
et.dependencies.add(t);
}
// Note the default is already set to -1 (no care)
class DelayVisitor extends Visitor {
TreeSet<EquationSet> containers = new TreeSet<EquationSet>();
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
// could include the target part itself, if in fact we use local variables
containers.add(av.reference.variable.container);
return false;
}
return true;
}
}
DelayVisitor dv = new DelayVisitor();
if (de.operands.length >= 2) {
if (de.operands[1] instanceof Constant) {
Constant c = (Constant) de.operands[1];
et.delay = (float) ((Scalar) c.value).value;
if (et.delay < 0)
et.delay = -1;
} else {
// indicates that we need to evaluate delay at run time
et.delay = -2;
de.operands[1].visit(dv);
}
}
// Set up monitors in source parts
class ConditionVisitor extends Visitor {
TreeSet<EquationSet> containers = new TreeSet<EquationSet>();
public boolean visit(Operator op) {
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
Variable v = av.reference.variable;
EquationSet sourceContainer = v.container;
containers.add(sourceContainer);
// Set up monitors for values that can vary during update.
if (!v.hasAttribute("constant") && !v.hasAttribute("initOnly") && !et.monitors(sourceContainer)) {
EventSource es = new EventSource(sourceContainer, et);
// null means self-reference, a special case handled in Part
if (sourceContainer != s)
es.reference = av.reference;
et.sources.add(es);
}
return false;
}
return true;
}
}
ConditionVisitor cv = new ConditionVisitor();
de.operands[0].visit(cv);
// Special case for event with no references that vary
if (et.sources.isEmpty()) {
// We can avoid creating a self monitor if we know for certain that the event will never fire
boolean neverFires = false;
if (de.operands[0] instanceof Constant) {
if (et.edge == EventTarget.NONZERO) {
Type op0 = ((Constant) de.operands[0]).value;
if (op0 instanceof Scalar) {
neverFires = ((Scalar) op0).value == 0;
} else {
Backend.err.get().println("ERROR: Condition for event() must resolve to a number.");
throw new Backend.AbortRun();
}
} else {
neverFires = true;
}
}
if (!neverFires) {
EventSource es = new EventSource(s, et);
// This is a self-reference, so es.reference should be null.
et.sources.add(es);
}
}
// Determine if monitor needs to test every target, or if one representative target is sufficient
for (EventSource source : et.sources) {
// associated with any given source instance, so every target must be evaluated separately.
if (cv.containers.size() > 1)
source.testEach = true;
if (dv.containers.size() > 1 || (dv.containers.size() == 1 && dv.containers.first() != source.container))
source.delayEach = true;
}
}
}
}
return true;
}
}
EventVisitor eventVisitor = new EventVisitor();
for (Variable v : s.variables) {
eventVisitor.found = false;
v.visit(eventVisitor);
if ((eventVisitor.found || v.dependsOnEvent()) && v.reference.variable != v)
eventReferences.add(v);
}
}
use of gov.sandia.n2a.language.Visitor in project n2a by frothga.
the class Output method isStringExpression.
/**
* Determines if the given operator is a string expression.
* This is the case if any operator it depends on is a string.
* If an operand is a variable, then its equations must contain a string.
*/
public static boolean isStringExpression(Variable v, Operator op) {
class StringVisitor extends Visitor {
boolean foundString;
Variable from;
public StringVisitor(Variable from) {
this.from = from;
from.visited = null;
}
public boolean visit(Operator op) {
if (op instanceof Constant) {
Constant c = (Constant) op;
if (c.value instanceof Text)
foundString = true;
return false;
}
if (op instanceof AccessVariable) {
AccessVariable av = (AccessVariable) op;
Variable v = av.reference.variable;
// Prevent infinite recursion
Variable p = from;
while (p != null) {
if (p == v)
return false;
p = p.visited;
}
v.visited = from;
from = v;
v.visit(this);
from = v.visited;
return false;
}
// no reason to dig any further
if (foundString)
return false;
// Add is the only operator that can propagate string values. All other operators and functions return scalars or matrices.
return op instanceof Add;
}
}
StringVisitor visitor = new StringVisitor(v);
op.visit(visitor);
return visitor.foundString;
}
use of gov.sandia.n2a.language.Visitor in project n2a by frothga.
the class JobC method prepareDynamicObjects.
/**
* Build complex sub-expressions into a single local variable that can be referenced by the equation.
*/
public void prepareDynamicObjects(Operator op, final CRenderer context, final boolean init, final String pad) throws Exception {
// Pass 1 -- Strings and matrix expressions
Visitor visitor1 = new Visitor() {
public boolean visit(Operator op) {
if (op instanceof BuildMatrix) {
BuildMatrix m = (BuildMatrix) op;
int rows = m.getRows();
int cols = m.getColumns();
String matrixName = "Matrix" + matrixNames.size();
matrixNames.put(m, matrixName);
if (rows == 3 && cols == 1)
context.result.append(pad + "Vector3 " + matrixName + ";\n");
else
context.result.append(pad + "Matrix<float> " + matrixName + " (" + rows + ", " + cols + ");\n");
for (int r = 0; r < rows; r++) {
if (cols == 1) {
context.result.append(pad + matrixName + "[" + r + "] = ");
m.operands[0][r].render(context);
context.result.append(";\n");
} else {
for (int c = 0; c < cols; c++) {
context.result.append(pad + matrixName + "(" + r + "," + c + ") = ");
m.operands[c][r].render(context);
context.result.append(";\n");
}
}
}
return false;
}
if (op instanceof Add) {
Add a = (Add) op;
String stringName = stringNames.get(a);
if (stringName != null) {
context.result.append(pad + "String " + stringName + ";\n");
for (Operator o : flattenAdd(a)) {
context.result.append(pad + stringName + " += ");
o.render(context);
context.result.append(";\n");
}
return false;
}
}
return true;
}
};
op.visit(visitor1);
// Pass 2 -- Input functions
Visitor visitor2 = new Visitor() {
public boolean visit(Operator op) {
if (op instanceof ReadMatrix) {
ReadMatrix r = (ReadMatrix) op;
if (!(r.operands[0] instanceof Constant)) {
String matrixName = matrixNames.get(r);
String stringName = stringNames.get(r.operands[0]);
context.result.append(pad + "MatrixInput * " + matrixName + " = matrixHelper (" + stringName + ");\n");
}
return false;
}
if (op instanceof Input) {
Input i = (Input) op;
if (!(i.operands[0] instanceof Constant)) {
String inputName = inputNames.get(i);
String stringName = stringNames.get(i.operands[0]);
context.result.append(pad + "InputHolder * " + inputName + " = inputHelper (" + stringName + ");\n");
if (!context.global) {
context.result.append(pad + inputName + "->epsilon = " + resolve(context.bed.dt.reference, context, false) + " / 1000;\n");
}
// Detect time flag
String mode = "";
if (i.operands.length > 3) {
// just assuming it's a constant string
mode = i.operands[3].toString();
} else if (i.operands[1] instanceof Constant) {
Constant c = (Constant) i.operands[1];
if (c.value instanceof Text)
mode = c.toString();
}
if (mode.contains("time")) {
context.result.append(pad + inputName + "->time = true;\n");
}
}
// I/O functions can be nested
return true;
}
if (op instanceof Output) {
Output o = (Output) op;
if (!(o.operands[0] instanceof Constant)) {
String outputName = outputNames.get(o);
String stringName = stringNames.get(o.operands[0]);
context.result.append(pad + "OutputHolder * " + outputName + " = outputHelper (" + stringName + ");\n");
// Detect raw flag
if (o.operands.length > 3) {
Operator op3 = o.operands[3];
if (op3 instanceof Constant) {
if (op3.toString().contains("raw")) {
context.result.append(pad + outputName + "->raw = true;\n");
}
}
}
}
return true;
}
return true;
}
};
op.visit(visitor2);
}
Aggregations