Example usage for org.eclipse.jdt.internal.compiler.ast Argument Argument

List of usage examples for org.eclipse.jdt.internal.compiler.ast Argument Argument

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast Argument Argument.

Prototype

public Argument(char[] name, long posNom, TypeReference tr, int modifiers) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private AbstractMethodDeclaration convert(SourceMethod methodHandle, SourceMethodElementInfo methodInfo,
        CompilationResult compilationResult) throws JavaModelException {
    AbstractMethodDeclaration method;// w  ww  . j  a  va  2  s .c  o  m

    /* only source positions available */
    int start = methodInfo.getNameSourceStart();
    int end = methodInfo.getNameSourceEnd();

    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=324850, Even when this type is being constructed
       on behalf of a 1.4 project we must internalize type variables properly in order to be able to
       recognize usages of them in the method signature, to apply substitutions and thus to be able to
       detect overriding in the presence of generics. If we simply drop them, when the method signature
       refers to the type parameter, we won't know it should be bound to the type parameter and perform
       incorrect lookup and may mistakenly end up with missing types
     */
    TypeParameter[] typeParams = null;
    char[][] typeParameterNames = methodInfo.getTypeParameterNames();
    if (typeParameterNames != null) {
        int parameterCount = typeParameterNames.length;
        if (parameterCount > 0) { // method's type parameters must be null if no type parameter
            char[][][] typeParameterBounds = methodInfo.getTypeParameterBounds();
            typeParams = new TypeParameter[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                typeParams[i] = createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start, end);
            }
        }
    }

    int modifiers = methodInfo.getModifiers();
    if (methodInfo.isConstructor()) {
        ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
        decl.bits &= ~ASTNode.IsDefaultConstructor;
        method = decl;
        decl.typeParameters = typeParams;
    } else {
        MethodDeclaration decl;
        if (methodInfo.isAnnotationMethod()) {
            AnnotationMethodDeclaration annotationMethodDeclaration = new AnnotationMethodDeclaration(
                    compilationResult);

            /* conversion of default value */
            SourceAnnotationMethodInfo annotationMethodInfo = (SourceAnnotationMethodInfo) methodInfo;
            boolean hasDefaultValue = annotationMethodInfo.defaultValueStart != -1
                    || annotationMethodInfo.defaultValueEnd != -1;
            if ((this.flags & FIELD_INITIALIZATION) != 0) {
                if (hasDefaultValue) {
                    char[] defaultValueSource = CharOperation.subarray(getSource(),
                            annotationMethodInfo.defaultValueStart, annotationMethodInfo.defaultValueEnd + 1);
                    if (defaultValueSource != null) {
                        Expression expression = parseMemberValue(defaultValueSource);
                        if (expression != null) {
                            annotationMethodDeclaration.defaultValue = expression;
                        }
                    } else {
                        // could not retrieve the default value
                        hasDefaultValue = false;
                    }
                }
            }
            if (hasDefaultValue)
                modifiers |= ClassFileConstants.AccAnnotationDefault;
            decl = annotationMethodDeclaration;
        } else {
            decl = new MethodDeclaration(compilationResult);
        }

        // convert return type
        decl.returnType = createTypeReference(methodInfo.getReturnTypeName(), start, end);

        // type parameters
        decl.typeParameters = typeParams;

        method = decl;
    }
    method.selector = methodHandle.getElementName().toCharArray();
    boolean isVarargs = (modifiers & ClassFileConstants.AccVarargs) != 0;
    method.modifiers = modifiers & ~ClassFileConstants.AccVarargs;
    method.sourceStart = start;
    method.sourceEnd = end;
    method.declarationSourceStart = methodInfo.getDeclarationSourceStart();
    method.declarationSourceEnd = methodInfo.getDeclarationSourceEnd();

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert annotations */
        method.annotations = convertAnnotations(methodHandle);
    }

    /* convert arguments */
    String[] argumentTypeSignatures = methodHandle.getParameterTypes();
    char[][] argumentNames = methodInfo.getArgumentNames();
    int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
    if (argumentCount > 0) {
        ILocalVariable[] parameters = methodHandle.getParameters();
        long position = ((long) start << 32) + end;
        method.arguments = new Argument[argumentCount];
        for (int i = 0; i < argumentCount; i++) {
            TypeReference typeReference = createTypeReference(argumentTypeSignatures[i], start, end);
            if (isVarargs && i == argumentCount - 1) {
                typeReference.bits |= ASTNode.IsVarArgs;
            }
            method.arguments[i] = new Argument(argumentNames[i], position, typeReference,
                    ClassFileConstants.AccDefault);
            // do not care whether was final or not
            // convert 1.5 specific constructs only if compliance is 1.5 or above
            if (this.has1_5Compliance) {
                /* convert annotations */
                method.arguments[i].annotations = convertAnnotations(parameters[i]);
            }
        }
    }

    /* convert thrown exceptions */
    char[][] exceptionTypeNames = methodInfo.getExceptionTypeNames();
    int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
    if (exceptionCount > 0) {
        method.thrownExceptions = new TypeReference[exceptionCount];
        for (int i = 0; i < exceptionCount; i++) {
            method.thrownExceptions[i] = createTypeReference(exceptionTypeNames[i], start, end);
        }
    }

    /* convert local and anonymous types */
    if ((this.flags & LOCAL_TYPE) != 0) {
        IJavaElement[] children = methodInfo.getChildren();
        int typesLength = children.length;
        if (typesLength != 0) {
            Statement[] statements = new Statement[typesLength];
            for (int i = 0; i < typesLength; i++) {
                SourceType type = (SourceType) children[i];
                TypeDeclaration localType = convert(type, compilationResult);
                if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
                    QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
                    expression.type = localType.superclass;
                    localType.superclass = null;
                    localType.superInterfaces = null;
                    localType.allocation = expression;
                    statements[i] = expression;
                } else {
                    statements[i] = localType;
                }
            }
            method.statements = statements;
        }
    }

    return method;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.BinaryTypeConverter.java

License:Open Source License

private AbstractMethodDeclaration convert(IMethod method, IType type) throws JavaModelException {

    AbstractMethodDeclaration methodDeclaration;

    org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParams = null;

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert type parameters */
        ITypeParameter[] typeParameters = method.getTypeParameters();
        if (typeParameters != null && typeParameters.length > 0) {
            int parameterCount = typeParameters.length;
            typeParams = new org.eclipse.jdt.internal.compiler.ast.TypeParameter[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                ITypeParameter typeParameter = typeParameters[i];
                typeParams[i] = createTypeParameter(typeParameter.getElementName().toCharArray(),
                        stringArrayToCharArray(typeParameter.getBounds()), 0, 0);
            }//  ww  w. j  a va2 s  .co  m
        }
    }

    if (method.isConstructor()) {
        ConstructorDeclaration decl = new ConstructorDeclaration(this.compilationResult);
        decl.bits &= ~ASTNode.IsDefaultConstructor;
        decl.typeParameters = typeParams;
        methodDeclaration = decl;
    } else {
        MethodDeclaration decl = type.isAnnotation() ? new AnnotationMethodDeclaration(this.compilationResult)
                : new MethodDeclaration(this.compilationResult);
        /* convert return type */
        TypeReference typeReference = createTypeReference(method.getReturnType());
        if (typeReference == null)
            return null;
        decl.returnType = typeReference;
        decl.typeParameters = typeParams;
        methodDeclaration = decl;
    }
    methodDeclaration.selector = method.getElementName().toCharArray();
    int flags = method.getFlags();
    boolean isVarargs = Flags.isVarargs(flags);
    methodDeclaration.modifiers = flags & ~Flags.AccVarargs;

    /* convert arguments */
    String[] argumentTypeNames = method.getParameterTypes();
    String[] argumentNames = method.getParameterNames();
    int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length;
    // Ignore synthetic arguments (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=212224)
    int startIndex = (method.isConstructor() && type.isMember() && !Flags.isStatic(type.getFlags())) ? 1 : 0;
    argumentCount -= startIndex;
    methodDeclaration.arguments = new Argument[argumentCount];
    for (int i = 0; i < argumentCount; i++) {
        String argumentTypeName = argumentTypeNames[startIndex + i];
        TypeReference typeReference = createTypeReference(argumentTypeName);
        if (typeReference == null)
            return null;
        if (isVarargs && i == argumentCount - 1) {
            typeReference.bits |= ASTNode.IsVarArgs;
        }
        methodDeclaration.arguments[i] = new Argument(argumentNames[i].toCharArray(), 0, typeReference,
                ClassFileConstants.AccDefault);
        // do not care whether was final or not
    }

    /* convert thrown exceptions */
    String[] exceptionTypeNames = method.getExceptionTypes();
    int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
    if (exceptionCount > 0) {
        methodDeclaration.thrownExceptions = new TypeReference[exceptionCount];
        for (int i = 0; i < exceptionCount; i++) {
            TypeReference typeReference = createTypeReference(exceptionTypeNames[i]);
            if (typeReference == null)
                return null;
            methodDeclaration.thrownExceptions[i] = typeReference;
        }
    }
    return methodDeclaration;
}

From source file:lombok.eclipse.agent.PatchDelegate.java

License:Open Source License

private static MethodDeclaration createDelegateMethod(char[] name, EclipseNode typeNode, BindingTuple pair,
        CompilationResult compilationResult, EclipseNode annNode, DelegateReceiver delegateReceiver) {
    /* public <T, U, ...> ReturnType methodName(ParamType1 name1, ParamType2 name2, ...) throws T1, T2, ... {
     *      (return) delegate.<T, U>methodName(name1, name2);
     *  }/*from w w  w .  ja v a 2s.  c o m*/
     */

    boolean isVarargs = (pair.base.modifiers & ClassFileConstants.AccVarargs) != 0;

    try {
        checkConflictOfTypeVarNames(pair, typeNode);
    } catch (CantMakeDelegates e) {
        annNode.addError(
                "There's a conflict in the names of type parameters. Fix it by renaming the following type parameters of your class: "
                        + e.conflicted);
        return null;
    }

    ASTNode source = annNode.get();

    int pS = source.sourceStart, pE = source.sourceEnd;

    MethodBinding binding = pair.parameterized;
    MethodDeclaration method = new MethodDeclaration(compilationResult);
    setGeneratedBy(method, source);
    method.sourceStart = pS;
    method.sourceEnd = pE;
    method.modifiers = ClassFileConstants.AccPublic;

    method.returnType = makeType(binding.returnType, source, false);
    boolean isDeprecated = binding.isDeprecated();

    method.selector = binding.selector;

    if (binding.thrownExceptions != null && binding.thrownExceptions.length > 0) {
        method.thrownExceptions = new TypeReference[binding.thrownExceptions.length];
        for (int i = 0; i < method.thrownExceptions.length; i++) {
            method.thrownExceptions[i] = makeType(binding.thrownExceptions[i], source, false);
        }
    }

    MessageSend call = new MessageSend();
    call.sourceStart = pS;
    call.sourceEnd = pE;
    call.nameSourcePosition = pos(source);
    setGeneratedBy(call, source);
    call.receiver = delegateReceiver.get(source, name);
    call.selector = binding.selector;

    if (binding.typeVariables != null && binding.typeVariables.length > 0) {
        method.typeParameters = new TypeParameter[binding.typeVariables.length];
        call.typeArguments = new TypeReference[binding.typeVariables.length];
        for (int i = 0; i < method.typeParameters.length; i++) {
            method.typeParameters[i] = new TypeParameter();
            method.typeParameters[i].sourceStart = pS;
            method.typeParameters[i].sourceEnd = pE;
            setGeneratedBy(method.typeParameters[i], source);
            method.typeParameters[i].name = binding.typeVariables[i].sourceName;
            call.typeArguments[i] = new SingleTypeReference(binding.typeVariables[i].sourceName, pos(source));
            setGeneratedBy(call.typeArguments[i], source);
            ReferenceBinding super1 = binding.typeVariables[i].superclass;
            ReferenceBinding[] super2 = binding.typeVariables[i].superInterfaces;
            if (super2 == null)
                super2 = new ReferenceBinding[0];
            if (super1 != null || super2.length > 0) {
                int offset = super1 == null ? 0 : 1;
                method.typeParameters[i].bounds = new TypeReference[super2.length + offset - 1];
                if (super1 != null)
                    method.typeParameters[i].type = makeType(super1, source, false);
                else
                    method.typeParameters[i].type = makeType(super2[0], source, false);
                int ctr = 0;
                for (int j = (super1 == null) ? 1 : 0; j < super2.length; j++) {
                    method.typeParameters[i].bounds[ctr] = makeType(super2[j], source, false);
                    method.typeParameters[i].bounds[ctr++].bits |= ASTNode.IsSuperType;
                }
            }
        }
    }

    if (isDeprecated) {
        method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) };
    }

    method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;

    if (binding.parameters != null && binding.parameters.length > 0) {
        method.arguments = new Argument[binding.parameters.length];
        call.arguments = new Expression[method.arguments.length];
        for (int i = 0; i < method.arguments.length; i++) {
            AbstractMethodDeclaration sourceElem;
            try {
                sourceElem = pair.base.sourceMethod();
            } catch (Exception e) {
                sourceElem = null;
            }
            char[] argName;
            if (sourceElem == null)
                argName = ("arg" + i).toCharArray();
            else {
                argName = sourceElem.arguments[i].name;
            }
            method.arguments[i] = new Argument(argName, pos(source),
                    makeType(binding.parameters[i], source, false), ClassFileConstants.AccFinal);
            setGeneratedBy(method.arguments[i], source);
            call.arguments[i] = new SingleNameReference(argName, pos(source));
            setGeneratedBy(call.arguments[i], source);
        }
        if (isVarargs) {
            method.arguments[method.arguments.length - 1].type.bits |= ASTNode.IsVarArgs;
        }
    }

    Statement body;
    if (method.returnType instanceof SingleTypeReference
            && ((SingleTypeReference) method.returnType).token == TypeConstants.VOID) {
        body = call;
    } else {
        body = new ReturnStatement(call, source.sourceStart, source.sourceEnd);
        setGeneratedBy(body, source);
    }

    method.statements = new Statement[] { body };
    return method;
}

From source file:lombok.eclipse.handlers.ast.EclipseASTMaker.java

License:Open Source License

@Override
public ASTNode visitArgument(final lombok.ast.Argument node, final Void p) {
    final Argument argument = new Argument(node.getName().toCharArray(), 0, null, 0);
    setGeneratedByAndCopyPos(argument, source, posHintOf(node));
    argument.modifiers = modifiersFor(node.getModifiers());
    argument.annotations = toArray(build(node.getAnnotations()), new Annotation[0]);
    argument.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    argument.type = build(node.getType());
    return argument;
}

From source file:lombok.eclipse.handlers.HandleConstructor.java

License:Open Source License

public static ConstructorDeclaration createConstructor(AccessLevel level, EclipseNode type,
        Collection<EclipseNode> fields, boolean allToDefault, Boolean suppressConstructorProperties,
        EclipseNode sourceNode, List<Annotation> onConstructor) {

    ASTNode source = sourceNode.get();/*ww  w . j  ava 2 s .c  o m*/
    TypeDeclaration typeDeclaration = ((TypeDeclaration) type.get());
    long p = (long) source.sourceStart << 32 | source.sourceEnd;

    boolean isEnum = (((TypeDeclaration) type.get()).modifiers & ClassFileConstants.AccEnum) != 0;

    if (isEnum)
        level = AccessLevel.PRIVATE;

    if (suppressConstructorProperties == null) {
        if (fields.isEmpty()) {
            suppressConstructorProperties = false;
        } else {
            suppressConstructorProperties = Boolean.TRUE.equals(type.getAst()
                    .readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES));
        }
    }

    ConstructorDeclaration constructor = new ConstructorDeclaration(
            ((CompilationUnitDeclaration) type.top().get()).compilationResult);

    constructor.modifiers = toEclipseModifier(level);
    constructor.selector = typeDeclaration.name;
    constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
    constructor.constructorCall.sourceStart = source.sourceStart;
    constructor.constructorCall.sourceEnd = source.sourceEnd;
    constructor.thrownExceptions = null;
    constructor.typeParameters = null;
    constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
    constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;
    constructor.arguments = null;

    List<Argument> params = new ArrayList<Argument>();
    List<Statement> assigns = new ArrayList<Statement>();
    List<Statement> nullChecks = new ArrayList<Statement>();

    for (EclipseNode fieldNode : fields) {
        FieldDeclaration field = (FieldDeclaration) fieldNode.get();
        char[] rawName = field.name;
        char[] fieldName = removePrefixFromField(fieldNode);
        FieldReference thisX = new FieldReference(rawName, p);
        int s = (int) (p >> 32);
        int e = (int) p;
        thisX.receiver = new ThisReference(s, e);

        Expression assignmentExpr = allToDefault ? getDefaultExpr(field.type, s, e)
                : new SingleNameReference(fieldName, p);

        Assignment assignment = new Assignment(thisX, assignmentExpr, (int) p);
        assignment.sourceStart = (int) (p >> 32);
        assignment.sourceEnd = assignment.statementEnd = (int) (p >> 32);
        assigns.add(assignment);
        if (!allToDefault) {
            long fieldPos = (((long) field.sourceStart) << 32) | field.sourceEnd;
            Argument parameter = new Argument(fieldName, fieldPos, copyType(field.type, source),
                    Modifier.FINAL);
            Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN);
            Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN);
            if (nonNulls.length != 0) {
                Statement nullCheck = generateNullCheck(field, sourceNode);
                if (nullCheck != null)
                    nullChecks.add(nullCheck);
            }
            parameter.annotations = copyAnnotations(source, nonNulls, nullables);
            params.add(parameter);
        }
    }

    nullChecks.addAll(assigns);
    constructor.statements = nullChecks.isEmpty() ? null : nullChecks.toArray(new Statement[nullChecks.size()]);
    constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]);

    /* Generate annotations that must  be put on the generated method, and attach them. */ {
        Annotation[] constructorProperties = null;
        if (!allToDefault && !suppressConstructorProperties && level != AccessLevel.PRIVATE
                && level != AccessLevel.PACKAGE && !isLocalType(type)) {
            constructorProperties = createConstructorProperties(source, fields);
        }

        constructor.annotations = copyAnnotations(source, onConstructor.toArray(new Annotation[0]),
                constructorProperties);
    }

    constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope);
    return constructor;
}

From source file:lombok.eclipse.handlers.HandleConstructor.java

License:Open Source License

public MethodDeclaration createStaticConstructor(AccessLevel level, String name, EclipseNode type,
        Collection<EclipseNode> fields, ASTNode source) {
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    MethodDeclaration constructor = new MethodDeclaration(
            ((CompilationUnitDeclaration) type.top().get()).compilationResult);

    constructor.modifiers = toEclipseModifier(level) | ClassFileConstants.AccStatic;
    TypeDeclaration typeDecl = (TypeDeclaration) type.get();
    constructor.returnType = EclipseHandlerUtil.namePlusTypeParamsToTypeReference(typeDecl.name,
            typeDecl.typeParameters, p);
    constructor.annotations = null;//  ww w .j  a  va 2s .  co  m
    constructor.selector = name.toCharArray();
    constructor.thrownExceptions = null;
    constructor.typeParameters = copyTypeParams(((TypeDeclaration) type.get()).typeParameters, source);
    constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
    constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;

    List<Argument> params = new ArrayList<Argument>();
    List<Expression> assigns = new ArrayList<Expression>();
    AllocationExpression statement = new AllocationExpression();
    statement.sourceStart = pS;
    statement.sourceEnd = pE;
    statement.type = copyType(constructor.returnType, source);

    for (EclipseNode fieldNode : fields) {
        FieldDeclaration field = (FieldDeclaration) fieldNode.get();
        long fieldPos = (((long) field.sourceStart) << 32) | field.sourceEnd;
        SingleNameReference nameRef = new SingleNameReference(field.name, fieldPos);
        assigns.add(nameRef);

        Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL);
        parameter.annotations = copyAnnotations(source, findAnnotations(field, NON_NULL_PATTERN),
                findAnnotations(field, NULLABLE_PATTERN));
        params.add(parameter);
    }

    statement.arguments = assigns.isEmpty() ? null : assigns.toArray(new Expression[assigns.size()]);
    constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]);
    constructor.statements = new Statement[] { new ReturnStatement(statement, (int) (p >> 32), (int) p) };

    constructor.traverse(new SetGeneratedByVisitor(source), typeDecl.scope);
    return constructor;
}

From source file:lombok.eclipse.handlers.HandleEqualsAndHashCode.java

License:Open Source License

public MethodDeclaration createEquals(EclipseNode type, Collection<EclipseNode> fields, boolean callSuper,
        ASTNode source, FieldAccess fieldAccess, boolean needsCanEqual, List<Annotation> onParam) {
    int pS = source.sourceStart;
    int pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;
    TypeDeclaration typeDecl = (TypeDeclaration) type.get();

    MethodDeclaration method = new MethodDeclaration(
            ((CompilationUnitDeclaration) type.top().get()).compilationResult);
    setGeneratedBy(method, source);//from w  w  w . ja  v a  2  s .co  m
    method.modifiers = toEclipseModifier(AccessLevel.PUBLIC);
    method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
    method.returnType.sourceStart = pS;
    method.returnType.sourceEnd = pE;
    setGeneratedBy(method.returnType, source);
    method.annotations = new Annotation[] { makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source) };
    method.selector = "equals".toCharArray();
    method.thrownExceptions = null;
    method.typeParameters = null;
    method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
    method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
    TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT,
            new long[] { p, p, p });
    setGeneratedBy(objectRef, source);
    method.arguments = new Argument[] { new Argument(new char[] { 'o' }, 0, objectRef, Modifier.FINAL) };
    method.arguments[0].sourceStart = pS;
    method.arguments[0].sourceEnd = pE;
    if (!onParam.isEmpty())
        method.arguments[0].annotations = onParam.toArray(new Annotation[0]);
    setGeneratedBy(method.arguments[0], source);

    List<Statement> statements = new ArrayList<Statement>();

    /* if (o == this) return true; */ {
        SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p);
        setGeneratedBy(oRef, source);
        ThisReference thisRef = new ThisReference(pS, pE);
        setGeneratedBy(thisRef, source);
        EqualExpression otherEqualsThis = new EqualExpression(oRef, thisRef, OperatorIds.EQUAL_EQUAL);
        setGeneratedBy(otherEqualsThis, source);

        TrueLiteral trueLiteral = new TrueLiteral(pS, pE);
        setGeneratedBy(trueLiteral, source);
        ReturnStatement returnTrue = new ReturnStatement(trueLiteral, pS, pE);
        setGeneratedBy(returnTrue, source);
        IfStatement ifOtherEqualsThis = new IfStatement(otherEqualsThis, returnTrue, pS, pE);
        setGeneratedBy(ifOtherEqualsThis, source);
        statements.add(ifOtherEqualsThis);
    }

    /* if (!(o instanceof Outer.Inner.MyType) return false; */ {
        SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p);
        setGeneratedBy(oRef, source);

        TypeReference typeReference = createTypeReference(type, p);
        setGeneratedBy(typeReference, source);

        InstanceOfExpression instanceOf = new InstanceOfExpression(oRef, typeReference);
        instanceOf.sourceStart = pS;
        instanceOf.sourceEnd = pE;
        setGeneratedBy(instanceOf, source);

        Expression notInstanceOf = new UnaryExpression(instanceOf, OperatorIds.NOT);
        setGeneratedBy(notInstanceOf, source);

        FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
        setGeneratedBy(falseLiteral, source);

        ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE);
        setGeneratedBy(returnFalse, source);

        IfStatement ifNotInstanceOf = new IfStatement(notInstanceOf, returnFalse, pS, pE);
        setGeneratedBy(ifNotInstanceOf, source);
        statements.add(ifNotInstanceOf);
    }

    char[] otherName = "other".toCharArray();

    /* MyType<?> other = (MyType<?>) o; */ {
        if (!fields.isEmpty() || needsCanEqual) {
            LocalDeclaration other = new LocalDeclaration(otherName, pS, pE);
            other.modifiers |= ClassFileConstants.AccFinal;
            setGeneratedBy(other, source);
            char[] typeName = typeDecl.name;
            TypeReference targetType;
            if (typeDecl.typeParameters == null || typeDecl.typeParameters.length == 0) {
                targetType = new SingleTypeReference(typeName, p);
                setGeneratedBy(targetType, source);
                other.type = new SingleTypeReference(typeName, p);
                setGeneratedBy(other.type, source);
            } else {
                TypeReference[] typeArgs = new TypeReference[typeDecl.typeParameters.length];
                for (int i = 0; i < typeArgs.length; i++) {
                    typeArgs[i] = new Wildcard(Wildcard.UNBOUND);
                    typeArgs[i].sourceStart = pS;
                    typeArgs[i].sourceEnd = pE;
                    setGeneratedBy(typeArgs[i], source);
                }
                targetType = new ParameterizedSingleTypeReference(typeName, typeArgs, 0, p);
                setGeneratedBy(targetType, source);
                other.type = new ParameterizedSingleTypeReference(typeName, copyTypes(typeArgs, source), 0, p);
                setGeneratedBy(other.type, source);
            }
            NameReference oRef = new SingleNameReference(new char[] { 'o' }, p);
            setGeneratedBy(oRef, source);
            other.initialization = makeCastExpression(oRef, targetType, source);
            statements.add(other);
        }
    }

    /* if (!other.canEqual((java.lang.Object) this)) return false; */ {
        if (needsCanEqual) {
            MessageSend otherCanEqual = new MessageSend();
            otherCanEqual.sourceStart = pS;
            otherCanEqual.sourceEnd = pE;
            setGeneratedBy(otherCanEqual, source);
            otherCanEqual.receiver = new SingleNameReference(otherName, p);
            setGeneratedBy(otherCanEqual.receiver, source);
            otherCanEqual.selector = "canEqual".toCharArray();

            ThisReference thisReference = new ThisReference(pS, pE);
            setGeneratedBy(thisReference, source);
            CastExpression castThisRef = makeCastExpression(thisReference,
                    generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), source);
            castThisRef.sourceStart = pS;
            castThisRef.sourceEnd = pE;

            otherCanEqual.arguments = new Expression[] { castThisRef };

            Expression notOtherCanEqual = new UnaryExpression(otherCanEqual, OperatorIds.NOT);
            setGeneratedBy(notOtherCanEqual, source);

            FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
            setGeneratedBy(falseLiteral, source);

            ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE);
            setGeneratedBy(returnFalse, source);

            IfStatement ifNotCanEqual = new IfStatement(notOtherCanEqual, returnFalse, pS, pE);
            setGeneratedBy(ifNotCanEqual, source);

            statements.add(ifNotCanEqual);
        }
    }

    /* if (!super.equals(o)) return false; */
    if (callSuper) {
        MessageSend callToSuper = new MessageSend();
        callToSuper.sourceStart = pS;
        callToSuper.sourceEnd = pE;
        setGeneratedBy(callToSuper, source);
        callToSuper.receiver = new SuperReference(pS, pE);
        setGeneratedBy(callToSuper.receiver, source);
        callToSuper.selector = "equals".toCharArray();
        SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p);
        setGeneratedBy(oRef, source);
        callToSuper.arguments = new Expression[] { oRef };
        Expression superNotEqual = new UnaryExpression(callToSuper, OperatorIds.NOT);
        setGeneratedBy(superNotEqual, source);
        FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
        setGeneratedBy(falseLiteral, source);
        ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE);
        setGeneratedBy(returnFalse, source);
        IfStatement ifSuperEquals = new IfStatement(superNotEqual, returnFalse, pS, pE);
        setGeneratedBy(ifSuperEquals, source);
        statements.add(ifSuperEquals);
    }

    for (EclipseNode field : fields) {
        TypeReference fType = getFieldType(field, fieldAccess);
        char[] token = fType.getLastToken();
        Expression thisFieldAccessor = createFieldAccessor(field, fieldAccess, source);
        Expression otherFieldAccessor = createFieldAccessor(field, fieldAccess, source, otherName);

        if (fType.dimensions() == 0 && token != null) {
            if (Arrays.equals(TypeConstants.FLOAT, token)) {
                statements.add(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor,
                        "Float".toCharArray(), source));
            } else if (Arrays.equals(TypeConstants.DOUBLE, token)) {
                statements.add(generateCompareFloatOrDouble(thisFieldAccessor, otherFieldAccessor,
                        "Double".toCharArray(), source));
            } else if (BUILT_IN_TYPES.contains(new String(token))) {
                EqualExpression fieldsNotEqual = new EqualExpression(thisFieldAccessor, otherFieldAccessor,
                        OperatorIds.NOT_EQUAL);
                setGeneratedBy(fieldsNotEqual, source);
                FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
                setGeneratedBy(falseLiteral, source);
                ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE);
                setGeneratedBy(returnStatement, source);
                IfStatement ifStatement = new IfStatement(fieldsNotEqual, returnStatement, pS, pE);
                setGeneratedBy(ifStatement, source);
                statements.add(ifStatement);
            } else /* objects */ {
                /* final java.lang.Object this$fieldName = this.fieldName; */
                /* final java.lang.Object other$fieldName = other.fieldName; */
                /* if (this$fieldName == null ? other$fieldName != null : !this$fieldName.equals(other$fieldName)) return false;; */
                char[] thisDollarFieldName = ("this$" + field.getName()).toCharArray();
                char[] otherDollarFieldName = ("other$" + field.getName()).toCharArray();

                statements.add(createLocalDeclaration(source, thisDollarFieldName,
                        generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), thisFieldAccessor));
                statements.add(createLocalDeclaration(source, otherDollarFieldName,
                        generateQualifiedTypeRef(source, TypeConstants.JAVA_LANG_OBJECT), otherFieldAccessor));

                SingleNameReference this1 = new SingleNameReference(thisDollarFieldName, p);
                setGeneratedBy(this1, source);
                SingleNameReference this2 = new SingleNameReference(thisDollarFieldName, p);
                setGeneratedBy(this2, source);
                SingleNameReference other1 = new SingleNameReference(otherDollarFieldName, p);
                setGeneratedBy(other1, source);
                SingleNameReference other2 = new SingleNameReference(otherDollarFieldName, p);
                setGeneratedBy(other2, source);

                NullLiteral nullLiteral = new NullLiteral(pS, pE);
                setGeneratedBy(nullLiteral, source);
                EqualExpression fieldIsNull = new EqualExpression(this1, nullLiteral, OperatorIds.EQUAL_EQUAL);
                nullLiteral = new NullLiteral(pS, pE);
                setGeneratedBy(nullLiteral, source);
                EqualExpression otherFieldIsntNull = new EqualExpression(other1, nullLiteral,
                        OperatorIds.NOT_EQUAL);
                MessageSend equalsCall = new MessageSend();
                equalsCall.sourceStart = pS;
                equalsCall.sourceEnd = pE;
                setGeneratedBy(equalsCall, source);
                equalsCall.receiver = this2;
                equalsCall.selector = "equals".toCharArray();
                equalsCall.arguments = new Expression[] { other2 };
                UnaryExpression fieldsNotEqual = new UnaryExpression(equalsCall, OperatorIds.NOT);
                fieldsNotEqual.sourceStart = pS;
                fieldsNotEqual.sourceEnd = pE;
                setGeneratedBy(fieldsNotEqual, source);
                ConditionalExpression fullEquals = new ConditionalExpression(fieldIsNull, otherFieldIsntNull,
                        fieldsNotEqual);
                fullEquals.sourceStart = pS;
                fullEquals.sourceEnd = pE;
                setGeneratedBy(fullEquals, source);
                FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
                setGeneratedBy(falseLiteral, source);
                ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE);
                setGeneratedBy(returnStatement, source);
                IfStatement ifStatement = new IfStatement(fullEquals, returnStatement, pS, pE);
                setGeneratedBy(ifStatement, source);
                statements.add(ifStatement);
            }
        } else if (fType.dimensions() > 0 && token != null) {
            MessageSend arraysEqualCall = new MessageSend();
            arraysEqualCall.sourceStart = pS;
            arraysEqualCall.sourceEnd = pE;
            setGeneratedBy(arraysEqualCall, source);
            arraysEqualCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL,
                    "Arrays".toCharArray());
            if (fType.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) {
                arraysEqualCall.selector = "deepEquals".toCharArray();
            } else {
                arraysEqualCall.selector = "equals".toCharArray();
            }
            arraysEqualCall.arguments = new Expression[] { thisFieldAccessor, otherFieldAccessor };
            UnaryExpression arraysNotEqual = new UnaryExpression(arraysEqualCall, OperatorIds.NOT);
            arraysNotEqual.sourceStart = pS;
            arraysNotEqual.sourceEnd = pE;
            setGeneratedBy(arraysNotEqual, source);
            FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
            setGeneratedBy(falseLiteral, source);
            ReturnStatement returnStatement = new ReturnStatement(falseLiteral, pS, pE);
            setGeneratedBy(returnStatement, source);
            IfStatement ifStatement = new IfStatement(arraysNotEqual, returnStatement, pS, pE);
            setGeneratedBy(ifStatement, source);
            statements.add(ifStatement);
        }
    }

    /* return true; */ {
        TrueLiteral trueLiteral = new TrueLiteral(pS, pE);
        setGeneratedBy(trueLiteral, source);
        ReturnStatement returnStatement = new ReturnStatement(trueLiteral, pS, pE);
        setGeneratedBy(returnStatement, source);
        statements.add(returnStatement);
    }
    method.statements = statements.toArray(new Statement[statements.size()]);
    return method;
}

From source file:lombok.eclipse.handlers.HandleEqualsAndHashCode.java

License:Open Source License

public MethodDeclaration createCanEqual(EclipseNode type, ASTNode source, List<Annotation> onParam) {
    /* public boolean canEqual(final java.lang.Object other) {
     *     return other instanceof Outer.Inner.MyType;
     * }/*  w w  w. j a  v  a 2s  . c o m*/
     */
    int pS = source.sourceStart;
    int pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    char[] otherName = "other".toCharArray();

    MethodDeclaration method = new MethodDeclaration(
            ((CompilationUnitDeclaration) type.top().get()).compilationResult);
    setGeneratedBy(method, source);
    method.modifiers = toEclipseModifier(AccessLevel.PROTECTED);
    method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
    method.returnType.sourceStart = pS;
    method.returnType.sourceEnd = pE;
    setGeneratedBy(method.returnType, source);
    method.selector = "canEqual".toCharArray();
    method.thrownExceptions = null;
    method.typeParameters = null;
    method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
    method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
    TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT,
            new long[] { p, p, p });
    setGeneratedBy(objectRef, source);
    method.arguments = new Argument[] { new Argument(otherName, 0, objectRef, Modifier.FINAL) };
    method.arguments[0].sourceStart = pS;
    method.arguments[0].sourceEnd = pE;
    if (!onParam.isEmpty())
        method.arguments[0].annotations = onParam.toArray(new Annotation[0]);
    setGeneratedBy(method.arguments[0], source);

    SingleNameReference otherRef = new SingleNameReference(otherName, p);
    setGeneratedBy(otherRef, source);

    TypeReference typeReference = createTypeReference(type, p);
    setGeneratedBy(typeReference, source);

    InstanceOfExpression instanceOf = new InstanceOfExpression(otherRef, typeReference);
    instanceOf.sourceStart = pS;
    instanceOf.sourceEnd = pE;
    setGeneratedBy(instanceOf, source);

    ReturnStatement returnStatement = new ReturnStatement(instanceOf, pS, pE);
    setGeneratedBy(returnStatement, source);

    method.statements = new Statement[] { returnStatement };
    return method;
}

From source file:lombok.eclipse.handlers.HandleRelations.java

License:Open Source License

private static MethodDeclaration createGetReferencedKeyMethod(ASTNode source, String relatedFieldName,
        boolean isOneToOne, TypeReference baseType, TypeReference referenceType, CompilationResult compResult) {
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    MethodDeclaration getReferencedKey = new MethodDeclaration(compResult);
    setGeneratedBy(getReferencedKey, source);
    getReferencedKey.modifiers = ClassFileConstants.AccPublic;
    getReferencedKey.annotations = new Annotation[] {
            makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source) };
    getReferencedKey.returnType = createTypeReference(Long.class, p);
    setGeneratedBy(getReferencedKey.returnType, source);
    getReferencedKey.returnType.sourceStart = pS;
    getReferencedKey.returnType.sourceEnd = pE;
    getReferencedKey.arguments = new Argument[] { new Argument("item".toCharArray(), 0,
            (isOneToOne ? baseType : referenceType), ClassFileConstants.AccFinal) };
    setGeneratedBy(getReferencedKey.arguments[0], source);
    getReferencedKey.arguments[0].sourceStart = pS;
    getReferencedKey.arguments[0].sourceEnd = pE;
    getReferencedKey.selector = "getReferencedKey".toCharArray();
    getReferencedKey.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    getReferencedKey.bodyStart = getReferencedKey.declarationSourceStart = getReferencedKey.sourceStart = source.sourceStart;
    getReferencedKey.bodyEnd = getReferencedKey.declarationSourceEnd = getReferencedKey.sourceEnd = source.sourceEnd;

    MessageSend getRelatedFieldName = new MessageSend();
    setGeneratedBy(getRelatedFieldName, source);
    getRelatedFieldName.sourceStart = pS;
    getRelatedFieldName.sourceEnd = pE;//from   ww w .j  av a2 s. c  o  m
    getRelatedFieldName.receiver = new SingleNameReference("item".toCharArray(), p);
    setGeneratedBy(getRelatedFieldName.receiver, source);
    getRelatedFieldName.receiver.sourceStart = pS;
    getRelatedFieldName.receiver.sourceEnd = pE;
    getRelatedFieldName.selector = ("get" + toProperCase(relatedFieldName)).toCharArray();

    ReturnStatement returnStatement = new ReturnStatement(getRelatedFieldName, pS, pE);
    setGeneratedBy(returnStatement, source);

    getReferencedKey.statements = new Statement[] { returnStatement };

    return getReferencedKey;
}

From source file:lombok.eclipse.handlers.HandleRelations.java

License:Open Source License

private static MethodDeclaration createSetReferencedObjectMethod(FieldDeclaration fieldDecl, ASTNode source,
        String relatedFieldName, boolean isOneToOne, boolean isUnique, TypeReference baseType,
        TypeReference referenceType, CompilationUnitDeclaration compilationUnitDeclaration) {
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    TypeReference refType = fieldDecl.type;

    if (isUnique) {
        refType = new ParameterizedQualifiedTypeReference(Eclipse.fromQualifiedName(List.class.getName()),
                new TypeReference[][] { null, null, new TypeReference[] { refType } }, 0,
                new long[] { p, p, p });
        setGeneratedBy(refType, source);
        refType.sourceStart = pS;/*from  w  w w  .j a v  a2  s .c o m*/
        refType.sourceEnd = pE;
    }

    MethodDeclaration setReferencedObject = new MethodDeclaration(compilationUnitDeclaration.compilationResult);
    setGeneratedBy(setReferencedObject, source);
    setReferencedObject.modifiers = ClassFileConstants.AccPublic;
    setReferencedObject.annotations = new Annotation[] {
            makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source) };
    setReferencedObject.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
    setReferencedObject.returnType.sourceStart = pS;
    setReferencedObject.returnType.sourceEnd = pE;
    setReferencedObject.arguments = new Argument[] {
            new Argument("item".toCharArray(), 0, baseType, ClassFileConstants.AccFinal),
            new Argument("related".toCharArray(), 0, refType, ClassFileConstants.AccFinal), };
    setGeneratedBy(setReferencedObject.arguments[0], source);
    setGeneratedBy(setReferencedObject.arguments[1], source);
    setReferencedObject.arguments[0].sourceStart = pS;
    setReferencedObject.arguments[0].sourceEnd = pE;
    setReferencedObject.arguments[1].sourceStart = pS;
    setReferencedObject.arguments[1].sourceEnd = pE;
    setReferencedObject.selector = "setReferencedObject".toCharArray();
    setReferencedObject.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    setReferencedObject.bodyStart = setReferencedObject.declarationSourceStart = setReferencedObject.sourceStart = source.sourceStart;
    setReferencedObject.bodyEnd = setReferencedObject.declarationSourceEnd = setReferencedObject.sourceEnd = source.sourceEnd;

    List<Statement> statements = new ArrayList<Statement>();

    SingleNameReference fieldNameRef = new SingleNameReference("related".toCharArray(), p);
    setGeneratedBy(fieldNameRef, source);
    Expression fieldRef = createFieldAccessor(new String(fieldDecl.name), source, "item".toCharArray());
    setGeneratedBy(fieldRef, source);
    fieldRef.sourceStart = pS;
    fieldRef.sourceEnd = pE;

    if (isUnique) {
        MessageSend get = new MessageSend();
        setGeneratedBy(get, source);
        get.sourceStart = pS;
        get.sourceEnd = get.statementEnd = pE;
        get.receiver = new ThisReference(pS, pE);
        get.selector = "firstOrDefault".toCharArray();
        get.arguments = new Expression[] { fieldNameRef };

        Assignment assignment = new Assignment(fieldRef, get, pE);
        setGeneratedBy(assignment, source);
        assignment.sourceStart = pS;
        assignment.sourceEnd = assignment.statementEnd = pE;

        statements.add(assignment);
    } else {
        Assignment assignment = new Assignment(fieldRef, fieldNameRef, pE);
        assignment.sourceStart = pS;
        assignment.sourceEnd = assignment.statementEnd = pE;
        setGeneratedBy(assignment, source);
        statements.add(assignment);
    }

    setReferencedObject.statements = statements.toArray(new Statement[statements.size()]);

    return setReferencedObject;
}