flattened == null ? Lists.newArrayList(children) : flattened);
List<Statement> newChildren = joined != null ? joined : flattened;
if (newChildren != null) { nChildren = newChildren.size(); }
if (!needsBlock) {
switch (nChildren) {
case 0: return new Noop(n.getFilePosition());
case 1: return (newChildren == null ? children : newChildren).get(0);
}
}
return newChildren != null
? new Block(n.getFilePosition(), newChildren) : n;
} else if (n instanceof SwitchStmt) {
return optimizeSwitch((SwitchStmt) n);
} else if (n instanceof ReturnStmt) {
ReturnStmt rs = (ReturnStmt) n;
Expression returnValue = rs.getReturnValue();
Expression optReturnValue = returnValue != null
? (Expression) optimize(returnValue, false)
: null;
if (optReturnValue != null && returnValue != null // 2nd implied by 1st
&& "undefined".equals(returnValue.typeOf())
&& optReturnValue.simplifyForSideEffect() == null) {
return new ReturnStmt(rs.getFilePosition(), null);
} else if (optReturnValue != returnValue) {
return new ReturnStmt(rs.getFilePosition(), optReturnValue);
}
return rs;
} else {
List<? extends ParseTreeNode> children = n.children();
int nChildren = children.size();
List<ParseTreeNode> newChildren = null;
boolean childNeedsBlock = (
n instanceof FunctionConstructor || n instanceof TryStmt
|| n instanceof CatchStmt || n instanceof FinallyStmt
|| n instanceof SwitchCase);
for (int i = 0; i < nChildren; ++i) {
ParseTreeNode child = children.get(i);
ParseTreeNode newChild = optimize(child, childNeedsBlock);
if (child != newChild) {
if (newChildren == null) {
newChildren = Lists.newArrayListWithCapacity(nChildren);
}
newChildren.addAll(children.subList(newChildren.size(), i));
newChildren.add(newChild);
}
}
if (newChildren != null) {
newChildren.addAll(children.subList(newChildren.size(), nChildren));
}
List<? extends ParseTreeNode> outChildren = newChildren == null
? children : newChildren;
if (n instanceof ExpressionStmt) {
Expression e = (Expression) outChildren.get(0);
Expression simple = e.simplifyForSideEffect();
if (simple == null) { return new Noop(n.getFilePosition()); }
if (simple != e) {
newChildren = Collections.<ParseTreeNode>singletonList(simple);
}
} else if (n instanceof Conditional) {
List<ParseTreeNode> condParts = newChildren != null