com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop Java Examples

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransTypes.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitForeachLoop(JCEnhancedForLoop tree) {
    tree.var = translate(tree.var, null);
    Type iterableType = tree.expr.type;
    tree.expr = translate(tree.expr, erasure(tree.expr.type));
    if (types.elemtype(tree.expr.type) == null)
        tree.expr.type = iterableType; // preserve type for Lower
    tree.body = translate(tree.body);
    result = tree;
}
 
Example #2
Source File: UEnhancedForLoop.java    From Refaster with Apache License 2.0 5 votes vote down vote up
@Override
public JCEnhancedForLoop inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().ForeachLoop(
      getVariable().inline(inliner),
      getExpression().inline(inliner),
      getStatement().inline(inliner));
}
 
Example #3
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void visitForeachLoop(JCEnhancedForLoop tree) {
	try {
		print("for (");
		printExpr(tree.var);
		print(" : ");
		printExpr(tree.expr);
		print(") ");
		printStat(tree.body);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #4
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private ForStatement convertEnhancedForLoop(JCEnhancedForLoop statement) {
  if (statement.getExpression().type.getKind() == TypeKind.ARRAY) {
    return convertForEachArray(statement);
  }

  return convertForEachInstance(statement);
}
 
Example #5
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
List<JCEnhancedForLoop> rewrite(JCEnhancedForLoop oldTree) {
    JCEnhancedForLoop newTree = copier.copy(oldTree);
    newTree.var = rewriteVarType(oldTree.var);
    newTree.body = make.Block(0, List.nil());
    return List.of(newTree);
}
 
Example #6
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Translate away the foreach loop.  */
public void visitForeachLoop(JCEnhancedForLoop tree) {
    if (types.elemtype(tree.expr.type) == null)
        visitIterableForeachLoop(tree);
    else
        visitArrayForeachLoop(tree);
}
 
Example #7
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitForeachLoop(JCEnhancedForLoop tree) {
    visitVarDef(tree.var);

    ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
    FlowKind prevFlowKind = flowKind;
    flowKind = FlowKind.NORMAL;
    int nextadrPrev = nextadr;
    scan(tree.expr);
    final Bits initsStart = new Bits(inits);
    final Bits uninitsStart = new Bits(uninits);

    letInit(tree.pos(), tree.var.sym);
    pendingExits = new ListBuffer<>();
    int prevErrors = log.nerrors;
    do {
        final Bits uninitsEntry = new Bits(uninits);
        uninitsEntry.excludeFrom(nextadr);
        scan(tree.body);
        resolveContinues(tree);
        if (log.nerrors != prevErrors ||
            flowKind.isFinal() ||
            new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
            break;
        uninits.assign(uninitsEntry.andSet(uninits));
        flowKind = FlowKind.SPECULATIVE_LOOP;
    } while (true);
    flowKind = prevFlowKind;
    inits.assign(initsStart);
    uninits.assign(uninitsStart.andSet(uninits));
    resolveBreaks(tree, prevPendingExits);
    nextadr = nextadrPrev;
}
 
Example #8
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitForeachLoop(JCEnhancedForLoop tree) {
    visitVarDef(tree.var);
    ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
    scan(tree.expr);
    pendingExits = new ListBuffer<>();
    scan(tree.body);
    resolveContinues(tree);
    resolveBreaks(tree, prevPendingExits);
}
 
Example #9
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitForeachLoop(JCEnhancedForLoop tree) {
    visitVarDef(tree.var);
    ListBuffer<PendingExit> prevPendingExits = pendingExits;
    scan(tree.expr);
    pendingExits = new ListBuffer<>();
    scanStat(tree.body);
    alive |= resolveContinues(tree);
    resolveBreaks(tree, prevPendingExits);
    alive = true;
}
 
Example #10
Source File: CRTable.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitForeachLoop(JCEnhancedForLoop tree) {
    SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
    sr.mergeWith(csp(tree.var));
    sr.mergeWith(csp(tree.expr));
    sr.mergeWith(csp(tree.body));
    result = sr;
}
 
Example #11
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * A statement of the form
 *
 * <pre>
 *     for ( T v : arrayexpr ) stmt;
 * </pre>
 *
 * (where arrayexpr is of an array type) gets translated to
 *
 * <pre>{@code
 *     for ( { arraytype #arr = arrayexpr;
 *             int #len = array.length;
 *             int #i = 0; };
 *           #i < #len; i$++ ) {
 *         T v = arr$[#i];
 *         stmt;
 *     }
 * }</pre>
 *
 * where #arr, #len, and #i are freshly named synthetic local variables.
 */
private void visitArrayForeachLoop(JCEnhancedForLoop tree) {
    make_at(tree.expr.pos());
    VarSymbol arraycache = new VarSymbol(SYNTHETIC,
                                         names.fromString("arr" + target.syntheticNameChar()),
                                         tree.expr.type,
                                         currentMethodSym);
    JCStatement arraycachedef = make.VarDef(arraycache, tree.expr);
    VarSymbol lencache = new VarSymbol(SYNTHETIC,
                                       names.fromString("len" + target.syntheticNameChar()),
                                       syms.intType,
                                       currentMethodSym);
    JCStatement lencachedef = make.
        VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar));
    VarSymbol index = new VarSymbol(SYNTHETIC,
                                    names.fromString("i" + target.syntheticNameChar()),
                                    syms.intType,
                                    currentMethodSym);

    JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0));
    indexdef.init.type = indexdef.type = syms.intType.constType(0);

    List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef);
    JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache));

    JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index)));

    Type elemtype = types.elemtype(tree.expr.type);
    JCExpression loopvarinit = make.Indexed(make.Ident(arraycache),
                                            make.Ident(index)).setType(elemtype);
    JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods,
                                          tree.var.name,
                                          tree.var.vartype,
                                          loopvarinit).setType(tree.var.type);
    loopvardef.sym = tree.var.sym;
    JCBlock body = make.
        Block(0, List.of(loopvardef, tree.body));

    result = translate(make.
                       ForLoop(loopinit,
                               cond,
                               List.of(step),
                               body));
    patchTargets(body, tree, result);
}
 
Example #12
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * A statement of the form
 *
 * <pre>
 *     for ( T v : coll ) stmt ;
 * </pre>
 *
 * (where coll implements {@code Iterable<? extends T>}) gets translated to
 *
 * <pre>{@code
 *     for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) {
 *         T v = (T) #i.next();
 *         stmt;
 *     }
 * }</pre>
 *
 * where #i is a freshly named synthetic local variable.
 */
private void visitIterableForeachLoop(JCEnhancedForLoop tree) {
    make_at(tree.expr.pos());
    Type iteratorTarget = syms.objectType;
    Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type),
                                      syms.iterableType.tsym);
    if (iterableType.getTypeArguments().nonEmpty())
        iteratorTarget = types.erasure(iterableType.getTypeArguments().head);
    Type eType = types.skipTypeVars(tree.expr.type, false);
    tree.expr.type = types.erasure(eType);
    if (eType.isCompound())
        tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr);
    Symbol iterator = lookupMethod(tree.expr.pos(),
                                   names.iterator,
                                   eType,
                                   List.nil());
    VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()),
                                    types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)),
                                    currentMethodSym);

     JCStatement init = make.
        VarDef(itvar, make.App(make.Select(tree.expr, iterator)
             .setType(types.erasure(iterator.type))));

    Symbol hasNext = lookupMethod(tree.expr.pos(),
                                  names.hasNext,
                                  itvar.type,
                                  List.nil());
    JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext));
    Symbol next = lookupMethod(tree.expr.pos(),
                               names.next,
                               itvar.type,
                               List.nil());
    JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next));
    if (tree.var.type.isPrimitive())
        vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit);
    else
        vardefinit = make.TypeCast(tree.var.type, vardefinit);
    JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods,
                                          tree.var.name,
                                          tree.var.vartype,
                                          vardefinit).setType(tree.var.type);
    indexDef.sym = tree.var.sym;
    JCBlock body = make.Block(0, List.of(indexDef, tree.body));
    body.endpos = TreeInfo.endPos(tree.body);
    result = translate(make.
        ForLoop(List.of(init),
                cond,
                List.nil(),
                body));
    patchTargets(body, tree, result);
}
 
Example #13
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
boolean match(JCEnhancedForLoop tree){
    return !tree.var.isImplicitlyTyped();
}
 
Example #14
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
void process(JCEnhancedForLoop oldTree, JCEnhancedForLoop newTree, boolean hasErrors){
    processVar(oldTree.var, newTree.var, hasErrors);
}
 
Example #15
Source File: Analyzer.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void visitForeachLoop(JCEnhancedForLoop tree) {
    //skip body (to prevents same statements to be analyzed twice)
    scan(tree.getExpression());
}
 
Example #16
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private ForStatement convertForEachArray(JCEnhancedForLoop statement) {
  // Converts
  //
  //   for(T v : exp) S
  //
  // into
  //
  //   for(T[] $array = (exp), int $index = 0; $index < $array.length; $index++ ) {
  //        T v = (T) $array[$index];
  //        S;
  //   }

  TypeMirror expressionTypeBinding = statement.getExpression().type;

  // T[] array = exp.
  Variable arrayVariable =
      Variable.newBuilder()
          .setName("$array")
          .setTypeDescriptor(environment.createTypeDescriptor(expressionTypeBinding))
          .setFinal(true)
          .build();

  // int index = 0;
  Variable indexVariable =
      Variable.newBuilder().setName("$index").setTypeDescriptor(PrimitiveTypes.INT).build();

  // $index < $array.length
  Expression condition =
      BinaryExpression.newBuilder()
          .setLeftOperand(indexVariable)
          .setOperator(BinaryOperator.LESS)
          .setRightOperand(
              ArrayLength.newBuilder().setArrayExpression(arrayVariable.getReference()).build())
          .build();

  ExpressionStatement forVariableDeclarationStatement =
      VariableDeclarationExpression.newBuilder()
          .addVariableDeclaration(
              createVariable(statement.getVariable(), false),
              ArrayAccess.newBuilder()
                  .setArrayExpression(arrayVariable.getReference())
                  .setIndexExpression(indexVariable.getReference())
                  .build())
          .build()
          .makeStatement(getSourcePosition(statement));

  return ForStatement.newBuilder()
      .setConditionExpression(condition)
      //  {   T t = $array[$index]; S; }
      .setBody(convertStatement(statement.getStatement()))
      // prepend the variable declaration.
      .addStatement(0, forVariableDeclarationStatement)
      .setInitializers(
          VariableDeclarationExpression.newBuilder()
              .addVariableDeclaration(arrayVariable, convertExpression(statement.getExpression()))
              .addVariableDeclaration(indexVariable, NumberLiteral.fromInt(0))
              .build())
      .setUpdates(
          PostfixExpression.newBuilder()
              .setOperand(indexVariable.getReference())
              .setOperator(PostfixOperator.INCREMENT)
              .build())
      .setSourcePosition(getSourcePosition(statement))
      .build();
}
 
Example #17
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private ForStatement convertForEachInstance(JCEnhancedForLoop statement) {
  // Converts
  //
  //   for(T v : exp) S
  //
  // into
  //
  //   for(Iterator<T> $iterator = (exp).iterator(); $iterator.hasNext(); ) {
  //        T v = (T) $iterator.next();
  //        S;
  //   }

  TypeMirror expressionTypeBinding = statement.getExpression().type;

  MethodDescriptor iteratorMethodDescriptor =
      environment
          .createDeclaredTypeDescriptor(expressionTypeBinding)
          .getMethodDescriptorByName("iterator");
  DeclaredTypeDescriptor iteratorTypeDescriptor =
      (DeclaredTypeDescriptor) iteratorMethodDescriptor.getReturnTypeDescriptor();
  Variable iteratorVariable =
      Variable.newBuilder()
          .setName("$iterator")
          .setTypeDescriptor(iteratorTypeDescriptor)
          .setFinal(true)
          .build();

  VariableDeclarationExpression iteratorDeclaration =
      VariableDeclarationExpression.newBuilder()
          .addVariableDeclaration(
              iteratorVariable,
              MethodCall.Builder.from(iteratorMethodDescriptor)
                  .setQualifier(convertExpression(statement.getExpression()))
                  .build())
          .build();

  // $iterator.hasNext();
  MethodDescriptor hasNextMethodDescriptor =
      iteratorTypeDescriptor.getMethodDescriptorByName("hasNext");
  Expression condition =
      MethodCall.Builder.from(hasNextMethodDescriptor)
          .setQualifier(iteratorVariable.getReference())
          .build();

  // T v = $iterator.next();
  MethodDescriptor nextMethodDescriptor =
      iteratorTypeDescriptor.getMethodDescriptorByName("next");
  ExpressionStatement forVariableDeclarationStatement =
      VariableDeclarationExpression.newBuilder()
          .addVariableDeclaration(
              createVariable(statement.getVariable(), false),
              MethodCall.Builder.from(nextMethodDescriptor)
                  .setQualifier(iteratorVariable.getReference())
                  .build())
          .build()
          .makeStatement(getSourcePosition(statement));

  return ForStatement.newBuilder()
      .setConditionExpression(condition)
      .setBody(convertStatement(statement.getStatement()))
      // Prepend the variable declaration.
      .addStatement(0, forVariableDeclarationStatement)
      .setInitializers(iteratorDeclaration)
      .setSourcePosition(getSourcePosition(statement))
      .build();
}
 
Example #18
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private Statement convertStatement(JCStatement jcStatement) {
  switch (jcStatement.getKind()) {
    case ASSERT:
      return convertAssert((JCAssert) jcStatement);
    case BLOCK:
      return convertBlock((JCBlock) jcStatement);
    case BREAK:
      return convertBreak((JCBreak) jcStatement);
    case CLASS:
      convertClassDeclaration((JCClassDecl) jcStatement);
      return null;
    case CONTINUE:
      return convertContinue((JCContinue) jcStatement);
    case DO_WHILE_LOOP:
      return convertDoWhileLoop((JCDoWhileLoop) jcStatement);
    case EMPTY_STATEMENT:
      return new EmptyStatement(getSourcePosition(jcStatement));
    case ENHANCED_FOR_LOOP:
      return convertEnhancedForLoop((JCEnhancedForLoop) jcStatement);
    case EXPRESSION_STATEMENT:
      return convertExpressionStatement((JCExpressionStatement) jcStatement);
    case FOR_LOOP:
      return convertForLoop((JCForLoop) jcStatement);
    case IF:
      return convertIf((JCIf) jcStatement);
    case LABELED_STATEMENT:
      return convertLabeledStatement((JCLabeledStatement) jcStatement);
    case RETURN:
      return convertReturn((JCReturn) jcStatement);
    case SWITCH:
      return convertSwitch((JCSwitch) jcStatement);
    case THROW:
      return convertThrow((JCThrow) jcStatement);
    case TRY:
      return convertTry((JCTry) jcStatement);
    case VARIABLE:
      return convertVariableDeclaration((JCVariableDecl) jcStatement);
    case WHILE_LOOP:
      return convertWhileLoop((JCWhileLoop) jcStatement);
    case SYNCHRONIZED:
      return convertSynchronized((JCSynchronized) jcStatement);
    default:
      throw new AssertionError("Unknown statement node type: " + jcStatement.getKind());
  }
}
 
Example #19
Source File: Analyzer.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visitForeachLoop(JCEnhancedForLoop tree) {
    scan(tree.getExpression());
}
 
Example #20
Source File: JavacTreeMaker.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCEnhancedForLoop ForeachLoop(JCVariableDecl var, JCExpression expr, JCStatement body) {
	return invoke(ForeachLoop, var, expr, body);
}