private void print(ArrayComprehension node) throws IOException { writer.append("["); for (ArrayComprehensionLoop loop : node.getLoops()) { writer.append("for").ws().append("("); print(loop.getIterator()); writer.append(" of "); print(loop.getIteratedObject()); writer.append(')'); } if (node.getFilter() != null) { writer.append("if").ws().append("("); print(node.getFilter()); writer.append(")"); } print(node.getResult()); writer.append(']'); }
/** * Parse a JavaScript 1.7 Array comprehension. * @param result the first expression after the opening left-bracket * @param pos start of LB token that begins the array comprehension * @return the array comprehension or an error node */ private AstNode arrayComprehension(AstNode result, int pos) throws IOException { List<ArrayComprehensionLoop> loops = new ArrayList<ArrayComprehensionLoop>(); while (peekToken() == Token.FOR) { loops.add(arrayComprehensionLoop()); } int ifPos = -1; ConditionData data = null; if (peekToken() == Token.IF) { consumeToken(); ifPos = ts.tokenBeg - pos; data = condition(); } mustMatchToken(Token.RB, "msg.no.bracket.arg"); ArrayComprehension pn = new ArrayComprehension(pos, ts.tokenEnd - pos); pn.setResult(result); pn.setLoops(loops); if (data != null) { pn.setIfPosition(ifPos); pn.setFilter(data.condition); pn.setFilterLp(data.lp - pos); pn.setFilterRp(data.rp - pos); } return pn; }
private Node transformArrayComp(ArrayComprehension node) { // An array comprehension expression such as // // [expr for (x in foo) for each ([y, z] in bar) if (cond)] // // is rewritten approximately as // // new Scope(ARRAYCOMP) { // new Node(BLOCK) { // let tmp1 = new Array; // for (let x in foo) { // for each (let tmp2 in bar) { // if (cond) { // tmp1.push([y, z] = tmp2, expr); // } // } // } // } // createName(tmp1) // } int lineno = node.getLineno(); Scope scopeNode = createScopeNode(Token.ARRAYCOMP, lineno); String arrayName = currentScriptOrFn.getNextTempName(); pushScope(scopeNode); try { defineSymbol(Token.LET, arrayName, false); Node block = new Node(Token.BLOCK, lineno); Node newArray = createCallOrNew(Token.NEW, createName("Array")); Node init = new Node(Token.EXPR_VOID, createAssignment(Token.ASSIGN, createName(arrayName), newArray), lineno); block.addChildToBack(init); block.addChildToBack(arrayCompTransformHelper(node, arrayName)); scopeNode.addChildToBack(block); scopeNode.addChildToBack(createName(arrayName)); return scopeNode; } finally { popScope(); } }