Search in sources :

Example 36 with JCMethodDecl

use of com.sun.tools.javac.tree.JCTree.JCMethodDecl in project error-prone by google.

the class JUnit3TestNotRun method matchMethod.

/**
   * Matches if:
   * 1) Method's name begins with misspelled variation of "test".
   * 2) Method is public, returns void, and has no parameters.
   * 3) Enclosing class is JUnit3 test (extends TestCase, has no RunWith annotation,
   *    and is not abstract).
   */
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
    Matcher<MethodTree> methodMatcher = allOf(not(methodNameStartsWith("test")), Matchers.<MethodTree>hasModifier(Modifier.PUBLIC), methodReturns(VOID_TYPE), methodHasParameters(), enclosingClass(isJUnit3TestClass));
    if (!methodMatcher.matches(methodTree, state)) {
        return Description.NO_MATCH;
    }
    String name = methodTree.getName().toString();
    String fixedName;
    // regex.Matcher class name collides with errorprone.Matcher
    java.util.regex.Matcher matcher = MISSPELLED_NAME.matcher(name);
    if (matcher.lookingAt()) {
        fixedName = matcher.replaceFirst("test");
    } else if (wouldRunInJUnit4.matches(methodTree, state)) {
        fixedName = "test" + name.substring(0, 1).toUpperCase() + name.substring(1);
    } else {
        return Description.NO_MATCH;
    }
    // We don't have start position for a method symbol, so we replace everything between result
    // type and body.
    JCMethodDecl decl = (JCMethodDecl) methodTree;
    Fix fix = SuggestedFix.replace(decl.restype.getStartPosition() + 4, decl.body.getStartPosition(), " " + fixedName + "() ");
    return describeMatch(methodTree, fix);
}
Also used : JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) Fix(com.google.errorprone.fixes.Fix) MethodTree(com.sun.source.tree.MethodTree)

Example 37 with JCMethodDecl

use of com.sun.tools.javac.tree.JCTree.JCMethodDecl in project lombok by rzwitserloot.

the class JavacJavaUtilMapSingularizer method generateSingularMethod.

private void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrown = List.nil();
    JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
    statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, true, source));
    Name keyName = builderType.toName(data.getSingularName().toString() + "Key");
    Name valueName = builderType.toName(data.getSingularName().toString() + "Value");
    /* this.pluralname$key.add(singularnameKey); */
    {
        JCExpression thisDotKeyFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$key", "add");
        JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotKeyFieldDotAdd, List.<JCExpression>of(maker.Ident(keyName)));
        statements.append(maker.Exec(invokeAdd));
    }
    /* this.pluralname$value.add(singularnameValue); */
    {
        JCExpression thisDotValueFieldDotAdd = chainDots(builderType, "this", data.getPluralName() + "$value", "add");
        JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotValueFieldDotAdd, List.<JCExpression>of(maker.Ident(valueName)));
        statements.append(maker.Exec(invokeAdd));
    }
    if (returnStatement != null)
        statements.append(returnStatement);
    JCBlock body = maker.Block(0, statements.toList());
    long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
    Name name = data.getSingularName();
    if (!fluent)
        name = builderType.toName(HandlerUtil.buildAccessorName("put", name.toString()));
    JCExpression paramTypeKey = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
    JCExpression paramTypeValue = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
    JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, paramTypeKey, null);
    JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, paramTypeValue, null);
    JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(paramKey, paramValue), thrown, body, null);
    injectMethod(builderType, method);
}
Also used : JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Name(com.sun.tools.javac.util.Name) JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCModifiers(com.sun.tools.javac.tree.JCTree.JCModifiers)

Example 38 with JCMethodDecl

use of com.sun.tools.javac.tree.JCTree.JCMethodDecl in project lombok by rzwitserloot.

the class JavacNode method traverse.

/**
	 * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods.
	 */
public void traverse(JavacASTVisitor visitor) {
    switch(this.getKind()) {
        case COMPILATION_UNIT:
            visitor.visitCompilationUnit(this, (JCCompilationUnit) get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitCompilationUnit(this, (JCCompilationUnit) get());
            break;
        case TYPE:
            visitor.visitType(this, (JCClassDecl) get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitType(this, (JCClassDecl) get());
            break;
        case FIELD:
            visitor.visitField(this, (JCVariableDecl) get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitField(this, (JCVariableDecl) get());
            break;
        case METHOD:
            visitor.visitMethod(this, (JCMethodDecl) get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitMethod(this, (JCMethodDecl) get());
            break;
        case INITIALIZER:
            visitor.visitInitializer(this, (JCBlock) get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitInitializer(this, (JCBlock) get());
            break;
        case ARGUMENT:
            JCMethodDecl parentMethod = (JCMethodDecl) up().get();
            visitor.visitMethodArgument(this, (JCVariableDecl) get(), parentMethod);
            ast.traverseChildren(visitor, this);
            visitor.endVisitMethodArgument(this, (JCVariableDecl) get(), parentMethod);
            break;
        case LOCAL:
            visitor.visitLocal(this, (JCVariableDecl) get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitLocal(this, (JCVariableDecl) get());
            break;
        case STATEMENT:
            visitor.visitStatement(this, get());
            ast.traverseChildren(visitor, this);
            visitor.endVisitStatement(this, get());
            break;
        case ANNOTATION:
            switch(up().getKind()) {
                case TYPE:
                    visitor.visitAnnotationOnType((JCClassDecl) up().get(), this, (JCAnnotation) get());
                    break;
                case FIELD:
                    visitor.visitAnnotationOnField((JCVariableDecl) up().get(), this, (JCAnnotation) get());
                    break;
                case METHOD:
                    visitor.visitAnnotationOnMethod((JCMethodDecl) up().get(), this, (JCAnnotation) get());
                    break;
                case ARGUMENT:
                    JCVariableDecl argument = (JCVariableDecl) up().get();
                    JCMethodDecl method = (JCMethodDecl) up().up().get();
                    visitor.visitAnnotationOnMethodArgument(argument, method, this, (JCAnnotation) get());
                    break;
                case LOCAL:
                    visitor.visitAnnotationOnLocal((JCVariableDecl) up().get(), this, (JCAnnotation) get());
                    break;
                default:
                    throw new AssertionError("Annotion not expected as child of a " + up().getKind());
            }
            break;
        default:
            throw new AssertionError("Unexpected kind during node traversal: " + getKind());
    }
}
Also used : JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl)

Example 39 with JCMethodDecl

use of com.sun.tools.javac.tree.JCTree.JCMethodDecl in project lombok by rzwitserloot.

the class HandleUtilityClass method changeModifiersAndGenerateConstructor.

private void changeModifiersAndGenerateConstructor(JavacNode typeNode, JavacNode errorNode) {
    JCClassDecl classDecl = (JCClassDecl) typeNode.get();
    boolean makeConstructor = true;
    classDecl.mods.flags |= Flags.FINAL;
    boolean markStatic = true;
    if (typeNode.up().getKind() == Kind.COMPILATION_UNIT)
        markStatic = false;
    if (markStatic && typeNode.up().getKind() == Kind.TYPE) {
        JCClassDecl typeDecl = (JCClassDecl) typeNode.up().get();
        if ((typeDecl.mods.flags & Flags.INTERFACE) != 0)
            markStatic = false;
    }
    if (markStatic)
        classDecl.mods.flags |= Flags.STATIC;
    for (JavacNode element : typeNode.down()) {
        if (element.getKind() == Kind.FIELD) {
            JCVariableDecl fieldDecl = (JCVariableDecl) element.get();
            fieldDecl.mods.flags |= Flags.STATIC;
        } else if (element.getKind() == Kind.METHOD) {
            JCMethodDecl methodDecl = (JCMethodDecl) element.get();
            if (methodDecl.name.contentEquals("<init>")) {
                if (getGeneratedBy(methodDecl) == null && (methodDecl.mods.flags & Flags.GENERATEDCONSTR) == 0) {
                    element.addError("@UtilityClasses cannot have declared constructors.");
                    makeConstructor = false;
                    continue;
                }
            }
            methodDecl.mods.flags |= Flags.STATIC;
        } else if (element.getKind() == Kind.TYPE) {
            JCClassDecl innerClassDecl = (JCClassDecl) element.get();
            innerClassDecl.mods.flags |= Flags.STATIC;
        }
    }
    if (makeConstructor)
        createPrivateDefaultConstructor(typeNode);
}
Also used : JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JavacNode(lombok.javac.JavacNode) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl)

Example 40 with JCMethodDecl

use of com.sun.tools.javac.tree.JCTree.JCMethodDecl in project lombok by rzwitserloot.

the class HandleSetter method createSetterForField.

public void createSetterForField(AccessLevel level, JavacNode fieldNode, JavacNode sourceNode, boolean whineIfExists, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) {
    if (fieldNode.getKind() != Kind.FIELD) {
        fieldNode.addError("@Setter is only supported on a class or a field.");
        return;
    }
    JCVariableDecl fieldDecl = (JCVariableDecl) fieldNode.get();
    String methodName = toSetterName(fieldNode);
    if (methodName == null) {
        fieldNode.addWarning("Not generating setter for this field: It does not fit your @Accessors prefix list.");
        return;
    }
    if ((fieldDecl.mods.flags & Flags.FINAL) != 0) {
        fieldNode.addWarning("Not generating setter for this field: Setters cannot be generated for final fields.");
        return;
    }
    for (String altName : toAllSetterNames(fieldNode)) {
        switch(methodExists(altName, fieldNode, false, 1)) {
            case EXISTS_BY_LOMBOK:
                return;
            case EXISTS_BY_USER:
                if (whineIfExists) {
                    String altNameExpl = "";
                    if (!altName.equals(methodName))
                        altNameExpl = String.format(" (%s)", altName);
                    fieldNode.addWarning(String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl));
                }
                return;
            default:
            case NOT_EXISTS:
        }
    }
    long access = toJavacModifier(level) | (fieldDecl.mods.flags & Flags.STATIC);
    JCMethodDecl createdSetter = createSetter(access, fieldNode, fieldNode.getTreeMaker(), sourceNode, onMethod, onParam);
    Type fieldType = getMirrorForFieldType(fieldNode);
    Type returnType;
    if (shouldReturnThis(fieldNode)) {
        ClassSymbol sym = ((JCClassDecl) fieldNode.up().get()).sym;
        returnType = sym == null ? null : sym.type;
    } else {
        returnType = Javac.createVoidType(fieldNode.getSymbolTable(), CTC_VOID);
    }
    injectMethod(fieldNode.up(), createdSetter, fieldType == null ? null : List.of(fieldType), returnType);
}
Also used : Type(com.sun.tools.javac.code.Type) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl)

Aggregations

JCMethodDecl (com.sun.tools.javac.tree.JCTree.JCMethodDecl)45 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)31 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)20 Name (com.sun.tools.javac.util.Name)17 JCBlock (com.sun.tools.javac.tree.JCTree.JCBlock)16 JCStatement (com.sun.tools.javac.tree.JCTree.JCStatement)16 JCTypeParameter (com.sun.tools.javac.tree.JCTree.JCTypeParameter)15 ListBuffer (com.sun.tools.javac.util.ListBuffer)14 JCClassDecl (com.sun.tools.javac.tree.JCTree.JCClassDecl)13 JCModifiers (com.sun.tools.javac.tree.JCTree.JCModifiers)13 JavacNode (lombok.javac.JavacNode)13 JCTree (com.sun.tools.javac.tree.JCTree)12 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)5 Type (com.sun.tools.javac.code.Type)5 JCAnnotation (com.sun.tools.javac.tree.JCTree.JCAnnotation)5 JCFieldAccess (com.sun.tools.javac.tree.JCTree.JCFieldAccess)5 JCNewClass (com.sun.tools.javac.tree.JCTree.JCNewClass)5 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)4 JavacTreeMaker (lombok.javac.JavacTreeMaker)4 JCExpressionStatement (com.sun.tools.javac.tree.JCTree.JCExpressionStatement)3