Example usage for org.eclipse.jdt.internal.compiler.ast Expression resolveType

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

Introduction

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

Prototype

public TypeBinding resolveType(ClassScope scope) 

Source Link

Document

Resolve the type of this expression in the context of a classScope

Usage

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

License:Open Source License

public static TypeBinding skipResolveInitializerIfAlreadyCalled(Expression expr, BlockScope scope) {
    if (expr.resolvedType != null)
        return expr.resolvedType;
    try {//from  w  w  w  .ja  v  a 2  s .  co m
        return expr.resolveType(scope);
    } catch (NullPointerException e) {
        return null;
    }
}

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

License:Open Source License

public static TypeBinding skipResolveInitializerIfAlreadyCalled2(Expression expr, BlockScope scope,
        LocalDeclaration decl) {//from   w w w.j  ava  2  s.  c  o  m
    if (decl != null && LocalDeclaration.class.equals(decl.getClass()) && expr.resolvedType != null)
        return expr.resolvedType;
    try {
        return expr.resolveType(scope);
    } catch (NullPointerException e) {
        return null;
    }
}

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

License:Open Source License

public static boolean handleValForLocalDeclaration(LocalDeclaration local, BlockScope scope) {
    if (local == null || !LocalDeclaration.class.equals(local.getClass()))
        return false;
    boolean decomponent = false;

    if (!isVal(local.type, scope))
        return false;

    StackTraceElement[] st = new Throwable().getStackTrace();
    for (int i = 0; i < st.length - 2 && i < 10; i++) {
        if (st[i].getClassName().equals("lombok.launch.PatchFixesHider$Val")) {
            if (st[i + 1].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration")
                    && st[i + 2].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.ForStatement"))
                return false;
            break;
        }//from w w  w .j a v a 2  s  .  c  o  m
    }

    Expression init = local.initialization;
    if (init == null && Reflection.initCopyField != null) {
        try {
            init = (Expression) Reflection.initCopyField.get(local);
        } catch (Exception e) {
            // init remains null.
        }
    }

    if (init == null && Reflection.iterableCopyField != null) {
        try {
            init = (Expression) Reflection.iterableCopyField.get(local);
            decomponent = true;
        } catch (Exception e) {
            // init remains null.
        }
    }

    TypeReference replacement = null;

    if (init != null) {
        if (init.getClass().getName().equals("org.eclipse.jdt.internal.compiler.ast.LambdaExpression")) {
            return false;
        }

        TypeBinding resolved = null;
        try {
            resolved = decomponent ? getForEachComponentType(init, scope) : init.resolveType(scope);
        } catch (NullPointerException e) {
            // This definitely occurs if as part of resolving the initializer expression, a
            // lambda expression in it must also be resolved (such as when lambdas are part of
            // a ternary expression). This can't result in a viable 'val' matching, so, we
            // just go with 'Object' and let the IDE print the appropriate errors.
            resolved = null;
        }
        if (resolved != null) {
            try {
                replacement = makeType(resolved, local.type, false);
            } catch (Exception e) {
                // Some type thing failed. It might be an IntersectionType
            }
        }
    }

    local.modifiers |= ClassFileConstants.AccFinal;
    local.annotations = addValAnnotation(local.annotations, local.type, scope);
    local.type = replacement != null ? replacement
            : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(local.type, 3));

    return false;
}

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

License:Open Source License

private static TypeBinding getForEachComponentType(Expression collection, BlockScope scope) {
    if (collection != null) {
        TypeBinding resolved = collection.resolvedType;
        if (resolved == null)
            resolved = collection.resolveType(scope);
        if (resolved == null)
            return null;
        if (resolved.isArrayType()) {
            resolved = ((ArrayBinding) resolved).elementsType();
            return resolved;
        } else if (resolved instanceof ReferenceBinding) {
            ReferenceBinding iterableType = ((ReferenceBinding) resolved)
                    .findSuperTypeOriginatingFrom(TypeIds.T_JavaLangIterable, false);

            TypeBinding[] arguments = null;
            if (iterableType != null)
                switch (iterableType.kind()) {
                case Binding.GENERIC_TYPE: // for (T t : Iterable<T>) - in case used inside Iterable itself
                    arguments = iterableType.typeVariables();
                    break;
                case Binding.PARAMETERIZED_TYPE: // for(E e : Iterable<E>)
                    arguments = ((ParameterizedTypeBinding) iterableType).arguments;
                    break;
                case Binding.RAW_TYPE: // for(Object e : Iterable)
                    return null;
                }//from  w w w .j  a va2  s .c  o  m

            if (arguments != null && arguments.length == 1) {
                return arguments[0];
            }
        }
    }

    return null;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.lifting.Lowering.java

License:Open Source License

public Expression lowerExpression(final BlockScope scope, final Expression expression,
        TypeBinding unloweredType, TypeBinding requiredType, final Expression teamExpression,
        boolean needNullCheck, boolean deferredResolve) {
    // Note, unless deferredResolve, this method is responsible for 'resolving' all AST nodes it generates!

    int sourceStart = expression.sourceStart;
    int sourceEnd = expression.sourceEnd;
    AstGenerator gen = new AstGenerator(sourceStart, sourceEnd);

    unloweredType = TeamModel.strengthenRoleType(scope.enclosingSourceType(), unloweredType);
    Expression loweringExpr = null;

    TypeBinding expressionType = expression.resolvedType;
    // this assertion needed for pushing/casting using unchecked one-byte opcodes.
    assert expressionType == null || expressionType.leafComponentType() instanceof ReferenceBinding;

    LocalVariableBinding localVar = null;
    Expression unloweredExpression = expression;
    if (expression instanceof ThisReference || expression instanceof AllocationExpression)
        needNullCheck = false;/*from w  w w  .  j  ava  2 s  .c om*/
    if (needNullCheck) {
        localVar = makeNewLocal(scope, unloweredType, sourceStart, sourceEnd, deferredResolve);
        SingleNameReference varRef = gen.singleNameReference(localVar.name);
        if (!deferredResolve) {
            varRef.binding = localVar;
            varRef.bits = Binding.LOCAL;
            varRef.constant = Constant.NotAConstant;
            varRef.resolvedType = unloweredType;
        }
        unloweredExpression = varRef;
    }

    if (unloweredType.isArrayType()) {
        // (1) array translation:
        ArrayLowering trans = new ArrayLowering(teamExpression);
        loweringExpr = trans.lowerArray(scope, unloweredExpression, unloweredType, requiredType,
                deferredResolve);
    } else {
        RoleTypeBinding roleType = (RoleTypeBinding) unloweredType;
        boolean needMethod = roleType.isRegularInterface()
                || !roleType.isSiblingRole(scope.enclosingSourceType());
        if (needMethod) {
            // (3) translation using _OT$.getBase() method:
            MessageSend callLower = gen.messageSend(unloweredExpression, IOTConstants._OT_GETBASE,
                    new Expression[0]);

            // manual resolving:
            if (!deferredResolve) {
                callLower.constant = Constant.NotAConstant;
                callLower.actualReceiverType = unloweredType;
                if (unloweredExpression.constant == null)
                    unloweredExpression.resolveType(scope);
                callLower.resolvedType = roleType.baseclass();

                callLower.binding = StandardElementGenerator.getGetBaseMethod(scope, roleType.roleModel,
                        roleType.baseclass());
            }
            loweringExpr = callLower;
        } else {
            // (2) translation using field _OT$base:
            FieldReference invokeBaseOnRole = new FieldReference(IOTConstants._OT_BASE,
                    (((long) sourceStart) << 32) + sourceEnd);
            ReferenceBinding roleClass = roleType.roleModel.getClassPartBinding();
            TypeReference classRef = gen.typeReference(roleClass);
            if (classRef != null) {
                // field access needs cast to the role-class.
                // FIXME(SH): use synthetic role field accessor instead!
                classRef.constant = Constant.NotAConstant;
                classRef.resolvedType = roleClass;
                CastExpression unloweredExpr;
                unloweredExpr = new CastExpression(unloweredExpression, classRef, CastExpression.NEED_CLASS);
                unloweredExpr.constant = Constant.NotAConstant;
                unloweredExpr.resolvedType = roleClass;
                unloweredExpr.bits |= ASTNode.GenerateCheckcast;
                invokeBaseOnRole.receiver = unloweredExpr;
            } else {
                invokeBaseOnRole.receiver = unloweredExpression;
            }

            invokeBaseOnRole.actualReceiverType = roleClass;
            invokeBaseOnRole.resolvedType = roleClass.baseclass();
            invokeBaseOnRole.binding = scope.findField(roleClass, IOTConstants._OT_BASE, invokeBaseOnRole,
                    true);
            invokeBaseOnRole.constant = Constant.NotAConstant;
            loweringExpr = invokeBaseOnRole;
        }
    }
    if (needNullCheck) {
        // ((local = (expression)) == null) ? (RequiredType)local : lower(local));
        @SuppressWarnings("null") // needNullCheck => localVar != null
        SingleNameReference lhs = gen.singleNameReference(localVar.name);
        Assignment assignment = gen.assignment(lhs, expression);
        loweringExpr = new CheckedLoweringExpression(expression, gen.nullCheck(assignment), gen.nullLiteral(),
                loweringExpr, localVar, teamExpression);
        if (!deferredResolve) {
            lhs.binding = localVar;
            lhs.resolvedType = unloweredType;
            lhs.bits = Binding.LOCAL | ASTNode.FirstAssignmentToLocal;
            assignment.constant = Constant.NotAConstant;
            loweringExpr.constant = Constant.NotAConstant;
            loweringExpr.resolvedType = requiredType;
        }
    }
    return loweringExpr;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.statemachine.transformer.StandardElementGenerator.java

License:Open Source License

/**
 * @param scope use this for resolving a newly generated team expression
 * @param roleType retrieve the anchor from this type.
 * @param gen represents faked source code position.
 * @return a new reference/*from   ww  w.  j a  v a  2 s.  c om*/
 */
private static Expression createTeamAnchorReference(BlockScope scope, DependentTypeBinding roleType,
        AstGenerator gen) {
    Expression teamExpr = createTeamExpression(roleType, gen);
    teamExpr.resolveType(scope);
    return teamExpr;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.util.AstGenerator.java

License:Open Source License

/**
 * Create a message send that has a custom resolve method (see inside for details).
 *//*from  w ww .jav a 2s .co  m*/
public MessageSend messageSendWithResolveHook(Expression receiver, final MethodBinding method,
        Expression[] parameters, final IRunInScope hook) {
    MessageSend messageSend = new MessageSend() {
        @Override
        public TypeBinding resolveType(BlockScope scope) {
            this.constant = Constant.NotAConstant;
            // arguments always need resolving:
            if (this.arguments != null) {
                int length = this.arguments.length;
                for (int i = 0; i < length; i++) {
                    Expression argument = this.arguments[i];
                    if (argument.resolvedType == null)
                        argument.resolveType(scope);
                }
            }
            // skip the receiver unless its again a hooked message send:
            if (this.receiver.getClass() == this.getClass())
                this.receiver.resolveType(scope);

            this.binding = method;
            this.resolvedType = method.returnType;

            // the main payload:
            hook.run(scope);

            this.actualReceiverType = this.binding.declaringClass;
            return this.resolvedType;
        }
    };
    messageSend.isGenerated = true;
    messageSend.sourceStart = this.sourceStart;
    messageSend.sourceEnd = this.sourceEnd;
    messageSend.statementEnd = this.sourceEnd;
    messageSend.nameSourcePosition = this.pos;
    messageSend.receiver = receiver;
    messageSend.selector = method.selector;
    messageSend.arguments = parameters;
    return messageSend;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.util.AstGenerator.java

License:Open Source License

/**
 * Assemble an ifstatement with negated condition, that hides the branch instruction from the debugger,
 * even when stepping into the condition. 
 *///from  w w  w  .  ja  v a2s . c  o  m
public IfStatement stealthIfNotStatement(final Expression condition, Statement thenStatement) {
    // mark step-over after the condition:
    Expression recordingCondition = new Expression() {
        public StringBuffer printExpression(int indent, StringBuffer output) {
            return condition.print(indent, output);
        }

        public TypeBinding resolveType(BlockScope scope) {
            return condition.resolveType(scope);
        }

        public void computeConversion(Scope scope, TypeBinding runtimeType, TypeBinding compileTimeType) {
            condition.computeConversion(scope, runtimeType, compileTimeType);
            this.constant = condition.constant;
            this.bits = condition.bits;
        }

        public Constant optimizedBooleanConstant() {
            this.constant = condition.optimizedBooleanConstant();
            this.bits = condition.bits;
            return this.constant;
        }

        public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo,
                boolean valueRequired) {
            return condition.analyseCode(currentScope, flowContext, flowInfo, valueRequired);
        }

        public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
            return condition.analyseCode(currentScope, flowContext, flowInfo);
        }

        public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
            condition.generateCode(currentScope, codeStream, valueRequired);
            // payload:
            codeStream.pcToSourceMap[codeStream.pcToSourceMapSize++] = codeStream.position;
            codeStream.pcToSourceMap[codeStream.pcToSourceMapSize++] = STEP_OVER_LINENUMBER;
        }
    };
    return new IfStatement(new UnaryExpression( // NOT
            recordingCondition, OperatorIds.NOT), thenStatement, this.sourceStart, this.sourceEnd);
}