Java 类com.sun.tools.javac.tree.JCTree.JCStatement 实例源码

项目:java-code-templates    文件:AstSubstitutionProcessor.java   
private String applySubstitutions(final ExecutableElement element, final ImmutableSet<String> replacements) {
    if (Util.isAbstract(element)) {
        return "";
    }

    final StringWriter writer = new StringWriter();
    final SubstitutingPretty visitor = new SubstitutingPretty(writer,
            replacements,
            trees.getPath(element).getCompilationUnit(),
            Util.substitutePartialTypeNames(element));

    trees.getTree(element)
        .getBody()
        .getStatements()
        .stream()
        .map(JCStatement.class::cast)
        .forEach(tree -> {
            visitor.clearSubstitutions();
            visitor.printStat(tree);
            visitor.println();
        });

    return writer.toString();
}
项目:java-code-templates    文件:AstSubstitutionProcessor.java   
@Override
public void visitForLoop(final JCForLoop node) {
    print("for (");
    if (node.init.nonEmpty()) {
        if (node.init.head instanceof JCVariableDecl) {
            handleVarDef((JCVariableDecl)node.init.head, false);
            for (List<JCStatement> l = node.init.tail; l.nonEmpty(); l = l.tail) {
                final JCVariableDecl decl = (JCVariableDecl)l.head;
                print(", " + decl.name + " = ");
                printExpr(decl.init);
            }
        } else {
            printExprs(node.init);
        }
    }

    print("; ");
    if (node.cond != null) {
        printExpr(node.cond);
    }

    print("; ");
    printExprs(node.step);
    print(") ");
    printStat(node.body);
}
项目:openjdk9    文件:Corraller.java   
private JCBlock resolutionExceptionBlock() {
    if (resolutionExceptionBlock == null) {
        JCExpression expClass = null;
        // Split the exception class name at dots
        for (String id : SPIResolutionException.class.getName().split("\\.")) {
            Name nm = names.fromString(id);
            if (expClass == null) {
                expClass = make.Ident(nm);
            } else {
                expClass = make.Select(expClass, nm);
            }
        }
        JCNewClass exp = make.NewClass(null,
                null, expClass, List.of(make.Literal(keyIndex)), null);
        resolutionExceptionBlock = make.Block(0L, List.<JCStatement>of(
                make.Throw(exp)));
    }
    return resolutionExceptionBlock;
}
项目:lombok-ianchiu    文件:JavacHandlerUtil.java   
public static boolean isConstructorCall(final JCStatement statement) {
    if (!(statement instanceof JCExpressionStatement)) return false;
    JCExpression expr = ((JCExpressionStatement) statement).expr;
    if (!(expr instanceof JCMethodInvocation)) return false;
    JCExpression invocation = ((JCMethodInvocation) expr).meth;
    String name;
    if (invocation instanceof JCFieldAccess) {
        name = ((JCFieldAccess) invocation).name.toString();
    } else if (invocation instanceof JCIdent) {
        name = ((JCIdent) invocation).name.toString();
    } else {
        name = "";
    }

    return "super".equals(name) || "this".equals(name);
}
项目:lombok-ianchiu    文件:HandleSneakyThrows.java   
public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
    JavacTreeMaker maker = node.getTreeMaker();

    Context context = node.getContext();
    JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
    JCExpression varType = chainDots(node, exception.split("\\."));

    JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
    JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
    JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(
            List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef,
            List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
    JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
    if (JavacHandlerUtil.inNetbeansEditor(node)) {
        //set span (start and end position) of the try statement and the main block
        //this allows NetBeans to dive into the statement correctly:
        JCCompilationUnit top = (JCCompilationUnit) node.top().get();
        int startPos = contents.head.pos;
        int endPos = Javac.getEndPosition(contents.last().pos(), top);
        tryBlock.pos = startPos;
        tryStatement.pos = startPos;
        Javac.storeEnd(tryBlock, endPos, top);
        Javac.storeEnd(tryStatement, endPos, top);
    }
    return setGeneratedBy(tryStatement, source, context);
}
项目:lombok-ianchiu    文件:HandleBuilder.java   
private JCMethodDecl generateCleanMethod(java.util.List<BuilderFieldData> builderFields, JavacNode type, JCTree source) {
    JavacTreeMaker maker = type.getTreeMaker();
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, type, source, statements);
        }
    }

    statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, false))));
    JCBlock body = maker.Block(0, statements.toList());
    return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName("$lombokClean"), maker.Type(Javac.createVoidType(maker, CTC_VOID)), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
    /*
     *      if (shouldReturnThis) {
        methodType = cloneSelfType(field);
    }

    if (methodType == null) {
        //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6.
        methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));
        shouldReturnThis = false;
    }

     */
}
项目:lombok-ianchiu    文件:HandleBuilder.java   
public JCMethodDecl generateBuilderMethod(boolean isStatic, String builderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams) {
    JavacTreeMaker maker = type.getTreeMaker();

    ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
    for (JCTypeParameter typeParam : typeParams) {
        typeArgs.append(maker.Ident(typeParam.name));
    }

    JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
    JCStatement statement = maker.Return(call);

    JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
    int modifiers = Flags.PUBLIC;
    if (isStatic) modifiers |= Flags.STATIC;
    return maker.MethodDef(maker.Modifiers(modifiers), type.toName(builderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), copyTypeParams(maker, typeParams), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
}
项目:lombok-ianchiu    文件:HandleEqualsAndHashCode.java   
public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List<JCAnnotation> onParam) {
    /* protected boolean canEqual(final java.lang.Object other) {
     *     return other instanceof Outer.Inner.MyType;
     * }
     */
    JavacTreeMaker maker = typeNode.getTreeMaker();

    JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.<JCAnnotation>nil());
    JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
    Name canEqualName = typeNode.toName("canEqual");
    JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
    Name otherName = typeNode.toName("other");
    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
    List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null));

    JCBlock body = maker.Block(0, List.<JCStatement>of(
            maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));

    return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
项目:lombok-ianchiu    文件:JavacJavaUtilMapSingularizer.java   
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
    if (useGuavaInstead(builderType)) {
        guavaMapSingularizer.generateMethods(data, builderType, source, fluent, chain);
        return;
    }

    JavacTreeMaker maker = builderType.getTreeMaker();

    JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
    generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);

    returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
    generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);

    returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
    generateClearMethod(maker, returnType, returnStatement, data, builderType, source);
}
项目:lombok-ianchiu    文件:JavacJavaUtilMapSingularizer.java   
private void generateClearMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source) {
    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();
    List<JCVariableDecl> params = List.nil();
    List<JCExpression> jceBlank = List.nil();

    JCExpression thisDotKeyField = chainDots(builderType, "this", data.getPluralName() + "$key");
    JCExpression thisDotKeyFieldDotClear = chainDots(builderType, "this", data.getPluralName() + "$key", "clear");
    JCExpression thisDotValueFieldDotClear = chainDots(builderType, "this", data.getPluralName() + "$value", "clear");
    JCStatement clearKeyCall = maker.Exec(maker.Apply(jceBlank, thisDotKeyFieldDotClear, jceBlank));
    JCStatement clearValueCall = maker.Exec(maker.Apply(jceBlank, thisDotValueFieldDotClear, jceBlank));
    JCExpression cond = maker.Binary(CTC_NOT_EQUAL, thisDotKeyField, maker.Literal(CTC_BOT, null));
    JCBlock clearCalls = maker.Block(0, List.of(clearKeyCall, clearValueCall));
    JCStatement ifSetCallClear = maker.If(cond, clearCalls, null);
    List<JCStatement> statements = returnStatement != null ? List.of(ifSetCallClear, returnStatement) : List.of(ifSetCallClear);

    JCBlock body = maker.Block(0, statements);
    Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString()));
    JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
    injectMethod(builderType, method);
}
项目:lombok-ianchiu    文件:JavacJavaUtilListSetSingularizer.java   
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
    if (useGuavaInstead(builderType)) {
        guavaListSetSingularizer.generateMethods(data, builderType, source, fluent, chain);
        return;
    }

    JavacTreeMaker maker = builderType.getTreeMaker();
    Name thisName = builderType.toName("this");

    JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    JCStatement returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
    generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);

    returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
    generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);

    returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
    generateClearMethod(maker, returnType, returnStatement, data, builderType, source);
}
项目:lombok-ianchiu    文件:JavacJavaUtilListSetSingularizer.java   
private void generateClearMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source) {
    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();
    List<JCVariableDecl> params = List.nil();
    List<JCExpression> jceBlank = List.nil();

    JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
    JCExpression thisDotFieldDotClear = maker.Select(maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), builderType.toName("clear"));
    JCStatement clearCall = maker.Exec(maker.Apply(jceBlank, thisDotFieldDotClear, jceBlank));
    JCExpression cond = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
    JCStatement ifSetCallClear = maker.If(cond, clearCall, null);
    List<JCStatement> statements = returnStatement != null ? List.of(ifSetCallClear, returnStatement) : List.of(ifSetCallClear);

    JCBlock body = maker.Block(0, statements);
    Name methodName = builderType.toName(HandlerUtil.buildAccessorName("clear", data.getPluralName().toString()));
    JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
    injectMethod(builderType, method);
}
项目:lombok-ianchiu    文件:JavacJavaUtilListSetSingularizer.java   
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();

    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
    JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add");
    JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getSingularName())));
    statements.append(maker.Exec(invokeAdd));
    if (returnStatement != null) statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    Name name = data.getSingularName();
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString()));
    JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
    JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
    injectMethod(builderType, method);
}
项目:lombok-ianchiu    文件:JavacJavaUtilListSetSingularizer.java   
void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();

    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
    JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "addAll");
    JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getPluralName())));
    statements.append(maker.Exec(invokeAdd));
    if (returnStatement != null) statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    Name name = data.getPluralName();
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("addAll", name.toString()));
    JCExpression paramType = chainDots(builderType, "java", "util", "Collection");
    paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs(), source);
    JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
    injectMethod(builderType, method);
}
项目:lombok-ianchiu    文件:JavacJavaUtilListSingularizer.java   
private List<JCStatement> createListCopy(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) {
    List<JCExpression> jceBlank = List.nil();
    Name thisName = builderType.toName("this");

    JCExpression argToUnmodifiable; {
         // new java.util.ArrayList<Generics>(this.pluralName);
        List<JCExpression> constructorArgs = List.nil();
        JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
        constructorArgs = List.<JCExpression>of(thisDotPluralName);
        JCExpression targetTypeExpr = chainDots(builderType, "java", "util", "ArrayList");
        targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
        argToUnmodifiable = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
    }

    JCStatement unmodifiableStat; {
        // pluralname = Collections.unmodifiableInterfaceType(-newlist-);
        JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiableList"), List.of(argToUnmodifiable));
        unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
    }

    return List.of(unmodifiableStat);
}
项目:javaparser2jctree    文件:JavaParser2JCTree.java   
@Override
public JCTree visit(final BlockStmt n, final Object arg) {
    // ARG0: long flags
    // It is logically endend with Flags.STATIC is static init
    long arg0 = 0;

    // ARG1: List<JCStatement> stats
    List<JCStatement> arg1 = List.<JCStatement>nil();
    if (n.getStmts() != null) {
        for (final Statement s : n.getStmts()) {
            arg1 = arg1.append((JCStatement) s.accept(this, arg));
        }
    }

    return new AJCBlock(make.Block(arg0, arg1), ((n.getComment() != null) ? n.getComment().getContent() : null));
}
项目:javaparser2jctree    文件:JavaParser2JCTree.java   
@Override
  public JCTree visit(final InitializerDeclaration n, final Object arg) {
      //ARG0: long flags
      long arg0 = ModifierSet.STATIC;

       /* TODO - Ignoring javadoc 
if (n.getJavaDoc() != null) {
      JCTree result = n.getJavaDoc().accept(this, arg);
}
       */

      //ARG1: List<JCStatement> stats
      List<JCStatement> arg1 = List.<JCStatement>nil();
      if (n.getBlock().getStmts() != null) {
          for (final Statement s : n.getBlock().getStmts()) {
              arg1 = arg1.append((JCStatement) s.accept(this, arg));
          }
      }
      return new AJCBlock(make.Block(arg0, arg1), ((n.getComment() != null) ? n.getComment().getContent() : null));
  }
项目:javaparser2jctree    文件:JavaParser2JCTree.java   
@Override
public JCTree visit(final SwitchEntryStmt n, final Object arg) {
    //ARG0: JCExpression pat
    JCExpression arg0 = null;
    if (n.getLabel() != null) {
        arg0 = (JCExpression) n.getLabel().accept(this, arg);
    }

    //ARG1: List<JCStatement> stats
    List<JCStatement> arg1 = List.<JCStatement>nil();
    if (n.getStmts() != null) {
        for (final Statement s : n.getStmts()) {
            arg1 = arg1.append((JCStatement) s.accept(this, arg));
        }
    }

    return new AJCCase(make.Case(arg0, arg1), ((n.getComment() != null) ? n.getComment().getContent() : null));
}
项目:EasyMPermission    文件:PrettyCommentsPrinter.java   
public void visitForLoop(JCForLoop tree) {
    try {
        print("for (");
        if (tree.init.nonEmpty()) {
            if (VARDEF.equals(treeTag(tree.init.head))) {
                printExpr(tree.init.head);
                for (List<JCStatement> l = tree.init.tail; l.nonEmpty(); l = l.tail) {
                    JCVariableDecl vdef = (JCVariableDecl)l.head;
                    print(", " + vdef.name + " = ");
                    printExpr(vdef.init);
                }
            } else {
                printExprs(tree.init);
            }
        }
        print("; ");
        if (tree.cond != null) printExpr(tree.cond);
        print("; ");
        printExprs(tree.step);
        print(") ");
        printStat(tree.body);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:EasyMPermission    文件:JavacHandlerUtil.java   
public static boolean isConstructorCall(final JCStatement statement) {
    if (!(statement instanceof JCExpressionStatement)) return false;
    JCExpression expr = ((JCExpressionStatement) statement).expr;
    if (!(expr instanceof JCMethodInvocation)) return false;
    JCExpression invocation = ((JCMethodInvocation) expr).meth;
    String name;
    if (invocation instanceof JCFieldAccess) {
        name = ((JCFieldAccess) invocation).name.toString();
    } else if (invocation instanceof JCIdent) {
        name = ((JCIdent) invocation).name.toString();
    } else {
        name = "";
    }

    return "super".equals(name) || "this".equals(name);
}
项目:EasyMPermission    文件:HandleSneakyThrows.java   
public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
    JavacTreeMaker maker = node.getTreeMaker();

    Context context = node.getContext();
    JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
    JCExpression varType = chainDots(node, exception.split("\\."));

    JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
    JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
    JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(
            List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef,
            List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
    JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
    if (JavacHandlerUtil.inNetbeansEditor(node)) {
        //set span (start and end position) of the try statement and the main block
        //this allows NetBeans to dive into the statement correctly:
        JCCompilationUnit top = (JCCompilationUnit) node.top().get();
        int startPos = contents.head.pos;
        int endPos = Javac.getEndPosition(contents.last().pos(), top);
        tryBlock.pos = startPos;
        tryStatement.pos = startPos;
        Javac.storeEnd(tryBlock, endPos, top);
        Javac.storeEnd(tryStatement, endPos, top);
    }
    return setGeneratedBy(tryStatement, source, context);
}
项目:EasyMPermission    文件:HandleBuilder.java   
private JCMethodDecl generateCleanMethod(java.util.List<BuilderFieldData> builderFields, JavacNode type, JCTree source) {
    JavacTreeMaker maker = type.getTreeMaker();
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, type, source, statements);
        }
    }

    statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, false))));
    JCBlock body = maker.Block(0, statements.toList());
    return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName("$lombokClean"), maker.Type(Javac.createVoidType(maker, CTC_VOID)), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
    /*
     *      if (shouldReturnThis) {
        methodType = cloneSelfType(field);
    }

    if (methodType == null) {
        //WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6.
        methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));
        shouldReturnThis = false;
    }

     */
}
项目:EasyMPermission    文件:HandleEqualsAndHashCode.java   
public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List<JCAnnotation> onParam) {
    /* public boolean canEqual(final java.lang.Object other) {
     *     return other instanceof Outer.Inner.MyType;
     * }
     */
    JavacTreeMaker maker = typeNode.getTreeMaker();

    JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.<JCAnnotation>nil());
    JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
    Name canEqualName = typeNode.toName("canEqual");
    JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
    Name otherName = typeNode.toName("other");
    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
    List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null));

    JCBlock body = maker.Block(0, List.<JCStatement>of(
            maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));

    return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
项目:EasyMPermission    文件:JavacJavaUtilMapSingularizer.java   
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
    if (useGuavaInstead(builderType)) {
        guavaMapSingularizer.generateMethods(data, builderType, source, fluent, chain);
        return;
    }

    JavacTreeMaker maker = builderType.getTreeMaker();

    JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
    generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);

    returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
    generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
项目:EasyMPermission    文件:JavacJavaUtilListSetSingularizer.java   
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
    if (useGuavaInstead(builderType)) {
        guavaListSetSingularizer.generateMethods(data, builderType, source, fluent, chain);
        return;
    }

    JavacTreeMaker maker = builderType.getTreeMaker();
    Name thisName = builderType.toName("this");

    JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    JCStatement returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
    generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);

    returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
    returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
    generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
项目:EasyMPermission    文件:JavacJavaUtilListSetSingularizer.java   
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();

    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
    JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add");
    JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getSingularName())));
    statements.append(maker.Exec(invokeAdd));
    if (returnStatement != null) statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    Name name = data.getSingularName();
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString()));
    JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
    JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
    injectMethod(builderType, method);
}
项目:EasyMPermission    文件:JavacJavaUtilListSetSingularizer.java   
void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();

    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
    JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "addAll");
    JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getPluralName())));
    statements.append(maker.Exec(invokeAdd));
    if (returnStatement != null) statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    Name name = data.getPluralName();
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("addAll", name.toString()));
    JCExpression paramType = chainDots(builderType, "java", "util", "Collection");
    paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs(), source);
    JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
    injectMethod(builderType, method);
}
项目:EasyMPermission    文件:JavacJavaUtilListSingularizer.java   
private List<JCStatement> createListCopy(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) {
    List<JCExpression> jceBlank = List.nil();
    Name thisName = builderType.toName("this");

    JCExpression argToUnmodifiable; {
         // new java.util.ArrayList<Generics>(this.pluralName);
        List<JCExpression> constructorArgs = List.nil();
        JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
        constructorArgs = List.<JCExpression>of(thisDotPluralName);
        JCExpression targetTypeExpr = chainDots(builderType, "java", "util", "ArrayList");
        targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
        argToUnmodifiable = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
    }

    JCStatement unmodifiableStat; {
        // pluralname = Collections.unmodifiableInterfaceType(-newlist-);
        JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiableList"), List.of(argToUnmodifiable));
        unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
    }

    return List.of(unmodifiableStat);
}
项目:refactor-faster    文件:BlockTemplate.java   
/**
 * If the tree is a {@link JCBlock}, returns a list of disjoint matches corresponding to
 * the exact list of template statements found consecutively; otherwise, returns an
 * empty list.
 */
@Override
public Iterable<BlockTemplateMatch> match(JCTree tree, Context context) {
  // TODO(lowasser): consider nonconsecutive matches?
  if (tree instanceof JCBlock) {
    JCBlock block = (JCBlock) tree;
    List<JCStatement> targetStatements = ImmutableList.copyOf(block.getStatements());
    ImmutableList.Builder<BlockTemplateMatch> builder = ImmutableList.builder();
    for (int start = 0; start + templateStatements().size() <= targetStatements.size(); 
        start++) {
      int end = start + templateStatements().size();
      Unifier unifier = match(targetStatements.subList(start, end), context);
      if (unifier != null) {
        builder.add(new BlockTemplateMatch(block, unifier, start, end));
        start = end - 1;
      }
    }
    return builder.build();
  }
  return ImmutableList.of();
}
项目:refactor-faster    文件:BlockTemplate.java   
@Nullable
private Unifier match(List<JCStatement> targetStatements, Context context) {
  checkArgument(templateStatements().size() == targetStatements.size());
  Unifier unifier = new Unifier(context);
  for (int i = 0; i < templateStatements().size() && unifier != null; i++) {
    unifier = templateStatements().get(i).unify(targetStatements.get(i), unifier);
  }
  if (unifier != null) {
    Inliner inliner = unifier.createInliner();
    try {
      return typecheck(
          unifier, inliner, new Warner(targetStatements.get(0)), expectedTypes(inliner),
          actualTypes(inliner));
    } catch (CouldNotResolveImportException e) {
      logger.log(FINE, "Failure to resolve import", e);
    }
  }
  return null;
}
项目:jmlok    文件:Examinator.java   
/**
 * Verify if all variables were initialized on the constructor.
 * @param block The lines of the constructor.
 * @return true if all variables were initialized on the constructor.
 */
private boolean isAllVariableInitialized(JCBlock block) {
    for (com.sun.tools.javac.util.List<JCStatement> traversing = block.stats; !traversing.isEmpty(); traversing = traversing.tail){
        if(traversing.head instanceof JCExpressionStatement){
            if(((JCExpressionStatement) traversing.head).expr instanceof JCAssign 
            && !((JCAssign) ((JCExpressionStatement) traversing.head).expr).rhs.toString().equals("null")){
                String toTest = ((JCAssign) ((JCExpressionStatement) traversing.head).expr).lhs.toString();     
                int i = 0; boolean isNecessaryToRemove = false;
                for(i = 0; i < this.variables.size(); i++){
                    if(toTest.equals(this.variables.get(i)) || toTest.equals("this." + this.variables.get(i))){
                        isNecessaryToRemove = true;
                        break;
                    }
                }
                if(isNecessaryToRemove)
                    this.variables.remove(i);
            }
        }
    }
    return this.variables.isEmpty();
}
项目:error-prone    文件:RefasterScanner.java   
@Override
public Void visitClass(ClassTree node, Context context) {
  Symbol sym = ASTHelpers.getSymbol(node);
  if (sym == null || !sym.getQualifiedName().contentEquals(rule().qualifiedTemplateClass())) {
    ListBuffer<JCStatement> statements = new ListBuffer<>();
    for (Tree tree : node.getMembers()) {
      if (tree instanceof JCStatement) {
        statements.append((JCStatement) tree);
      } else {
        tree.accept(this, context);
      }
    }
    scan(TreeMaker.instance(context).Block(0, statements.toList()), context);
  }
  return null;
}
项目:error-prone    文件:ULambda.java   
JCTree inlineBody(Inliner inliner) throws CouldNotResolveImportException {
  if (getBody() instanceof UPlaceholderExpression) {
    UPlaceholderExpression body = (UPlaceholderExpression) getBody();
    Optional<List<JCStatement>> blockBinding =
        inliner.getOptionalBinding(body.placeholder().blockKey());
    if (blockBinding.isPresent()) {
      // this lambda is of the form args -> blockPlaceholder();
      List<JCStatement> blockInlined =
          UPlaceholderExpression.copier(body.arguments(), inliner)
              .copy(blockBinding.get(), inliner);
      if (blockInlined.size() == 1) {
        if (blockInlined.get(0) instanceof JCReturn) {
          return ((JCReturn) blockInlined.get(0)).getExpression();
        } else if (blockInlined.get(0) instanceof JCExpressionStatement) {
          return ((JCExpressionStatement) blockInlined.get(0)).getExpression();
        }
      }
      return inliner.maker().Block(0, blockInlined);
    }
  }
  return getBody().inline(inliner);
}
项目:s4j    文件:Pretty.java   
public void visitForLoop(JCForLoop tree) {
    try {
        print("for (");
        if (tree.init.nonEmpty()) {
            if (tree.init.head.getTag() == JCTree.VARDEF) {
                printExpr(tree.init.head);
                for (List<JCStatement> l = tree.init.tail; l.nonEmpty(); l = l.tail) {
                    JCVariableDecl vdef = (JCVariableDecl)l.head;
                    print(", " + vdef.name + " = ");
                    printExpr(vdef.init);
                }
            } else {
                printExprs(tree.init);
            }
        }
        print("; ");
        if (tree.cond != null) printExpr(tree.cond);
        print("; ");
        printExprs(tree.step);
        print(") ");
        printStat(tree.body);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:Refaster    文件:BlockTemplate.java   
/**
 * If the tree is a {@link JCBlock}, returns a list of disjoint matches corresponding to
 * the exact list of template statements found consecutively; otherwise, returns an
 * empty list.
 */
@Override
public Iterable<BlockTemplateMatch> match(JCTree tree, Context context) {
  // TODO(lowasser): consider nonconsecutive matches?
  if (tree instanceof JCBlock) {
    JCBlock block = (JCBlock) tree;
    List<JCStatement> targetStatements = ImmutableList.copyOf(block.getStatements());
    ImmutableList.Builder<BlockTemplateMatch> builder = ImmutableList.builder();
    for (int start = 0; start + templateStatements().size() <= targetStatements.size(); 
        start++) {
      int end = start + templateStatements().size();
      Unifier unifier = match(targetStatements.subList(start, end), context);
      if (unifier != null) {
        builder.add(new BlockTemplateMatch(block, unifier, start, end));
        start = end - 1;
      }
    }
    return builder.build();
  }
  return ImmutableList.of();
}
项目:Refaster    文件:BlockTemplate.java   
@Nullable
private Unifier match(List<JCStatement> targetStatements, Context context) {
  checkArgument(templateStatements().size() == targetStatements.size());
  Unifier unifier = new Unifier(context);
  for (int i = 0; i < templateStatements().size() && unifier != null; i++) {
    unifier = templateStatements().get(i).unify(targetStatements.get(i), unifier);
  }
  if (unifier != null) {
    Inliner inliner = unifier.createInliner();
    try {
      return typecheck(
          unifier, inliner, new Warner(targetStatements.get(0)), expectedTypes(inliner),
          actualTypes(inliner));
    } catch (CouldNotResolveImportException e) {
      logger.log(FINE, "Failure to resolve import", e);
    }
  }
  return null;
}
项目:bazel    文件:TreePruner.java   
private static boolean delegatingConstructor(List<JCStatement> stats) {
  if (stats.isEmpty()) {
    return false;
  }
  JCStatement stat = stats.get(0);
  if (stat.getKind() != Kind.EXPRESSION_STATEMENT) {
    return false;
  }
  JCExpression expr = ((JCExpressionStatement) stat).getExpression();
  if (expr.getKind() != Kind.METHOD_INVOCATION) {
    return false;
  }
  JCExpression method = ((JCMethodInvocation) expr).getMethodSelect();
  Name name;
  switch (method.getKind()) {
    case IDENTIFIER:
      name = ((JCIdent) method).getName();
      break;
    case MEMBER_SELECT:
      name = ((JCFieldAccess) method).getIdentifier();
      break;
    default:
      return false;
  }
  return name.contentEquals("this") || name.contentEquals("super");
}
项目:lombok    文件:PrettyCommentsPrinter.java   
public void visitForLoop(JCForLoop tree) {
    try {
        print("for (");
        if (tree.init.nonEmpty()) {
            if (getTag(tree.init.head) == VARDEF) {
                printExpr(tree.init.head);
                for (List<JCStatement> l = tree.init.tail; l.nonEmpty(); l = l.tail) {
                    JCVariableDecl vdef = (JCVariableDecl)l.head;
                    print(", " + vdef.name + " = ");
                    printExpr(vdef.init);
                }
            } else {
                printExprs(tree.init);
            }
        }
        print("; ");
        if (tree.cond != null) printExpr(tree.cond);
        print("; ");
        printExprs(tree.step);
        print(") ");
        printStat(tree.body);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:lombok    文件:HandleEqualsAndHashCode.java   
private JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source) {
    /* public boolean canEqual(final java.lang.Object other) {
     *     return other instanceof Outer.Inner.MyType;
     * }
     */
    TreeMaker maker = typeNode.getTreeMaker();

    JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.<JCAnnotation>nil());
    JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
    Name canEqualName = typeNode.toName("canEqual");
    JCExpression objectType = chainDots(typeNode, "java", "lang", "Object");
    Name otherName = typeNode.toName("other");
    List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(Flags.FINAL), otherName, objectType, null));

    JCBlock body = maker.Block(0, List.<JCStatement>of(
            maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));

    return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source);
}
项目:incubator-netbeans    文件:CasualDiff.java   
private static boolean containsVariable(List<JCStatement> statements) {
    for (JCStatement s : statements) {
        if (s.getKind() == Kind.VARIABLE) {
            return true;
        }
    }

    return false;
}