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

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCAnnotation. 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: JavacAST.java    From EasyMPermission with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected JavacNode buildTree(JCTree node, Kind kind) {
	switch (kind) {
	case COMPILATION_UNIT:
		return buildCompilationUnit((JCCompilationUnit) node);
	case TYPE:
		return buildType((JCClassDecl) node);
	case FIELD:
		return buildField((JCVariableDecl) node);
	case INITIALIZER:
		return buildInitializer((JCBlock) node);
	case METHOD:
		return buildMethod((JCMethodDecl) node);
	case ARGUMENT:
		return buildLocalVar((JCVariableDecl) node, kind);
	case LOCAL:
		return buildLocalVar((JCVariableDecl) node, kind);
	case STATEMENT:
		return buildStatementOrExpression(node);
	case ANNOTATION:
		return buildAnnotation((JCAnnotation) node, false);
	default:
		throw new AssertionError("Did not expect: " + kind);
	}
}
 
Example #2
Source File: JavaCompiler.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve an identifier.
 *
 * @param name The identifier to resolve
 */
public Symbol resolveIdent(String name) {
    if (name.equals(""))
        return syms.errSymbol;
    JavaFileObject prev = log.useSource(null);
    try {
        JCExpression tree = null;
        for (String s : name.split("\\.", -1)) {
            if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
                return syms.errSymbol;
            tree = (tree == null) ? make.Ident(names.fromString(s))
                    : make.Select(tree, names.fromString(s));
        }
        JCCompilationUnit toplevel =
                make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>nil());
        toplevel.packge = syms.unnamedPackage;
        return attr.attribIdent(tree, toplevel);
    } finally {
        log.useSource(prev);
    }
}
 
Example #3
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 #4
Source File: HandleSetter.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<Setter> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.SETTER_FLAG_USAGE, "@Setter");
	
	Collection<JavacNode> fields = annotationNode.upFromAnnotationToFields();
	deleteAnnotationIfNeccessary(annotationNode, Setter.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	AccessLevel level = annotation.getInstance().value();
	
	if (level == AccessLevel.NONE || node == null) return;
	
	List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod=", annotationNode);
	List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam=", annotationNode);
	
	switch (node.getKind()) {
	case FIELD:
		createSetterForFields(level, fields, annotationNode, true, onMethod, onParam);
		break;
	case TYPE:
		if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Setter on a type.");
		if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Setter on a type.");
		generateSetterForType(node, annotationNode, level, false);
		break;
	}
}
 
Example #5
Source File: Annotate.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Attribute and store a semantic representation of the type annotation tree {@code tree} into
 * the tree.attribute field.
 *
 * @param a the tree representing an annotation
 * @param expectedAnnotationType the expected (super)type of the annotation
 * @param env the the current env in where the annotation instance is found
 */
public Attribute.TypeCompound attributeTypeAnnotation(JCAnnotation a, Type expectedAnnotationType,
                                                      Env<AttrContext> env)
{
    // The attribute might have been entered if it is Target or Repetable
    // Because TreeCopier does not copy type, redo this if type is null
    if (a.attribute == null || a.type == null || !(a.attribute instanceof Attribute.TypeCompound)) {
        // Create a new TypeCompound
        List<Pair<MethodSymbol,Attribute>> elems =
                attributeAnnotationValues(a, expectedAnnotationType, env);

        Attribute.TypeCompound tc =
                new Attribute.TypeCompound(a.type, elems, TypeAnnotationPosition.unknown);
        a.attribute = tc;
        return tc;
    } else {
        // Use an existing TypeCompound
        return (Attribute.TypeCompound)a.attribute;
    }
}
 
Example #6
Source File: Annotate.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Attribute the list of annotations and enter them onto s.
 */
public void enterTypeAnnotations(List<JCAnnotation> annotations, Env<AttrContext> env,
        Symbol s, DiagnosticPosition deferPos, boolean isTypeParam)
{
    Assert.checkNonNull(s, "Symbol argument to actualEnterTypeAnnotations is nul/");
    JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
    DiagnosticPosition prevLintPos = null;

    if (deferPos != null) {
        prevLintPos = deferredLintHandler.setPos(deferPos);
    }
    try {
        annotateNow(s, annotations, env, true, isTypeParam);
    } finally {
        if (prevLintPos != null)
            deferredLintHandler.setPos(prevLintPos);
        log.useSource(prev);
    }
}
 
Example #7
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<SneakyThrows> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.SNEAKY_THROWS_FLAG_USAGE, "@SneakyThrows");
	
	deleteAnnotationIfNeccessary(annotationNode, SneakyThrows.class);
	Collection<String> exceptionNames = annotation.getRawExpressions("value");
	if (exceptionNames.isEmpty()) {
		exceptionNames = Collections.singleton("java.lang.Throwable");
	}
	
	java.util.List<String> exceptions = new ArrayList<String>();
	for (String exception : exceptionNames) {
		if (exception.endsWith(".class")) exception = exception.substring(0, exception.length() - 6);
		exceptions.add(exception);
	}
	
	JavacNode owner = annotationNode.up();
	switch (owner.getKind()) {
	case METHOD:
		handleMethod(annotationNode, (JCMethodDecl)owner.get(), exceptions);
		break;
	default:
		annotationNode.addError("@SneakyThrows is legal only on methods and constructors.");
		break;
	}
}
 
Example #8
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 #9
Source File: JavaCompiler.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resolve an identifier.
 *
 * @param name The identifier to resolve
 */
public Symbol resolveIdent(String name) {
    if (name.equals(""))
        return syms.errSymbol;
    JavaFileObject prev = log.useSource(null);
    try {
        JCExpression tree = null;
        for (String s : name.split("\\.", -1)) {
            if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
                return syms.errSymbol;
            tree = (tree == null) ? make.Ident(names.fromString(s))
                    : make.Select(tree, names.fromString(s));
        }
        JCCompilationUnit toplevel =
                make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>nil());
        toplevel.packge = syms.unnamedPackage;
        return attr.attribIdent(tree, toplevel);
    } finally {
        log.useSource(prev);
    }
}
 
Example #10
Source File: HandleConstructor.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<AllArgsConstructor> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.ALL_ARGS_CONSTRUCTOR_FLAG_USAGE, "@AllArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor");
	
	deleteAnnotationIfNeccessary(annotationNode, AllArgsConstructor.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode typeNode = annotationNode.up();
	if (!checkLegality(typeNode, annotationNode, AllArgsConstructor.class.getSimpleName())) return;
	List<JCAnnotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@AllArgsConstructor(onConstructor=", annotationNode);
	AllArgsConstructor ann = annotation.getInstance();
	AccessLevel level = ann.access();
	if (level == AccessLevel.NONE) return;
	String staticName = ann.staticName();
	Boolean suppressConstructorProperties = null;
	if (annotation.isExplicit("suppressConstructorProperties")) {
		@SuppressWarnings("deprecation")
		boolean suppress = ann.suppressConstructorProperties();
		suppressConstructorProperties = suppress;
	}
	new HandleConstructor().generateConstructor(typeNode, level, onConstructor, findAllFields(typeNode), staticName, SkipIfConstructorExists.NO, suppressConstructorProperties, annotationNode);
}
 
Example #11
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 #12
Source File: HandleWither.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<Wither> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITHER_FLAG_USAGE, "@Wither");
	
	Collection<JavacNode> fields = annotationNode.upFromAnnotationToFields();
	deleteAnnotationIfNeccessary(annotationNode, Wither.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	AccessLevel level = annotation.getInstance().value();
	
	if (level == AccessLevel.NONE || node == null) return;
	
	List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Wither(onMethod=", annotationNode);
	List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Wither(onParam=", annotationNode);
	
	switch (node.getKind()) {
	case FIELD:
		createWitherForFields(level, fields, annotationNode, true, onMethod, onParam);
		break;
	case TYPE:
		if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Wither on a type.");
		if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Wither on a type.");
		generateWitherForType(node, annotationNode, level, false);
		break;
	}
}
 
Example #13
Source File: HandlerLibrary.java    From EasyMPermission with MIT License 6 votes vote down vote up
/**
 * Handles the provided annotation node by first finding a qualifying instance of
 * {@link JavacAnnotationHandler} and if one exists, calling it with a freshly cooked up
 * instance of {@link lombok.core.AnnotationValues}.
 * 
 * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation
 * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped.
 * 
 * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation.
 * For example, if {@code lombok.*} is in the import list, then this method will guess that
 * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.javac.handlers.HandleGetter}
 * has been loaded.
 * 
 * @param unit The Compilation Unit that contains the Annotation AST Node.
 * @param node The Lombok AST Node representing the Annotation AST Node.
 * @param annotation 'node.get()' - convenience parameter.
 */
public void handleAnnotation(JCCompilationUnit unit, JavacNode node, JCAnnotation annotation, long priority) {
	TypeResolver resolver = new TypeResolver(node.getImportList());
	String rawType = annotation.annotationType.toString();
	String fqn = resolver.typeRefToFullyQualifiedName(node, typeLibrary, rawType);
	if (fqn == null) return;
	AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn);
	if (container == null) return;
	
	try {
		if (container.getPriority() == priority) {
			if (checkAndSetHandled(annotation)) container.handle(node);
		}
	} catch (AnnotationValueDecodeFail fail) {
		fail.owner.setError(fail.getMessage(), fail.idx);
	} catch (Throwable t) {
		String sourceName = "(unknown).java";
		if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName();
		javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t);
	}
}
 
Example #14
Source File: JavacAST.java    From EasyMPermission with MIT License 6 votes vote down vote up
private JavacNode buildType(JCClassDecl type) {
	if (setAndGetAsHandled(type)) return null;
	List<JavacNode> childNodes = new ArrayList<JavacNode>();
	
	for (JCAnnotation annotation : type.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, false));
	for (JCTree def : type.defs) {
		/* A def can be:
		 *   JCClassDecl for inner types
		 *   JCMethodDecl for constructors and methods
		 *   JCVariableDecl for fields
		 *   JCBlock for (static) initializers
		 */
		if (def instanceof JCMethodDecl) addIfNotNull(childNodes, buildMethod((JCMethodDecl)def));
		else if (def instanceof JCClassDecl) addIfNotNull(childNodes, buildType((JCClassDecl)def));
		else if (def instanceof JCVariableDecl) addIfNotNull(childNodes, buildField((JCVariableDecl)def));
		else if (def instanceof JCBlock) addIfNotNull(childNodes, buildInitializer((JCBlock)def));
	}
	
	return putInMap(new JavacNode(this, type, childNodes, Kind.TYPE));
}
 
Example #15
Source File: HandleConstructor.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static void addConstructorProperties(JCModifiers mods, JavacNode node, List<JavacNode> fields) {
	if (fields.isEmpty()) return;
	JavacTreeMaker maker = node.getTreeMaker();
	JCExpression constructorPropertiesType = chainDots(node, "java", "beans", "ConstructorProperties");
	ListBuffer<JCExpression> fieldNames = new ListBuffer<JCExpression>();
	for (JavacNode field : fields) {
		Name fieldName = removePrefixFromField(field);
		fieldNames.append(maker.Literal(fieldName.toString()));
	}
	JCExpression fieldNamesArray = maker.NewArray(null, List.<JCExpression>nil(), fieldNames.toList());
	JCAnnotation annotation = maker.Annotation(constructorPropertiesType, List.of(fieldNamesArray));
	mods.annotations = mods.annotations.append(annotation);
}
 
Example #16
Source File: HandleAccessors.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<Accessors> annotation, JCAnnotation ast, JavacNode annotationNode) {
	// Accessors itself is handled by HandleGetter/Setter; this is just to ensure that the annotation is removed
	// from the AST when delomboking.
	
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.ACCESSORS_FLAG_USAGE, "@Accessors");
	
	deleteAnnotationIfNeccessary(annotationNode, Accessors.class);
}
 
Example #17
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 visitAnnotation(JCAnnotation tree) {
    Type t = tree.annotationType.type;
    if (t == null) {
        t = attr.attribType(tree.annotationType, env);
        tree.annotationType.type = t = check.checkType(tree.annotationType.pos(), t, tab.annotationType);
    }

    if (t == tab.annotationTargetType) {
        target = Annotate.this.attributeAnnotation(tree, tab.annotationTargetType, env);
    } else if (t == tab.repeatableType) {
        repeatable = Annotate.this.attributeAnnotation(tree, tab.repeatableType, env);
    }
}
 
Example #18
Source File: TypeEnter.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Mark sym deprecated if annotations contain @Deprecated annotation.
 */
public void markDeprecated(Symbol sym, List<JCAnnotation> annotations, Env<AttrContext> env) {
    // In general, we cannot fully process annotations yet,  but we
    // can attribute the annotation types and then check to see if the
    // @Deprecated annotation is present.
    attr.attribAnnotationTypes(annotations, env);
    handleDeprecatedAnnotations(annotations, sym);
}
 
Example #19
Source File: HandleValue.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<Value> annotation, JCAnnotation ast, JavacNode annotationNode) {
	@SuppressWarnings("deprecation")
	Class<? extends Annotation> oldExperimentalValue = lombok.experimental.Value.class;
	
	handleFlagUsage(annotationNode, ConfigurationKeys.VALUE_FLAG_USAGE, "@Value");
	
	deleteAnnotationIfNeccessary(annotationNode, Value.class, oldExperimentalValue);
	JavacNode typeNode = annotationNode.up();
	boolean notAClass = !isClass(typeNode);
	
	if (notAClass) {
		annotationNode.addError("@Value is only supported on a class.");
		return;
	}
	
	String staticConstructorName = annotation.getInstance().staticConstructor();
	
	if (!hasAnnotationAndDeleteIfNeccessary(NonFinal.class, typeNode)) {
		JCModifiers jcm = ((JCClassDecl) typeNode.get()).mods;
		if ((jcm.flags & Flags.FINAL) == 0) {
			jcm.flags |= Flags.FINAL;
			typeNode.rebuild();
		}
	}
	new HandleFieldDefaults().generateFieldDefaultsForType(typeNode, annotationNode, AccessLevel.PRIVATE, true, true);
	
	// TODO move this to the end OR move it to the top in eclipse.
	new HandleConstructor().generateAllArgsConstructor(typeNode, AccessLevel.PUBLIC, staticConstructorName, SkipIfConstructorExists.YES, annotationNode);
	new HandleGetter().generateGetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true);
	new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode);
	new HandleToString().generateToStringForType(typeNode, annotationNode);
}
 
Example #20
Source File: HandleUtilityClass.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<UtilityClass> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.UTLITY_CLASS_FLAG_USAGE, "@UtilityClass");
	
	deleteAnnotationIfNeccessary(annotationNode, UtilityClass.class);
	
	JavacNode typeNode = annotationNode.up();
	if (!checkLegality(typeNode, annotationNode)) return;
	changeModifiersAndGenerateConstructor(annotationNode.up(), annotationNode);
}
 
Example #21
Source File: HandleConstructor.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<NoArgsConstructor> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.NO_ARGS_CONSTRUCTOR_FLAG_USAGE, "@NoArgsConstructor", ConfigurationKeys.ANY_CONSTRUCTOR_FLAG_USAGE, "any @xArgsConstructor");
	
	deleteAnnotationIfNeccessary(annotationNode, NoArgsConstructor.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode typeNode = annotationNode.up();
	if (!checkLegality(typeNode, annotationNode, NoArgsConstructor.class.getSimpleName())) return;
	List<JCAnnotation> onConstructor = unboxAndRemoveAnnotationParameter(ast, "onConstructor", "@NoArgsConstructor(onConstructor=", annotationNode);
	NoArgsConstructor ann = annotation.getInstance();
	AccessLevel level = ann.access();
	if (level == AccessLevel.NONE) return;
	String staticName = ann.staticName();
	List<JavacNode> fields = List.nil();
	new HandleConstructor().generateConstructor(typeNode, level, onConstructor, fields, staticName, SkipIfConstructorExists.NO, null, annotationNode);
}
 
Example #22
Source File: TypeAnnotations.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void setTypeAnnotationPos(List<JCAnnotation> annotations, TypeAnnotationPosition position)
{
    // attribute might be null during DeferredAttr;
    // we will be back later.
    for (JCAnnotation anno : annotations) {
        if (anno.attribute != null)
            ((Attribute.TypeCompound) anno.attribute).position = position;
    }
}
 
Example #23
Source File: TypeAnnotations.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void findPosition(JCTree tree, JCTree frame, List<JCAnnotation> annotations) {
    if (!annotations.isEmpty())
    {
        final TypeAnnotationPosition p =
            resolveFrame(tree, frame, frames, currentLambda, 0, new ListBuffer<>());

        setTypeAnnotationPos(annotations, p);
    }
}
 
Example #24
Source File: JavacNode.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override protected boolean fieldContainsAnnotation(JCTree field, JCTree annotation) {
	if (!(field instanceof JCVariableDecl)) return false;
	JCVariableDecl f = (JCVariableDecl) field;
	if (f.mods.annotations == null) return false;
	for (JCAnnotation childAnnotation : f.mods.annotations) {
		if (childAnnotation == annotation) return true;
	}
	return false;
}
 
Example #25
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildStatementOrExpression(JCTree statement) {
	if (statement == null) return null;
	if (statement instanceof JCAnnotation) return null;
	if (statement instanceof JCClassDecl) return buildType((JCClassDecl)statement);
	if (statement instanceof JCVariableDecl) return buildLocalVar((JCVariableDecl)statement, Kind.LOCAL);
	if (statement instanceof JCTry) return buildTry((JCTry) statement);
	
	if (setAndGetAsHandled(statement)) return null;
	
	return drill(statement);
}
 
Example #26
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildAnnotation(JCAnnotation annotation, boolean varDecl) {
	boolean handled = setAndGetAsHandled(annotation);
	if (!varDecl && handled) {
		// @Foo int x, y; is handled in javac by putting the same annotation node on 2 JCVariableDecls.
		return null;
	}
	
	return putInMap(new JavacNode(this, annotation, null, Kind.ANNOTATION));
}
 
Example #27
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildMethod(JCMethodDecl method) {
	if (setAndGetAsHandled(method)) return null;
	List<JavacNode> childNodes = new ArrayList<JavacNode>();
	for (JCAnnotation annotation : method.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, false));
	for (JCVariableDecl param : method.params) addIfNotNull(childNodes, buildLocalVar(param, Kind.ARGUMENT));
	if (method.body != null && method.body.stats != null) {
		for (JCStatement statement : method.body.stats) addIfNotNull(childNodes, buildStatement(statement));
	}
	return putInMap(new JavacNode(this, method, childNodes, Kind.METHOD));
}
 
Example #28
Source File: JavacAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private JavacNode buildLocalVar(JCVariableDecl local, Kind kind) {
	if (setAndGetAsHandled(local)) return null;
	List<JavacNode> childNodes = new ArrayList<JavacNode>();
	for (JCAnnotation annotation : local.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation, true));
	addIfNotNull(childNodes, buildExpression(local.init));
	return putInMap(new JavacNode(this, local, childNodes, kind));
}
 
Example #29
Source File: JavacElements.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the tree for an annotation given a list of annotations
 * in which to search (recursively) and their corresponding trees.
 * Returns null if the tree cannot be found.
 */
private JCTree matchAnnoToTree(Attribute.Compound findme,
                               List<Attribute.Compound> annos,
                               List<JCAnnotation> trees) {
    for (Attribute.Compound anno : annos) {
        for (JCAnnotation tree : trees) {
            if (tree.type.tsym != anno.type.tsym)
                continue;
            JCTree match = matchAttributeToTree(findme, anno, tree);
            if (match != null)
                return match;
        }
    }
    return null;
}
 
Example #30
Source File: HandleGetter.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_FLAG_USAGE, "@Getter");
	
	Collection<JavacNode> fields = annotationNode.upFromAnnotationToFields();
	deleteAnnotationIfNeccessary(annotationNode, Getter.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	Getter annotationInstance = annotation.getInstance();
	AccessLevel level = annotationInstance.value();
	boolean lazy = annotationInstance.lazy();
	if (lazy) handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_LAZY_FLAG_USAGE, "@Getter(lazy=true)");
	
	if (level == AccessLevel.NONE) {
		if (lazy) annotationNode.addWarning("'lazy' does not work with AccessLevel.NONE.");
		return;
	}
	
	if (node == null) return;
	
	List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Getter(onMethod=", annotationNode);
	
	switch (node.getKind()) {
	case FIELD:
		createGetterForFields(level, fields, annotationNode, true, lazy, onMethod);
		break;
	case TYPE:
		if (!onMethod.isEmpty()) {
			annotationNode.addError("'onMethod' is not supported for @Getter on a type.");
		}
		if (lazy) annotationNode.addError("'lazy' is not supported for @Getter on a type.");
		generateGetterForType(node, annotationNode, level, false);
		break;
	}
}