com.sun.tools.javac.tree.JCTree.JCNewArray Java Examples

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCNewArray. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
boolean validateTargetAnnotationValue(JCAnnotation a) {
    // special case: java.lang.annotation.Target must not have
    // repeated values in its value member
    if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
            a.args.tail == null)
        return true;

    boolean isValid = true;
    if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
    JCAssign assign = (JCAssign) a.args.head;
    Symbol m = TreeInfo.symbol(assign.lhs);
    if (m.name != names.value) return false;
    JCTree rhs = assign.rhs;
    if (!rhs.hasTag(NEWARRAY)) return false;
    JCNewArray na = (JCNewArray) rhs;
    Set<Symbol> targets = new HashSet<>();
    for (JCTree elem : na.elems) {
        if (!targets.add(TreeInfo.symbol(elem))) {
            isValid = false;
            log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
        }
    }
    return isValid;
}
 
Example #2
Source File: Annotate.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Attribute getAnnotationArrayValue(Type expectedElementType, JCExpression tree, Env<AttrContext> env) {
    // Special case, implicit array
    if (!tree.hasTag(NEWARRAY)) {
        tree = make.at(tree.pos).
                NewArray(null, List.nil(), List.of(tree));
    }

    JCNewArray na = (JCNewArray)tree;
    if (na.elemtype != null) {
        log.error(na.elemtype.pos(), Errors.NewNotAllowedInAnnotation);
    }
    ListBuffer<Attribute> buf = new ListBuffer<>();
    for (List<JCExpression> l = na.elems; l.nonEmpty(); l=l.tail) {
        buf.append(attributeAnnotationValue(types.elemtype(expectedElementType),
                l.head,
                env));
    }
    na.type = expectedElementType;
    return new Attribute.
            Array(expectedElementType, buf.toArray(new Attribute[buf.length()]));
}
 
Example #3
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Lambda body to use for a 'new'.
 */
private JCExpression expressionNew() {
    if (tree.kind == ReferenceKind.ARRAY_CTOR) {
        //create the array creation expression
        JCNewArray newArr = make.NewArray(
                make.Type(types.elemtype(tree.getQualifierExpression().type)),
                List.of(make.Ident(params.first())),
                null);
        newArr.type = tree.getQualifierExpression().type;
        return newArr;
    } else {
        //create the instance creation expression
        //note that method reference syntax does not allow an explicit
        //enclosing class (so the enclosing class is null)
        JCNewClass newClass = make.NewClass(null,
                List.nil(),
                make.Type(tree.getQualifierExpression().type),
                convertArgs(tree.sym, args.toList(), tree.varargsElement),
                null);
        newClass.constructor = tree.sym;
        newClass.constructorType = tree.sym.erasure(types);
        newClass.type = tree.getQualifierExpression().type;
        setVarargsIfNeeded(newClass, tree.varargsElement);
        return newClass;
    }
}
 
Example #4
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private NewArray convertNewArray(JCNewArray expression) {
  ArrayTypeDescriptor typeDescriptor =
      environment.createTypeDescriptor(expression.type, ArrayTypeDescriptor.class);

  List<Expression> dimensionExpressions = convertExpressions(expression.getDimensions());
  // If some dimensions are not initialized then make that explicit.
  while (dimensionExpressions.size() < typeDescriptor.getDimensions()) {
    dimensionExpressions.add(NullLiteral.get());
  }

  ArrayLiteral arrayLiteral =
      expression.getInitializers() == null
          ? null
          : new ArrayLiteral(typeDescriptor, convertExpressions(expression.getInitializers()));

  return NewArray.newBuilder()
      .setTypeDescriptor(typeDescriptor)
      .setDimensionExpressions(dimensionExpressions)
      .setArrayLiteral(arrayLiteral)
      .build();
}
 
Example #5
Source File: ArrayCreationTree.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #6
Source File: UNewArray.java    From Refaster with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example #7
Source File: TreeFinder.java    From annotation-tools with MIT License 5 votes vote down vote up
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());
}
 
Example #8
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 5 votes vote down vote up
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);
	}
}
 
Example #9
Source File: ArrayCreationTree.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #10
Source File: ArrayCreationTree.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #11
Source File: ArrayCreationTree.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #12
Source File: ArrayCreationTree.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: ArrayCreationTree.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #14
Source File: Annotate.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void visitNewArray(JCNewArray tree) {
    enterTypeAnnotations(tree.annotations, env, sym, deferPos, false);
    for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
        enterTypeAnnotations(dimAnnos, env, sym, deferPos, false);
    scan(tree.elemtype);
    scan(tree.elems);
}
 
Example #15
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitNewArray(JCNewArray tree) {
    tree.elemtype = translate(tree.elemtype);
    for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail)
        if (t.head != null) t.head = translate(t.head, syms.intType);
    tree.elems = translate(tree.elems, types.elemtype(tree.type));
    result = tree;
}
 
Example #16
Source File: TransTypes.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitNewArray(JCNewArray tree) {
    tree.elemtype = translate(tree.elemtype, null);
    translate(tree.dims, syms.intType);
    if (tree.type != null) {
        tree.elems = translate(tree.elems, erasure(types.elemtype(tree.type)));
        tree.type = erasure(tree.type);
    } else {
        tree.elems = translate(tree.elems, null);
    }

    result = tree;
}
 
Example #17
Source File: CRTable.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitNewArray(JCNewArray tree) {
    SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
    sr.mergeWith(csp(tree.elemtype));
    sr.mergeWith(csp(tree.dims));
    sr.mergeWith(csp(tree.elems));
    result = sr;
}
 
Example #18
Source File: ArrayCreationTree.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #19
Source File: ArrayCreationTree.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #20
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void visitNewArray(JCNewArray tree) {
    scanExprs(tree.dims);
    scanExprs(tree.elems);
}
 
Example #21
Source File: JavacTreeMaker.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCNewArray NewArray(JCExpression elemtype, List<JCExpression> dims, List<JCExpression> elems) {
	return invoke(NewArray, elemtype, dims, elems);
}
 
Example #22
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 4 votes vote down vote up
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();
}
 
Example #23
Source File: HandleSynchronized.java    From EasyMPermission with MIT License 4 votes vote down vote up
@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();
}