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

项目:lombok-ianchiu    文件:PrettyPrinter.java   
@Override public void visitAnnotation(JCAnnotation tree) {
    print("@");
    print(tree.annotationType);
    if (tree.args.isEmpty()) return;
    print("(");
    boolean done = false;
    if (tree.args.length() == 1 && tree.args.get(0) instanceof JCAssign) {
        JCAssign arg1 = (JCAssign) tree.args.get(0);
        JCIdent arg1Name = arg1.lhs instanceof JCIdent ? ((JCIdent) arg1.lhs) : null;
        if (arg1Name != null && arg1Name.name == name_value(arg1Name.name)) {
            print(arg1.rhs);
            done = true;
        }
    }
    if (!done) print(tree.args, ", ");
    print(")");
}
项目:EasyMPermission    文件:PrettyCommentsPrinter.java   
public void visitAnnotation(JCAnnotation tree) {
    try {
        print("@");
        printExpr(tree.annotationType);
        if (tree.args.nonEmpty()) {
            print("(");
            if (tree.args.length() == 1 && tree.args.get(0) instanceof JCAssign) {
                 JCExpression lhs = ((JCAssign)tree.args.get(0)).lhs;
                 if (lhs instanceof JCIdent && ((JCIdent)lhs).name.toString().equals("value")) tree.args = List.of(((JCAssign)tree.args.get(0)).rhs);
            }
            printExprs(tree.args);
            print(")");
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目: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();
}
项目:lombok    文件:PrettyCommentsPrinter.java   
public void visitAnnotation(JCAnnotation tree) {
    try {
        print("@");
        printExpr(tree.annotationType);
        if (tree.args.nonEmpty()) {
            print("(");
            if (tree.args.length() == 1 && tree.args.get(0) instanceof JCAssign) {
                 JCExpression lhs = ((JCAssign)tree.args.get(0)).lhs;
                 if (lhs instanceof JCIdent && ((JCIdent)lhs).name.toString().equals("value")) tree.args = List.of(((JCAssign)tree.args.get(0)).rhs);
            }
            printExprs(tree.args);
            print(")");
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:incubator-netbeans    文件:CasualDiff.java   
protected int diffAssign(JCAssign oldT, JCAssign newT, JCTree parent, int[] bounds) {
    int localPointer = bounds[0];
    // lhs
    int[] lhsBounds = getBounds(oldT.lhs);
    if (lhsBounds[0] < 0) {
        lhsBounds[0] = getOldPos(oldT.rhs);
        lhsBounds[1] = -1;
    }
    copyTo(localPointer, lhsBounds[0]);
    localPointer = diffTree(oldT.lhs, newT.lhs, lhsBounds);
    int[] rhsBounds = getCommentCorrectedBounds(oldT.rhs);

    //#174552: '=' may be missing if this is a synthetic annotation attribute assignment (of attribute name "value"):
    if (   oldT.lhs.getKind() == Kind.IDENTIFIER
        && newT.lhs.getKind() == Kind.IDENTIFIER
        && !((JCIdent) oldT.lhs).name.equals(((JCIdent) newT.lhs).name)) {
        tokenSequence.move(rhsBounds[0]);
        moveToSrcRelevant(tokenSequence, Direction.BACKWARD);
        if (tokenSequence.token().id() != JavaTokenId.EQ) {
            boolean spaceAroundAssignOps = (parent.getKind() == Kind.ANNOTATION || parent.getKind() == Kind.TYPE_ANNOTATION) ? diffContext.style.spaceAroundAnnotationValueAssignOps() : diffContext.style.spaceAroundAssignOps();
            if (spaceAroundAssignOps)
                printer.print(" = ");
            else
                printer.print("=");
            localPointer = lhsBounds[0];
        }
    }
    //#174552 end

    // rhs
    copyTo(localPointer, rhsBounds[0]);
    localPointer = diffTree(oldT.rhs, newT.rhs, rhsBounds);

    copyTo(localPointer, bounds[1]);
    return bounds[1];
}
项目:ghostwriter    文件:BlockBasedMutatedVariableCollector.java   
@Override
public void visitAssign(JCAssign assignment) {
    // super call comes first in order to ensure the correct sequence of valueChange triggers
    super.visitAssign(assignment);
    final JCTree.JCExpression assignmentVariable = assignment.getVariable();
    if (doesContainMutation(assignmentVariable)) {
        // for example in case of an array access we only need the array[index] combination instead of array[++index]
        // so we can pass it to the GW.valueChange hook without producing side effects and altering the original behaviour
        collect(extractAssignmentTarget(assignmentVariable));
    }
    else {
        collect(assignmentVariable);
    }
}
项目:lombok-ianchiu    文件:HandleCleanup.java   
public void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) {
    if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name);
    if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node,
            ((JCExpressionStatement)statement).expr, name);
    if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name);
    if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name);
    if (statement instanceof JCIdent) {
        if (((JCIdent)statement).name.contentEquals(name)) {
            JavacNode problemNode = node.getNodeFor(statement);
            if (problemNode != null) problemNode.addWarning(
            "You're assigning an auto-cleanup variable to something else. This is a bad idea.");
        }
    }
}
项目:javaparser2jctree    文件:PrintAstVisitor.java   
public void visitAssign(JCAssign that) {
    try {
        print("JCAssign:");
    } catch (Exception e) {
    }
    super.visitAssign(that);
}
项目:EasyMPermission    文件:PrettyCommentsPrinter.java   
public void visitAssign(JCAssign tree) {
    try {
        open(prec, TreeInfo.assignPrec);
        printExpr(tree.lhs, TreeInfo.assignPrec + 1);
        print(" = ");
        printExpr(tree.rhs, TreeInfo.assignPrec);
        close(prec, TreeInfo.assignPrec);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:EasyMPermission    文件:HandleCleanup.java   
public void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) {
    if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name);
    if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node,
            ((JCExpressionStatement)statement).expr, name);
    if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name);
    if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name);
    if (statement instanceof JCIdent) {
        if (((JCIdent)statement).name.contentEquals(name)) {
            JavacNode problemNode = node.getNodeFor(statement);
            if (problemNode != null) problemNode.addWarning(
            "You're assigning an auto-cleanup variable to something else. This is a bad idea.");
        }
    }
}
项目:genaroid    文件:ViewByIdPlugin.java   
@Override
public void process() {
    fieldsMap.clear();

    JavacElements utils = getEnvironment().getUtils();
    Symbol.ClassSymbol viewByIdType = utils.getTypeElement(ANNOTATION_CLASS_NAME);
    ViewWrapper viewWrapper = new ViewWrapper(utils);
    BindableWrapper bindableWrapper = new BindableWrapper(utils);

    Set<GField> allFields = getEnvironment().getGElementsAnnotatedWith(ViewById.class, GField.class);
    for (GField field : allFields) {
        JCTree.JCAnnotation annotation = field.extractAnnotation(viewByIdType);
        JCTree fieldType = field.getTree().getType();
        JCExpression value = annotation.getArguments().get(0);
        if (value instanceof JCAssign) {
            value = ((JCAssign) value).rhs;
        }
        if (!getEnvironment().getTypes().isSubtype(((Symbol.VarSymbol) field.getElement()).asType(), viewWrapper.getClassSymbol().asType())) {
            getEnvironment().getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "Annotation " + viewByIdType.getSimpleName() + " can be applied only to field with type extended of View",
                    field.getElement());
        }

        field.getGClass().implementInBestParent(bindableWrapper.getClassSymbol(), allFields);

        field.getGClass().overrideMethod(bindableWrapper.getBindMethod(), true)
                .prependCode("this.%s = (%s) $p0.findViewById(%s);", field.getName(), fieldType, value);
        field.getGClass().overrideMethod(bindableWrapper.getUnbindMethod(), true)
                .prependCode("this.%s = null;", field.getName());

        Map<String, GField> classFieldsMap = fieldsMap.get(field.getGClass());
        if (classFieldsMap == null) {
            classFieldsMap = new HashMap<>();
            fieldsMap.put(field.getGClass(), classFieldsMap);
        }
        classFieldsMap.put(value.toString(), field);
    }
}
项目:android-retrolambda-lombok    文件:JcTreeConverter.java   
@Override public void visitAssign(JCAssign node) {
    BinaryExpression expr = new BinaryExpression();
    expr.rawRight(toTree(node.getExpression()));
    expr.rawLeft(toTree(node.getVariable()));
    expr.astOperator(BinaryOperator.ASSIGN);
    set(node, expr);
}
项目:android-retrolambda-lombok    文件:JcTreeConverter.java   
@Override public void visitAnnotation(JCAnnotation node) {
    Annotation a = new Annotation();
    a.rawAnnotationTypeReference(toTree(node.getAnnotationType(), FlagKey.TYPE_REFERENCE));
    for (JCExpression elem : node.getArguments()) {
        AnnotationElement e = new AnnotationElement();
        if (elem instanceof JCAssign) {
            JCExpression rawName = ((JCAssign) elem).getVariable();
            if (rawName instanceof JCIdent) e.astName(setPos(rawName, new Identifier().astValue(((JCIdent)rawName).getName().toString())));
            elem = ((JCAssign) elem).getExpression();
        }
        e.rawValue(toTree(elem));
        a.astElements().addToEnd(e);
    }
    set(node, a);
}
项目:error-prone    文件:PlaceholderUnificationVisitor.java   
@Override
public Choice<State<JCAssign>> visitAssignment(final AssignmentTree node, State<?> state) {
  return chooseSubtrees(
          state,
          s -> unifyExpression(node.getVariable(), s),
          s -> unifyExpression(node.getExpression(), s),
          maker()::Assign)
      .condition(s -> !(s.result().getVariable() instanceof PlaceholderParamIdent));
}
项目:error-prone    文件:AbstractTestExceptionChecker.java   
/**
 * Searches the annotation list for {@code @Test(expected=...)}. If found, deletes the exception
 * attribute from the annotation, and returns its value.
 */
private static JCExpression deleteExpectedException(
    SuggestedFix.Builder fix, List<JCAnnotation> annotations, VisitorState state) {
  Type testAnnotation = state.getTypeFromString(JUnitMatchers.JUNIT4_TEST_ANNOTATION);
  for (JCAnnotation annotationTree : annotations) {
    if (!ASTHelpers.isSameType(testAnnotation, annotationTree.type, state)) {
      continue;
    }
    com.sun.tools.javac.util.List<JCExpression> arguments = annotationTree.getArguments();
    for (JCExpression arg : arguments) {
      if (!arg.hasTag(Tag.ASSIGN)) {
        continue;
      }
      JCAssign assign = (JCAssign) arg;
      if (assign.lhs.hasTag(Tag.IDENT)
          && ((JCIdent) assign.lhs).getName().contentEquals("expected")) {
        if (arguments.size() == 1) {
          fix.replace(annotationTree, "@Test");
        } else {
          removeFromList(fix, state, arguments, assign);
        }
        return assign.rhs;
      }
    }
  }
  return null;
}
项目:s4j    文件:Pretty.java   
public void visitAssign(JCAssign tree) {
    try {
        open(prec, TreeInfo.assignPrec);
        printExpr(tree.lhs, TreeInfo.assignPrec + 1);
        print(" = ");
        printExpr(tree.rhs, TreeInfo.assignPrec);
        close(prec, TreeInfo.assignPrec);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:s4j    文件:Attr.java   
public void visitAssign(JCAssign tree) {
    Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
    Type capturedType = capture(owntype);
    tree.rhs = SqlQueryNodeTransformer.getInstance()
            .transformPotentialSqlQuery(tree.rhs, env, owntype, this, enter, memberEnter);
    attribExpr(tree.rhs, env, owntype);
    result = check(tree, capturedType, VAL, pkind, pt);
}
项目:s4j    文件:Attr.java   
/** Check that variable is initialized and evaluate the variable's
         *  initializer, if not yet done. Also check that variable is not
         *  referenced before it is defined.
         *  @param tree    The tree making up the variable reference.
         *  @param env     The current environment.
         *  @param v       The variable's symbol.
         */
        private void checkInit(JCTree tree,
                               Env<AttrContext> env,
                               VarSymbol v,
                               boolean onlyWarning) {
//          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
//                             tree.pos + " " + v.pos + " " +
//                             Resolve.isStatic(env));//DEBUG

            // A forward reference is diagnosed if the declaration position
            // of the variable is greater than the current tree position
            // and the tree and variable definition occur in the same class
            // definition.  Note that writes don't count as references.
            // This check applies only to class and instance
            // variables.  Local variables follow different scope rules,
            // and are subject to definite assignment checking.
            if ((env.info.enclVar == v || v.pos > tree.pos) &&
                v.owner.kind == TYP &&
                canOwnInitializer(env.info.scope.owner) &&
                v.owner == env.info.scope.owner.enclClass() &&
                ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
                (env.tree.getTag() != JCTree.ASSIGN ||
                 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
                String suffix = (env.info.enclVar == v) ?
                                "self.ref" : "forward.ref";
                if (!onlyWarning || isStaticEnumField(v)) {
                    log.error(tree.pos(), "illegal." + suffix);
                } else if (useBeforeDeclarationWarning) {
                    log.warning(tree.pos(), suffix, v);
                }
            }

            v.getConstValue(); // ensure initializer is evaluated

            checkEnumInitializer(tree, env, v);
        }
项目:lombok    文件:PrettyCommentsPrinter.java   
public void visitAssign(JCAssign tree) {
    try {
        open(prec, TreeInfo.assignPrec);
        printExpr(tree.lhs, TreeInfo.assignPrec + 1);
        print(" = ");
        printExpr(tree.rhs, TreeInfo.assignPrec);
        close(prec, TreeInfo.assignPrec);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:lombok    文件:HandleCleanup.java   
private void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) {
    if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name);
    if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node,
            ((JCExpressionStatement)statement).expr, name);
    if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name);
    if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name);
    if (statement instanceof JCIdent) {
        if (((JCIdent)statement).name.contentEquals(name)) {
            JavacNode problemNode = node.getNodeFor(statement);
            if (problemNode != null) problemNode.addWarning(
            "You're assigning an auto-cleanup variable to something else. This is a bad idea.");
        }
    }
}
项目:incubator-netbeans    文件:CasualDiff.java   
private boolean matchAssign(JCAssign t1, JCAssign t2) {
    return treesMatch(t1.lhs, t2.lhs) && treesMatch(t1.rhs, t2.rhs);
}
项目:lombok-ianchiu    文件:JavacTreeMaker.java   
public JCAssign Assign(JCExpression lhs, JCExpression rhs) {
    return invoke(Assign, lhs, rhs);
}
项目:lombok-ianchiu    文件:PrettyPrinter.java   
@Override public void visitAssign(JCAssign tree) {
    print(tree.lhs);
    print(" = ");
    print(tree.rhs);
}
项目:lombok-ianchiu    文件:HandleSetter.java   
public static JCMethodDecl createSetter(long access, JavacNode field, JavacTreeMaker treeMaker, String setterName, boolean shouldReturnThis, JavacNode source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) {
    if (setterName == null) return null;

    JCVariableDecl fieldDecl = (JCVariableDecl) field.get();

    JCExpression fieldRef = createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD);
    JCAssign assign = treeMaker.Assign(fieldRef, treeMaker.Ident(fieldDecl.name));

    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    List<JCAnnotation> nonNulls = findAnnotations(field, NON_NULL_PATTERN);
    List<JCAnnotation> nullables = findAnnotations(field, NULLABLE_PATTERN);

    Name methodName = field.toName(setterName);
    List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables);

    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext());
    JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null);

    if (nonNulls.isEmpty()) {
        statements.append(treeMaker.Exec(assign));
    } else {
        JCStatement nullCheck = generateNullCheck(treeMaker, field, source);
        if (nullCheck != null) statements.append(nullCheck);
        statements.append(treeMaker.Exec(assign));
    }

    JCExpression methodType = 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;
    }

    if (shouldReturnThis) {
        JCReturn returnStatement = treeMaker.Return(treeMaker.Ident(field.toName("this")));
        statements.append(returnStatement);
    }

    JCBlock methodBody = treeMaker.Block(0, statements.toList());
    List<JCTypeParameter> methodGenericParams = List.nil();
    List<JCVariableDecl> parameters = List.of(param);
    List<JCExpression> throwsClauses = List.nil();
    JCExpression annotationMethodDefaultValue = null;

    List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
    if (isFieldDeprecated(field)) {
        annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
    }

    JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType,
            methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext());
    copyJavadoc(field, decl, CopyJavadoc.SETTER);
    return decl;
}
项目:lombok-ianchiu    文件:JavacHandlerUtil.java   
static List<JCAnnotation> unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode annotationNode) {
    ListBuffer<JCExpression> params = new ListBuffer<JCExpression>();
    ListBuffer<JCAnnotation> result = new ListBuffer<JCAnnotation>();

    try {
        for (JCExpression arg : ast.args) {
            String argName = "value";
            if (arg instanceof JCAssign) {
                JCAssign as = (JCAssign) arg;
                argName = as.lhs.toString();
            }
            if (!argName.equals(parameterName)) continue;
        }
    } catch (Exception ignore) {}

    outer:
    for (JCExpression param : ast.args) {
        String nameOfParam = "value";
        JCExpression valueOfParam = null;
        if (param instanceof JCAssign) {
            JCAssign assign = (JCAssign) param;
            if (assign.lhs instanceof JCIdent) {
                JCIdent ident = (JCIdent) assign.lhs;
                nameOfParam = ident.name.toString();
            }
            valueOfParam = assign.rhs;
        }

        if (!parameterName.equals(nameOfParam)) {
            params.append(param);
            continue outer;
        }

        int endPos = Javac.getEndPosition(param.pos(), (JCCompilationUnit) annotationNode.top().get());
        annotationNode.getAst().removeFromDeferredDiagnostics(param.pos, endPos);

        if (valueOfParam instanceof JCAnnotation) {
            String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString();
            dummyAnnotationName = dummyAnnotationName.replace("_", "").replace("$", "").replace("x", "").replace("X", "");
            if (dummyAnnotationName.length() > 0) {
                annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                continue outer;
            }
            for (JCExpression expr : ((JCAnnotation) valueOfParam).args) {
                if (expr instanceof JCAssign && ((JCAssign) expr).lhs instanceof JCIdent) {
                    JCIdent id = (JCIdent) ((JCAssign) expr).lhs;
                    if ("value".equals(id.name.toString())) {
                        expr = ((JCAssign) expr).rhs;
                    } else {
                        annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                        continue outer;
                    }
                }

                if (expr instanceof JCAnnotation) {
                    result.append((JCAnnotation) expr);
                } else if (expr instanceof JCNewArray) {
                    for (JCExpression expr2 : ((JCNewArray) expr).elems) {
                        if (expr2 instanceof JCAnnotation) {
                            result.append((JCAnnotation) expr2);
                        } else {
                            annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                            continue outer;
                        }
                    }
                } else {
                    annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                    continue outer;
                }
            }
        } else {
            if (valueOfParam instanceof JCNewArray && ((JCNewArray) valueOfParam).elems.isEmpty()) {
                // Then we just remove it and move on (it's onMethod={} for example).
            } else {
                annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
            }
        }
    }
    ast.args = params.toList();
    return result.toList();
}
项目:javaparser2jctree    文件:AJCAssign.java   
public AJCAssign(JCAssign ltree) {
    super(ltree.lhs, ltree.rhs);
}
项目:javaparser2jctree    文件:AJCAssign.java   
public AJCAssign(JCAssign ltree, String lcomment) {
    this(ltree);
    setComment(lcomment);
}
项目:EasyMPermission    文件:JavacTreeMaker.java   
public JCAssign Assign(JCExpression lhs, JCExpression rhs) {
    return invoke(Assign, lhs, rhs);
}
项目:EasyMPermission    文件:HandleSetter.java   
public static JCMethodDecl createSetter(long access, JavacNode field, JavacTreeMaker treeMaker, String setterName, boolean shouldReturnThis, JavacNode source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) {
    if (setterName == null) return null;

    JCVariableDecl fieldDecl = (JCVariableDecl) field.get();

    JCExpression fieldRef = createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD);
    JCAssign assign = treeMaker.Assign(fieldRef, treeMaker.Ident(fieldDecl.name));

    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    List<JCAnnotation> nonNulls = findAnnotations(field, NON_NULL_PATTERN);
    List<JCAnnotation> nullables = findAnnotations(field, NULLABLE_PATTERN);

    Name methodName = field.toName(setterName);
    List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables);

    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext());
    JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null);

    if (nonNulls.isEmpty()) {
        statements.append(treeMaker.Exec(assign));
    } else {
        JCStatement nullCheck = generateNullCheck(treeMaker, field, source);
        if (nullCheck != null) statements.append(nullCheck);
        statements.append(treeMaker.Exec(assign));
    }

    JCExpression methodType = 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;
    }

    if (shouldReturnThis) {
        JCReturn returnStatement = treeMaker.Return(treeMaker.Ident(field.toName("this")));
        statements.append(returnStatement);
    }

    JCBlock methodBody = treeMaker.Block(0, statements.toList());
    List<JCTypeParameter> methodGenericParams = List.nil();
    List<JCVariableDecl> parameters = List.of(param);
    List<JCExpression> throwsClauses = List.nil();
    JCExpression annotationMethodDefaultValue = null;

    List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
    if (isFieldDeprecated(field)) {
        annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
    }

    JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType,
            methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext());
    copyJavadoc(field, decl, CopyJavadoc.SETTER);
    return decl;
}
项目:EasyMPermission    文件:JavacHandlerUtil.java   
static List<JCAnnotation> unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode annotationNode) {
    ListBuffer<JCExpression> params = new ListBuffer<JCExpression>();
    ListBuffer<JCAnnotation> result = new ListBuffer<JCAnnotation>();

    try {
        for (JCExpression arg : ast.args) {
            String argName = "value";
            if (arg instanceof JCAssign) {
                JCAssign as = (JCAssign) arg;
                argName = as.lhs.toString();
            }
            if (!argName.equals(parameterName)) continue;
        }
    } catch (Exception ignore) {}

    outer:
    for (JCExpression param : ast.args) {
        String nameOfParam = "value";
        JCExpression valueOfParam = null;
        if (param instanceof JCAssign) {
            JCAssign assign = (JCAssign) param;
            if (assign.lhs instanceof JCIdent) {
                JCIdent ident = (JCIdent) assign.lhs;
                nameOfParam = ident.name.toString();
            }
            valueOfParam = assign.rhs;
        }

        if (!parameterName.equals(nameOfParam)) {
            params.append(param);
            continue outer;
        }

        int endPos = Javac.getEndPosition(param.pos(), (JCCompilationUnit) annotationNode.top().get());
        annotationNode.getAst().removeFromDeferredDiagnostics(param.pos, endPos);

        if (valueOfParam instanceof JCAnnotation) {
            String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString();
            dummyAnnotationName = dummyAnnotationName.replace("_", "").replace("$", "").replace("x", "").replace("X", "");
            if (dummyAnnotationName.length() > 0) {
                annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                continue outer;
            }
            for (JCExpression expr : ((JCAnnotation) valueOfParam).args) {
                if (expr instanceof JCAssign && ((JCAssign) expr).lhs instanceof JCIdent) {
                    JCIdent id = (JCIdent) ((JCAssign) expr).lhs;
                    if ("value".equals(id.name.toString())) {
                        expr = ((JCAssign) expr).rhs;
                    } else {
                        annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                        continue outer;
                    }
                }

                if (expr instanceof JCAnnotation) {
                    result.append((JCAnnotation) expr);
                } else if (expr instanceof JCNewArray) {
                    for (JCExpression expr2 : ((JCNewArray) expr).elems) {
                        if (expr2 instanceof JCAnnotation) {
                            result.append((JCAnnotation) expr2);
                        } else {
                            annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                            continue outer;
                        }
                    }
                } else {
                    annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
                    continue outer;
                }
            }
        } else {
            if (valueOfParam instanceof JCNewArray && ((JCNewArray) valueOfParam).elems.isEmpty()) {
                // Then we just remove it and move on (it's onMethod={} for example).
            } else {
                annotationNode.addError("The correct format is " + errorName + "@__({@SomeAnnotation, @SomeOtherAnnotation}))");
            }
        }
    }
    ast.args = params.toList();
    return result.toList();
}
项目:EasyMPermission    文件:Assign.java   
@Override
public JCAssign build() {
    return treeMaker.Assign(leftExpression, rightExpression);
}
项目:refactor-faster    文件:UAssign.java   
@Override
public JCAssign inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().Assign(getVariable().inline(inliner), getExpression().inline(inliner));
}
项目:refactor-faster    文件:ExpressionTemplate.java   
/**
 * Returns the precedence level appropriate for unambiguously printing
 * leaf as a subexpression of its parent.
 */
private static int getPrecedence(JCTree leaf, Context context) {
  JCCompilationUnit comp = context.get(JCCompilationUnit.class);
  JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);

  // In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
  //
  // TODO(mdempsky): There are probably cases where we could omit parentheses
  // by tweaking the returned precedence, but they need careful review.
  // For example, consider a template to replace "add(a, b)" with "a + b",
  // which applied to "x + add(y, z)" would result in "x + (y + z)".
  // In most cases, we'd likely prefer "x + y + z" instead, but those aren't
  // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
  // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
  // to integer promotion rules.

  if (parent instanceof JCConditional) {
    // This intentionally differs from Pretty, because Pretty appears buggy:
    // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
    JCConditional conditional = (JCConditional) parent;
    return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssign) {
    JCAssign assign = (JCAssign) parent;
    return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssignOp) {
    JCAssignOp assignOp = (JCAssignOp) parent;
    return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCUnary) {
    return TreeInfo.opPrec(parent.getTag());
  } else if (parent instanceof JCBinary) {
    JCBinary binary = (JCBinary) parent;
    return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCTypeCast) {
    JCTypeCast typeCast = (JCTypeCast) parent;
    return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCInstanceOf) {
    JCInstanceOf instanceOf = (JCInstanceOf) parent;
    return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
  } else if (parent instanceof JCArrayAccess) {
    JCArrayAccess arrayAccess = (JCArrayAccess) parent;
    return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCFieldAccess) {
    JCFieldAccess fieldAccess = (JCFieldAccess) parent;
    return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else {
    return TreeInfo.noPrec;
  }
}
项目:android-retrolambda-lombok    文件:JcTreePrinter.java   
@Override public void visitAssign(JCAssign tree) {
    printNode(tree);
    child("lhs", tree.lhs);
    child("rhs", tree.rhs);
    indent--;
}
项目:error-prone    文件:UAssign.java   
@Override
public JCAssign inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().Assign(getVariable().inline(inliner), getExpression().inline(inliner));
}
项目:error-prone    文件:ExpressionTemplate.java   
/**
 * Returns the precedence level appropriate for unambiguously printing leaf as a subexpression of
 * its parent.
 */
private static int getPrecedence(JCTree leaf, Context context) {
  JCCompilationUnit comp = context.get(JCCompilationUnit.class);
  JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);

  // In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
  //
  // TODO(mdempsky): There are probably cases where we could omit parentheses
  // by tweaking the returned precedence, but they need careful review.
  // For example, consider a template to replace "add(a, b)" with "a + b",
  // which applied to "x + add(y, z)" would result in "x + (y + z)".
  // In most cases, we'd likely prefer "x + y + z" instead, but those aren't
  // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
  // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
  // to integer promotion rules.

  if (parent instanceof JCConditional) {
    // This intentionally differs from Pretty, because Pretty appears buggy:
    // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
    JCConditional conditional = (JCConditional) parent;
    return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssign) {
    JCAssign assign = (JCAssign) parent;
    return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssignOp) {
    JCAssignOp assignOp = (JCAssignOp) parent;
    return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCUnary) {
    return TreeInfo.opPrec(parent.getTag());
  } else if (parent instanceof JCBinary) {
    JCBinary binary = (JCBinary) parent;
    return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCTypeCast) {
    JCTypeCast typeCast = (JCTypeCast) parent;
    return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCInstanceOf) {
    JCInstanceOf instanceOf = (JCInstanceOf) parent;
    return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
  } else if (parent instanceof JCArrayAccess) {
    JCArrayAccess arrayAccess = (JCArrayAccess) parent;
    return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCFieldAccess) {
    JCFieldAccess fieldAccess = (JCFieldAccess) parent;
    return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else {
    return TreeInfo.noPrec;
  }
}
项目:error-prone    文件:UseBinds.java   
private SuggestedFix.Builder convertMethodToBinds(MethodTree method, VisitorState state) {
  SuggestedFix.Builder fix = SuggestedFix.builder();

  JCModifiers modifiers = ((JCMethodDecl) method).getModifiers();
  ImmutableList.Builder<String> modifierStringsBuilder =
      ImmutableList.<String>builder().add("@Binds");

  for (JCAnnotation annotation : modifiers.annotations) {
    Name annotationQualifiedName = getSymbol(annotation).getQualifiedName();
    if (annotationQualifiedName.contentEquals(PROVIDES_CLASS_NAME)
        || annotationQualifiedName.contentEquals(PRODUCES_CLASS_NAME)) {
      List<JCExpression> arguments = annotation.getArguments();
      if (!arguments.isEmpty()) {
        JCExpression argument = Iterables.getOnlyElement(arguments);
        checkState(argument.getKind().equals(ASSIGNMENT));
        JCAssign assignment = (JCAssign) argument;
        checkState(getSymbol(assignment.getVariable()).getSimpleName().contentEquals("type"));
        String typeName = getSymbol(assignment.getExpression()).getSimpleName().toString();
        switch (typeName) {
          case "SET":
            modifierStringsBuilder.add("@IntoSet");
            fix.addImport(INTO_SET_CLASS_NAME);
            break;
          case "SET_VALUES":
            modifierStringsBuilder.add("@ElementsIntoSet");
            fix.addImport(ELEMENTS_INTO_SET_CLASS_NAME);
            break;
          case "MAP":
            modifierStringsBuilder.add("@IntoMap");
            fix.addImport(INTO_MAP_CLASS_NAME);
            break;
          default:
            throw new AssertionError("Unknown type name: " + typeName);
        }
      }
    } else {
      modifierStringsBuilder.add(state.getSourceForNode(annotation));
    }
  }

  EnumSet<Flag> methodFlags = Flags.asFlagSet(modifiers.flags);
  methodFlags.remove(Flags.Flag.STATIC);
  methodFlags.remove(Flags.Flag.FINAL);
  methodFlags.add(Flags.Flag.ABSTRACT);

  for (Flag flag : methodFlags) {
    modifierStringsBuilder.add(flag.toString());
  }

  fix.replace(modifiers, Joiner.on(' ').join(modifierStringsBuilder.build()));
  fix.replace(method.getBody(), ";");
  return fix;
}
项目:error-prone-aspirator    文件:ElementsCountedInLoop.java   
/**
 * @return identifier which is being incremented by constant one. Returns null if no such
 *         identifier is found.
 */
private IdentifierTree getIncrementedIdentifer(JCStatement statement) {
  if (statement == null) {
    return null;
  }
  if (statement.getKind() == Kind.EXPRESSION_STATEMENT) {
    Tree.Kind kind = ((JCExpressionStatement) statement).getExpression().getKind();
    if (kind == Kind.PREFIX_INCREMENT || kind == Kind.POSTFIX_INCREMENT) {
      JCUnary unary = (JCUnary) ((JCExpressionStatement) statement).getExpression();
      if (unary.arg.getKind() == Kind.IDENTIFIER) {
        return (IdentifierTree) unary.arg;
      }
      return null;
    } else if (kind == Kind.PLUS_ASSIGNMENT) {
      JCAssignOp assignOp = (JCAssignOp) ((JCExpressionStatement) statement).getExpression();
      if (assignOp.lhs.getKind() == Kind.IDENTIFIER && (isConstantOne(assignOp.rhs))) {
        return (IdentifierTree) assignOp.lhs;
      }
    } else if (kind == Kind.ASSIGNMENT) {
      JCAssign assign = (JCAssign) ((JCExpressionStatement) statement).getExpression();
      if (assign.lhs.getKind() == Kind.IDENTIFIER && assign.rhs.getKind() == Kind.PLUS) {
        JCBinary binary = (JCBinary) assign.rhs;
        if (binary.lhs.getKind() == Kind.IDENTIFIER) {
          if (((JCIdent) assign.lhs).sym == ((JCIdent) binary.lhs).sym) {
            if (isConstantOne(binary.rhs)) {
              return (IdentifierTree) binary.lhs;
            }
          }
        }
        if (binary.rhs.getKind() == Kind.IDENTIFIER) {
          if (((JCIdent) assign.lhs).sym == ((JCIdent) binary.rhs).sym) {
            if (isConstantOne(binary.lhs)) {
              return (IdentifierTree) binary.rhs;
            }
          }
        }
      }
    }
  }
  return null;
}
项目:Refaster    文件:UAssign.java   
@Override
public JCAssign inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().Assign(getVariable().inline(inliner), getExpression().inline(inliner));
}
项目:Refaster    文件:ExpressionTemplate.java   
/**
 * Returns the precedence level appropriate for unambiguously printing
 * leaf as a subexpression of its parent.
 */
private static int getPrecedence(JCTree leaf, Context context) {
  JCCompilationUnit comp = context.get(JCCompilationUnit.class);
  JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);

  // In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
  //
  // TODO(mdempsky): There are probably cases where we could omit parentheses
  // by tweaking the returned precedence, but they need careful review.
  // For example, consider a template to replace "add(a, b)" with "a + b",
  // which applied to "x + add(y, z)" would result in "x + (y + z)".
  // In most cases, we'd likely prefer "x + y + z" instead, but those aren't
  // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
  // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
  // to integer promotion rules.

  if (parent instanceof JCConditional) {
    // This intentionally differs from Pretty, because Pretty appears buggy:
    // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
    JCConditional conditional = (JCConditional) parent;
    return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssign) {
    JCAssign assign = (JCAssign) parent;
    return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssignOp) {
    JCAssignOp assignOp = (JCAssignOp) parent;
    return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCUnary) {
    return TreeInfo.opPrec(parent.getTag());
  } else if (parent instanceof JCBinary) {
    JCBinary binary = (JCBinary) parent;
    return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCTypeCast) {
    JCTypeCast typeCast = (JCTypeCast) parent;
    return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCInstanceOf) {
    JCInstanceOf instanceOf = (JCInstanceOf) parent;
    return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
  } else if (parent instanceof JCArrayAccess) {
    JCArrayAccess arrayAccess = (JCArrayAccess) parent;
    return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCFieldAccess) {
    JCFieldAccess fieldAccess = (JCFieldAccess) parent;
    return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else {
    return TreeInfo.noPrec;
  }
}