Example usage for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding getExactConstructor

List of usage examples for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding getExactConstructor

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding getExactConstructor.

Prototype

public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) 

Source Link

Usage

From source file:com.google.gwt.dev.jdt.WebModeCompilerFrontEnd.java

License:Apache License

private void checkRebindResultInstantiable(MessageSendSite site, String typeName) {
    /*/*from   ww w .j a  v a2 s.  c  om*/
     * This causes the compiler to find the additional type, possibly winding
     * its back to ask for the compilation unit from the source oracle.
     */
    ReferenceBinding type = resolvePossiblyNestedType(typeName);

    // Sanity check rebind results.
    if (type == null) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' could not be found");
        return;
    }
    if (!type.isClass()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' must be a class");
        return;
    }
    if (type.isAbstract()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' cannot be abstract");
        return;
    }
    if (type.isNestedType() && !type.isStatic()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' cannot be a non-static nested class");
        return;
    }
    if (type.isLocalType()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' cannot be a local class");
        return;
    }
    // Look for a noArg ctor.
    MethodBinding noArgCtor = type.getExactConstructor(Binding.NO_PARAMETERS);
    if (noArgCtor == null) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' has no default (zero argument) constructors");
        return;
    }
}

From source file:org.eclipse.jdt.internal.compiler.lookup.Scope.java

License:Open Source License

public MethodBinding getConstructor(ReferenceBinding receiverType, TypeBinding[] argumentTypes,
        InvocationSite invocationSite) {
    CompilationUnitScope unitScope = compilationUnitScope();
    LookupEnvironment env = unitScope.environment;
    try {//ww  w . j av  a  2 s.  c om
        env.missingClassFileLocation = invocationSite;
        unitScope.recordTypeReference(receiverType);
        unitScope.recordTypeReferences(argumentTypes);
        MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
        if (methodBinding != null && methodBinding.canBeSeenBy(invocationSite, this)) {
            // targeting a non generic constructor with type arguments ?
            if (invocationSite.genericTypeArguments() != null)
                methodBinding = computeCompatibleMethod(methodBinding, argumentTypes, invocationSite);
            return methodBinding;
        }
        MethodBinding[] methods = receiverType.getMethods(TypeConstants.INIT, argumentTypes.length);
        if (methods == Binding.NO_METHODS)
            return new ProblemMethodBinding(TypeConstants.INIT, argumentTypes, ProblemReasons.NotFound);

        MethodBinding[] compatible = new MethodBinding[methods.length];
        int compatibleIndex = 0;
        MethodBinding problemMethod = null;
        for (int i = 0, length = methods.length; i < length; i++) {
            MethodBinding compatibleMethod = computeCompatibleMethod(methods[i], argumentTypes, invocationSite);
            if (compatibleMethod != null) {
                if (compatibleMethod.isValidBinding())
                    compatible[compatibleIndex++] = compatibleMethod;
                else if (problemMethod == null)
                    problemMethod = compatibleMethod;
            }
        }
        if (compatibleIndex == 0) {
            if (problemMethod == null)
                return new ProblemMethodBinding(methods[0], TypeConstants.INIT, argumentTypes,
                        ProblemReasons.NotFound);
            return problemMethod;
        }
        // need a more descriptive error... cannot convert from X to Y

        MethodBinding[] visible = new MethodBinding[compatibleIndex];
        int visibleIndex = 0;
        for (int i = 0; i < compatibleIndex; i++) {
            MethodBinding method = compatible[i];
            if (method.canBeSeenBy(invocationSite, this))
                visible[visibleIndex++] = method;
        }
        if (visibleIndex == 1)
            return visible[0];
        if (visibleIndex == 0)
            return new ProblemMethodBinding(compatible[0], TypeConstants.INIT, compatible[0].parameters,
                    ProblemReasons.NotVisible);
        // all of visible are from the same declaringClass, even before 1.4 we can call this method instead of mostSpecificClassMethodBinding
        return mostSpecificMethodBinding(visible, visibleIndex, argumentTypes, invocationSite, receiverType);
    } catch (AbortCompilation e) {
        e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
        throw e;
    } finally {
        env.missingClassFileLocation = null;
    }
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.ast.OTQualifiedAllocationExpression.java

License:Open Source License

/**
* During resolve we make the decision which variant to use.
*/// w w w  . j  a va2s  . com
public TypeBinding resolveType(BlockScope scope) {
    if (this.anonymousType == null && this.creatorCall == null && this.enclosingInstance == null) // special case during code assist
        return super.resolveType(scope);

    CompilationResult compilationResult = scope.referenceContext().compilationResult();
    CheckPoint cp = compilationResult.getCheckPoint(scope.referenceContext());
    this.hasEnclosingInstanceProblem = false;
    if (this.anonymousType == null && this.creatorCall == null) { // no double processing

        if (this.enclosingInstance instanceof CastExpression)
            this.enclosingInstance.bits |= DisableUnnecessaryCastCheck; // will check later on (within super.resolveType())

        TypeBinding enclosingInstanceType = this.enclosingInstance.resolveType(scope);
        this.hasEnclosingInstanceProblem = enclosingInstanceType == null;

        if (!scope.isGeneratedScope() && enclosingInstanceType != null && enclosingInstanceType.isTeam()) // non reference types will trigger error reporting via super.resolveType()
        {
            if (this.enclosingInstance instanceof NameReference) {
                final NameReference anchorRef = (NameReference) this.enclosingInstance;
                if (!((VariableBinding) anchorRef.binding).isFinal()) {

                    // replace non-final anchor with fake-binding,
                    // so that this type is not compatibly to anything else:
                    char[] variableName = ((VariableBinding) anchorRef.binding).name;
                    switch (anchorRef.bits & ASTNode.RestrictiveFlagMASK) {
                    case Binding.LOCAL:
                        final LocalVariableBinding localOrig = (LocalVariableBinding) anchorRef.binding;
                        // mark the original as used before we procede with a fake copy:
                        localOrig.useFlag = LocalVariableBinding.USED;
                        anchorRef.binding = new LocalVariableBinding(variableName, enclosingInstanceType,
                                ClassFileConstants.AccFinal, false) {
                            @Override
                            public int problemId() {
                                return IProblem.AnchorNotFinal;
                            }
                        };
                        this.preGenerateTask = new Runnable() {
                            public void run() {
                                // need to transfer this info from the real local to the fake one (don't have that info yet):
                                ((LocalVariableBinding) anchorRef.binding).resolvedPosition = localOrig.resolvedPosition;
                            }
                        };
                        break;
                    case Binding.FIELD:
                        anchorRef.binding = new FieldBinding(variableName, enclosingInstanceType,
                                ClassFileConstants.AccFinal, scope.referenceType().binding,
                                Constant.NotAConstant) {
                            @Override
                            public int problemId() {
                                return IProblem.AnchorNotFinal;
                            }
                        };
                        break;
                    default:
                        throw new InternalCompilerError("Unexpected bits, neither local nor field " //$NON-NLS-1$
                                + anchorRef.bits + ": " + anchorRef); //$NON-NLS-1$
                    }
                }
            }

            if (this.type.getTypeName().length > 1) {
                scope.problemReporter().roleCreationNotRelativeToEnclosingTeam(this);
                return null;
            }

            // now it's finally time to create the alternate version:
            this.creatorCall = CopyInheritance.createConstructorMethodInvocationExpression(scope, this);
            if (this.creatorCall == null)
                return null;
        }
    }
    if (this.creatorCall == null) {
        TypeBinding typ = super.resolveType(scope);
        if (typ == null || typ instanceof PolyTypeBinding)
            return typ;

        if (!this.hasEnclosingInstanceProblem) { // more checks only if no error already
            // if enclosing is a role request a cast to the class part as required by the inner constructor
            if (this.enclosingInstance != null) {
                TypeBinding enclosingType = this.enclosingInstance.resolvedType;
                if (enclosingType instanceof ReferenceBinding
                        && ((ReferenceBinding) enclosingType).isDirectRole())
                    this.enclosingInstanceCast = ((ReferenceBinding) enclosingType).getRealClass();
            }
            ReferenceBinding superType = null;
            if (this.resolvedType instanceof ReferenceBinding)
                superType = ((ReferenceBinding) this.resolvedType).superclass();
            if (superType != null && (superType instanceof RoleTypeBinding)) {
                RoleTypeBinding superRole = (RoleTypeBinding) superType;
                if (superRole.hasExplicitAnchor())
                    scope.problemReporter().extendingExternalizedRole(superRole, this.type);
            }
        }
    } else { // === with creatorCall ===

        this.constant = Constant.NotAConstant;

        this.resolvedType = this.creatorCall.resolveType(scope);
        // when creating role nested instance, no cast of enclosing role needed in this branch,
        // because creator call is routed via the interface of the enclosing role.
        if (this.resolvedType != null) {
            if (((ReferenceBinding) this.resolvedType).isAbstract()) {
                if (!((ReferenceBinding) enclosingInstance().resolvedType).isAbstract())
                    scope.problemReporter().abstractRoleIsRelevant(this,
                            (ReferenceBinding) this.creatorCall.resolvedType);
            }
            if (this.resolvedType.isValidBinding()) {
                // FIXME(SH): remove cast unwrapping
                Expression createExpr = this.creatorCall;
                while (createExpr instanceof CastExpression) // may have been wrapped using CollectedReplacementsTransformer
                    createExpr = ((CastExpression) createExpr).expression;

                this.binding = ((MessageSend) createExpr).binding; // store the method binding

                // using lift-ctor in a qualified way? (OTJDL 2.4.1(a))
                ReferenceBinding role = (ReferenceBinding) this.resolvedType;
                MethodBinding creator = this.binding;
                if (creator != null) {
                    MethodBinding ctor = role.getExactConstructor(creator.parameters);
                    if (Lifting.isLiftToConstructor(ctor, role))
                        scope.problemReporter().qualifiedUseOfLiftingConstructor(ctor, this.creatorCall);
                }
            }
        }
    }
    return this.resolvedType;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.bytecode.ConstantPoolObjectMapper.java

License:Open Source License

private static MethodBinding getConfinedSuperCtor(MethodBinding dstMethod) {
    ReferenceBinding newSuperclass = dstMethod.declaringClass.superclass();
    if (newSuperclass == null)
        throw new InternalCompilerError("copying byte code to class without superclass?"); //$NON-NLS-1$
    return newSuperclass.getExactConstructor(new TypeBinding[0]);
}

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

License:Open Source License

public ConstructorDeclaration createLiftToConstructorDeclaration(TreeNode roleNode, boolean needMethodBodies) {
    TreeNode instantiableBoundRootRoleNode = roleNode.getTopmostBoundParent(false);
    if (instantiableBoundRootRoleNode == null)
        return null;

    TypeDeclaration roleDecl = roleNode.getTreeObject().getAst();
    ClassScope scope = roleDecl.scope;/*from   w w  w .j  av  a2s  .co m*/
    if (instantiableBoundRootRoleNode == TreeNode.ProblemNode) {
        scope.problemReporter().overlappingRoleHierarchies(roleDecl, TreeNode.ProblemNode.toString());
        return null;
    }
    TypeDeclaration roleType = roleNode.getTreeObject().getAst();
    ConstructorDeclaration existingConstructor = findLiftToConstructor(roleType);
    if (existingConstructor == null && !roleNode.hasBoundParent(false)
            && !roleNode.getTreeObject().isIgnoreFurtherInvestigation()) {
        ReferenceBinding parent = roleNode.getTreeObject().getBinding().superclass();
        MethodBinding defCtor = parent.getExactConstructor(Binding.NO_PARAMETERS);
        boolean hasEmptyCtor = (defCtor != null) ? defCtor.isValidBinding()
                : (parent.getMethods(TypeConstants.INIT) == Binding.NO_METHODS);
        if (!hasEmptyCtor) {
            scope.problemReporter().missingEmptyCtorForLiftingCtor(roleDecl, parent);
            return null;
        }
    }

    // for determining the cache interfaces are allowed:
    this._boundRootRoleModel = roleNode.getTopmostBoundParent(true).getTreeObject();
    if (this._boundRootRoleModel != null)
        roleNode.getTreeObject()._boundRootRole = this._boundRootRoleModel;

    TypeDeclaration teamTypeDeclaration = roleType.enclosingType;
    ReferenceBinding baseClassBinding = roleType.binding.baseclass();

    if (baseClassBinding == null && ((roleType.binding.tagBits & TagBits.HierarchyHasProblems) != 0))
        return null; // assume base class could not be resolved.

    AstGenerator gen = existingConstructor == null ? new AstGenerator(roleType)
            : new AstGenerator(existingConstructor);
    gen.replaceableEnclosingClass = roleType.binding.enclosingType();
    // public MyRole(MyBase base)
    Argument arg;
    ConstructorDeclaration generatedConstructor = gen.constructor(teamTypeDeclaration.compilationResult,
            ClassFileConstants.AccPublic, roleType.name, new Argument[] { // (MyBase base)
                    arg = gen.argument(BASE, // name
                            gen.baseclassReference(baseClassBinding)) // type
            });
    gen.addNonNullAnnotation(arg, scope.environment());

    // default arg name is base.
    char[] baseArgName = BASE;
    if (existingConstructor != null) {
        if (existingConstructor.isCopied) {
            if (roleNode.getTreeObject().getImplicitSuperRole().isBound()) // parent must be class.
                return null; // copied constructor has everything we need.
        }
        // use the argument name of the existing constructor
        baseArgName = existingConstructor.arguments[0].name;
    }

    if (needMethodBodies) {
        if (instantiableBoundRootRoleNode == roleNode)
            genLiftToConstructorStatements(baseClassBinding, roleType, generatedConstructor, baseArgName, gen);
        else
            genLiftToConstructorSuperCall(baseClassBinding, roleType, generatedConstructor, baseArgName, gen);
    }

    this._boundRootRoleModel = null;

    if (existingConstructor != null) {
        //if constructor exists with same signature, merge statements.
        if (needMethodBodies) {
            // Also see Parser.parse(ConstructorDeclaration) for merging and
            // for checking illegal explicit super call.
            if (existingConstructor.statements != null) {
                int len1 = generatedConstructor.statements.length;
                int len2 = existingConstructor.statements.length;
                Statement[] newStatements = new Statement[len1 + len2];
                System.arraycopy(generatedConstructor.statements, 0, newStatements, 0, len1);
                System.arraycopy(existingConstructor.statements, 0, newStatements, len1, len2);
                existingConstructor.setStatements(newStatements);
            } else {
                existingConstructor.setStatements(generatedConstructor.statements);
            }
            // Keep arguments.
            // If constructorCall is explicit keep it.
            if (existingConstructor.constructorCall == null
                    || existingConstructor.constructorCall.isImplicitSuper())
                existingConstructor.constructorCall = generatedConstructor.constructorCall;
        }
        return existingConstructor;
    } else {
        //otherhwise insert new constructor
        AstEdit.addMethod(roleType, generatedConstructor);
        return generatedConstructor;
    }
}

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

License:Open Source License

/**
* API for AbstractMethodDeclaration://from   w w  w  .  j  av  a2 s. c om
*
 *  Create a byte code sequence for a runtime check in a creation method:
 *  R _OT$create_OT$R(B b) {
 *       if (this._OT$cache_OT$R.contains(b))
 *       throw new DuplicateRoleException("R");
 *     // continue regular code.
 *  }
 *
 * Note, the need for this runtime check is detected quite late.
 * At this point it is easier to create the byte code sequence directly,
 * rather the creating AST first.
 */
public static void createDuplicateRoleCheck(CodeStream codeStream, AbstractMethodDeclaration method) {
    MethodBinding binding = method.binding;
    Scope scope = method.scope;

    ReferenceBinding roleType = (ReferenceBinding) binding.returnType;
    String roleName = new String(roleType.readableName());
    // TODO(SH): check why roleType.getRoleModel().getClassPartBinding().roleModel may yield a different result.
    // I think it occured in haeder/stopwatch from smile-CVS.
    //RoleModel role = roleType.getRealClass().roleModel;
    char[] cacheName = LiftingEnvironment.getCacheName(roleType.roleModel.getBoundRootRole());

    ReferenceBinding teamBinding = roleType.enclosingType();//role.getTeamModel().getBinding();
    FieldBinding cache = TypeAnalyzer.findField(teamBinding, cacheName, /*static*/false, /*outer*/false,
            ITranslationStates.STATE_FULL_LIFTING); // generated by this state
    if (cache == null)
        throw new InternalCompilerError("generated cache field not found: " + new String(cacheName)); //$NON-NLS-1$
    ReferenceBinding map = (ReferenceBinding) scope.getType(IOTConstants.WEAK_HASH_MAP, 3);
    MethodBinding contains = map.getMethod(scope, IOTConstants.CONTAINS_KEY);

    ReferenceBinding exc = (ReferenceBinding) scope.getType(IOTConstants.ORG_OBJECTTEAMS_DUPLICATE_ROLE, 3);
    TypeBinding[] types = new TypeBinding[] { scope.getJavaLangString() };
    MethodBinding excInit = exc.getExactConstructor(types);

    BranchLabel normalCase = new BranchLabel(codeStream);

    codeStream.aload_0(); // this
    codeStream.fieldAccess(Opcodes.OPC_getfield, cache, teamBinding); // getfield      MyTeam._OT$cache_OT$R Ljava/util/WeakHashMap;
    codeStream.aload_1(); // arg0
    codeStream.invoke(Opcodes.OPC_invokevirtual, contains, map); // invokevirtual java.util.WeakHashMap.containsKey (Ljava/lang/Object;)Z
    codeStream.ifeq(normalCase); // false -> #endif
    codeStream.new_(exc); // new           <org.objectteams.DuplicateRoleException>
    codeStream.dup(); // dup
    codeStream.ldc(roleName); // ldc "R"
    codeStream.invoke(Opcodes.OPC_invokespecial, excInit, exc); // invokespecial org.objectteams.DuplicateRoleException.<init> (Ljava/lang/String;)V
    codeStream.athrow(); // athrow
    normalCase.place(); // #endif
}