use of com.google.template.soy.exprtree.AbstractParentExprNode in project closure-templates by google.
the class TranslateToPyExprVisitor method visitLegacyObjectMapLiteralOrMapLiteralNode.
private PyExpr visitLegacyObjectMapLiteralOrMapLiteralNode(AbstractParentExprNode node) {
Preconditions.checkState(node.getKind() == ExprNode.Kind.LEGACY_OBJECT_MAP_LITERAL_NODE || node.getKind() == ExprNode.Kind.MAP_LITERAL_NODE);
Preconditions.checkArgument(node.numChildren() % 2 == 0);
Map<PyExpr, PyExpr> dict = new LinkedHashMap<>();
boolean needsRuntimeNullCheck = node.getKind() == ExprNode.Kind.MAP_LITERAL_NODE;
for (int i = 0, n = node.numChildren(); i < n; i += 2) {
ExprNode keyNode = node.getChild(i);
PyExpr key = visit(keyNode);
if (needsRuntimeNullCheck) {
key = new PyFunctionExprBuilder("runtime.check_not_null").addArg(key).asPyExpr();
}
ExprNode valueNode = node.getChild(i + 1);
dict.put(key, visit(valueNode));
}
// to index into the map with the wrong convention.
return PyExprUtils.convertMapToOrderedDict(dict);
}
use of com.google.template.soy.exprtree.AbstractParentExprNode in project closure-templates by google.
the class EvalVisitor method visitLegacyObjectMapLiteralOrMapLiteralNode.
private SoyValue visitLegacyObjectMapLiteralOrMapLiteralNode(AbstractParentExprNode node) {
checkState(node.getKind() == ExprNode.Kind.LEGACY_OBJECT_MAP_LITERAL_NODE || node.getKind() == ExprNode.Kind.MAP_LITERAL_NODE);
int numItems = node.numChildren() / 2;
boolean isStringKeyed = true;
ExprNode firstNonstringKeyNode = null;
List<SoyValue> keys = Lists.newArrayListWithCapacity(numItems);
List<SoyValue> values = Lists.newArrayListWithCapacity(numItems);
for (int i = 0; i < numItems; i++) {
SoyValue key = visit(node.getChild(2 * i));
if (isStringKeyed && !(key instanceof StringData)) {
isStringKeyed = false;
// temporary until we support nonstring key
firstNonstringKeyNode = node.getChild(2 * i);
}
keys.add(key);
values.add(visit(node.getChild(2 * i + 1)));
}
if (node.getKind() == ExprNode.Kind.LEGACY_OBJECT_MAP_LITERAL_NODE) {
if (!isStringKeyed) {
throw RenderException.create(String.format("legacy_object_map literals must have string keys (key \"%s\" in map %s does not " + "evaluate to a string).", firstNonstringKeyNode.toSourceString(), node.toSourceString()));
}
// Not an ImmutableMap, because map literals allow duplicate keys (last one wins).
Map<String, SoyValue> map = new LinkedHashMap<>();
for (int i = 0; i < numItems; i++) {
map.put(keys.get(i).stringValue(), values.get(i));
}
return DictImpl.forProviderMap(map, RuntimeMapTypeTracker.Type.LEGACY_OBJECT_MAP_OR_RECORD);
} else {
ImmutableMap.Builder<SoyValue, SoyValue> builder = ImmutableMap.builder();
for (int i = 0; i < numItems; ++i) {
SoyValue key = keys.get(i);
SoyValue value = values.get(i);
if (isNullOrUndefinedBase(key)) {
throw RenderException.create(String.format("null key in entry: null=%s", value));
}
builder.put(key, value);
}
return SoyMapImpl.forProviderMap(builder.build());
}
}
Aggregations