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

项目:openjdk-jdk10    文件:ArrayCreationTree.java   
public Void visitNewArray(NewArrayTree node, Void ignore) {
    // the Tree API hasn't been updated to expose annotations yet
    JCNewArray newArray = (JCNewArray)node;
    int totalLength = node.getDimensions().size()
                        + arrayLength(node.getType())
                        + ((newArray.getInitializers() != null) ? 1 : 0);
    testAnnotations(newArray.annotations, totalLength);
    int count = 0;
    for (List<? extends AnnotationTree> annos : newArray.dimAnnotations) {
        testAnnotations(annos, totalLength - count);
        count++;
    }
    return super.visitNewArray(node, ignore);
}
项目:openjdk9    文件:ArrayCreationTree.java   
public Void visitNewArray(NewArrayTree node, Void ignore) {
    // the Tree API hasn't been updated to expose annotations yet
    JCNewArray newArray = (JCNewArray)node;
    int totalLength = node.getDimensions().size()
                        + arrayLength(node.getType())
                        + ((newArray.getInitializers() != null) ? 1 : 0);
    testAnnotations(newArray.annotations, totalLength);
    int count = 0;
    for (List<? extends AnnotationTree> annos : newArray.dimAnnotations) {
        testAnnotations(annos, totalLength - count);
        count++;
    }
    return super.visitNewArray(node, ignore);
}
项目:lombok-ianchiu    文件:PrettyPrinter.java   
@Override public void visitNewArray(JCNewArray tree) {
    JCTree elem = tree.elemtype;
    int dims = 0;
    if (elem != null) {
        print("new ");

        while (elem instanceof JCArrayTypeTree) {
            dims++;
            elem = ((JCArrayTypeTree) elem).elemtype;
        }
        print(elem);

        for (JCExpression expr : tree.dims) {
            print("[");
            print(expr);
            print("]");
        }
    }

    for (int i = 0; i < dims; i++) print("[]");

    if (tree.elems != null) {
        if (elem != null) print("[] ");
        print("{");
        print(tree.elems, ", ");
        print("}");
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:ArrayCreationTree.java   
public Void visitNewArray(NewArrayTree node, Void ignore) {
    // the Tree API hasn't been updated to expose annotations yet
    JCNewArray newArray = (JCNewArray)node;
    int totalLength = node.getDimensions().size()
                        + arrayLength(node.getType())
                        + ((newArray.getInitializers() != null) ? 1 : 0);
    testAnnotations(newArray.annotations, totalLength);
    int count = 0;
    for (List<? extends AnnotationTree> annos : newArray.dimAnnotations) {
        testAnnotations(annos, totalLength - count);
        count++;
    }
    return super.visitNewArray(node, ignore);
}
项目:javaparser2jctree    文件:PrintAstVisitor.java   
public void visitNewArray(JCNewArray that) {
    try {
        print("JCNewArray:");
    } catch (Exception e) {
    }
    super.visitNewArray(that);
}
项目:jsr308-langtools    文件:ArrayCreationTree.java   
public Void visitNewArray(NewArrayTree node, Void ignore) {
    // the Tree API hasn't been updated to expose annotations yet
    JCNewArray newArray = (JCNewArray)node;
    int totalLength = node.getDimensions().size()
                        + arrayLength(node.getType())
                        + ((newArray.getInitializers() != null) ? 1 : 0);
    testAnnotations(newArray.annotations, totalLength);
    int count = 0;
    for (List<? extends AnnotationTree> annos : newArray.dimAnnotations) {
        testAnnotations(annos, totalLength - count);
        count++;
    }
    return super.visitNewArray(node, ignore);
}
项目:EasyMPermission    文件:PrettyCommentsPrinter.java   
public void visitNewArray(JCNewArray tree) {
    try {
        if (tree.elemtype != null) {
            print("new ");
            JCTree elem = tree.elemtype;
            if (elem instanceof JCArrayTypeTree)
                printBaseElementType((JCArrayTypeTree) elem);
            else
                printExpr(elem);
            for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
                print("[");
                printExpr(l.head);
                print("]");
            }
            if (elem instanceof JCArrayTypeTree)
                printBrackets((JCArrayTypeTree) elem);
        }
        if (tree.elems != null) {
            if (tree.elemtype != null) print("[]");
            print("{");
            printExprs(tree.elems);
            print("}");
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:annotation-tools    文件:TreeFinder.java   
private void addNewType(TreePath path, NewInsertion neu,
    NewArrayTree newArray) {
  DeclaredType baseType = neu.getBaseType();
  if (baseType.getName().isEmpty()) {
    List<String> annotations = neu.getType().getAnnotations();
    Type newType = Insertions.TypeTree.javacTypeToType(
        ((JCTree.JCNewArray) newArray).type);
    for (String ann : annotations) {
      newType.addAnnotation(ann);
    }
    neu.setType(newType);
  }
  Insertion.decorateType(neu.getInnerTypeInsertions(), neu.getType(),
      neu.getCriteria().getASTPath());
}
项目:refactor-faster    文件:UNewArray.java   
@Override
public JCNewArray inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().NewArray(
      (getType() == null) ? null : getType().inline(inliner),
      (getDimensions() == null) ? null :
          inliner.<JCExpression, UExpression>inlineList(getDimensions()),
      (getInitializers() == null) ? null :
          inliner.<JCExpression, UExpression>inlineList(getInitializers()));
}
项目:android-retrolambda-lombok    文件:JcTreePrinter.java   
@Override public void visitNewArray(JCNewArray tree) {
    printNode(tree);
    child("elemtype", tree.elemtype);
    children("dims", tree.dims);
    children("elems", tree.elems);
    indent--;
}
项目:infobip-open-jdk-8    文件:ArrayCreationTree.java   
public Void visitNewArray(NewArrayTree node, Void ignore) {
    // the Tree API hasn't been updated to expose annotations yet
    JCNewArray newArray = (JCNewArray)node;
    int totalLength = node.getDimensions().size()
                        + arrayLength(node.getType())
                        + ((newArray.getInitializers() != null) ? 1 : 0);
    testAnnotations(newArray.annotations, totalLength);
    int count = 0;
    for (List<? extends AnnotationTree> annos : newArray.dimAnnotations) {
        testAnnotations(annos, totalLength - count);
        count++;
    }
    return super.visitNewArray(node, ignore);
}
项目:error-prone    文件:PlaceholderUnificationVisitor.java   
@Override
public Choice<State<JCNewArray>> visitNewArray(final NewArrayTree node, State<?> state) {
  return chooseSubtrees(
      state,
      s -> unifyExpressions(node.getDimensions(), s),
      s -> unifyExpressions(node.getInitializers(), s),
      (dims, inits) -> maker().NewArray((JCExpression) node.getType(), dims, inits));
}
项目:error-prone    文件:UNewArray.java   
@Override
public JCNewArray inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner
      .maker()
      .NewArray(
          (getType() == null) ? null : getType().inline(inliner),
          (getDimensions() == null) ? null : inliner.<JCExpression>inlineList(getDimensions()),
          (getInitializers() == null)
              ? null
              : inliner.<JCExpression>inlineList(getInitializers()));
}
项目:OLD-OpenJDK8    文件:ArrayCreationTree.java   
public Void visitNewArray(NewArrayTree node, Void ignore) {
    // the Tree API hasn't been updated to expose annotations yet
    JCNewArray newArray = (JCNewArray)node;
    int totalLength = node.getDimensions().size()
                        + arrayLength(node.getType())
                        + ((newArray.getInitializers() != null) ? 1 : 0);
    testAnnotations(newArray.annotations, totalLength);
    int count = 0;
    for (List<? extends AnnotationTree> annos : newArray.dimAnnotations) {
        testAnnotations(annos, totalLength - count);
        count++;
    }
    return super.visitNewArray(node, ignore);
}
项目:s4j    文件:Pretty.java   
public void visitNewArray(JCNewArray tree) {
    try {
        if (tree.elemtype != null) {
            print("new ");
            JCTree elem = tree.elemtype;
            if (elem.getTag() == JCTree.TYPEARRAY)
                printBaseElementType((JCArrayTypeTree) elem);
            else
                printExpr(elem);
            for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
                print("[");
                printExpr(l.head);
                print("]");
            }
            if (elem instanceof JCArrayTypeTree)
                printBrackets((JCArrayTypeTree) elem);
        }
        if (tree.elems != null) {
            if (tree.elemtype != null) print("[]");
            print("{");
            printExprs(tree.elems);
            print("}");
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:checker-framework    文件:TreeDebug.java   
@Override
public Void visitNewArray(NewArrayTree node, Void p) {
    insert(((JCNewArray)node).annotations);
    insert("|");
    insert(((JCNewArray)node).dimAnnotations);
    return super.visitNewArray(node, p);
}
项目:Refaster    文件:UNewArray.java   
@Override
public JCNewArray inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().NewArray(
      (getType() == null) ? null : getType().inline(inliner),
      (getDimensions() == null) ? null :
          inliner.<JCExpression, UExpression>inlineList(getDimensions()),
      (getInitializers() == null) ? null :
          inliner.<JCExpression, UExpression>inlineList(getInitializers()));
}
项目:lombok    文件:PrettyCommentsPrinter.java   
public void visitNewArray(JCNewArray tree) {
    try {
        if (tree.elemtype != null) {
            print("new ");
            JCTree elem = tree.elemtype;
            if (elem instanceof JCArrayTypeTree)
                printBaseElementType((JCArrayTypeTree) elem);
            else
                printExpr(elem);
            for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
                print("[");
                printExpr(l.head);
                print("]");
            }
            if (elem instanceof JCArrayTypeTree)
                printBrackets((JCArrayTypeTree) elem);
        }
        if (tree.elems != null) {
            if (tree.elemtype != null) print("[]");
            print("{");
            printExprs(tree.elems);
            print("}");
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:incubator-netbeans    文件:CasualDiff.java   
protected int diffNewArray(JCNewArray oldT, JCNewArray newT, int[] bounds) {
        int localPointer = bounds[0];
        // elemtype
        if (newT.elemtype != null) {
            if (oldT.elemtype != null) {
                int[] elemtypeBounds = getBounds(oldT.elemtype);
                copyTo(localPointer, elemtypeBounds[0]);
                localPointer = diffTree(oldT.elemtype, newT.elemtype, elemtypeBounds);
            }
            if (!listsMatch(oldT.dims, newT.dims) && !newT.dims.isEmpty()) {
                // solved just for the change, not insert and delete
                for (com.sun.tools.javac.util.List<JCExpression> l1 = oldT.dims, l2 = newT.dims;
                    l1.nonEmpty(); l1 = l1.tail, l2 = l2.tail) {
                    int[] span = getBounds(l1.head);
                    copyTo(localPointer, span[0]);
                    localPointer = diffTree(l1.head, l2.head, span);
                }
            }
        } else if (oldT.elemtype != null) {
            //remove new <type><dimensions>
            copyTo(localPointer, getOldPos(oldT));
            if (oldT.elems != null) {
                localPointer = oldT.dims != null && !oldT.dims.isEmpty() ? endPos(oldT.dims) : endPos(oldT.elemtype);
                moveFwdToToken(tokenSequence, localPointer, JavaTokenId.LBRACE);
                localPointer = tokenSequence.offset();
            } else {
                localPointer = endPos(oldT);
            }
        }
        if (oldT.elems != null) {
            if (oldT.elems.head != null) {
                copyTo(localPointer, getOldPos(oldT.elems.head));
                localPointer = diffParameterList(oldT.elems, newT.elems, null, getOldPos(oldT.elems.head), Measure.ARGUMENT);
            } else if (newT.elems != null && !newT.elems.isEmpty()) {
                //empty initializer array, adding the first element to it
                //find {:
                moveFwdToToken(tokenSequence, localPointer, JavaTokenId.LBRACE);
                tokenSequence.moveNext();
                copyTo(localPointer, localPointer = tokenSequence.offset());
                localPointer = diffParameterList(oldT.elems, newT.elems, null, localPointer, Measure.ARGUMENT);
            }
        } else if (newT.elems != null && !newT.elems.isEmpty()) {
            //empty initializer array, adding the first element to it
            //find {:
            if (newT.elemtype != null) printer.print("[]");
            printer.print("{");
            localPointer = diffParameterList(Collections.<JCTree>emptyList(), newT.elems, null, localPointer, Measure.ARGUMENT);
            printer.print("}");
            moveFwdToToken(tokenSequence, localPointer, JavaTokenId.SEMICOLON);
            tokenSequence.moveNext();
            localPointer = bounds[1];
//            copyTo(localPointer, localPointer = tokenSequence.offset());
        }
        copyTo(localPointer, bounds[1]);
        return bounds[1];
    }
项目:incubator-netbeans    文件:CasualDiff.java   
private boolean matchNewArray(JCNewArray t1, JCNewArray t2) {
    return treesMatch(t1.elemtype, t2.elemtype) &&
           listsMatch(t1.dims, t2.dims) && listsMatch(t1.elems, t2.elems);
}
项目:lombok-ianchiu    文件:JavacTreeMaker.java   
public JCNewArray NewArray(JCExpression elemtype, List<JCExpression> dims, List<JCExpression> elems) {
    return invoke(NewArray, elemtype, dims, elems);
}
项目: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();
}
项目:lombok-ianchiu    文件:HandleSynchronized.java   
@Override public void handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized");

    if (inNetbeansEditor(annotationNode)) return;

    deleteAnnotationIfNeccessary(annotationNode, Synchronized.class);
    JavacNode methodNode = annotationNode.up();

    if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) {
        annotationNode.addError("@Synchronized is legal only on methods.");

        return;
    }

    JCMethodDecl method = (JCMethodDecl)methodNode.get();

    if ((method.mods.flags & Flags.ABSTRACT) != 0) {
        annotationNode.addError("@Synchronized is legal only on concrete methods.");

        return;
    }
    boolean isStatic = (method.mods.flags & Flags.STATIC) != 0;
    String lockName = annotation.getInstance().value();
    boolean autoMake = false;
    if (lockName.length() == 0) {
        autoMake = true;
        lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME;
    }

    JavacTreeMaker maker = methodNode.getTreeMaker().at(ast.pos);
    Context context = methodNode.getContext();

    if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) {
        if (!autoMake) {
            annotationNode.addError("The field " + lockName + " does not exist.");
            return;
        }
        JCExpression objectType = genJavaLangTypeRef(methodNode, ast.pos, "Object");
        //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
        JCNewArray newObjectArray = maker.NewArray(genJavaLangTypeRef(methodNode, ast.pos, "Object"),
                List.<JCExpression>of(maker.Literal(CTC_INT, 0)), null);
        JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(
                maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)),
                methodNode.toName(lockName), objectType, newObjectArray), ast, context);
        injectFieldAndMarkGenerated(methodNode.up(), fieldDecl);
    }

    if (method.body == null) return;

    JCExpression lockNode;
    if (isStatic) {
        lockNode = chainDots(methodNode, ast.pos, methodNode.up().getName(), lockName);
    } else {
        lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName));
    }

    recursiveSetGeneratedBy(lockNode, ast, context);
    method.body = setGeneratedBy(maker.Block(0, List.<JCStatement>of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast, context))), ast, context);

    methodNode.rebuild();
}
项目:javaparser2jctree    文件:AJCNewArray.java   
public AJCNewArray(JCNewArray ltree) {
    super(ltree.elemtype, ltree.dims, ltree.elems);
}
项目:javaparser2jctree    文件:AJCNewArray.java   
public AJCNewArray(JCNewArray ltree, String lcomment) {
    this(ltree);
    setComment(lcomment);
}
项目:EasyMPermission    文件:JavacTreeMaker.java   
public JCNewArray NewArray(JCExpression elemtype, List<JCExpression> dims, List<JCExpression> elems) {
    return invoke(NewArray, elemtype, dims, elems);
}
项目: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    文件:HandleSynchronized.java   
@Override public void handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized");

    if (inNetbeansEditor(annotationNode)) return;

    deleteAnnotationIfNeccessary(annotationNode, Synchronized.class);
    JavacNode methodNode = annotationNode.up();

    if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) {
        annotationNode.addError("@Synchronized is legal only on methods.");

        return;
    }

    JCMethodDecl method = (JCMethodDecl)methodNode.get();

    if ((method.mods.flags & Flags.ABSTRACT) != 0) {
        annotationNode.addError("@Synchronized is legal only on concrete methods.");

        return;
    }
    boolean isStatic = (method.mods.flags & Flags.STATIC) != 0;
    String lockName = annotation.getInstance().value();
    boolean autoMake = false;
    if (lockName.length() == 0) {
        autoMake = true;
        lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME;
    }

    JavacTreeMaker maker = methodNode.getTreeMaker().at(ast.pos);
    Context context = methodNode.getContext();

    if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) {
        if (!autoMake) {
            annotationNode.addError("The field " + lockName + " does not exist.");
            return;
        }
        JCExpression objectType = genJavaLangTypeRef(methodNode, ast.pos, "Object");
        //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
        JCNewArray newObjectArray = maker.NewArray(genJavaLangTypeRef(methodNode, ast.pos, "Object"),
                List.<JCExpression>of(maker.Literal(CTC_INT, 0)), null);
        JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(
                maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)),
                methodNode.toName(lockName), objectType, newObjectArray), ast, context);
        injectFieldAndMarkGenerated(methodNode.up(), fieldDecl);
    }

    if (method.body == null) return;

    JCExpression lockNode;
    if (isStatic) {
        lockNode = chainDots(methodNode, ast.pos, methodNode.up().getName(), lockName);
    } else {
        lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName));
    }

    recursiveSetGeneratedBy(lockNode, ast, context);
    method.body = setGeneratedBy(maker.Block(0, List.<JCStatement>of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast, context))), ast, context);

    methodNode.rebuild();
}
项目:lombok    文件:JavacHandlerUtil.java   
static List<JCAnnotation> unboxAndRemoveAnnotationParameter(JCAnnotation ast, String parameterName, String errorName, JavacNode errorNode) {
    ListBuffer<JCExpression> params = ListBuffer.lb();
    ListBuffer<JCAnnotation> result = ListBuffer.lb();

    errorNode.removeDeferredErrors();

    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;
        }

        if (valueOfParam instanceof JCAnnotation) {
            String dummyAnnotationName = ((JCAnnotation) valueOfParam).annotationType.toString();
            dummyAnnotationName = dummyAnnotationName.replace("_", "");
            if (dummyAnnotationName.length() > 0) {
                errorNode.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 {
                        errorNode.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 {
                            errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))");
                            continue outer;
                        }
                    }
                } else {
                    errorNode.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 {
                errorNode.addError("The correct format is " + errorName + "@_({@SomeAnnotation, @SomeOtherAnnotation}))");
            }
        }
    }
    ast.args = params.toList();
    return result.toList();
}
项目:lombok    文件:HandleSynchronized.java   
@Override public void handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, JavacNode annotationNode) {
    if (inNetbeansEditor(annotationNode)) return;

    deleteAnnotationIfNeccessary(annotationNode, Synchronized.class);
    JavacNode methodNode = annotationNode.up();

    if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) {
        annotationNode.addError("@Synchronized is legal only on methods.");

        return;
    }

    JCMethodDecl method = (JCMethodDecl)methodNode.get();

    if ((method.mods.flags & Flags.ABSTRACT) != 0) {
        annotationNode.addError("@Synchronized is legal only on concrete methods.");

        return;
    }
    boolean isStatic = (method.mods.flags & Flags.STATIC) != 0;
    String lockName = annotation.getInstance().value();
    boolean autoMake = false;
    if (lockName.length() == 0) {
        autoMake = true;
        lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME;
    }

    TreeMaker maker = methodNode.getTreeMaker().at(ast.pos);

    if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) {
        if (!autoMake) {
            annotationNode.addError("The field " + lockName + " does not exist.");
            return;
        }
        JCExpression objectType = chainDots(methodNode, ast.pos, "java", "lang", "Object");
        //We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
        JCNewArray newObjectArray = maker.NewArray(chainDots(methodNode, ast.pos, "java", "lang", "Object"),
                List.<JCExpression>of(maker.Literal(CTC_INT, 0)), null);
        JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(
                maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)),
                methodNode.toName(lockName), objectType, newObjectArray), ast);
        injectFieldSuppressWarnings(methodNode.up(), fieldDecl);
    }

    if (method.body == null) return;

    JCExpression lockNode;
    if (isStatic) {
        lockNode = chainDots(methodNode, ast.pos, methodNode.up().getName(), lockName);
    } else {
        lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName));
    }

    recursiveSetGeneratedBy(lockNode, ast);
    method.body = setGeneratedBy(maker.Block(0, List.<JCStatement>of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast))), ast);

    methodNode.rebuild();
}