Search in sources :

Example 1 with Name

use of com.sun.tools.javac.util.Name in project lombok by rzwitserloot.

the class HandleConstructor method createStaticConstructor.

public JCMethodDecl createStaticConstructor(String name, AccessLevel level, JavacNode typeNode, List<JavacNode> fields, JCTree source) {
    JavacTreeMaker maker = typeNode.getTreeMaker();
    JCClassDecl type = (JCClassDecl) typeNode.get();
    JCModifiers mods = maker.Modifiers(Flags.STATIC | toJavacModifier(level));
    JCExpression returnType, constructorType;
    ListBuffer<JCTypeParameter> typeParams = new ListBuffer<JCTypeParameter>();
    ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>();
    ListBuffer<JCExpression> typeArgs1 = new ListBuffer<JCExpression>();
    ListBuffer<JCExpression> typeArgs2 = new ListBuffer<JCExpression>();
    ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();
    if (!type.typarams.isEmpty()) {
        for (JCTypeParameter param : type.typarams) {
            typeArgs1.append(maker.Ident(param.name));
            typeArgs2.append(maker.Ident(param.name));
            typeParams.append(maker.TypeParameter(param.name, param.bounds));
        }
        returnType = maker.TypeApply(maker.Ident(type.name), typeArgs1.toList());
        constructorType = maker.TypeApply(maker.Ident(type.name), typeArgs2.toList());
    } else {
        returnType = maker.Ident(type.name);
        constructorType = maker.Ident(type.name);
    }
    for (JavacNode fieldNode : fields) {
        JCVariableDecl field = (JCVariableDecl) fieldNode.get();
        Name fieldName = removePrefixFromField(fieldNode);
        JCExpression pType = cloneType(maker, field.vartype, source, typeNode.getContext());
        List<JCAnnotation> nonNulls = findAnnotations(fieldNode, NON_NULL_PATTERN);
        List<JCAnnotation> nullables = findAnnotations(fieldNode, NULLABLE_PATTERN);
        long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
        JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, nonNulls.appendList(nullables)), fieldName, pType, null);
        params.append(param);
        args.append(maker.Ident(fieldName));
    }
    JCReturn returnStatement = maker.Return(maker.NewClass(null, List.<JCExpression>nil(), constructorType, args.toList(), null));
    JCBlock body = maker.Block(0, List.<JCStatement>of(returnStatement));
    return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName(name), returnType, typeParams.toList(), params.toList(), List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
Also used : JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JCReturn(com.sun.tools.javac.tree.JCTree.JCReturn) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JavacTreeMaker(lombok.javac.JavacTreeMaker) ListBuffer(com.sun.tools.javac.util.ListBuffer) 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) JavacNode(lombok.javac.JavacNode) JCModifiers(com.sun.tools.javac.tree.JCTree.JCModifiers) JCAnnotation(com.sun.tools.javac.tree.JCTree.JCAnnotation)

Example 2 with Name

use of com.sun.tools.javac.util.Name in project lombok by rzwitserloot.

the class HandleBuilder method generateToBuilderMethod.

private JCMethodDecl generateToBuilderMethod(String toBuilderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams, java.util.List<BuilderFieldData> builderFields, boolean fluent, JCAnnotation ast) {
    // return new ThingieBuilder<A, B>().setA(this.a).setB(this.b);
    JavacTreeMaker maker = type.getTreeMaker();
    ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
    for (JCTypeParameter typeParam : typeParams) {
        typeArgs.append(maker.Ident(typeParam.name));
    }
    JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
    JCExpression invoke = call;
    for (BuilderFieldData bfd : builderFields) {
        Name setterName = fluent ? bfd.name : type.toName(HandlerUtil.buildAccessorName("set", bfd.name.toString()));
        JCExpression arg;
        if (bfd.obtainVia == null || !bfd.obtainVia.field().isEmpty()) {
            arg = maker.Select(maker.Ident(type.toName("this")), bfd.obtainVia == null ? bfd.rawName : type.toName(bfd.obtainVia.field()));
        } else {
            if (bfd.obtainVia.isStatic()) {
                JCExpression c = maker.Select(maker.Ident(type.toName(type.getName())), type.toName(bfd.obtainVia.method()));
                arg = maker.Apply(List.<JCExpression>nil(), c, List.<JCExpression>of(maker.Ident(type.toName("this"))));
            } else {
                JCExpression c = maker.Select(maker.Ident(type.toName("this")), type.toName(bfd.obtainVia.method()));
                arg = maker.Apply(List.<JCExpression>nil(), c, List.<JCExpression>nil());
            }
        }
        invoke = maker.Apply(List.<JCExpression>nil(), maker.Select(invoke, setterName), List.of(arg));
    }
    JCStatement statement = maker.Return(invoke);
    JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
    return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName(toBuilderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
}
Also used : JCTypeParameter(com.sun.tools.javac.tree.JCTree.JCTypeParameter) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) Name(com.sun.tools.javac.util.Name)

Example 3 with Name

use of com.sun.tools.javac.util.Name in project bazel by bazelbuild.

the class Resolver method findMethod.

/**
     * Finds the method element for a given name and list of expected parameter
     * types.
     *
     * <p>
     * The method adheres to all the rules of Java's scoping (while also
     * considering the imports) for name resolution.
     *
     * @param methodName
     *            Name of the method to find.
     * @param receiverType
     *            Type of the receiver of the method
     * @param path
     *            Tree path.
     * @return The method element (if found).
     */
public Element findMethod(String methodName, TypeMirror receiverType, TreePath path, java.util.List<TypeMirror> argumentTypes) {
    Log.DiagnosticHandler discardDiagnosticHandler = new Log.DiscardDiagnosticHandler(log);
    try {
        JavacScope scope = (JavacScope) trees.getScope(path);
        Env<AttrContext> env = scope.getEnv();
        Type site = (Type) receiverType;
        Name name = names.fromString(methodName);
        List<Type> argtypes = List.nil();
        for (TypeMirror a : argumentTypes) {
            argtypes = argtypes.append((Type) a);
        }
        List<Type> typeargtypes = List.nil();
        boolean allowBoxing = true;
        boolean useVarargs = false;
        boolean operator = true;
        try {
            // For some reason we have to set our own method context, which is rather ugly.
            // TODO: find a nicer way to do this.
            Object methodContext = buildMethodContext();
            Object oldContext = getField(resolve, "currentResolutionContext");
            setField(resolve, "currentResolutionContext", methodContext);
            Element result = wrapInvocation(FIND_METHOD, env, site, name, argtypes, typeargtypes, allowBoxing, useVarargs, operator);
            setField(resolve, "currentResolutionContext", oldContext);
            return result;
        } catch (Throwable t) {
            Error err = new AssertionError("Unexpected Reflection error");
            err.initCause(t);
            throw err;
        }
    } finally {
        log.popDiagnosticHandler(discardDiagnosticHandler);
    }
}
Also used : Log(com.sun.tools.javac.util.Log) VariableElement(javax.lang.model.element.VariableElement) Element(javax.lang.model.element.Element) JavacScope(com.sun.tools.javac.api.JavacScope) AttrContext(com.sun.tools.javac.comp.AttrContext) Name(com.sun.tools.javac.util.Name) Type(com.sun.tools.javac.code.Type) TypeMirror(javax.lang.model.type.TypeMirror)

Example 4 with Name

use of com.sun.tools.javac.util.Name in project lombok by rzwitserloot.

the class HandleConstructor method addConstructorProperties.

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);
}
Also used : JavacTreeMaker(lombok.javac.JavacTreeMaker) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JavacNode(lombok.javac.JavacNode) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCAnnotation(com.sun.tools.javac.tree.JCTree.JCAnnotation) Name(com.sun.tools.javac.util.Name)

Example 5 with Name

use of com.sun.tools.javac.util.Name in project lombok by rzwitserloot.

the class HandleDelegate method handle.

@Override
public void handle(AnnotationValues<Delegate> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.DELEGATE_FLAG_USAGE, "@Delegate");
    @SuppressWarnings("deprecation") Class<? extends Annotation> oldDelegate = lombok.Delegate.class;
    deleteAnnotationIfNeccessary(annotationNode, Delegate.class, oldDelegate);
    Type delegateType;
    Name delegateName = annotationNode.toName(annotationNode.up().getName());
    DelegateReceiver delegateReceiver;
    JavacResolution reso = new JavacResolution(annotationNode.getContext());
    JCTree member = annotationNode.up().get();
    if (annotationNode.up().getKind() == Kind.FIELD) {
        if ((((JCVariableDecl) member).mods.flags & Flags.STATIC) != 0) {
            annotationNode.addError(LEGALITY_OF_DELEGATE);
            return;
        }
        delegateReceiver = DelegateReceiver.FIELD;
        delegateType = member.type;
        if (delegateType == null)
            reso.resolveClassMember(annotationNode.up());
        delegateType = member.type;
    } else if (annotationNode.up().getKind() == Kind.METHOD) {
        if (!(member instanceof JCMethodDecl)) {
            annotationNode.addError(LEGALITY_OF_DELEGATE);
            return;
        }
        JCMethodDecl methodDecl = (JCMethodDecl) member;
        if (!methodDecl.params.isEmpty() || (methodDecl.mods.flags & Flags.STATIC) != 0) {
            annotationNode.addError(LEGALITY_OF_DELEGATE);
            return;
        }
        delegateReceiver = DelegateReceiver.METHOD;
        delegateType = methodDecl.restype.type;
        if (delegateType == null)
            reso.resolveClassMember(annotationNode.up());
        delegateType = methodDecl.restype.type;
    } else {
        // As the annotation is legal on fields and methods only, javac itself will take care of printing an error message for this.
        return;
    }
    List<Object> delegateTypes = annotation.getActualExpressions("types");
    List<Object> excludeTypes = annotation.getActualExpressions("excludes");
    List<Type> toDelegate = new ArrayList<Type>();
    List<Type> toExclude = new ArrayList<Type>();
    if (delegateTypes.isEmpty()) {
        if (delegateType != null)
            toDelegate.add(delegateType);
    } else {
        for (Object dt : delegateTypes) {
            if (dt instanceof JCFieldAccess && ((JCFieldAccess) dt).name.toString().equals("class")) {
                Type type = ((JCFieldAccess) dt).selected.type;
                if (type == null)
                    reso.resolveClassMember(annotationNode);
                type = ((JCFieldAccess) dt).selected.type;
                if (type != null)
                    toDelegate.add(type);
            }
        }
    }
    for (Object et : excludeTypes) {
        if (et instanceof JCFieldAccess && ((JCFieldAccess) et).name.toString().equals("class")) {
            Type type = ((JCFieldAccess) et).selected.type;
            if (type == null)
                reso.resolveClassMember(annotationNode);
            type = ((JCFieldAccess) et).selected.type;
            if (type != null)
                toExclude.add(type);
        }
    }
    List<MethodSig> signaturesToDelegate = new ArrayList<MethodSig>();
    List<MethodSig> signaturesToExclude = new ArrayList<MethodSig>();
    Set<String> banList = new HashSet<String>();
    banList.addAll(METHODS_IN_OBJECT);
    try {
        for (Type t : toExclude) {
            if (t instanceof ClassType) {
                ClassType ct = (ClassType) t;
                addMethodBindings(signaturesToExclude, ct, annotationNode.getTypesUtil(), banList);
            } else {
                annotationNode.addError("@Delegate can only use concrete class types, not wildcards, arrays, type variables, or primitives.");
                return;
            }
        }
        for (MethodSig sig : signaturesToExclude) {
            banList.add(printSig(sig.type, sig.name, annotationNode.getTypesUtil()));
        }
        for (Type t : toDelegate) {
            if (t instanceof ClassType) {
                ClassType ct = (ClassType) t;
                addMethodBindings(signaturesToDelegate, ct, annotationNode.getTypesUtil(), banList);
            } else {
                annotationNode.addError("@Delegate can only use concrete class types, not wildcards, arrays, type variables, or primitives.");
                return;
            }
        }
        for (MethodSig sig : signaturesToDelegate) generateAndAdd(sig, annotationNode, delegateName, delegateReceiver);
    } catch (DelegateRecursion e) {
        annotationNode.addError(String.format(RECURSION_NOT_ALLOWED, e.member, e.type));
    }
}
Also used : JavacResolution(lombok.javac.JavacResolution) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) ArrayList(java.util.ArrayList) JCTree(com.sun.tools.javac.tree.JCTree) ClassType(com.sun.tools.javac.code.Type.ClassType) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) Name(com.sun.tools.javac.util.Name) ClassType(com.sun.tools.javac.code.Type.ClassType) Type(com.sun.tools.javac.code.Type) ExecutableType(javax.lang.model.type.ExecutableType) Delegate(lombok.experimental.Delegate) HashSet(java.util.HashSet)

Aggregations

Name (com.sun.tools.javac.util.Name)92 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)50 JCStatement (com.sun.tools.javac.tree.JCTree.JCStatement)43 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)43 JCBlock (com.sun.tools.javac.tree.JCTree.JCBlock)33 JCTypeParameter (com.sun.tools.javac.tree.JCTree.JCTypeParameter)32 JCMethodDecl (com.sun.tools.javac.tree.JCTree.JCMethodDecl)30 JCModifiers (com.sun.tools.javac.tree.JCTree.JCModifiers)29 ListBuffer (com.sun.tools.javac.util.ListBuffer)26 JavacTreeMaker (lombok.javac.JavacTreeMaker)18 JCAnnotation (com.sun.tools.javac.tree.JCTree.JCAnnotation)16 Symbol (com.sun.tools.javac.code.Symbol)15 Type (com.sun.tools.javac.code.Type)13 JCTree (com.sun.tools.javac.tree.JCTree)13 JavacNode (lombok.javac.JavacNode)12 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)10 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)10 PackageSymbol (com.sun.tools.javac.code.Symbol.PackageSymbol)8 TypeSymbol (com.sun.tools.javac.code.Symbol.TypeSymbol)8 JCClassDecl (com.sun.tools.javac.tree.JCTree.JCClassDecl)8