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

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCAssign. 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: TypeEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * If a list of annotations contains a reference to java.lang.Deprecated,
 * set the DEPRECATED flag.
 * If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL.
 **/
private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
    for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
        JCAnnotation a = al.head;
        if (a.annotationType.type == syms.deprecatedType) {
            sym.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION);
           StreamSupport.stream(a.args)
                    .filter(e -> e.hasTag(ASSIGN))
                    .map(e -> (JCAssign) e)
                    .filter(assign -> TreeInfo.name(assign.lhs) == names.forRemoval)
                    .findFirst()
                    .ifPresent(assign -> {
                        JCExpression rhs = TreeInfo.skipParens(assign.rhs);
                        if (rhs.hasTag(LITERAL)
                                && Boolean.TRUE.equals(((JCLiteral) rhs).getValue())) {
                            sym.flags_field |= DEPRECATED_REMOVAL;
                        }
                    });
        }
    }
}
 
Example #3
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 6 votes vote down vote up
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);
	}
}
 
Example #4
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitAssign(JCAssign tree) {
    JCTree lhs = TreeInfo.skipParens(tree.lhs);
    if (!isIdentOrThisDotIdent(lhs))
        scanExpr(lhs);
    scanExpr(tree.rhs);
    letInit(lhs);
}
 
Example #5
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitAssign(JCAssign tree) {
    JCTree lhs = TreeInfo.skipParens(tree.lhs);
    if (!(lhs instanceof JCIdent)) {
        scan(lhs);
    }
    scan(tree.rhs);
    letInit(lhs);
}
 
Example #6
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** return access code for identifier,
 *  @param tree     The tree representing the identifier use.
 *  @param enclOp   The closest enclosing operation node of tree,
 *                  null if tree is not a subtree of an operation.
 */
private static int accessCode(JCTree tree, JCTree enclOp) {
    if (enclOp == null)
        return AccessCode.DEREF.code;
    else if (enclOp.hasTag(ASSIGN) &&
             tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs))
        return AccessCode.ASSIGN.code;
    else if ((enclOp.getTag().isIncOrDecUnaryOp() || enclOp.getTag().isAssignop()) &&
            tree == TreeInfo.skipParens(((JCOperatorExpression) enclOp).getOperand(LEFT)))
        return (((JCOperatorExpression) enclOp).operator).getAccessCode(enclOp.getTag());
    else
        return AccessCode.DEREF.code;
}
 
Example #7
Source File: Lower.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void visitAssign(JCAssign tree) {
    tree.lhs = translate(tree.lhs, tree);
    tree.rhs = translate(tree.rhs, tree.lhs.type);

    // If translated left hand side is an Apply, we are
    // seeing an access method invocation. In this case, append
    // right hand side as last argument of the access method.
    if (tree.lhs.hasTag(APPLY)) {
        JCMethodInvocation app = (JCMethodInvocation)tree.lhs;
        app.args = List.of(tree.rhs).prependList(app.args);
        result = app;
    } else {
        result = tree;
    }
}
 
Example #8
Source File: Annotate.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Pair<MethodSymbol, Attribute> attributeAnnotationNameValuePair(JCExpression nameValuePair,
        Type thisAnnotationType, boolean badAnnotation, Env<AttrContext> env, boolean elidedValue)
{
    if (!nameValuePair.hasTag(ASSIGN)) {
        log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue);
        attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env);
        return null;
    }
    JCAssign assign = (JCAssign)nameValuePair;
    if (!assign.lhs.hasTag(IDENT)) {
        log.error(nameValuePair.pos(), Errors.AnnotationValueMustBeNameValue);
        attributeAnnotationValue(nameValuePair.type = syms.errType, nameValuePair, env);
        return null;
    }

    // Resolve element to MethodSym
    JCIdent left = (JCIdent)assign.lhs;
    Symbol method = resolve.resolveQualifiedMethod(elidedValue ? assign.rhs.pos() : left.pos(),
            env, thisAnnotationType,
            left.name, List.nil(), null);
    left.sym = method;
    left.type = method.type;
    if (method.owner != thisAnnotationType.tsym && !badAnnotation)
        log.error(left.pos(), Errors.NoAnnotationMember(left.name, thisAnnotationType));
    Type resultType = method.type.getReturnType();

    // Compute value part
    Attribute value = attributeAnnotationValue(resultType, assign.rhs, env);
    nameValuePair.type = resultType;

    return method.type.isErroneous() ? null : new Pair<>((MethodSymbol)method, value);

}
 
Example #9
Source File: LambdaToMethod.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
LambdaTranslationContext(JCLambda tree) {
    super(tree);
    Frame frame = frameStack.head;
    switch (frame.tree.getTag()) {
        case VARDEF:
            assignedTo = self = ((JCVariableDecl) frame.tree).sym;
            break;
        case ASSIGN:
            self = null;
            assignedTo = TreeInfo.symbol(((JCAssign) frame.tree).getVariable());
            break;
        default:
            assignedTo = self = null;
            break;
     }

    // This symbol will be filled-in in complete
    this.translatedSym = makePrivateSyntheticMethod(0, null, null, owner.enclClass());

    translatedSymbols = new EnumMap<>(LambdaSymbolKind.class);

    translatedSymbols.put(PARAM, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(LOCAL_VAR, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(CAPTURED_VAR, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(CAPTURED_THIS, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(CAPTURED_OUTER_THIS, new LinkedHashMap<Symbol, Symbol>());
    translatedSymbols.put(TYPE_VAR, new LinkedHashMap<Symbol, Symbol>());

    freeVarProcessedLocalClasses = new HashSet<>();
}
 
Example #10
Source File: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private BinaryExpression convertAssignment(JCAssign expression) {
  return BinaryExpression.newBuilder()
      .setLeftOperand(convertExpression(expression.getVariable()))
      .setOperator(JavaEnvironment.getBinaryOperator(expression.getKind()))
      .setRightOperand(convertExpression(expression.getExpression()))
      .build();
}
 
Example #11
Source File: PrettyCommentsPrinter.java    From EasyMPermission with MIT License 5 votes vote down vote up
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);
	}
}
 
Example #12
Source File: HandleCleanup.java    From EasyMPermission with MIT License 5 votes vote down vote up
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.");
		}
	}
}
 
Example #13
Source File: ExpressionTemplate.java    From Refaster with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
  }
}
 
Example #14
Source File: CRTable.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void visitAssign(JCAssign tree) {
    SourceRange sr = new SourceRange(startPos(tree), endPos(tree));
    sr.mergeWith(csp(tree.lhs));
    sr.mergeWith(csp(tree.rhs));
    result = sr;
}
 
Example #15
Source File: UAssign.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
public JCAssign inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().Assign(getVariable().inline(inliner), getExpression().inline(inliner));
}
 
Example #16
Source File: Assign.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override
public JCAssign build() {
    return treeMaker.Assign(leftExpression, rightExpression);
}
 
Example #17
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 #18
Source File: HandleSetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
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;
}
 
Example #19
Source File: JavacTreeMaker.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCAssign Assign(JCExpression lhs, JCExpression rhs) {
	return invoke(Assign, lhs, rhs);
}
 
Example #20
Source File: TransTypes.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void visitAssign(JCAssign tree) {
    tree.lhs = translate(tree.lhs, null);
    tree.rhs = translate(tree.rhs, erasure(tree.lhs.type));
    tree.type = erasure(tree.lhs.type);
    result = retype(tree, tree.type, pt);
}
 
Example #21
Source File: Assign.java    From EasyMPermission with MIT License votes vote down vote up
JCAssign build();