Java 类com.sun.source.tree.VariableTree 实例源码

项目:incubator-netbeans    文件:ProspectiveOperation.java   
List<ExpressionTree> getArguments() {
    VariableTree var;
    ExpressionTree lambda;
    Tree lambdaBody;
    if (this.correspondingTree.getKind() == Tree.Kind.BLOCK) {
        lambdaBody = this.correspondingTree;
    } else {
        if (this.opType == OperationType.FILTER || this.opType == OperationType.ANYMATCH || this.opType == OperationType.NONEMATCH) {
            lambdaBody = ((IfTree) this.correspondingTree).getCondition();
        } else if (this.opType == OperationType.MAP) {
            lambdaBody = getLambdaForMap();
        } else if (this.opType == OperationType.FOREACH) {
            lambdaBody = blockify(castToStatementTree(this.correspondingTree));
        } else //if(this.opType== OperationType.REDUCE)
        {
            return getArgumentsForReducer();
        }
    }
    var = getLambdaArguments();
    lambda = treeMaker.LambdaExpression(Arrays.asList(var), lambdaBody);
    List<ExpressionTree> args = new ArrayList<ExpressionTree>();

    args.add(lambda);
    return args;
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
/**
 * Creates a class constructor.
 *
 * @param clazz the class to create the constructor for
 * @param fields fields to be initialized by the constructor
 * @return the constructor
 * @since 0.20
 */
public MethodTree createConstructor(ClassTree clazz, Iterable<? extends VariableTree> fields) {
    assert clazz != null && fields != null;
    TreeMaker make = copy.getTreeMaker();
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    Set<Modifier> mods = EnumSet.of(copy.getTreeUtilities().isEnum(clazz) ? Modifier.PRIVATE : Modifier.PUBLIC);
    List<VariableTree> parameters = new ArrayList<VariableTree>();
    List<StatementTree> statements = new ArrayList<StatementTree>();
    ModifiersTree parameterModifiers = make.Modifiers(EnumSet.noneOf(Modifier.class));
    for (VariableTree vt : fields) {
        String paramName = addParamPrefixSuffix(removeFieldPrefixSuffix(vt, cs), cs);
        parameters.add(make.Variable(parameterModifiers, paramName, vt.getType(), null));
        statements.add(make.ExpressionStatement(make.Assignment(make.MemberSelect(make.Identifier("this"), vt.getName()), make.Identifier(paramName)))); //NOI18N
    }
    BlockTree body = make.Block(statements, false);
    return make.Method(make.Modifiers(mods), "<init>", null, Collections.<TypeParameterTree> emptyList(), parameters, Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
/**
 * Creates a getter method for a field.
 *
 * @param field field to create getter for
 * @return the getter method
 * @since 0.20
 */
public MethodTree createGetter(VariableTree field) {
    assert field != null;
    TreeMaker make = copy.getTreeMaker();
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().getFlags().contains(Modifier.STATIC);
    if (isStatic) {
        mods.add(Modifier.STATIC);
    }
    Tree type = field.getType();
    boolean isBoolean = type.getKind() == Tree.Kind.PRIMITIVE_TYPE && ((PrimitiveTypeTree) type).getPrimitiveTypeKind() == TypeKind.BOOLEAN;
    String getterName = CodeStyleUtils.computeGetterName(field.getName(), isBoolean, isStatic, cs);
    BlockTree body = make.Block(Collections.singletonList(make.Return(make.Identifier(field.getName()))), false);
    return make.Method(make.Modifiers(mods), getterName, type, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null);
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
/**
 * Creates a setter method for a field.
 *
 * @param clazz the class to create the setter within
 * @param field field to create setter for
 * @return the setter method
 * @since 0.20
 */
public MethodTree createSetter(ClassTree clazz, VariableTree field) {
    assert clazz != null && field != null;
    TreeMaker make = copy.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    boolean isStatic = field.getModifiers().getFlags().contains(Modifier.STATIC);
    if (isStatic)
        mods.add(Modifier.STATIC);
    CharSequence name = field.getName();
    assert name.length() > 0;
    CodeStyle cs = DiffContext.getCodeStyle(copy);
    String propName = removeFieldPrefixSuffix(field, cs);
    String setterName = CodeStyleUtils.computeSetterName(field.getName(), isStatic, cs);
    String paramName = addParamPrefixSuffix(propName, cs);
    List<VariableTree> params = Collections.singletonList(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), paramName, field.getType(), null));
    BlockTree body = make.Block(Collections.singletonList(make.ExpressionStatement(make.Assignment(make.MemberSelect(isStatic? make.Identifier(clazz.getSimpleName()) : make.Identifier("this"), name), make.Identifier(paramName)))), false); //NOI18N
    return make.Method(make.Modifiers(mods), setterName, make.Type(copy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), params, Collections.<ExpressionTree>emptyList(), body, null);
}
项目:incubator-netbeans    文件:TypeMirrorHandleTest.java   
public void testTypeMirrorHandleUnion() throws Exception {
    prepareTest();
    writeIntoFile(testSource, "package test; public class Test { void t() { try { throw new Exception(); } catch (java.io.IOException | javax.swing.text.BadLocationException e) { } } }");
    ClassPath empty = ClassPathSupport.createClassPath(new URL[0]);
    JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0])), empty, empty), testSource);

    js.runUserActionTask(new Task<CompilationController>() {

        public void run(final CompilationController info) throws Exception {
            info.toPhase(Phase.RESOLVED);
            new ErrorAwareTreePathScanner<Void, Void>() {
                @Override public Void visitVariable(VariableTree node, Void p) {
                    if (node.getName().contentEquals("e")) {
                        TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());

                        assertEquals(TypeKind.UNION, tm.getKind());

                        assertTrue(info.getTypes().isSameType(tm, TypeMirrorHandle.create(tm).resolve(info)));
                    }
                    return super.visitVariable(node, p);
                }
            }.scan(info.getCompilationUnit(), null);
        }
    }, true);
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.java   
/**
 */
@Override
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            createModifiersTree(ANN_TEST,
                                createModifierSet(PUBLIC),
                                workingCopy),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
项目:incubator-netbeans    文件:NCLOCVisitor.java   
@Override
public Object visitVariable(VariableTree node, Object p) {
    TreePath path = getCurrentPath();
    Tree parent = path.getParentPath().getLeaf();
    if (parent instanceof StatementTree) {
        boolean count = true;
        if (parent instanceof ForLoopTree) {
            count = !((ForLoopTree)parent).getInitializer().contains(node);
        } else if (parent instanceof EnhancedForLoopTree) {
            count = ((EnhancedForLoopTree)parent).getVariable() != node;
        }
        if (count) {
            statements++;
        }
    }
    return super.visitVariable(node, p);
}
项目:incubator-netbeans    文件:FieldTest1.java   
/**
 * Change whole initial value expression to literal 78.
 */
public void testFieldInitialValue() throws IOException {
    System.err.println("testFieldInitialValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueChanger".contentEquals(node.getName())) {
                    copy.rewrite(node.getInitializer(), make.Literal(Long.valueOf(78)));
                }
                return null;
            }
        }
    );
    assertFiles("testFieldInitialValue.pass");
}
项目:incubator-netbeans    文件:FieldTest1.java   
/**
 * copy the initialization 'new String("NetBeers")' to 'new String()'.
 * It tests only change in expression, no expression swap.
 */
public void testFieldChangeInInitValue() throws IOException {
    System.err.println("testFieldChangeInInitValue");
    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("initialValueReplacer".contentEquals(node.getName())) {
                    if (Tree.Kind.NEW_CLASS.equals(node.getInitializer().getKind())) {
                        NewClassTree nct = (NewClassTree) node.getInitializer();
                        NewClassTree njuNct = make.NewClass(
                                nct.getEnclosingExpression(), 
                                (List<ExpressionTree>) nct.getTypeArguments(),
                                nct.getIdentifier(),
                                Collections.singletonList(make.Literal("NetBeans")),
                                nct.getClassBody()
                        );
                        copy.rewrite(nct, njuNct);
                    }
                }
                return null;
            }
        }
    );
    assertFiles("testFieldChangeInInitValue.pass");
}
项目:incubator-netbeans    文件:FieldEncapsulation.java   
@Override
public ChangeInfo implement() throws Exception {
    final FileObject file = handle.getFileObject();
    final JTextComponent comp = EditorRegistry.lastFocusedComponent();
    if (file != null && file == getFileObject(comp)) {
        final int[] pos = new int[]{-1};
        JavaSource.forFileObject(file).runUserActionTask(new Task<CompilationController>(){
            @Override
            public void run(CompilationController info) throws Exception {
                info.toPhase(JavaSource.Phase.PARSED);
                final TreePath tp = handle.resolve(info);
                if (tp != null && tp.getLeaf().getKind() == Tree.Kind.VARIABLE) {
                    pos[0] = (int) info.getTrees().getSourcePositions().getEndPosition(
                            tp.getCompilationUnit(),
                            ((VariableTree)tp.getLeaf()).getType()) + 1;
                }
            }
        }, true);
        invokeRefactoring (comp, pos[0]);
    }
    return null;
}
项目:incubator-netbeans    文件:FindLocalUsagesQuery.java   
@Override
public Void visitVariable(VariableTree tree, Void d) {
    Element el = info.getTrees().getElement(getCurrentPath());
    if (toFind.equals(el)) {
        try {
            int[] span = treeUtils.findNameSpan(tree);
            if(span != null) {
                MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                usages.add(region);
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    if (el != null && el.getKind().isField()) {
        handleJavadoc(getCurrentPath());
    }
    return super.visitVariable(tree, d);
}
项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static List<VariableTree> getAllFields(JavaSource source) {
    final List<VariableTree> allFields = new ArrayList<VariableTree>();

    try {
        source.runUserActionTask(new AbstractTask<CompilationController>() {

            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement classElement = getTopLevelClassElement(controller);
                List<VariableElement> fields = ElementFilter.fieldsIn(classElement.getEnclosedElements());

                for (VariableElement field : fields) {
                    allFields.add((VariableTree) controller.getTrees().getTree(field));
                }
            }
        }, true);
    } catch (IOException ex) {
    }
    return allFields;
}
项目:incubator-netbeans    文件:RemoveInvalidModifier.java   
private ModifiersTree getModifierTree(TreePath treePath) {
    Kind kind = treePath.getLeaf().getKind();
    switch (kind) {
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            return ((ClassTree) treePath.getLeaf()).getModifiers();
        case VARIABLE:
            return ((VariableTree) treePath.getLeaf()).getModifiers();
        case METHOD:
            return ((MethodTree) treePath.getLeaf()).getModifiers();
        default:
            throw new UnsupportedOperationException("kind " + kind + " not yet suppported");
    }
}
项目:incubator-netbeans    文件:ConstantNameHint.java   
private static boolean checkZeroSizeArray(CompilationInfo info, TreePath val) {
    if (val.getLeaf().getKind() != Tree.Kind.VARIABLE) {
        return false;
    }
    VariableTree vt = (VariableTree)val.getLeaf();
    ExpressionTree xpr = vt.getInitializer();
    if (xpr == null) {
        return false;
    }
    if (xpr.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree)xpr;
        List<? extends ExpressionTree> dims = nat.getDimensions();
        if (dims != null && !dims.isEmpty()) {
            Object size = ArithmeticUtilities.compute(info, 
                    new TreePath(
                        new TreePath(val, xpr),
                        dims.get(dims.size() -1)), 
                    true);
            return ArithmeticUtilities.isRealValue(size) && Integer.valueOf(0).equals(size);
        } else {
            return nat.getInitializers() != null && nat.getInitializers().isEmpty();
        }
    }
    return false;
}
项目:affinechecker    文件:AffinePointerTransfer.java   
private Element elementOf(Node n) {
    Tree t = n.getTree();
    if (t instanceof ExpressionTree) {
        return TreeUtils.elementFromUse((ExpressionTree)t);
    } else if (t instanceof MethodInvocationTree) {
        return TreeUtils.elementFromUse((MethodInvocationTree)t);
    } else if (t instanceof NewClassTree) {
        return TreeUtils.elementFromUse((NewClassTree)t);
    } else if (t instanceof VariableTree) {
        return TreeUtils.elementFromDeclaration((VariableTree)t);
    } else if (t instanceof MethodTree) {
        return TreeUtils.elementFromDeclaration((MethodTree)t);
    } else if (t instanceof ClassTree) {
        return TreeUtils.elementFromDeclaration((ClassTree)t);
    } else {
        throw new RuntimeException("Unsupported tree type " + t.getClass());
    }
}
项目:incubator-netbeans    文件:GenerationUtils.java   
/**
 * Creates a new public property getter method.
 *
 * @param  modifiersTree the method modifiers; cannot be null.
 * @param  propertyType the property type; cannot be null.
 * @param  propertyName the property name; cannot be null.
 * @return the new method; never null.
 */
public MethodTree createPropertyGetterMethod(ModifiersTree modifiersTree, String propertyName, Tree propertyType) {
    Parameters.notNull("modifiersTree", modifiersTree); // NOI18N
    Parameters.javaIdentifier("propertyName", propertyName); // NOI18N
    Parameters.notNull("propertyType", propertyType); // NOI18N

    return getTreeMaker().Method(
            modifiersTree,
            createPropertyAccessorName(propertyName, true),
            propertyType,
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            Collections.<ExpressionTree>emptyList(),
            "{ return " + propertyName + "; }", // NOI18N
            null);
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
项目:incubator-netbeans    文件:JavaSourceHelper.java   
public static String createMethodSignature(MethodTree m, boolean skipName) {
    String sign = "";
    if (!skipName) {
        sign += m.getName();
    }
    sign += "(";
    if (m.getParameters() != null) {
        for (VariableTree p : m.getParameters()) {
            sign += getShortTypeName(p.getType()) + ",";
        }
        if (m.getParameters().size() > 0) {
            sign = sign.substring(0, sign.length() - 1);
        }
    }
    sign += ")";
    return sign;
}
项目:incubator-netbeans    文件:Common.java   
public static ClassTree getClassTree(
        TreeMaker make,
        WorkingCopy workingCopy,
        String name,
        String superClass,
        List<ExpressionTree> implementsList,
        Set<Modifier> modifiers) {        

    Tree extendsTree = make.QualIdent(workingCopy.getElements().getTypeElement(superClass));        
    Map<String,String> params = new HashMap<String, String>();
    params.put("param1", "String");
    MethodTree mt = Common.createMethod(make, "method", params);
    VariableTree vt = Common.createField(make, "variable", EnumSet.of(Modifier.PROTECTED), "double");
    List<Tree> members = new ArrayList<Tree>();
    members.add(mt);
    members.add(vt);
    members.add(make.Block(Collections.EMPTY_LIST, false));
    ClassTree innerClass = make.Class(
            make.Modifiers(modifiers),
            name,
            Collections.EMPTY_LIST,
            extendsTree,
            implementsList,
            members);        
    return innerClass;
}
项目:incubator-netbeans    文件:EntityManagerGenerationStrategySupport.java   
protected List<VariableTree> getParameterList(){
    if (getGenerationOptions().getParameterType() == null){
        return Collections.<VariableTree>emptyList();
    }
    VariableTree parameter = getTreeMaker().Variable(
            getTreeMaker().Modifiers(
            Collections.<Modifier>emptySet(),
            Collections.<AnnotationTree>emptyList()
            ),
            getGenerationOptions().getParameterName(),
            getGenUtils().createType(getGenerationOptions().getParameterType(), getClassElement()),
            null
            );
    return Collections.<VariableTree>singletonList(parameter);
}
项目:incubator-netbeans    文件:DeclarationForInstanceOf.java   
public ChangeInfo implement() throws Exception {
    js.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy wc) throws Exception {
            wc.toPhase(Phase.RESOLVED);

            TreePath ifTP = ifHandle.resolve(wc);
            TreePath resolvedExpression = expression.resolve(wc);
            TypeMirror resolvedType = type.resolve(wc);

            if (ifTP == null || resolvedType == null || resolvedExpression == null) {
                return ;
            }

            IfTree ift = (IfTree) ifTP.getLeaf();
            StatementTree then = ift.getThenStatement();

            if (then.getKind() == Kind.ERRONEOUS) {
                return ; //TODO.
            }

            List<StatementTree> statements = new LinkedList<StatementTree>();

            if (then.getKind() == Kind.BLOCK) {
                statements.addAll(((BlockTree) then).getStatements());
            } else {
                statements.add(then);
            }

            TreeMaker make = wc.getTreeMaker();
            VariableTree decl = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(resolvedType), make.TypeCast(make.Type(resolvedType), (ExpressionTree) resolvedExpression.getLeaf()));

            statements.add(0, decl);

            BlockTree nue = make.Block(statements, false);

            wc.rewrite(then, nue);
        }
    }).commit();
    return null;
}
项目:incubator-netbeans    文件:ConvertToLambdaPreconditionChecker.java   
@Override
public Tree visitVariable(VariableTree variableDeclTree, Trees trees) {

    //check for shadowed variable
    if (shadowsVariable(variableDeclTree.getName())) {
        foundShadowedVariable = true;
    }
    return super.visitVariable(variableDeclTree, trees);
}
项目:incubator-netbeans    文件:EntityManagerGenerationStrategySupport.java   
protected VariableTree createEntityManagerFactory(String name){
    return getTreeMaker().Variable(getTreeMaker().Modifiers(
            Collections.<Modifier>emptySet(), Collections.<AnnotationTree>emptyList()),
            name,
            getTypeTree(ENTITY_MANAGER_FACTORY_FQN),
            getTreeMaker().MethodInvocation(
            Collections.<ExpressionTree>emptyList(),
            getTreeMaker().MemberSelect(
            getTypeTree("javax.persistence.Persistence"), "createEntityManagerFactory"), // NOI18N
            Collections.<ExpressionTree>singletonList(getTreeMaker().Literal(getPersistenceUnitName()))
            )
            );
}
项目:incubator-netbeans    文件:JpaControllerUtil.java   
public static ClassTree addVariable(ClassTree classTree, WorkingCopy wc, String name, TypeInfo type, int modifiers, Object initializer, AnnotationInfo[] annotations) {
    Tree typeTree = createType(wc, type);
    ModifiersTree modTree = createModifiers(wc, modifiers, annotations);
    TreeMaker make = wc.getTreeMaker();
    VariableTree tree = make.Variable(modTree, name, typeTree, make.Literal(initializer));
    return make.addClassMember(classTree, tree);
}
项目:incubator-netbeans    文件:MethodArgumentsScanner.java   
@Override
public MethodArgument[] visitMethod(MethodTree node, Object p) {
    long startMethod = positions.getStartPosition(tree, node);
    long endMethod = positions.getEndPosition(tree, node);
    if (methodInvocation || startMethod == Diagnostic.NOPOS || endMethod == Diagnostic.NOPOS ||
                            !(offset >= lineMap.getLineNumber(startMethod) &&
                             (offset <= lineMap.getLineNumber(endMethod)))) {
        return super.visitMethod(node, p);
    }
    List<? extends VariableTree> args = node.getParameters();
    List<? extends TypeParameterTree> argTypes = node.getTypeParameters();
    int n = args.size();
    arguments = new MethodArgument[n];
    for (int i = 0; i < n; i++) {
        VariableTree var = args.get(i);
        long startOffset = positions.getStartPosition(tree, var);
        long endOffset = positions.getEndPosition(tree, var);
        if (startOffset == Diagnostic.NOPOS || endOffset == Diagnostic.NOPOS) {
            return new MethodArgument[] {};
        }
        arguments[i] = new MethodArgument(var.getName().toString(),
                                          var.getType().toString(),
                                          positionDelegate.createPosition(
                                            (int) startOffset,
                                            (int) lineMap.getLineNumber(startOffset),
                                            (int) lineMap.getColumnNumber(startOffset)),
                                          positionDelegate.createPosition(
                                            (int) endOffset,
                                            (int) lineMap.getLineNumber(endOffset),
                                            (int) lineMap.getColumnNumber(endOffset)));
    }
    return arguments;
    //return composeArguments(args, argTypes);
}
项目:incubator-netbeans    文件:ConvertToARM.java   
private static boolean splitVariablesClash(
        final Collection<? extends TreePath> statementsPaths,
        final Collection<? extends TreePath> tail,
        final Trees trees) {
    if (tail == null || tail.isEmpty()) return false;

    List<StatementTree> statements = new ArrayList<StatementTree>(statementsPaths.size());

    for (TreePath tp : statementsPaths) {
        statements.add((StatementTree) tp.getLeaf());
    }

    final Set<VariableTree> usedAfterCloseVarDecls = new HashSet<VariableTree>(findVarsUsages(
            findVariableDecls(statements, statementsPaths.isEmpty()? null : statementsPaths.iterator().next().getParentPath().getLeaf()),
            ConvertToARMFix.<StatementTree>asList(tail),
            tail.iterator().next().getCompilationUnit(),
            trees));

    final Set<String> usedAfterCloseVarNames = new HashSet<String>();

    for (VariableTree vt : usedAfterCloseVarDecls) {
        usedAfterCloseVarNames.add(vt.getName().toString());
    }

    ErrorAwareTreeScanner<Boolean, Void> scanner = new ErrorAwareTreeScanner<Boolean, Void>() {
        @Override public Boolean visitVariable(VariableTree node, Void p) {
            if (usedAfterCloseVarNames.contains(node.getName().toString()) && !usedAfterCloseVarDecls.contains(node)) {
                return true;
            }
            return super.visitVariable(node, p);
        }
        @Override public Boolean reduce(Boolean r1, Boolean r2) {
            return r1 == Boolean.TRUE || r2 == Boolean.TRUE;
        }
    };

    return scanner.scan(statements, null) == Boolean.TRUE;
}
项目:incubator-netbeans    文件:ConvertToLambdaConverter.java   
public static Tree methodInvocationToMemberReference(WorkingCopy copy, Tree tree, TreePath contextPath, List<? extends VariableTree> passedParameters, boolean addTypeCast) {
    if (tree.getKind() != Tree.Kind.METHOD_INVOCATION)
        return null;
    ExpressionTree ms = ((MethodInvocationTree)tree).getMethodSelect();
    Element e = copy.getTrees().getElement(new TreePath(contextPath, ms));
    if (e == null || e.getKind() != ElementKind.METHOD) {
        return null;
    }
    Name name = null;
    ExpressionTree expr = null;
    TreeMaker make = copy.getTreeMaker();

    if (ms.getKind() == Tree.Kind.IDENTIFIER) {
        name = ((IdentifierTree)ms).getName();
        expr = e.getModifiers().contains(Modifier.STATIC) ? 
                make.Identifier(e.getEnclosingElement()) :
                make.Identifier("this"); //NOI18N
    } else if (ms.getKind() == Tree.Kind.MEMBER_SELECT) {
        name = ((MemberSelectTree)ms).getIdentifier();
        if (passedParameters.size() == ((MethodInvocationTree)tree).getArguments().size()) {
            expr = ((MemberSelectTree)ms).getExpression();
        } else {
            expr = make.Identifier(e.getEnclosingElement());
        }
    }
    if (name == null || expr == null) {
        return null;
    }
    return possiblyCast(copy, 
            make.MemberReference(MemberReferenceTree.ReferenceMode.INVOKE, expr, name, Collections.<ExpressionTree>emptyList()),
            contextPath, addTypeCast
    );
}
项目:incubator-netbeans    文件:EntityMethodGenerator.java   
private String createEqualsLineForField(VariableTree field) {
    Name fieldName = field.getName();
    Tree fieldType = field.getType();
    if (fieldType.getKind() == Tree.Kind.PRIMITIVE_TYPE) {
        return "if (this." + fieldName + " != other." + fieldName + ") return false;"; // NOI18N
    }
    return "if ((this." + fieldName + " == null && other." + fieldName + " != null) || " + "(this." + fieldName +
            " != null && !this." + fieldName + ".equals(other." + fieldName + "))) return false;"; // NOI18N
}
项目:incubator-netbeans    文件:Utilities.java   
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) {
    HashSet<Element> refs = new HashSet<Element>();
    while(path != null) {
        switch(path.getLeaf().getKind()) {
            case BLOCK:
                if (path.getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION)
                    break;
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
                return refs;
            case VARIABLE:
                refs.add(trees.getElement(path));
                TreePath parent = path.getParentPath();
                if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) {
                    boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC);
                    for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) {
                        if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos &&
                                (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC)))
                            refs.add(trees.getElement(new TreePath(parent, member)));
                    }
                }
                return refs;
            case ENHANCED_FOR_LOOP:
                EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf();
                if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos)
                    refs.add(trees.getElement(new TreePath(path, efl.getVariable())));                        
        }
        path = path.getParentPath();
    }
    return refs;
}
项目:incubator-netbeans    文件:AddOrRemoveFinalModifier.java   
public ChangeInfo implement() throws IOException {
     JavaSource js = JavaSource.forFileObject(file);

     js.runModificationTask(new Task<WorkingCopy>() {
         public void run(WorkingCopy wc) throws IOException {
             wc.toPhase(Phase.RESOLVED);
             TreePath tp = variable.resolve(wc);

             if (tp == null) {
                 return;
             }

             VariableTree vt = (VariableTree) tp.getLeaf();
             ModifiersTree mt = vt.getModifiers();
             Set<Modifier> modifiers = EnumSet.noneOf(Modifier.class);

             modifiers.addAll(mt.getFlags());
             switch (type) {
                 case ADD:
modifiers.add(Modifier.FINAL);
                     break;
                 case REMOVE:
                     modifiers.remove(Modifier.FINAL);
                     break;
                 default:
                     throw new IllegalArgumentException("Type " + type + " not supported");
             }

             ModifiersTree newMod = wc.getTreeMaker().Modifiers(modifiers, mt.getAnnotations());

             wc.rewrite(mt, newMod);
         }
     }).commit();

     return null;
 }
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 * Makes a tree representing the given {@code VariableElement}.
 *
 * @param  paramElem  {@code VariableElement} to make a copy of
 * @param  maker  tree maker to use when for creation of the copy
 * @return  {@code Tree} respresenting the given {@code VariableElement}
 */
private static VariableTree makeCopy(VariableElement paramElem,
                                     TreeMaker maker) {
    return maker.Variable(
                maker.Modifiers(Collections.<Modifier>emptySet()),
                paramElem.getSimpleName(),
                maker.Type(paramElem.asType()),
                null);
}
项目:incubator-netbeans    文件:ConvertToARM.java   
private static VariableTree removeFinal(
        final WorkingCopy wc,
        final VariableTree varTree) {
    final ModifiersTree oldMods = varTree.getModifiers();
    if (oldMods != null && oldMods.getFlags().contains(Modifier.FINAL)) {
        final ModifiersTree newMods = wc.getTreeMaker().removeModifiersModifier(oldMods, Modifier.FINAL);
        rewriteCopyComments(wc, oldMods, newMods);
    }
    return varTree;
}
项目:incubator-netbeans    文件:IntroduceHint.java   
/**
 * Crates method formal parameters, following code style conventions.
 * The trees in 'statements' will be rewritten to use the new identifiers.
 * 
 * @param copy working copy
 * @param parameters variables to turn into parameters
 * @param statements trees that should refer to parameters
 * @return 
 */
static List<VariableTree> createVariables(WorkingCopy copy, List<VariableElement> parameters, 
        TreePath targetParent,
        List<TreePath> statements) {
    final TreeMaker make = copy.getTreeMaker();
    List<VariableTree> formalArguments = new LinkedList<VariableTree>();
    CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());

    String prefix = cs.getParameterNamePrefix();
    String suffix = cs.getParameterNameSuffix(); 
    Map<VariableElement, CharSequence> renamedVariables = new HashMap<VariableElement, CharSequence>();
    Set<Name> changedNames = new HashSet<Name>();
    for (VariableElement p : parameters) {
        TypeMirror tm = p.asType();
        Tree type = make.Type(tm);
        Name formalArgName = p.getSimpleName();
        Set<Modifier> formalArgMods = EnumSet.noneOf(Modifier.class);

        if (p.getModifiers().contains(Modifier.FINAL)) {
            formalArgMods.add(Modifier.FINAL);
        }
        String strippedName = Utilities.stripVariableName(cs, p);
        CharSequence codeStyleName = Utilities.guessName(copy, strippedName, targetParent, prefix, suffix, p.getKind() == ElementKind.PARAMETER);
        if (!formalArgName.contentEquals(codeStyleName)) {
            renamedVariables.put(p, codeStyleName);
            changedNames.add(formalArgName);
        } else {
            codeStyleName = formalArgName;
        }
        formalArguments.add(make.Variable(make.Modifiers(formalArgMods), codeStyleName, type, null));
    }
    if (!changedNames.isEmpty()) {
        VariableRenamer renamer = new VariableRenamer(copy, renamedVariables, changedNames);
        for (TreePath stPath : statements) {
            renamer.scan(stPath, null);
        }
    }
    return formalArguments;
}
项目:incubator-netbeans    文件:TestGenerator.java   
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 */
private MethodTree generateInitMethod(String methodName,
                                      String annotationClassName,
                                      boolean isStatic,
                                      WorkingCopy workingCopy) {
    Set<Modifier> methodModifiers
            = isStatic ? createModifierSet(PUBLIC, STATIC)
                       : Collections.<Modifier>singleton(PUBLIC);
    ModifiersTree modifiers = createModifiersTree(annotationClassName,
                                                  methodModifiers,
                                                  workingCopy);
    TreeMaker maker = workingCopy.getTreeMaker();
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>emptyList(),
            false);
    MethodTree method = maker.Method(
            modifiers,              // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
项目:incubator-netbeans    文件:Common.java   
public static MethodTree createMethod(TreeMaker make,String name, Map<String,String> params) {
    ModifiersTree methodModifiers = make.Modifiers(
            Collections.<Modifier>singleton(Modifier.PUBLIC),
            Collections.<AnnotationTree>emptyList()
            );
    List<VariableTree> paramList = new LinkedList<VariableTree>();
    for(String paramName: params.keySet()) {
        Tree paramType = getTreeForType(params.get(paramName), make);
        VariableTree parameter = make.Variable(
                make.Modifiers(
                Collections.<Modifier>emptySet(),
                Collections.<AnnotationTree>emptyList()
                ),
                paramName, // name
                paramType, // parameter type
                null // initializer - does not make sense in parameters.
                );
        paramList.add(parameter);
    }
    MethodTree newMethod = make.Method(
            methodModifiers, // public
            name, // name
            make.PrimitiveType(TypeKind.VOID), // return type "void"
            Collections.<TypeParameterTree>emptyList(), // type parameters - none
            paramList, // final ObjectOutput arg0
            Collections.<ExpressionTree>emptyList(), // throws
            "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", // body text
            null // default value - not applicable here, used by annotations
            );
    return newMethod;
}
项目:incubator-netbeans    文件:Field6Test.java   
public void testRemoveInitialValue() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "    int removeInitialValueField = null;\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "    int removeInitialValueField;\n" +
        "}\n";

    process(
        new Transformer<Void, Object>() {
            public Void visitVariable(VariableTree node, Object p) {
                super.visitVariable(node, p);
                if ("removeInitialValueField".contentEquals(node.getName())) {
                    VariableTree vt = make.Variable(
                            node.getModifiers(), 
                            node.getName(),
                            node.getType(),
                            null);
                    copy.rewrite(node, vt);
                }
                return null;
            }
        }
    );
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:Refactorer.java   
public Boolean isRefactorable() {
    prospectives = this.getListRepresentation(loop.getStatement(), true);
    if (prospectives != null && !prospectives.isEmpty()) {
        prospectives.get(prospectives.size() - 1).eagerize();
        if (this.untrasformable) {
            return false;
        }
        for ( int i = 0; i < prospectives.size() - 1; i++) {
            if (!prospectives.get(i).isLazy()) {
                return false;
            }
        }
        hasIterable = false;
        VariableTree var = loop.getVariable();
        TypeElement el = workingCopy.getElements().getTypeElement("java.lang.Iterable"); // NOI18N
        if (el != null) {
            TreePath path = TreePath.getPath(workingCopy.getCompilationUnit(), loop.getExpression());
            TypeMirror m = workingCopy.getTrees().getTypeMirror(path);
            Types types  = workingCopy.getTypes();
            hasIterable = 
                    types.isSubtype(
                        types.erasure(m),
                        types.erasure(el.asType())
                    );
        }
        prospectives = ProspectiveOperation.mergeIntoComposableOperations(prospectives);
        return prospectives != null;

    } else {
        return false;
    }

}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
private static void doMoveComments(WorkingCopy wc, Tree from,  Tree to, int offset, List<Comment> comments, int fromIdx, int toIdx) {
    if (comments.isEmpty()) {
        return;
    }
    TreeMaker tm = wc.getTreeMaker();
    Tree tree = from;
    switch (from.getKind()) {
        case METHOD:
            tree = tm.setLabel(from, ((MethodTree)from).getName());
            break;
        case VARIABLE:
            tree = tm.setLabel(from, ((VariableTree)from).getName());
            break;
        case BLOCK:
            tree = tm.Block(((BlockTree)from).getStatements(), ((BlockTree)from).isStatic());
            GeneratorUtilities gu = GeneratorUtilities.get(wc);
            gu.copyComments(from, tree, true);
            gu.copyComments(from, tree, false);
            break;
    }
    boolean before = (int)wc.getTrees().getSourcePositions().getStartPosition(wc.getCompilationUnit(), from) >= offset;
    if (fromIdx >=0 && toIdx >= 0 && toIdx - fromIdx > 0) {
        for (int i = toIdx - 1; i >= fromIdx; i--) {
            tm.removeComment(tree, i, before);
        }
    }
    wc.rewrite(from, tree);
    for (Comment comment : comments) {
        tm.addComment(to, comment, comment.pos() <= offset);
    }
}
项目:incubator-netbeans    文件:MultipleRewritesTest.java   
public void testRewriteRewrittenTree() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package hierbas.del.litoral;\n\n" +
            "public class Test {\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "public class Test {\n" +
            "\n" +
            "    @Deprecated\n" +
            "    public void taragui() {\n" +
            "    }\n" +
            "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC));
            MethodTree method = make.Method(mods, "taragui", make.Type(workingCopy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);

            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));

            ModifiersTree nueMods = make.Modifiers(EnumSet.of(Modifier.PUBLIC), Collections.singletonList(make.Annotation(make.QualIdent(workingCopy.getElements().getTypeElement("java.lang.Deprecated")), Collections.<ExpressionTree>emptyList())));

            workingCopy.rewrite(mods, nueMods);
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:LoggerGenerator.java   
private static VariableTree createLoggerField(TreeMaker make, ClassTree cls, CharSequence name, Set<Modifier> mods) {
    ModifiersTree modifiers = make.Modifiers(mods, Collections.<AnnotationTree>emptyList());
    final List<ExpressionTree> none = Collections.<ExpressionTree>emptyList();
    IdentifierTree className = make.Identifier(cls.getSimpleName());
    MemberSelectTree classType = make.MemberSelect(className, "class"); // NOI18N
    MemberSelectTree getName  = make.MemberSelect(classType, "getName"); // NOI18N
    MethodInvocationTree initClass = make.MethodInvocation(none, getName, none);
    final ExpressionTree logger = make.QualIdent(Logger.class.getName());
    MemberSelectTree getLogger = make.MemberSelect(logger, "getLogger"); // NOI18N
    MethodInvocationTree initField = make.MethodInvocation(none, getLogger, Collections.nCopies(1, initClass));
    return make.Variable(modifiers, name, logger, initField); // NOI18N
}