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

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

Introduction

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

Prototype

null sourceName

To view the source code for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding sourceName.

Click Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

private void selectFrom(Binding binding, CompilationUnitDeclaration parsedUnit, ICompilationUnit unit,
        boolean isDeclaration) {
    if (binding instanceof TypeVariableBinding) {
        TypeVariableBinding typeVariableBinding = (TypeVariableBinding) binding;
        Binding enclosingElement = typeVariableBinding.declaringElement;
        this.noProposal = false;

        if (enclosingElement instanceof SourceTypeBinding) {
            SourceTypeBinding enclosingType = (SourceTypeBinding) enclosingElement;
            if (isLocal(enclosingType) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalTypeParameter(typeVariableBinding);
            } else {
                this.requestor.acceptTypeParameter(enclosingType.qualifiedPackageName(),
                        enclosingType.qualifiedSourceName(), typeVariableBinding.sourceName(), false,
                        this.actualSelectionStart, this.actualSelectionEnd);
            }/*from ww w .  ja  v  a 2  s .  c  o m*/
        } else if (enclosingElement instanceof MethodBinding) {
            MethodBinding enclosingMethod = (MethodBinding) enclosingElement;
            if (isLocal(enclosingMethod.declaringClass) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalMethodTypeParameter(typeVariableBinding);
            } else {
                this.requestor.acceptMethodTypeParameter(enclosingMethod.declaringClass.qualifiedPackageName(),
                        enclosingMethod.declaringClass.qualifiedSourceName(),
                        enclosingMethod.isConstructor() ? enclosingMethod.declaringClass.sourceName()
                                : enclosingMethod.selector,
                        enclosingMethod.sourceStart(), enclosingMethod.sourceEnd(),
                        typeVariableBinding.sourceName(), false, this.actualSelectionStart,
                        this.actualSelectionEnd);
            }
        }
        this.acceptedAnswer = true;
    } else if (binding instanceof ReferenceBinding) {
        ReferenceBinding typeBinding = (ReferenceBinding) binding;
        if (typeBinding instanceof ProblemReferenceBinding) {
            TypeBinding closestMatch = typeBinding.closestMatch();
            if (closestMatch instanceof ReferenceBinding) {
                typeBinding = (ReferenceBinding) closestMatch;
            } else {
                typeBinding = null;
            }
        }
        if (typeBinding == null)
            return;
        if (isLocal(typeBinding) && this.requestor instanceof SelectionRequestor) {
            this.noProposal = false;
            ((SelectionRequestor) this.requestor).acceptLocalType(typeBinding);
        } else {
            this.noProposal = false;

            this.requestor.acceptType(typeBinding.qualifiedPackageName(), typeBinding.qualifiedSourceName(),
                    typeBinding.modifiers, false, typeBinding.computeUniqueKey(), this.actualSelectionStart,
                    this.actualSelectionEnd);
        }
        this.acceptedAnswer = true;
    } else if (binding instanceof MethodBinding) {
        MethodBinding methodBinding = getCorrectMethodBinding((MethodBinding) binding);
        this.noProposal = false;

        boolean isValuesOrValueOf = false;
        if (binding instanceof SyntheticMethodBinding) {
            SyntheticMethodBinding syntheticMethodBinding = (SyntheticMethodBinding) binding;
            if (syntheticMethodBinding.purpose == SyntheticMethodBinding.EnumValues
                    || syntheticMethodBinding.purpose == SyntheticMethodBinding.EnumValueOf) {
                isValuesOrValueOf = true;
            }
        }

        if (!isValuesOrValueOf && !methodBinding.isSynthetic()) {
            TypeBinding[] parameterTypes = methodBinding.original().parameters;
            int length = parameterTypes.length;
            char[][] parameterPackageNames = new char[length][];
            char[][] parameterTypeNames = new char[length][];
            String[] parameterSignatures = new String[length];
            for (int i = 0; i < length; i++) {
                parameterPackageNames[i] = parameterTypes[i].qualifiedPackageName();
                parameterTypeNames[i] = parameterTypes[i].qualifiedSourceName();
                parameterSignatures[i] = new String(getSignature(parameterTypes[i])).replace('/', '.');
            }

            TypeVariableBinding[] typeVariables = methodBinding.original().typeVariables;
            length = typeVariables == null ? 0 : typeVariables.length;
            char[][] typeParameterNames = new char[length][];
            char[][][] typeParameterBoundNames = new char[length][][];
            for (int i = 0; i < length; i++) {
                TypeVariableBinding typeVariable = typeVariables[i];
                typeParameterNames[i] = typeVariable.sourceName;
                if (typeVariable.firstBound == null) {
                    typeParameterBoundNames[i] = new char[0][];
                } else if (TypeBinding.equalsEquals(typeVariable.firstBound, typeVariable.superclass)) {
                    int boundCount = 1
                            + (typeVariable.superInterfaces == null ? 0 : typeVariable.superInterfaces.length);
                    typeParameterBoundNames[i] = new char[boundCount][];
                    typeParameterBoundNames[i][0] = typeVariable.superclass.sourceName;
                    for (int j = 1; j < boundCount; j++) {
                        typeParameterBoundNames[i][j] = typeVariables[i].superInterfaces[j - 1].sourceName;
                    }
                } else {
                    int boundCount = typeVariable.superInterfaces == null ? 0
                            : typeVariable.superInterfaces.length;
                    typeParameterBoundNames[i] = new char[boundCount][];
                    for (int j = 0; j < boundCount; j++) {
                        typeParameterBoundNames[i][j] = typeVariables[i].superInterfaces[j].sourceName;
                    }
                }
            }

            ReferenceBinding declaringClass = methodBinding.declaringClass;
            if (isLocal(declaringClass) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalMethod(methodBinding);
            } else {
                this.requestor.acceptMethod(declaringClass.qualifiedPackageName(),
                        declaringClass.qualifiedSourceName(),
                        declaringClass.enclosingType() == null ? null
                                : new String(getSignature(declaringClass.enclosingType())),
                        methodBinding.isConstructor() ? declaringClass.sourceName() : methodBinding.selector,
                        parameterPackageNames, parameterTypeNames, parameterSignatures, typeParameterNames,
                        typeParameterBoundNames, methodBinding.isConstructor(), isDeclaration,
                        methodBinding.computeUniqueKey(), this.actualSelectionStart, this.actualSelectionEnd);
            }
        }
        this.acceptedAnswer = true;
    } else if (binding instanceof FieldBinding) {
        FieldBinding fieldBinding = (FieldBinding) binding;
        ReferenceBinding declaringClass = fieldBinding.declaringClass;
        if (declaringClass != null) { // arraylength
            this.noProposal = false;
            if (isLocal(declaringClass) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalField(fieldBinding);
            } else {
                // if the binding is a problem field binding, we want to make sure
                // we can retrieve the closestMatch if the problem reason is NotVisible
                FieldBinding currentFieldBinding = fieldBinding;
                while (currentFieldBinding instanceof ProblemFieldBinding) {
                    ProblemFieldBinding problemFieldBinding = (ProblemFieldBinding) currentFieldBinding;
                    if (problemFieldBinding.problemId() == ProblemReasons.NotVisible) {
                        currentFieldBinding = problemFieldBinding.closestMatch;
                    } else {
                        currentFieldBinding = null;
                    }
                }
                char[] fieldName = null;
                char[] key = null;
                if (currentFieldBinding != null) {
                    fieldName = currentFieldBinding.name;
                    key = currentFieldBinding.computeUniqueKey();
                } else {
                    fieldName = fieldBinding.name;
                    key = fieldBinding.computeUniqueKey();
                }
                this.requestor.acceptField(declaringClass.qualifiedPackageName(),
                        declaringClass.qualifiedSourceName(), fieldName, false, key, this.actualSelectionStart,
                        this.actualSelectionEnd);
            }
            this.acceptedAnswer = true;
        }
    } else if (binding instanceof LocalVariableBinding) {
        if (this.requestor instanceof SelectionRequestor) {
            ((SelectionRequestor) this.requestor).acceptLocalVariable((LocalVariableBinding) binding, unit);
            this.acceptedAnswer = true;
        } else {
            // open on the type of the variable
            selectFrom(((LocalVariableBinding) binding).type, parsedUnit, false);
        }
    } else if (binding instanceof ArrayBinding) {
        selectFrom(((ArrayBinding) binding).leafComponentType, parsedUnit, false);
        // open on the type of the array
    } else if (binding instanceof PackageBinding) {
        PackageBinding packageBinding = (PackageBinding) binding;
        this.noProposal = false;
        this.requestor.acceptPackage(packageBinding.readableName());
        this.acceptedAnswer = true;
    } else if (binding instanceof BaseTypeBinding) {
        this.acceptedAnswer = true;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.PatternLocator.java

License:Open Source License

public static char[] qualifiedSourceName(TypeBinding binding) {
    if (binding instanceof ReferenceBinding) {
        ReferenceBinding type = (ReferenceBinding) binding;
        if (type.isLocalType())
            return type.isMemberType()
                    ? CharOperation.concat(qualifiedSourceName(type.enclosingType()), type.sourceName(), '.')
                    : CharOperation.concat(qualifiedSourceName(type.enclosingType()),
                            new char[] { '.', '1', '.' }, type.sourceName());
    }//  w w w .  j av  a 2  s.c o  m
    return binding != null ? binding.qualifiedSourceName() : null;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.PatternLocator.java

License:Open Source License

protected int resolveLevelForType(char[] simpleNamePattern, char[] qualificationPattern,
        char[][][] patternTypeArguments, int depth, TypeBinding type) {
    // standard search with no generic additional information must succeed
    int level = resolveLevelForType(simpleNamePattern, qualificationPattern, type);
    if (level == IMPOSSIBLE_MATCH)
        return IMPOSSIBLE_MATCH;
    if (type == null || patternTypeArguments == null || patternTypeArguments.length == 0
            || depth >= patternTypeArguments.length) {
        return level;
    }//from w w  w .  ja  va 2 s . c  o  m

    // if pattern is erasure match (see bug 79790), commute impossible to erasure
    int impossible = this.isErasureMatch ? ERASURE_MATCH : IMPOSSIBLE_MATCH;

    // pattern has type parameter(s) or type argument(s)
    if (type.isGenericType()) {
        // Binding is generic, get its type variable(s)
        TypeVariableBinding[] typeVariables = null;
        if (type instanceof SourceTypeBinding) {
            SourceTypeBinding sourceTypeBinding = (SourceTypeBinding) type;
            typeVariables = sourceTypeBinding.typeVariables;
        } else if (type instanceof BinaryTypeBinding) {
            BinaryTypeBinding binaryTypeBinding = (BinaryTypeBinding) type;
            if (this.mustResolve)
                typeVariables = binaryTypeBinding.typeVariables(); // TODO (frederic) verify performance
        }
        if (patternTypeArguments[depth] != null && patternTypeArguments[depth].length > 0
                && typeVariables != null && typeVariables.length > 0) {
            if (typeVariables.length != patternTypeArguments[depth].length)
                return IMPOSSIBLE_MATCH;
        }
        // TODO (frederic) do we need to verify each parameter?
        return level; // we can't do better
    }

    // raw type always match
    if (type.isRawType()) {
        return level;
    }

    // Standard types (i.e. neither generic nor parameterized nor raw types)
    // cannot match pattern with type parameters or arguments
    TypeBinding leafType = type.leafComponentType();
    if (!leafType.isParameterizedType()) {
        return (patternTypeArguments[depth] == null || patternTypeArguments[depth].length == 0) ? level
                : IMPOSSIBLE_MATCH;
    }

    // Parameterized type
    ParameterizedTypeBinding paramTypeBinding = (ParameterizedTypeBinding) leafType;

    // Compare arguments only if there ones on both sides
    if (patternTypeArguments[depth] != null && patternTypeArguments[depth].length > 0
            && paramTypeBinding.arguments != null && paramTypeBinding.arguments.length > 0) {

        // type parameters length must match at least specified type names length
        int length = patternTypeArguments[depth].length;
        if (paramTypeBinding.arguments.length != length)
            return IMPOSSIBLE_MATCH;

        // verify each pattern type parameter
        nextTypeArgument: for (int i = 0; i < length; i++) {
            char[] patternTypeArgument = patternTypeArguments[depth][i];
            TypeBinding argTypeBinding = paramTypeBinding.arguments[i];
            // get corresponding pattern wildcard
            switch (patternTypeArgument[0]) {
            case Signature.C_STAR: // unbound parameter always match
            case Signature.C_SUPER: // needs pattern type parameter binding
                // skip to next type argument as it will be resolved later
                continue nextTypeArgument;
            case Signature.C_EXTENDS:
                // remove wildcard from patter type argument
                patternTypeArgument = CharOperation.subarray(patternTypeArgument, 1,
                        patternTypeArgument.length);
                break;
            default:
                // no wildcard
                break;
            }
            // get pattern type argument from its signature
            patternTypeArgument = Signature.toCharArray(patternTypeArgument);
            if (!this.isCaseSensitive)
                patternTypeArgument = CharOperation.toLowerCase(patternTypeArgument);
            boolean patternTypeArgHasAnyChars = CharOperation.contains(new char[] { '*', '?' },
                    patternTypeArgument);

            // Verify that names match...
            // ...special case for wildcard
            if (argTypeBinding instanceof CaptureBinding) {
                WildcardBinding capturedWildcard = ((CaptureBinding) argTypeBinding).wildcard;
                if (capturedWildcard != null)
                    argTypeBinding = capturedWildcard;
            }
            if (argTypeBinding.isWildcard()) {
                WildcardBinding wildcardBinding = (WildcardBinding) argTypeBinding;
                switch (wildcardBinding.boundKind) {
                case Wildcard.EXTENDS:
                    // Invalid if type argument is not exact
                    if (patternTypeArgHasAnyChars)
                        return impossible;
                    continue nextTypeArgument;
                case Wildcard.UNBOUND:
                    // there's no bound name to match => valid
                    continue nextTypeArgument;
                }
                // Look if bound name match pattern type argument
                ReferenceBinding boundBinding = (ReferenceBinding) wildcardBinding.bound;
                if (CharOperation.match(patternTypeArgument, boundBinding.shortReadableName(),
                        this.isCaseSensitive)
                        || CharOperation.match(patternTypeArgument, boundBinding.readableName(),
                                this.isCaseSensitive)) {
                    // found name in hierarchy => match
                    continue nextTypeArgument;
                }

                // If pattern is not exact then match fails
                if (patternTypeArgHasAnyChars)
                    return impossible;

                // Look for bound name in type argument superclasses
                boundBinding = boundBinding.superclass();
                while (boundBinding != null) {
                    if (CharOperation.equals(patternTypeArgument, boundBinding.shortReadableName(),
                            this.isCaseSensitive)
                            || CharOperation.equals(patternTypeArgument, boundBinding.readableName(),
                                    this.isCaseSensitive)) {
                        // found name in hierarchy => match
                        continue nextTypeArgument;
                    } else if (boundBinding.isLocalType() || boundBinding.isMemberType()) {
                        // for local or member type, verify also source name (bug 81084)
                        if (CharOperation.match(patternTypeArgument, boundBinding.sourceName(),
                                this.isCaseSensitive))
                            continue nextTypeArgument;
                    }
                    boundBinding = boundBinding.superclass();
                }
                return impossible;
            }

            // See if names match
            if (CharOperation.match(patternTypeArgument, argTypeBinding.shortReadableName(),
                    this.isCaseSensitive)
                    || CharOperation.match(patternTypeArgument, argTypeBinding.readableName(),
                            this.isCaseSensitive)) {
                continue nextTypeArgument;
            } else if (argTypeBinding.isLocalType() || argTypeBinding.isMemberType()) {
                // for local or member type, verify also source name (bug 81084)
                if (CharOperation.match(patternTypeArgument, argTypeBinding.sourceName(), this.isCaseSensitive))
                    continue nextTypeArgument;
            }

            // If pattern is not exact then match fails
            if (patternTypeArgHasAnyChars)
                return impossible;

            // Scan hierarchy
            TypeBinding leafTypeBinding = argTypeBinding.leafComponentType();
            if (leafTypeBinding.isBaseType())
                return impossible;
            ReferenceBinding refBinding = ((ReferenceBinding) leafTypeBinding).superclass();
            while (refBinding != null) {
                if (CharOperation.equals(patternTypeArgument, refBinding.shortReadableName(),
                        this.isCaseSensitive)
                        || CharOperation.equals(patternTypeArgument, refBinding.readableName(),
                                this.isCaseSensitive)) {
                    // found name in hierarchy => match
                    continue nextTypeArgument;
                } else if (refBinding.isLocalType() || refBinding.isMemberType()) {
                    // for local or member type, verify also source name (bug 81084)
                    if (CharOperation.match(patternTypeArgument, refBinding.sourceName(), this.isCaseSensitive))
                        continue nextTypeArgument;
                }
                refBinding = refBinding.superclass();
            }
            return impossible;
        }
    }

    // Recurse on enclosing type
    TypeBinding enclosingType = paramTypeBinding.enclosingType();
    if (enclosingType != null && enclosingType.isParameterizedType() && depth < patternTypeArguments.length
            && qualificationPattern != null) {
        int lastDot = CharOperation.lastIndexOf('.', qualificationPattern);
        char[] enclosingQualificationPattern = lastDot == -1 ? null
                : CharOperation.subarray(qualificationPattern, 0, lastDot);
        char[] enclosingSimpleNamePattern = lastDot == -1 ? qualificationPattern
                : CharOperation.subarray(qualificationPattern, lastDot + 1, qualificationPattern.length);
        int enclosingLevel = resolveLevelForType(enclosingSimpleNamePattern, enclosingQualificationPattern,
                patternTypeArguments, depth + 1, enclosingType);
        if (enclosingLevel == impossible)
            return impossible;
        if (enclosingLevel == IMPOSSIBLE_MATCH)
            return IMPOSSIBLE_MATCH;
    }
    return level;
}

From source file:com.redhat.ceylon.eclipse.core.model.mirror.UnknownClassMirror.java

License:Open Source License

public JDTClass(ReferenceBinding klass, IType type) {
    this.type = type;
    bindingRef = new WeakReference<ReferenceBinding>(klass);
    pkg = new JDTPackage(klass.getPackage());
    simpleName = new String(klass.sourceName());
    qualifiedName = JDTUtils.getFullyQualifiedName(klass);
    isPublic = klass.isPublic();//from w  w  w  .ja v  a 2  s. c  om
    isInterface = klass.isInterface();
    isAbstract = klass.isAbstract();
    isProtected = klass.isProtected();
    isDefaultAccess = klass.isDefault();
    isLocalType = klass.isLocalType();
    isStatic = (klass.modifiers & ClassFileConstants.AccStatic) != 0;
    isFinal = klass.isFinal();
    isEnum = klass.isEnum();
    isBinary = klass.isBinaryBinding();
    isAnonymous = klass.isAnonymousType();
    isJavaSource = (klass instanceof SourceTypeBinding)
            && new String(((SourceTypeBinding) klass).getFileName()).endsWith(".java");
    isAnnotationType = klass.isAnnotationType();
    bindingKey = klass.computeUniqueKey();

    char[] bindingFileName = klass.getFileName();
    int start = CharOperation.lastIndexOf('/', bindingFileName) + 1;
    if (start == 0 || start < CharOperation.lastIndexOf('\\', bindingFileName))
        start = CharOperation.lastIndexOf('\\', bindingFileName) + 1;
    fileName = new String(CharOperation.subarray(bindingFileName, start, -1));

    int jarFileEntrySeparatorIndex = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR,
            bindingFileName);
    if (jarFileEntrySeparatorIndex > 0) {
        char[] jarPart = CharOperation.subarray(bindingFileName, 0, jarFileEntrySeparatorIndex);
        IJavaElement jarPackageFragmentRoot = JavaCore.create(new String(jarPart));
        String jarPath = jarPackageFragmentRoot.getPath().toOSString();
        char[] entryPart = CharOperation.subarray(bindingFileName, jarFileEntrySeparatorIndex + 1,
                bindingFileName.length);
        fullPath = new StringBuilder(jarPath).append("!/").append(entryPart).toString();
    } else {
        fullPath = new String(bindingFileName);
    }

    ReferenceBinding sourceOrClass = klass;
    if (!klass.isBinaryBinding()) {
        sourceOrClass = klass.outermostEnclosingType();
    }
    char[] classFullName = new char[0];
    for (char[] part : sourceOrClass.compoundName) {
        classFullName = CharOperation.concat(classFullName, part, '/');
    }
    char[][] temp = CharOperation.splitOn('.', sourceOrClass.getFileName());
    String extension = temp.length > 1 ? "." + new String(temp[temp.length - 1]) : "";
    javaModelPath = new String(classFullName) + extension;

    if (type == null) {
        annotations = new HashMap<>();
        methods = Collections.emptyList();
        interfaces = Collections.emptyList();
        typeParams = Collections.emptyList();
        fields = Collections.emptyList();
        innerClasses = Collections.emptyList();
    }
}

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

License:Open Source License

/**
 * Initialize the type to create from the "playedBy" clause.
 * @param scope non-null/*from w w w  .  j a v  a  2  s .  c  o  m*/
 */
private void createAst(BlockScope scope) {
    if (this.isAstCreated)
        return; // already done.

    this.isAstCreated = true; // even if creation fails, don't try again.

    ReferenceBinding enclType;
    AbstractMethodDeclaration enclMethodDecl;
    ReferenceBinding baseclass = null;

    enclType = scope.enclosingSourceType();
    enclMethodDecl = (AbstractMethodDeclaration) scope.methodScope().referenceContext;

    if (enclType.isDirectRole())
        baseclass = ((MemberTypeBinding) enclType).baseclass();
    if (baseclass == null || !enclMethodDecl.isConstructor()) {
        scope.problemReporter().baseConstructorCallInWrongMethod(this, scope.methodScope().referenceContext);
        return;
    }
    ConstructorDeclaration enclCtor = (ConstructorDeclaration) enclMethodDecl;
    if (this.isExpression) {
        if (!isArgOfOtherCtor(enclCtor, scope))
            scope.problemReporter().baseConstructorExpressionOutsideCtorCall(this);
    } else {
        if (enclCtor.statements[0] != this)
            scope.problemReporter().baseConstructorCallIsNotFirst(this);
    }

    AstGenerator gen = new AstGenerator(this.sourceStart, this.sourceEnd);
    Expression allocation;
    if (this.enclosingInstance != null) {
        this.enclosingInstance = new PotentialLowerExpression(this.enclosingInstance,
                baseclass.enclosingType());
        // FIXME(SH): check baseclass.enclosingType();
    }

    if (baseclass.isDirectRole()) {
        // instead of new B() create:
        //       receiver._OT$createB():
        Expression receiver;
        if (RoleTypeBinding.isRoleWithExplicitAnchor(baseclass)) {
            RoleTypeBinding baseRole = (RoleTypeBinding) baseclass;
            ITeamAnchor anchor = baseRole._teamAnchor;
            ReferenceBinding startClass = anchor.getFirstDeclaringClass();
            char[][] tokens = anchor.tokens();
            if (startClass != null) {
                // relevant start class, create as receiver:
                //     EnclType.this.field1.
                TypeReference startReference = gen.typeReference(startClass);
                startReference.setBaseclassDecapsulation(DecapsulationState.ALLOWED);
                receiver = gen.qualifiedThisReference(startReference);
                for (int i = 0; i < tokens.length; i++) {
                    receiver = gen.fieldReference(receiver, tokens[i]);
                }
            } else {
                // the best name path defines the receiver:
                receiver = gen.qualifiedNameReference(tokens);
            }
        } else {
            if (this.enclosingInstance != null) {
                receiver = this.enclosingInstance;
            } else {
                if (TypeBinding.equalsEquals(baseclass.enclosingType(), enclType.enclosingType()))
                    receiver = gen.thisReference(); // creating a role of the same team as base instance??
                else
                    receiver = gen.qualifiedThisReference(gen.typeReference(baseclass.enclosingType()));
            }
        }
        char[] selector = CharOperation.concat(CREATOR_PREFIX_NAME, baseclass.sourceName());

        MessageSend allocSend = new MessageSend() {
            @Override
            public boolean isDecapsulationAllowed(Scope scope2) {
                // this message send can decapsulate independent of scope
                return true;
            }

            @Override
            public DecapsulationState getBaseclassDecapsulation() {
                return DecapsulationState.ALLOWED;
            }
        };
        gen.setPositions(allocSend);
        allocSend.receiver = receiver;
        allocSend.selector = selector;
        allocSend.arguments = this.arguments;
        allocSend.accessId = -1; // request that MessageSend.resolveType() assigns a fresh accessId if decapsulation is detected
        allocation = allocSend;
    } else {
        AllocationExpression alloc = newAllocation(baseclass, gen);
        alloc.type.setBaseclassDecapsulation(DecapsulationState.ALLOWED); // report individually
        alloc.arguments = this.arguments;
        alloc.sourceStart = this.sourceStart;
        alloc.sourceEnd = this.sourceEnd;
        alloc.statementEnd = this.statementEnd;
        allocation = alloc;
    }
    this.arguments = null; // don't use any more.

    ExplicitConstructorCall selfcall = enclCtor.constructorCall;
    if (selfcall.isImplicitSuper() && enclType.superclass().isDirectRole()
            && enclType.superclass().baseclass() != null) {
        // implement 2.4.2(c):
        // transform "super(); base(args);" => "super(new MyBase(args)); nop;"
        enclCtor.constructorCall = genLiftCtorCall(allocation);
        enclCtor.statements[0] = new AstGenerator(this.sourceStart, this.sourceEnd).emptyStatement();
        // pretend we are not calling base() because we already call the lifting-ctor.
    } else if (this.isExpression) {
        // similar to above:
        // translate "super(base(args), ...);" as "super(new MyBase(args), ...);"
        this.expression = allocation; // and ignore the assignment flavor of this node.
    } else {
        // needed by ASTConverter:
        this.expression = allocation;
        if (!enclType.roleModel.hasBaseclassProblem() && !scope.referenceType().ignoreFurtherInvestigation) {

            MethodModel.setCallsBaseCtor(enclCtor);

            // really creating base here, need to register this base object
            RoleModel boundRootRoleModel = enclType.roleModel.getBoundRootRole();
            if (boundRootRoleModel == null)
                throw new InternalCompilerError(
                        "Unexpected: role has neither baseclassProblem nor boundRootRole"); //$NON-NLS-1$
            Statement[] regStats = Lifting.genRoleRegistrationStatements(scope, boundRootRoleModel, baseclass,
                    enclCtor, gen);
            int len = enclCtor.statements.length;
            Statement[] newStats = new Statement[len + regStats.length];
            newStats[0] = this;
            System.arraycopy(regStats, 0, newStats, 1, regStats.length);
            System.arraycopy(enclCtor.statements, 1, newStats, regStats.length + 1, len - 1);
            enclCtor.setStatements(newStats);
        }
    }
}

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

License:Open Source License

public TypeBinding resolveType(BlockScope scope) {
    WeavingScheme weavingScheme = scope.compilerOptions().weavingScheme;
    AstGenerator gen = new AstGenerator(this._wrappee.sourceStart, this._wrappee.sourceEnd);
    MessageSend wrappedSend = this._sendOrig;
    AbstractMethodDeclaration referenceMethod = scope.methodScope().referenceMethod();
    boolean isStatic = scope.methodScope().isStatic;

    // === re-wire the message send to the base call surrogate
    // receiver:/*w w  w . j  a  va 2s  .co  m*/
    MethodDeclaration outerCallinMethod = getOuterCallinMethod(scope.methodScope());
    MethodBinding enclosingCallinMethod = outerCallinMethod != null ? outerCallinMethod.binding
            : scope.methodScope().referenceMethodBinding();
    if (outerCallinMethod != null && outerCallinMethod.binding == null)
        return null; // no hope
    ReferenceBinding roleType = scope.enclosingSourceType();
    this._receiver.adjustReceiver(roleType, isStatic, outerCallinMethod, gen, weavingScheme);

    // empty base call surrogate is handled using a synthetic base call surrogate:
    boolean isCallinBound = false;
    if (enclosingCallinMethod != null) {
        isCallinBound = SyntheticBaseCallSurrogate.isCallinMethodBoundIn(enclosingCallinMethod,
                enclosingCallinMethod.declaringClass);
    } else {
        isCallinBound = roleType.roleModel.isBound();
    }

    // who should work, compiler or OTRE?
    if (!isCallinBound && weavingScheme == WeavingScheme.OTRE) {
        resolveSyntheticBaseCallSurrogate(outerCallinMethod, scope, weavingScheme);
        return this.resolvedType;
    }

    // selector:
    if (weavingScheme == WeavingScheme.OTDRE) {
        wrappedSend.selector = CallinImplementorDyn.OT_CALL_NEXT;
    } else {
        wrappedSend.selector = SyntheticBaseCallSurrogate.genSurrogateName(wrappedSend.selector,
                roleType.sourceName(), isStatic);
    }

    // arguments are enhanced by the TransformStatementsVisitor

    // return type:
    TypeBinding returnType = null;
    if (referenceMethod != null) {
        MethodBinding methodBinding = referenceMethod.binding;
        if (methodBinding != null) {
            returnType = MethodModel.getReturnType(methodBinding);
            if (returnType != null && returnType.isBaseType()) {
                if (returnType != TypeBinding.VOID)
                    this._wrappee = gen.createUnboxing(this._wrappee, (BaseTypeBinding) returnType);
                else if (outerCallinMethod == null)
                    // store value which is not used locally but has to be chained to the caller.
                    // (cannot set result in outer callin method!)
                    this._wrappee = gen.assignment(gen.singleNameReference(IOTConstants.OT_RESULT),
                            this._wrappee);
            }
        }
    }

    // check context:
    if (outerCallinMethod == null) // already found appropriate context?
    {
        if (!checkContext(scope))
            return null;
    }

    BlockScopeWrapper baseCallScope = new BlockScopeWrapper(scope, this);
    super.resolveType(baseCallScope);
    if (weavingScheme == WeavingScheme.OTDRE) {
        // convert Object result from callNext
        if (returnType != null && !returnType.isBaseType()) {
            this.resolvedType = returnType;
            this._sendOrig.valueCast = returnType;
        }
    }
    return this.resolvedType;
}

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

License:Open Source License

private void resolveSyntheticBaseCallSurrogate(MethodDeclaration outerCallinMethod, BlockScope scope,
        WeavingScheme weavingScheme) {// www. ja  v a  2  s  . co m
    // find the method:
    AbstractMethodDeclaration callinMethodDecl = outerCallinMethod;
    if (callinMethodDecl == null) {
        if (checkContext(scope)) {
            callinMethodDecl = scope.methodScope().referenceMethod();
        } else {
            return; // error reported by checkContext
        }
    }
    MethodBinding callinMethod = callinMethodDecl.binding;
    if (callinMethod == null) {
        if (callinMethodDecl.ignoreFurtherInvestigation)
            return;
        throw new InternalCompilerError("Unresolved method without an error"); //$NON-NLS-1$
    }
    // check name match:
    if (!CharOperation.equals(this._sendOrig.selector, callinMethod.selector))
        scope.problemReporter().baseCallNotSameMethod(callinMethodDecl, this._sendOrig);

    // find the receiver type:
    this._receiver.resolve(scope);
    int depth = 0;
    while (this._receiver.resolvedType.isLocalType()) {
        this._receiver.resolvedType = this._receiver.resolvedType.enclosingType();
        depth++;
    }
    this._receiver.bits |= depth << DepthSHIFT;
    if (this._receiver.resolvedType instanceof ReferenceBinding) {
        ReferenceBinding receiverType = (ReferenceBinding) this._receiver.resolvedType;
        this._receiver.resolvedType = receiverType.getRealClass();
    }

    // resolve arguments:
    TypeBinding[] sendparams = new TypeBinding[this._sendOrig.arguments.length];
    for (int i = 0; i < sendparams.length; i++)
        sendparams[i] = this._sendOrig.arguments[i].resolveType(scope);

    // check arguments:
    int sourceArgsLen = 0;
    if (this.sourceArgs != null)
        sourceArgsLen = this.sourceArgs.length;
    TypeBinding[] methodParams = callinMethod.getSourceParameters();
    if (sourceArgsLen != methodParams.length) {
        scope.problemReporter().baseCallDoesntMatchRoleMethodSignature(this);
    } else {
        for (int i = 0; i < sourceArgsLen; i++) {
            TypeBinding srcArgType = this.sourceArgs[i].resolvedType;
            if (srcArgType == null) {
                if (!callinMethodDecl.hasErrors())
                    throw new InternalCompilerError(
                            "Unexpected: srcArgType should only ever be missing in declarations with reported errors"); //$NON-NLS-1$
                continue;
            }
            if (!srcArgType.isCompatibleWith(methodParams[i])) {
                if (isBoxingCompatible(srcArgType, methodParams[i], this.sourceArgs[i], scope)) {
                    int enhancedArgIdx = i + MethodSignatureEnhancer.getEnhancingArgLen(weavingScheme) + 1; // normal enhancement plus isSuperAccess flag
                    this._sendOrig.arguments[enhancedArgIdx].computeConversion(scope, methodParams[i],
                            srcArgType);
                } else {
                    scope.problemReporter().baseCallDoesntMatchRoleMethodSignature(this);
                    break;
                }
            }
        }
    }

    // create and link the synthetic method binding:
    MethodBinding surrogate = null;
    MethodModel model = callinMethod.model;
    if (model != null)
        surrogate = model.getBaseCallSurrogate();
    if (surrogate == null) {
        SourceTypeBinding receiverClass = ((SourceTypeBinding) ((ReferenceBinding) this._receiver.resolvedType)
                .getRealClass());
        if (SyntheticBaseCallSurrogate.isBindingForCallinMethodInherited(callinMethod)) {
            ReferenceBinding currentRole = callinMethod.declaringClass;
            while (surrogate == null && ((currentRole = currentRole.superclass()) != null)) {
                surrogate = receiverClass
                        .getExactMethod(SyntheticBaseCallSurrogate.genSurrogateName(this.sourceSelector,
                                currentRole.sourceName(), callinMethod.isStatic()), sendparams, null);
            }
        } else {
            surrogate = receiverClass.addSyntheticBaseCallSurrogate(callinMethod);
        }
    }
    this._sendOrig.binding = surrogate;
    this._sendOrig.actualReceiverType = this._receiver.resolvedType;
    this._sendOrig.constant = Constant.NotAConstant;
    this.resolvedType = this._sendOrig.resolvedType = MethodModel.getReturnType(this._sendOrig.binding);
}

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

License:Open Source License

/**
 * Answer the name of the role that introduced this callin mapping 
 * (support for overriding in otredyn)./*from  w w w  .  j  ava2  s  .c o m*/
 */
public char[] declaringRoleName() {
    char[] roleName = this.scope.enclosingSourceType().sourceName();
    if (this.name == null)
        return roleName;
    if (this.name[0] != '<') {
        ReferenceBinding currentRole = this.scope.enclosingSourceType();
        while (currentRole != null && currentRole.isRole()) {
            for (CallinCalloutBinding mapping : currentRole.callinCallouts) {
                if (CharOperation.equals(this.name, mapping.name)) {
                    roleName = currentRole.sourceName();
                    break;
                }
            }
            currentRole = currentRole.superclass();
        }
    }
    return roleName;
}

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

License:Open Source License

/**
 * Resolve the method or field (see FieldAccessSpec).
 *
 * @param receiverType receiver of the method call.
 * @param scope//from   w  ww  . j  a v a2 s .  c o  m
 * @param callinExpected whether this method spec is the LHS of a replace callin.
 * @param isBaseSide     whether this method spec is the RHS (any binding kind)
 * @param allowEnclosing whether a method may be found in an enclosing type of receiverType
 * @return the resolved method (may be problem method) or null
 */
public MethodBinding resolveFeature(ReferenceBinding receiverType, BlockScope scope, boolean callinExpected,
        boolean isBaseSide, boolean allowEnclosing) {
    // getRealClass() is used, because decapsulation needs to find private methods,
    // which for roles are found only in the class part.
    ReferenceBinding receiverClass = receiverType.getRealClass();
    boolean isConstructorSpec = CharOperation.equals(this.selector, receiverClass.sourceName());
    char[] realSelector = isConstructorSpec ? TypeConstants.INIT : this.selector;
    if (this.hasSignature) {
        TypeBinding[] enhancedParameters = this.parameters;
        // first chance: try enhanced:
        enhancedParameters = MethodSignatureEnhancer.enhanceParameters(scope, this.parameters);
        CompilationResult compilationResult = scope.referenceContext().compilationResult();
        CheckPoint cp = compilationResult.getCheckPoint(scope.referenceContext());

        this.resolvedMethod = TypeAnalyzer.findMethod(scope, receiverClass, realSelector, enhancedParameters,
                isBaseSide, isBaseSide ? this : null);
        if (!this.resolvedMethod.isValidBinding()
                && this.resolvedMethod.problemId() == ProblemReasons.NotFound) {
            // second+ chance: try plain:
            while (receiverClass != null) {
                compilationResult.rollBack(cp);
                MethodBinding plainMethod = TypeAnalyzer.findMethod(scope, receiverClass, realSelector,
                        this.parameters, isBaseSide, isBaseSide ? this : null);
                if (!callinExpected) {
                    this.resolvedMethod = plainMethod;
                } else {
                    if (plainMethod != null && plainMethod.isValidBinding())
                        scope.problemReporter().replaceMappingToNonCallin(this, plainMethod);
                    // mark the ProblemMethodBinding consistently to what we have been looking for last:
                    this.resolvedMethod.modifiers |= ExtraCompilerModifiers.AccCallin
                            | ClassFileConstants.AccStatic;
                }
                if (plainMethod != null && plainMethod.isValidBinding())
                    break;
                if (allowEnclosing)
                    receiverClass = receiverClass.enclosingType();
                else
                    receiverClass = null;
            }
        }
    } else {
        CompilationResult compilationResult = scope.referenceContext().compilationResult();
        CheckPoint cp = compilationResult.getCheckPoint(scope.referenceContext());
        while (receiverClass != null) {
            this.resolvedMethod = receiverClass.getMethod(scope, realSelector);
            if (this.resolvedMethod != null && this.resolvedMethod.isValidBinding())
                break; // good
            if (!allowEnclosing)
                break; // bad
            compilationResult.rollBack(cp);
            receiverClass = receiverClass.enclosingType();
        }
    }
    if (this.resolvedMethod != null) {
        if (this.resolvedMethod.isValidBinding()) {
            // check visibility of role-side in callin:
            if (!isBaseSide && scope.referenceContext() instanceof CallinMappingDeclaration
                    && !this.resolvedMethod.canBeSeenBy(this, scope)) {
                scope.problemReporter().invisibleMethod(this, this.resolvedMethod);
                this.resolvedMethod = new ProblemMethodBinding(this.resolvedMethod, this.selector,
                        this.parameters, ProblemReasons.NotVisible);
            }
        }
        if (!this.resolvedMethod.isValidBinding() && this.resolvedMethod.declaringClass == null)
            this.resolvedMethod.declaringClass = receiverClass; // needed for computeUniqueKey (via CallinCalloutBinding.computeUniqueKey)
    }
    return this.resolvedMethod;
}

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

License:Open Source License

private void generateMessageSend(TypeBinding expressionType) {
    AstGenerator gen = new AstGenerator(this.type.sourceStart, this.sourceEnd);
    ReferenceBinding roleBinding = (ReferenceBinding) this.type.resolvedType;
    this.teamBinding = roleBinding.enclosingType();
    if (!roleBinding.isValidBinding()) {
        this.resolvedType = expressionType; // pre-computed type of getclass method
        return; // don't generate illegal message send
    }//from  w ww.  j  a  v a  2s. c  o m
    Expression receiver;
    if (RoleTypeBinding.isRoleWithExplicitAnchor(roleBinding)) {
        // create some.anchor._OT$getClass$R()
        char[][] tokens = ((RoleTypeBinding) roleBinding)._teamAnchor.tokens();
        if (tokens.length == 1)
            receiver = gen.singleNameReference(tokens[0]);
        else
            receiver = gen.qualifiedNameReference(tokens);
    } else {
        // create MyTeam.this._OT$getClass$R()
        receiver = gen.qualifiedThisReference(this.teamBinding);
    }
    this.send = gen.messageSend(receiver, CharOperation.concat(GET_CLASS_PREFIX, roleBinding.sourceName()),
            new Expression[] {});
}