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

项目:incubator-netbeans    文件:SuspiciousToArray.java   
private void rewriteNewArrayTree(WorkingCopy copy, TreeMaker mk, TreePath natPath, TypeMirror compType) {
    NewArrayTree nat = (NewArrayTree)natPath.getLeaf();
    TypeMirror existing = copy.getTrees().getTypeMirror(natPath);
    int existingDim = numberOfDimensions(existing);
    int newDim = numberOfDimensions(compType);

    if (existingDim == newDim + 1 /* newDim is counted from component type, lacks the enclosing array */) {
        // simple, number of dimensions does not change
        copy.rewrite(nat.getType(), mk.Type(compType));
        return;
    }
    List<ExpressionTree> l = new ArrayList<ExpressionTree>(nat.getDimensions().subList(
            0, Math.min(newDim + 1, nat.getDimensions().size())));
    Tree replacement = mk.NewArray(mk.Type(compType), l, null);
    GeneratorUtilities.get(copy).copyComments(nat, replacement, true);
    GeneratorUtilities.get(copy).copyComments(nat, replacement, false);

    copy.rewrite(nat, replacement);
}
项目:incubator-netbeans    文件:Utilities.java   
public static List<AnnotationTree> findArrayValue(AnnotationTree at, String name) {
    ExpressionTree fixesArray = findValue(at, name);
    List<AnnotationTree> fixes = new LinkedList<AnnotationTree>();

    if (fixesArray != null && fixesArray.getKind() == Kind.NEW_ARRAY) {
        NewArrayTree trees = (NewArrayTree) fixesArray;

        for (ExpressionTree fix : trees.getInitializers()) {
            if (fix.getKind() == Kind.ANNOTATION) {
                fixes.add((AnnotationTree) fix);
            }
        }
    }

    if (fixesArray != null && fixesArray.getKind() == Kind.ANNOTATION) {
        fixes.add((AnnotationTree) fixesArray);
    }

    return fixes;
}
项目: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;
}
项目:incubator-netbeans    文件:EvaluatorVisitor.java   
private ArrayType getArrayType(NewArrayTree arg0, Type type, int depth, EvaluationContext evaluationContext) {
    String arrayClassName;
    if (depth < BRACKETS.length()/2) {
        arrayClassName = type.name() + BRACKETS.substring(0, 2*depth);
    } else {
        arrayClassName = type.name() + BRACKETS;
        for (int i = BRACKETS.length()/2; i < depth; i++) {
            arrayClassName += "[]"; // NOI18N
        }
    }
    ReferenceType rt = getOrLoadClass(type.virtualMachine(), arrayClassName, evaluationContext);
    if (rt == null) {
        Assert.error(arg0, "unknownType", arrayClassName);
    }
    return (ArrayType) rt;
}
项目:javaide    文件:JavaInputAstVisitor.java   
static int rowLength(List<? extends ExpressionTree> row) {
    int size = 0;
    for (ExpressionTree tree : row) {
        if (tree.getKind() != NEW_ARRAY) {
            size++;
            continue;
        }
        NewArrayTree array = (NewArrayTree) tree;
        if (array.getInitializers() == null) {
            size++;
            continue;
        }
        size += rowLength(array.getInitializers());
    }
    return size;
}
项目:error-prone    文件:AnnotationHasArgumentWithValue.java   
@Override
public boolean matches(AnnotationTree annotationTree, VisitorState state) {
  ExpressionTree expressionTree = AnnotationMatcherUtils.getArgument(annotationTree, element);
  if (expressionTree == null) {
    return false;
  }

  expressionTree = ASTHelpers.stripParentheses(expressionTree);

  if (expressionTree instanceof NewArrayTree) {
    NewArrayTree arrayTree = (NewArrayTree) expressionTree;
    for (ExpressionTree elementTree : arrayTree.getInitializers()) {
      if (valueMatcher.matches(elementTree, state)) {
        return true;
      }
    }
    return false;
  }

  return valueMatcher.matches(expressionTree, state);
}
项目:checker-framework    文件:InternalUtils.java   
public final static List<? extends AnnotationMirror> annotationsFromArrayCreation(NewArrayTree node, int level) {

        assert node instanceof JCNewArray;
        final JCNewArray newArray = ((JCNewArray) node);

        if (level == -1) {
            return annotationsFromTypeAnnotationTrees(newArray.annotations);
        }

        if (newArray.dimAnnotations.length() > 0
                && (level >= 0)
                && (level < newArray.dimAnnotations.size()))
            return annotationsFromTypeAnnotationTrees(newArray.dimAnnotations.get(level));

        return Collections.emptyList();
    }
项目:checker-framework    文件:NullnessVisitor.java   
@Override
public Void visitNewArray(NewArrayTree node, Void p) {
    AnnotatedArrayType type = atypeFactory.getAnnotatedType(node);
    AnnotatedTypeMirror componentType = type.getComponentType();
    if (componentType.hasEffectiveAnnotation(NONNULL)
            && !isNewArrayAllZeroDims(node)
            && !isNewArrayInToArray(node)
            && !TypesUtils.isPrimitive(componentType.getUnderlyingType())
            && checker.getLintOption("arrays:forbidnonnullcomponents",
                    false)) {
        checker.report(
                Result.failure("new.array.type.invalid",
                        componentType.getAnnotations(), type.toString()),
                node);
    }

    return super.visitNewArray(node, p);
}
项目:checker-framework    文件:NullnessVisitor.java   
/**
 * Determine whether all dimensions given in a new array expression have
 * zero as length. For example "new Object[0][0];". Also true for empty
 * dimensions, as in "new Object[] {...}".
 */
private static boolean isNewArrayAllZeroDims(NewArrayTree node) {
    boolean isAllZeros = true;
    for (ExpressionTree dim : node.getDimensions()) {
        if (dim instanceof LiteralTree) {
            Object val = ((LiteralTree) dim).getValue();
            if (!(val instanceof Number) || !(new Integer(0).equals(val))) {
                isAllZeros = false;
                break;
            }
        } else {
            isAllZeros = false;
            break;
        }
    }
    return isAllZeros;
}
项目:checker-framework    文件:TypeFromTree.java   
private void annotateArrayAsArray(AnnotatedArrayType result, NewArrayTree node, AnnotatedTypeFactory f) {
    // Copy annotations from the type.
    AnnotatedTypeMirror treeElem = f.fromTypeTree(node.getType());
    boolean hasInit = node.getInitializers() != null;
    AnnotatedTypeMirror typeElem = descendBy(result,
            hasInit ? 1 : node.getDimensions().size());
    while (true) {
        typeElem.addAnnotations(treeElem.getAnnotations());
        if (!(treeElem instanceof AnnotatedArrayType)) break;
        assert typeElem instanceof AnnotatedArrayType;
        treeElem = ((AnnotatedArrayType)treeElem).getComponentType();
        typeElem = ((AnnotatedArrayType)typeElem).getComponentType();
    }
    // Add all dimension annotations.
    int idx = 0;
    AnnotatedTypeMirror level = result;
    while (level.getKind() == TypeKind.ARRAY) {
        AnnotatedArrayType array = (AnnotatedArrayType)level;
        List<? extends AnnotationMirror> annos = InternalUtils.annotationsFromArrayCreation(node, idx++);
        array.addAnnotations(annos);
        level = array.getComponentType();
    }

    // Add top-level annotations.
    result.addAnnotations(InternalUtils.annotationsFromArrayCreation(node, -1));
}
项目:bazel    文件:InternalUtils.java   
public static final List<? extends AnnotationMirror> annotationsFromArrayCreation(
        NewArrayTree node, int level) {

    assert node instanceof JCNewArray;
    final JCNewArray newArray = ((JCNewArray) node);

    if (level == -1) {
        return annotationsFromTypeAnnotationTrees(newArray.annotations);
    }

    if (newArray.dimAnnotations.length() > 0
            && (level >= 0)
            && (level < newArray.dimAnnotations.size()))
        return annotationsFromTypeAnnotationTrees(newArray.dimAnnotations.get(level));

    return Collections.emptyList();
}
项目:incubator-netbeans    文件:TreeDuplicator.java   
@Override
public Tree visitNewArray(NewArrayTree tree, Void p) {
    NewArrayTree n = make.NewArray(tree.getType(), tree.getDimensions(), tree.getInitializers());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
项目:incubator-netbeans    文件:CopyFinder.java   
public Boolean visitNewArray(NewArrayTree node, TreePath p) {
    if (p == null)
        return super.visitNewArray(node, p);

    NewArrayTree t = (NewArrayTree) p.getLeaf();

    if (!checkLists(node.getDimensions(), t.getDimensions(), p))
        return false;

    if (!checkLists(node.getInitializers(), t.getInitializers(), p))
        return false;

    return scan(node.getType(), t.getType(), p);
}
项目:incubator-netbeans    文件:ArraysTest.java   
public void test120768() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    byte[] test = new byte[10000];\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    byte[] test = new byte[WHAT_A_F];\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            VariableTree var = (VariableTree) clazz.getMembers().get(1);
            NewArrayTree nat = (NewArrayTree) var.getInitializer();
            workingCopy.rewrite(nat.getDimensions().get(0), make.Identifier("WHAT_A_F"));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ArraysTest.java   
public void test162485a() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Object test = new int[2];\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Object test = {{1}};\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            VariableTree var = (VariableTree) clazz.getMembers().get(1);
            NewArrayTree nat = (NewArrayTree) var.getInitializer();
            NewArrayTree dim2 = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.singletonList(make.Literal(Integer.valueOf(1))));
            NewArrayTree newTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.<ExpressionTree>singletonList(dim2));
            workingCopy.rewrite(nat, newTree);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:ArraysTest.java   
public void test162485b() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Object test = new int[] {};\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Object test = {{1}};\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            VariableTree var = (VariableTree) clazz.getMembers().get(1);
            NewArrayTree nat = (NewArrayTree) var.getInitializer();
            NewArrayTree dim2 = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.singletonList(make.Literal(Integer.valueOf(1))));
            NewArrayTree newTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.<ExpressionTree>singletonList(dim2));
            workingCopy.rewrite(nat, newTree);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:incubator-netbeans    文件:SemanticHighlighterBase.java   
@Override
public Void visitNewArray(NewArrayTree tree, EnumSet<UseTypes> d) {
    if (tree.getType() != null) {
        handlePossibleIdentifier(new TreePath(getCurrentPath(), tree.getType()), EnumSet.of(UseTypes.CLASS_USE));
    }

    scan(tree.getType(), null);
    scan(tree.getDimensions(), EnumSet.of(UseTypes.READ));
    scan(tree.getInitializers(), EnumSet.of(UseTypes.READ));

    return null;
}
项目:incubator-netbeans    文件:JavaFixUtilities.java   
@Override
public Number visitNewArray(NewArrayTree node, Void p) {
    List<? extends ExpressionTree> dimensions = (List<? extends ExpressionTree>) resolveMultiParameters(node.getDimensions());
    List<? extends ExpressionTree> initializers = (List<? extends ExpressionTree>) resolveMultiParameters(node.getInitializers());
    NewArrayTree nue = make.NewArray(node.getType(), dimensions, initializers);

    rewrite(node, nue);
    return super.visitNewArray(node, p);
}
项目:incubator-netbeans    文件:CreateElementUtilities.java   
private static List<? extends TypeMirror> computeNewArray(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    NewArrayTree nat = (NewArrayTree) parent.getLeaf();

    if (nat.getType() == error) {
        types.add(ElementKind.CLASS);
        types.add(ElementKind.ENUM);
        types.add(ElementKind.INTERFACE);

        return null;
    }

    for (Tree dimension : nat.getDimensions()) {
        if (dimension == error) {
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);

            return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
        }
    }

    for (Tree init : nat.getInitializers()) {
        if (init == error) {
            TypeMirror whole = info.getTrees().getTypeMirror(parent);

            if (whole == null || whole.getKind() != TypeKind.ARRAY)
                return null;

            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);

            return Collections.singletonList(((ArrayType) whole).getComponentType());
        }
    }

    return null;
}
项目:incubator-netbeans    文件:TreeNode.java   
@Override
public Void visitNewArray(NewArrayTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();

    addCorrespondingElement(below);
    addCorrespondingType(below);
    addCorrespondingComments(below);

    super.visitNewArray(tree, below);

    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
项目:incubator-netbeans    文件:Unbalanced.java   
@TriggerPattern(value="$mods$ $type[] $name = $init$;")
public static ErrorDescription after(HintContext ctx) {
    VariableElement var = testElement(ctx);

    if (var == null) return null;

    Tree parent = ctx.getPath().getParentPath().getLeaf();

    if (parent.getKind() == Kind.ENHANCED_FOR_LOOP
        && ((EnhancedForLoopTree) parent).getVariable() == ctx.getPath().getLeaf()) {
        return null;
    }

    TreePath init = ctx.getVariables().get("$init$");

    if (init != null) {
        boolean asWrite = true;

        if (init.getLeaf().getKind() == Kind.NEW_ARRAY) {
            NewArrayTree nat = (NewArrayTree) init.getLeaf();

            if (nat.getInitializers() == null || nat.getInitializers().isEmpty()) {
                asWrite = false;
            }
        }

        if (asWrite) {
            record(ctx.getInfo(), var, State.WRITE);
        }
    }

    return produceWarning(ctx, "ERR_UnbalancedArray");
}
项目:incubator-netbeans    文件:SuspiciousToArray.java   
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath path = ctx.getPath();
    TypeMirror compType = ctype.resolve(wc);
    if (compType == null) {
        return;
    }
    TreeMaker mk = wc.getTreeMaker();
    Tree l = path.getLeaf();
    if (l.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree)l;
        // if there are some initializers, we should probably rewrite the whole expression.
        if (nat.getInitializers() == null) {
            rewriteNewArrayTree(wc, mk, path, compType);
            return;
        }
    }
    // replace the entire tree
    TreePath colRef = null;
    if (colReference != null) {
        colRef = colReference.resolve(wc);
        if (colRef == null) {
            return;
        }
    }
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    Tree lc = gu.importComments(l, wc.getCompilationUnit());
    Tree newArrayTree = mk.NewArray(mk.Type(compType), Collections.<ExpressionTree>singletonList(
            mk.MethodInvocation(Collections.<ExpressionTree>emptyList(), 
                colRef == null ? mk.Identifier("size") :
                mk.MemberSelect((ExpressionTree)colRef.getLeaf(), "size"), // NOI18N
                Collections.<ExpressionTree>emptyList())),
            null);
    gu.copyComments(lc, newArrayTree, true);
    gu.copyComments(lc, newArrayTree, false);
    wc.rewrite(lc, newArrayTree);
}
项目:incubator-netbeans    文件:ReplaceBufferByString.java   
@Override
public Boolean visitNewArray(NewArrayTree node, Void p) {
    if (node.getInitializers() != null) {
        for (ExpressionTree et : node.getInitializers()) {
            if (scan(et, p) == Boolean.TRUE) {
                assignedToArray = true;
                break;
            }
        }
    }
    return false;
}
项目:incubator-netbeans    文件:CreateElementUtilities.java   
private static List<? extends TypeMirror> computeNewArray(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    NewArrayTree nat = (NewArrayTree) parent.getLeaf();

    if (nat.getType() == error) {
        types.add(ElementKind.CLASS);
        types.add(ElementKind.ENUM);
        types.add(ElementKind.INTERFACE);

        return null;
    }

    for (Tree dimension : nat.getDimensions()) {
        if (dimension == error) {
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);

            return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
        }
    }

    for (Tree init : nat.getInitializers()) {
        if (init == error) {
            TypeMirror whole = info.getTrees().getTypeMirror(parent);

            if (whole == null || whole.getKind() != TypeKind.ARRAY)
                return null;

            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);

            return Collections.singletonList(((ArrayType) whole).getComponentType());
        }
    }

    return null;
}
项目:incubator-netbeans    文件:ExpectedTypeResolver.java   
@Override
public List<? extends TypeMirror> visitNewArray(NewArrayTree node, Object p) {
    if (node.getDimensions() == null) {
        return null;
    }
    if (theExpression == null && node.getDimensions().size() == 1) {
        initExpression(node.getDimensions().get(0));
    } else if (!node.getDimensions().contains(theExpression.getLeaf())) {
        return null;
    }
    return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
}
项目:incubator-netbeans    文件:Move.java   
private ExpressionTree transformInitializer(ExpressionTree initializer, Tree type, TreeMaker make) {
    if(initializer.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree) initializer;
        if(nat.getType() == null) {
            if(type.getKind() == Tree.Kind.ARRAY_TYPE) {
                ArrayTypeTree arrayTypeTree = (ArrayTypeTree) type;
                type = arrayTypeTree.getType();
            }
            return make.NewArray(type, nat.getDimensions(), nat.getInitializers());
        }
    }
    return initializer;
}
项目:incubator-netbeans    文件:ComputeImports.java   
@Override
public Void visitNewArray(NewArrayTree node, Map<String, Object> p) {
    scan(node.getType(), p);
    scan(node.getDimensions(), new HashMap<String, Object>());
    scan(node.getInitializers(), new HashMap<String, Object>());
    return null;
}
项目:incubator-netbeans    文件:ExpressionScanner.java   
@Override
public List<Tree> visitNewArray(NewArrayTree node, ExpressionScanner.ExpressionsInfo p) {
    List<Tree> result = scan(node.getType(), p);
    result = reduce(result, scan(node.getDimensions(), p));
    result = reduce(result, scan(node.getInitializers(), p));
    return result;
}
项目:javaide    文件:JavaInputAstVisitor.java   
@Override
    public Void visitNewArray(NewArrayTree node, Void unused) {
        if (node.getType() != null) {
            builder.open(plusFour);
            token("new");
            builder.space();

            TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES);
            Tree base = extractedDims.node;

            Deque<ExpressionTree> dimExpressions = new ArrayDeque<>(node.getDimensions());

            Deque<List<AnnotationTree>> annotations = new ArrayDeque<>();
            // TODO: 22-Jul-17 missing method java8
//            annotations.add(ImmutableList.copyOf(node.getAnnotations()));
//            annotations.addAll((List<List<AnnotationTree>>) node.getDimAnnotations());
            annotations.addAll(extractedDims.dims);

            scan(base, null);
            builder.open(ZERO);
            maybeAddDims(dimExpressions, annotations);
            builder.close();
            builder.close();
        }
        if (node.getInitializers() != null) {
            if (node.getType() != null) {
                builder.space();
            }
            visitArrayInitializer(node.getInitializers());
        }
        return null;
    }
项目: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());
}
项目:annotation-tools    文件:NewScanner.java   
@Override
public Void visitNewArray(NewArrayTree node, Void p) {
    if (!done) {
        index++;
    }
    if (tree == node) {
        done = true;
    }
    return super.visitNewArray(node, p);
}
项目:refactor-faster    文件:UNewArray.java   
@Override
@Nullable
public Unifier visitNewArray(NewArrayTree newArray, @Nullable Unifier unifier) {
  unifier = Unifier.unifyNullable(unifier, getType(), newArray.getType());
  unifier = Unifier.unifyList(unifier, getDimensions(), newArray.getDimensions());

  boolean hasRepeated = getInitializers() != null 
      && Iterables.any(getInitializers(), Predicates.instanceOf(URepeated.class));
  return Unifier.unifyList(unifier, getInitializers(), newArray.getInitializers(), hasRepeated);
}
项目:generic-type-inference-solver    文件:DataflowInferenceTreeAnnotator.java   
@Override
public Void visitNewArray(final NewArrayTree newArrayTree, final AnnotatedTypeMirror atm) {
    TypeMirror tm = atm.getUnderlyingType();
    ((DataflowAnnotatedTypeFactory) this.realTypeFactory).getTypeNameMap().put(tm.toString(), tm);
    AnnotationMirror anno = DataflowUtils.genereateDataflowAnnoFromNewClass(atm,
            this.realTypeFactory.getProcessingEnv());
    replaceATM(atm, anno);
    return null;
}
项目:generic-type-inference-solver    文件:DataflowAnnotatedTypeFactory.java   
@Override
public Void visitNewArray(final NewArrayTree node, final AnnotatedTypeMirror type) {
    AnnotationMirror dataFlowType = DataflowUtils.genereateDataflowAnnoFromNewClass(type,
            processingEnv);
    TypeMirror tm = type.getUnderlyingType();
    typeNamesMap.put(tm.toString(), tm);
    type.replaceAnnotation(dataFlowType);
    return super.visitNewArray(node, type);
}
项目:error-prone    文件:SuggestedFixes.java   
/**
 * Returns a fix that appends {@code newValues} to the {@code parameterName} argument for {@code
 * annotation}, regardless of whether there is already an argument.
 *
 * <p>N.B.: {@code newValues} are source-code strings, not string literal values.
 */
public static Builder addValuesToAnnotationArgument(
    AnnotationTree annotation,
    String parameterName,
    Collection<String> newValues,
    VisitorState state) {
  if (annotation.getArguments().isEmpty()) {
    String parameterPrefix = parameterName.equals("value") ? "" : (parameterName + " = ");
    return SuggestedFix.builder()
        .replace(
            annotation,
            annotation
                .toString()
                .replaceFirst("\\(\\)", "(" + parameterPrefix + newArgument(newValues) + ")"));
  }
  Optional<ExpressionTree> maybeExistingArgument = findArgument(annotation, parameterName);
  if (!maybeExistingArgument.isPresent()) {
    return SuggestedFix.builder()
        .prefixWith(
            annotation.getArguments().get(0),
            parameterName + " = " + newArgument(newValues) + ", ");
  }

  ExpressionTree existingArgument = maybeExistingArgument.get();
  if (!existingArgument.getKind().equals(NEW_ARRAY)) {
    return SuggestedFix.builder()
        .replace(
            existingArgument, newArgument(state.getSourceForNode(existingArgument), newValues));
  }

  NewArrayTree newArray = (NewArrayTree) existingArgument;
  if (newArray.getInitializers().isEmpty()) {
    return SuggestedFix.builder().replace(newArray, newArgument(newValues));
  } else {
    return SuggestedFix.builder()
        .postfixWith(getLast(newArray.getInitializers()), ", " + Joiner.on(", ").join(newValues));
  }
}
项目:error-prone    文件:ErrorProneScanner.java   
@Override
public Void visitNewArray(NewArrayTree tree, VisitorState visitorState) {
  VisitorState state = visitorState.withPath(getCurrentPath());
  for (NewArrayTreeMatcher matcher : newArrayMatchers) {
    if (!isSuppressed(matcher, state)) {
      try {
        reportMatch(matcher.matchNewArray(tree, state), tree, state);
      } catch (Throwable t) {
        handleError(matcher, t);
      }
    }
  }
  return super.visitNewArray(tree, state);
}
项目:error-prone    文件:UTemplater.java   
@Override
public UNewArray visitNewArray(NewArrayTree tree, Void v) {
  return UNewArray.create(
      (UExpression) template(tree.getType()),
      templateExpressions(tree.getDimensions()),
      templateExpressions(tree.getInitializers()));
}
项目: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
@Nullable
public Choice<Unifier> visitNewArray(NewArrayTree newArray, @Nullable Unifier unifier) {
  boolean hasRepeated =
      getInitializers() != null
          && Iterables.any(getInitializers(), Predicates.instanceOf(URepeated.class));
  return unifyNullable(unifier, getType(), newArray.getType())
      .thenChoose(unifications(getDimensions(), newArray.getDimensions()))
      .thenChoose(unifications(getInitializers(), newArray.getInitializers(), hasRepeated));
}
项目:error-prone    文件:AbstractSuppressWarningsMatcher.java   
protected final Fix getSuggestedFix(AnnotationTree annotationTree) {
  List<String> values = new ArrayList<>();
  for (ExpressionTree argumentTree : annotationTree.getArguments()) {
    AssignmentTree assignmentTree = (AssignmentTree) argumentTree;
    if (assignmentTree.getVariable().toString().equals("value")) {
      ExpressionTree expressionTree = assignmentTree.getExpression();
      switch (expressionTree.getKind()) {
        case STRING_LITERAL:
          values.add(((String) ((JCTree.JCLiteral) expressionTree).value));
          break;
        case NEW_ARRAY:
          NewArrayTree newArrayTree = (NewArrayTree) expressionTree;
          for (ExpressionTree elementTree : newArrayTree.getInitializers()) {
            values.add((String) ((JCTree.JCLiteral) elementTree).value);
          }
          break;
        default:
          throw new AssertionError("Unknown kind: " + expressionTree.getKind());
      }
      processSuppressWarningsValues(values);
    } else {
      throw new AssertionError("SuppressWarnings has an element other than value=");
    }
  }

  if (values.isEmpty()) {
    return SuggestedFix.delete(annotationTree);
  } else if (values.size() == 1) {
    return SuggestedFix.replace(annotationTree, "@SuppressWarnings(\"" + values.get(0) + "\")");
  } else {
    return SuggestedFix.replace(
        annotationTree, "@SuppressWarnings({\"" + Joiner.on("\", \"").join(values) + "\"})");
  }
}