Example usage for org.eclipse.jdt.internal.compiler.lookup TypeBinding BOOLEAN

List of usage examples for org.eclipse.jdt.internal.compiler.lookup TypeBinding BOOLEAN

Introduction

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

Prototype

BaseTypeBinding BOOLEAN

To view the source code for org.eclipse.jdt.internal.compiler.lookup TypeBinding BOOLEAN.

Click Source Link

Usage

From source file:org.codehaus.jdt.groovy.internal.compiler.ast.GroovyClassScope.java

License:Open Source License

/**
 * Add any groovy specific method bindings to the set determined by the compiler. These
 *//*from www. j a v a2 s  . com*/
@Override
protected MethodBinding[] augmentMethodBindings(MethodBinding[] methodBindings) {
    // Don't add these methods to annotations
    SourceTypeBinding binding = this.referenceContext.binding;
    if (binding != null && (binding.isAnnotationType() || binding.isInterface())) {
        return methodBindings;
    }
    boolean implementsGroovyLangObject = false;

    ReferenceBinding[] superInterfaces = binding.superInterfaces;
    if (superInterfaces != null) {
        for (int i = 0, max = superInterfaces.length; i < max; i++) {
            char[][] interfaceName = superInterfaces[i].compoundName;
            if (CharOperation.equals(interfaceName, GROOVY_LANG_GROOVYOBJECT)) {
                implementsGroovyLangObject = true;
                break;
            }
        }
    }

    List<MethodBinding> groovyMethods = new ArrayList<MethodBinding>();

    // If we don't then a supertype did and these methods do not have to be added here
    if (implementsGroovyLangObject) {
        if (debugListener != null) {
            debugListener.record("augment: type " + new String(this.referenceContext.name)
                    + " having GroovyObject methods added");
        }
        TypeBinding bindingJLO = getJavaLangObject();
        TypeBinding bindingJLS = getJavaLangString();
        TypeBinding bindingGLM = getGroovyLangMetaClassBinding();

        // Now add the groovy.lang.GroovyObject methods:
        //
        // Object invokeMethod(String name, Object args);
        // Object getProperty(String propertyName);
        // void setProperty(String propertyName, Object newValue);
        // MetaClass getMetaClass();
        // void setMetaClass(MetaClass metaClass);

        // Note on synthetic
        // javac/ecj don't see synthetic methods when considering if a type implements an interface. So don't make these
        // synthetic

        // Visibility is public and possibly static/abstract depending on the containing type
        createMethod("invokeMethod", false, "", new TypeBinding[] { bindingJLS, bindingJLO }, bindingJLO,
                groovyMethods, methodBindings, null);
        createMethod("getProperty", false, "", new TypeBinding[] { bindingJLS }, bindingJLO, groovyMethods,
                methodBindings, null);
        createMethod("setProperty", false, "", new TypeBinding[] { bindingJLS, bindingJLO }, TypeBinding.VOID,
                groovyMethods, methodBindings, null);
        createMethod("getMetaClass", false, "", null, bindingGLM, groovyMethods, methodBindings, null);
        createMethod("setMetaClass", false, "", new TypeBinding[] { bindingGLM }, TypeBinding.VOID,
                groovyMethods, methodBindings, null);
    }
    // FIXASC decide what difference this makes - should we not be adding anything at all?
    // will not be an instance of GroovyTypeDeclaration if created through SourceTypeConverter
    if (this.referenceContext instanceof GroovyTypeDeclaration) {
        GroovyTypeDeclaration typeDeclaration = (GroovyTypeDeclaration) this.referenceContext;

        boolean useOldWay = false;
        if (useOldWay) {
            // FIXASC the methods created here need to be a subtype of
            // MethodBinding because they need their source position to be the
            // property
            List<PropertyNode> properties = typeDeclaration.properties;
            for (PropertyNode property : properties) {
                String name = property.getName();
                FieldBinding fBinding = typeDeclaration.binding.getField(name.toCharArray(), false);
                // null binding indicates there was a problem resolving its type
                if (fBinding != null && !(fBinding.type instanceof MissingTypeBinding)) {
                    String getterName = "get" + MetaClassHelper.capitalize(name);
                    createMethod(getterName, property.isStatic(), "", /* TypeBinding.NO_TYPES */null,
                            fBinding.type, groovyMethods, methodBindings, typeDeclaration);
                    if (!fBinding.isFinal()) {
                        String setterName = "set" + MetaClassHelper.capitalize(name);
                        createMethod(setterName, property.isStatic(), "", new TypeBinding[] { fBinding.type },
                                TypeBinding.VOID, groovyMethods, methodBindings, typeDeclaration);
                    }
                    if (fBinding.type == TypeBinding.BOOLEAN) {
                        createMethod("is" + MetaClassHelper.capitalize(name), property.isStatic(),
                                "", /* TypeBinding.NO_TYPES, */
                                null, fBinding.type, groovyMethods, methodBindings, typeDeclaration);
                    }
                }
            }
        } else {
            // Create getters/setters without resolving the types.
            List<PropertyNode> properties = typeDeclaration.properties;
            for (PropertyNode property : properties) {
                String name = property.getName();
                String capitalizedName = MetaClassHelper.capitalize(name);
                // Create getter
                createGetterMethod(name, "get" + capitalizedName, property.isStatic(), groovyMethods,
                        methodBindings, typeDeclaration);
                // Create setter if non-final property
                if (!Modifier.isFinal(property.getModifiers())) {
                    createSetterMethod(name, "set" + capitalizedName, property.isStatic(), groovyMethods,
                            methodBindings, typeDeclaration, property.getType().getName());
                }
                // Create isA if type is boolean
                String propertyType = property.getType().getName();
                if (propertyType.equals("boolean")) {
                    createGetterMethod(name, "is" + capitalizedName, property.isStatic(), groovyMethods,
                            methodBindings, typeDeclaration);
                }
            }
        }
    }

    MethodBinding[] newMethodBindings = groovyMethods
            .toArray(new MethodBinding[methodBindings.length + groovyMethods.size()]);
    System.arraycopy(methodBindings, 0, newMethodBindings, groovyMethods.size(), methodBindings.length);
    return newMethodBindings;
}

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

License:Open Source License

public static TypeBinding getBaseType(char[] name) {
    // list should be optimized (with most often used first)
    int length = name.length;
    if (length > 2 && length < 8) {
        switch (name[0]) {
        case 'i':
            if (length == 3 && name[1] == 'n' && name[2] == 't')
                return TypeBinding.INT;
            break;
        case 'v':
            if (length == 4 && name[1] == 'o' && name[2] == 'i' && name[3] == 'd')
                return TypeBinding.VOID;
            break;
        case 'b':
            if (length == 7 && name[1] == 'o' && name[2] == 'o' && name[3] == 'l' && name[4] == 'e'
                    && name[5] == 'a' && name[6] == 'n')
                return TypeBinding.BOOLEAN;
            if (length == 4 && name[1] == 'y' && name[2] == 't' && name[3] == 'e')
                return TypeBinding.BYTE;
            break;
        case 'c':
            if (length == 4 && name[1] == 'h' && name[2] == 'a' && name[3] == 'r')
                return TypeBinding.CHAR;
            break;
        case 'd':
            if (length == 6 && name[1] == 'o' && name[2] == 'u' && name[3] == 'b' && name[4] == 'l'
                    && name[5] == 'e')
                return TypeBinding.DOUBLE;
            break;
        case 'f':
            if (length == 5 && name[1] == 'l' && name[2] == 'o' && name[3] == 'a' && name[4] == 't')
                return TypeBinding.FLOAT;
            break;
        case 'l':
            if (length == 4 && name[1] == 'o' && name[2] == 'n' && name[3] == 'g')
                return TypeBinding.LONG;
            break;
        case 's':
            if (length == 5 && name[1] == 'h' && name[2] == 'o' && name[3] == 'r' && name[4] == 't')
                return TypeBinding.SHORT;
        }//from  ww w  . jav  a2 s. co m
    }
    return null;
}

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

License:Open Source License

public FieldBinding addSyntheticFieldForAssert(BlockScope blockScope) {
    if (this.synthetics == null)
        this.synthetics = new HashMap[MAX_SYNTHETICS];
    if (this.synthetics[SourceTypeBinding.FIELD_EMUL] == null)
        this.synthetics[SourceTypeBinding.FIELD_EMUL] = new HashMap(5);

    FieldBinding synthField = (FieldBinding) this.synthetics[SourceTypeBinding.FIELD_EMUL]
            .get("assertionEmulation"); //$NON-NLS-1$
    if (synthField == null) {
        synthField = new SyntheticFieldBinding(TypeConstants.SYNTHETIC_ASSERT_DISABLED, TypeBinding.BOOLEAN,
                ClassFileConstants.AccDefault | ClassFileConstants.AccStatic | ClassFileConstants.AccSynthetic
                        | ClassFileConstants.AccFinal,
                this, Constant.NotAConstant, this.synthetics[SourceTypeBinding.FIELD_EMUL].size());
        this.synthetics[SourceTypeBinding.FIELD_EMUL].put("assertionEmulation", synthField); //$NON-NLS-1$
    }/*from ww  w  .  j  av a2s  .co  m*/
    // ensure there is not already such a field defined by the user
    // ensure there is not already such a field defined by the user
    boolean needRecheck;
    int index = 0;
    do {
        needRecheck = false;
        FieldBinding existingField;
        if ((existingField = getField(synthField.name, true /*resolve*/)) != null) {
            TypeDeclaration typeDecl = this.scope.referenceContext;
            int max = (typeDecl.fields == null) ? 0 : typeDecl.fields.length;
            for (int i = 0; i < max; i++) {
                FieldDeclaration fieldDecl = typeDecl.fields[i];
                if (fieldDecl.binding == existingField) {
                    synthField.name = CharOperation.concat(TypeConstants.SYNTHETIC_ASSERT_DISABLED,
                            ("_" + String.valueOf(index++)).toCharArray()); //$NON-NLS-1$
                    needRecheck = true;
                    break;
                }
            }
        }
    } while (needRecheck);
    return synthField;
}

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

License:Open Source License

/** can only transfer some flags once we have the method binding */
public boolean evaluate(MethodInfo info, MethodBinding method, LookupEnvironment environment) {
    if (this._methodInfo != info)
        return false;
    // MODIFIERS and ROLECLASS_METHOD_MODIFIERS_NAME and CALLS_BASE_CTOR are already evaluated at the MethodInfo level.
    if (CharOperation.equals(this._name, IOTConstants.CALLIN_FLAGS)) {
        MethodModel.getModel(method).callinFlags = this._value & 0xFF;
        int typeCode = this._value & IOTConstants.CALLIN_RETURN_MASK;
        if (typeCode != 0) {
            TypeBinding returnType;/*from w  ww. ja  v a2  s. co  m*/
            switch (typeCode) {
            case IOTConstants.CALLIN_RETURN_VOID:
                returnType = TypeBinding.VOID;
                break;
            case IOTConstants.CALLIN_RETURN_BOOLEAN:
                returnType = TypeBinding.BOOLEAN;
                break;
            case IOTConstants.CALLIN_RETURN_BYTE:
                returnType = TypeBinding.BYTE;
                break;
            case IOTConstants.CALLIN_RETURN_CHAR:
                returnType = TypeBinding.CHAR;
                break;
            case IOTConstants.CALLIN_RETURN_SHORT:
                returnType = TypeBinding.SHORT;
                break;
            case IOTConstants.CALLIN_RETURN_DOUBLE:
                returnType = TypeBinding.DOUBLE;
                break;
            case IOTConstants.CALLIN_RETURN_FLOAT:
                returnType = TypeBinding.FLOAT;
                break;
            case IOTConstants.CALLIN_RETURN_INT:
                returnType = TypeBinding.INT;
                break;
            case IOTConstants.CALLIN_RETURN_LONG:
                returnType = TypeBinding.LONG;
                break;
            default:
                throw new InternalCompilerError("Unexpected callin return type code " + typeCode); //$NON-NLS-1$
            }
            MethodModel.saveReturnType(method, returnType);
        }
        return true;
    }
    return false; // not handled, keep it.
}

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

License:Open Source License

/**
 * Create a method that initializes all caches introduced in a given team.
 * Only create method declaration, no statements yet.
 * (see fillGeneratedMethods()).//from ww  w . j  a  v  a  2 s .  co  m
 *
 * @param teamType the type to add the method to.
 * @return the _OT$initCaches method
 */
private static MethodDeclaration generateInitCaches(TypeDeclaration teamType) {
    MethodDeclaration initMethod = AstConverter.findAndAdjustCopiedMethod(teamType, IOTConstants.OT_INIT_CACHES,
            null);
    if (initMethod == null) {
        AstGenerator gen = new AstGenerator(teamType.sourceStart, teamType.sourceEnd);
        gen.shiftPosition(); // don't let @SuppressWarnings interfere with non-generated code.

        initMethod = gen.method(teamType.compilationResult, ClassFileConstants.AccPrivate, // no overriding!!
                TypeBinding.BOOLEAN, IOTConstants.OT_INIT_CACHES, null);
        initMethod.statements = new Statement[0]; // to be filled by fillInitCaches()
        initMethod.annotations = new Annotation[] { // in case base type is a raw type
                gen.singleStringsMemberAnnotation(TypeConstants.JAVA_LANG_SUPPRESSWARNINGS,
                        new char[][] { "all".toCharArray() }) //$NON-NLS-1$   
        };
        AstEdit.addMethod(teamType, initMethod);
        initMethod.modifiers |= ExtraCompilerModifiers.AccLocallyUsed; // prevent 'unused' warning

        if (teamType.isRole()) {
            TypeDeclaration ifcPart = teamType.getRoleModel().getInterfaceAst();
            if (ifcPart != teamType) {
                AbstractMethodDeclaration methodIfcPart = TypeAnalyzer.findMethodDecl(ifcPart,
                        IOTConstants.OT_INIT_CACHES, 0);
                if (methodIfcPart == null) {
                    methodIfcPart = AstConverter.genRoleIfcMethod(teamType.enclosingType, initMethod);
                    AstEdit.addMethod(ifcPart, methodIfcPart);
                }
            }
        }

        // Serialization: generate restore methods to initialize caches/register roles:
        SerializationGenerator.generateRestoreMethods(teamType, gen);
    }

    return initMethod;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.lookup.SyntheticBaseCallSurrogate.java

License:Open Source License

static TypeBinding[] addIsSuperAccessArg(TypeBinding[] baseCallParameters, WeavingScheme weavingScheme) {
    int len = baseCallParameters.length;
    TypeBinding[] newParams = new TypeBinding[len + 1];
    int enhancingArgLen = MethodSignatureEnhancer.getEnhancingArgLen(weavingScheme);
    System.arraycopy(baseCallParameters, 0, newParams, 0, enhancingArgLen);
    newParams[enhancingArgLen] = TypeBinding.BOOLEAN;
    System.arraycopy(baseCallParameters, enhancingArgLen, newParams, enhancingArgLen + 1,
            len - enhancingArgLen);//from w  w w.  ja  va 2 s.c o m
    return newParams;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.mappings.CallinImplementor.java

License:Open Source License

/**
 * Create a call to _OT$setIsExecutingCallin()
 * @param roleModel      the role holding the current callin mapping
 * @param statements    where to add the call
 * @return an expression for resetting the flag.
 *//* w ww .j ava2s  .  co  m*/
public static MessageSend setExecutingCallin(RoleModel roleModel, List<Statement> statements) {
    // use a separate gen for stepOver, so we don't have to switch back/forth its positions:
    AstGenerator stepOverGen = new AstGenerator(STEP_OVER_SOURCEPOSITION_START, STEP_OVER_SOURCEPOSITION_END);
    // mark as step_over:
    roleModel.getLineNumberProvider().addLineInfo(roleModel.getBinding(), STEP_OVER_LINENUMBER, -1);
    // ignore line number returned by addLineInfo but use the corresponding source position

    statements.add(stepOverGen.localVariable(OLD_IS_EXECUTING, TypeBinding.BOOLEAN,
            stepOverGen.messageSend(stepOverGen.thisReference(), IOTConstants.SET_EXECUTING_CALLIN,
                    new Expression[] { stepOverGen.booleanLiteral(true) })));

    // _OT$setExecutingCallin(oldIsExecutingCallin); (to be inserted below)
    return stepOverGen.messageSend(stepOverGen.thisReference(), IOTConstants.SET_EXECUTING_CALLIN,
            new Expression[] { stepOverGen.singleNameReference(OLD_IS_EXECUTING) });
}

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

License:Open Source License

/**
 * Generate methods// w ww  .j  a  v  a2 s  . c  o  m
 *       boolean hasRole(Object aBase);
 *     boolean hasRole(Object aBase, Class roleType);
 *       Object  getRole(Object aBase);
 *     Object  getRole(Object aBase, Class roleType);
 *      void    unregisterRole(Object _OT$role_arg)
 *      void    unregisterRole(Object _OT$role_arg, Class class_arg)
 * Due to the similarities, we create all six methods simultaneously.
 *
 * @param teamDecl
 * @param weavingScheme TODO
 */
public static void createRoleQueryMethods(TypeDeclaration teamDecl, WeavingScheme weavingScheme) {
    if (TypeAnalyzer.isOrgObjectteamsTeam(teamDecl.binding)
            || Protections.hasClassKindProblem(teamDecl.binding))
        return;
    long sourceLevel = teamDecl.scope.compilerOptions().sourceLevel;
    AstGenerator gen = new AstGenerator(sourceLevel, teamDecl.sourceStart, teamDecl.sourceEnd);
    AstGenerator gen2 = gen;
    if (sourceLevel >= ClassFileConstants.JDK1_5) {
        // gen2 produces positions that have a slight offset against the type:
        // we're adding @SuppressWarnings("all") which shouldn't affect other diagnostics
        // against the type's positions! (see usage of gen2 for more comments).
        gen2 = new AstGenerator(teamDecl.sourceStart, teamDecl.sourceEnd);
        gen2.shiftPosition();
    }

    TypeBinding booleanBinding = TypeBinding.BOOLEAN;
    TypeBinding objectBinding = teamDecl.scope.getJavaLangObject();
    ReferenceBinding classBinding = teamDecl.scope.getJavaLangClass();
    TypeBinding stringBinding = teamDecl.scope.getJavaLangString();
    TypeBinding hashMapBinding = teamDecl.scope.getType(WEAK_HASH_MAP, 3);
    TypeBinding objectArrayBinding;
    try {
        objectArrayBinding = Config.getLookupEnvironment().createArrayType(objectBinding, 1);
    } catch (NotConfiguredException e) {
        e.logWarning("Not creating reflective methods"); //$NON-NLS-1$
        return;
    }
    TypeReference objectCollectionRef;
    TypeReference wildcardCollectionRef;
    TypeReference roleTypeRef;
    TypeReference roleArrayTypeRef;
    if (sourceLevel >= ClassFileConstants.JDK1_5) {
        objectCollectionRef = gen.parameterizedQualifiedTypeReference(COLLECTION,
                new TypeBinding[] { objectBinding });
        wildcardCollectionRef = gen.parameterizedQualifiedTypeReference(COLLECTION,
                new TypeReference[] { new Wildcard(Wildcard.UNBOUND) });
        roleTypeRef = gen.singleTypeReference(T);
        roleArrayTypeRef = gen.arrayTypeReference(T, 1);
    } else {
        objectCollectionRef = gen.qualifiedTypeReference(COLLECTION);
        wildcardCollectionRef = gen.qualifiedTypeReference(COLLECTION);
        roleTypeRef = gen.typeReference(objectBinding);
        roleArrayTypeRef = gen.typeReference(objectArrayBinding);
    }

    MethodDeclaration hasRole1 = findOrGeneratePublicMethod(teamDecl, booleanBinding, HAS_ROLE, // boolean hasRole(Object _OT$base_arg)
            new Argument[] { gen.argument(_OT_BASE_ARG, gen.singleTypeReference(objectBinding)) }, gen);
    MethodDeclaration hasRole2 = findOrGeneratePublicMethod( // boolean hasRole(Object _OT$base_arg, java.lang.Class class_arg)
            teamDecl, booleanBinding, HAS_ROLE,
            new Argument[] { gen.argument(_OT_BASE_ARG, gen.singleTypeReference(objectBinding)),
                    gen.argument(CLASS_ARG, gen.qualifiedTypeReference(classBinding.compoundName)) },
            gen);
    MethodDeclaration getRole1 = findOrGeneratePublicMethod( // Object getRole(Object _OT$base_arg)
            teamDecl, objectBinding, GET_ROLE,
            new Argument[] { gen2.argument(_OT_BASE_ARG, gen.singleTypeReference(objectBinding)) }, gen2);
    if (sourceLevel >= ClassFileConstants.JDK1_5) {
        getRole1.annotations = new Annotation[] {
                // report neither potential null access nor unnecessary SuppressWarnings:
                // (first_name is accessed in ctor call for DuplicateRoleException without explicit null-check.)
                gen2.singleStringsMemberAnnotation(TypeConstants.JAVA_LANG_SUPPRESSWARNINGS,
                        new char[][] { "all".toCharArray() }) //$NON-NLS-1$
                // Note: would like to say @SuppressWarnings({"null", "suppressWarnings"}).
                // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=252518
        };
    }
    MethodDeclaration getRole2 = findOrGeneratePublicMethod( // <T> T getRole(Object _OT$base_arg, java.lang.Class<T> class_arg)
            teamDecl, roleTypeRef, GET_ROLE,
            new Argument[] { gen.argument(_OT_BASE_ARG, gen.singleTypeReference(objectBinding)), gen.argument( // java.lang.Class<T> class_arg
                    CLASS_ARG, gen.parameterizedQualifiedTypeReference(classBinding.compoundName,
                            new TypeReference[] { gen.singleTypeReference(T) })) },
            gen);
    if (sourceLevel >= ClassFileConstants.JDK1_5)
        getRole2.typeParameters = new TypeParameter[] { gen.unboundedTypeParameter(T) };
    MethodDeclaration getARoles1 = findOrGeneratePublicMethod( // Object[] getAllRoles()
            teamDecl, objectArrayBinding, GET_ALL_ROLES, null, gen);
    MethodDeclaration getARoles2 = findOrGeneratePublicMethod( // <T> T[] getAllRoles(Class<T> class_arg)
            teamDecl, roleArrayTypeRef, GET_ALL_ROLES, new Argument[] { gen.argument( // java.lang.Class<T> class_arg
                    CLASS_ARG, gen.parameterizedQualifiedTypeReference(classBinding.compoundName,
                            new TypeReference[] { gen.singleTypeReference(T) })) },
            gen);
    if (sourceLevel >= ClassFileConstants.JDK1_5)
        getARoles2.typeParameters = new TypeParameter[] { gen.unboundedTypeParameter(T) };
    MethodDeclaration unregRole1 = findOrGeneratePublicMethod( // void unregisterRole(Object _OT$base_arg)
            teamDecl, TypeBinding.VOID, UNREGISTER_ROLE,
            new Argument[] { gen.argument(_OT_ROLE_ARG, gen.singleTypeReference(objectBinding)) }, gen2);
    if (sourceLevel >= ClassFileConstants.JDK1_5) {
        unregRole1.annotations = new Annotation[] {
                // found_base is accessed to call remove(role) without explicit null-check. [see also getRole1 above].
                gen2.singleStringsMemberAnnotation(TypeConstants.JAVA_LANG_SUPPRESSWARNINGS,
                        new char[][] { "all".toCharArray() }) //$NON-NLS-1$
        };
    }
    MethodDeclaration unregRole2 = findOrGeneratePublicMethod( // void unregisterRole(Object _OT$base_arg, Class class_arg)
            teamDecl, TypeBinding.VOID, UNREGISTER_ROLE,
            new Argument[] { gen.argument(_OT_ROLE_ARG, gen.singleTypeReference(objectBinding)),
                    gen.argument(CLASS_ARG, gen.qualifiedTypeReference(classBinding.compoundName)) },
            gen);

    RoleModel[] roles = teamDecl.getTeamModel().getRoles(false/*no synth ifc*/);
    int h1 = 0; // hasRole1
    int g1 = 0; // getRole1
    int ga = 0; // getAllRoles1
    int g2 = 0; // getAllRoles2
    int m2 = 0; // hasRole2, getRole2
    int u1 = 0; // unregRole1
    int u2 = 0; // unregRole2
    Statement[] hasStats1 = new Statement[roles.length]; // at most this many elements..
    Statement[] hasStats2 = new Statement[roles.length]; // .. compact below.
    Statement[] getStats1 = new Statement[roles.length + 2]; // ... (plus 2 locals)
    Statement[] getStats2 = new Statement[roles.length]; // ...
    Statement[] getAStats1 = new Statement[roles.length + 1]; // ... (plus 1 local)
    Statement[] getAStats2 = new Statement[roles.length + 2]; // ... (plus prefix (1 local) + postfix (1 block))
    Statement[] unregStats1 = new Statement[roles.length + 3]; // ... (plus 3 locals)
    Statement[] unregStats2 = new Statement[roles.length]; // ...

    getStats1[g1++] = gen.localVariable(FIRST_RESULT, objectBinding, gen.nullLiteral());
    getStats1[g1++] = gen.localVariable(FIRST_NAME, stringBinding, gen.nullLiteral());
    getAStats1[ga++] = gen.localVariable(FIRST_RESULT, objectCollectionRef, createMTList(gen, objectBinding));
    getAStats2[g2++] = gen.localVariable(VALUES, wildcardCollectionRef, gen.nullLiteral());
    unregStats1[u1++] = gen2.localVariable(FIRST_NAME, stringBinding, gen2.nullLiteral());
    unregStats1[u1++] = gen2.localVariable(FIRST_CACHE, hashMapBinding.erasure(), gen2.nullLiteral());
    unregStats1[u1++] = gen2.localVariable(FOUND_BASE, objectBinding, gen2.nullLiteral());
    HashSet<String> processedCaches = new HashSet<String>();
    for (int i = 0; i < roles.length; i++) {
        if (roles[i].isSynthInterface())
            continue;
        if (TypeAnalyzer.isTopConfined(roles[i].getBinding()))
            continue;
        if (roles[i].isIgnoreFurtherInvestigation())
            continue;
        RoleModel boundRootRole = roles[i].getBoundRootRole();
        if (boundRootRole != null && boundRootRole.isIgnoreFurtherInvestigation())
            continue;
        char[] cacheName = LiftingEnvironment.getCacheName(boundRootRole);
        if (cacheName != null) {
            String cacheString = new String(cacheName); // String for hashing!
            ReferenceBinding roleType = roles[i].getInterfacePartBinding();
            if (!processedCaches.contains(cacheString)) {
                // one lookup per cache:
                processedCaches.add(cacheString);
                hasStats1[h1++] = createIfContainsTrue(cacheName, gen);
                getStats1[g1++] = createIfContainsGet(cacheName, gen2, g1 == 3);
                getAStats1[ga++] = createAddAll(cacheName, gen);
                unregStats1[u1++] = createRememberIfContains(roleType, cacheName, gen2, u1 == 4);
            }
            // one lookup per bound role class:
            hasStats2[m2] = createIfTypeEqualAndContains(roleType, cacheName, gen, objectBinding);
            getStats2[m2++] = createIfTypeEqualAndGet(roleType, cacheName, gen);
            getAStats2[g2++] = createIfTypeEqualFetchValues(roleType, cacheName, gen);
            unregStats2[u2++] = createRemove(roleType, cacheName, gen, weavingScheme);
        }
    }
    if (g2 > 1)
        getAStats2[g2++] = createFilterValues(gen);
    else
        getAStats2[g2++] = createThrowNoSuchRole(gen); // no caches to search
    boolean needsAllMethods = needToImplementITeamMethods(teamDecl);
    if (h1 > 0 || needsAllMethods) {
        System.arraycopy(hasStats1, 0, hasStats1 = new Statement[h1 + 1], 0, h1);
        System.arraycopy(getStats1, 0, getStats1 = new Statement[g1 + 1], 0, g1);
        System.arraycopy(getAStats1, 0, getAStats1 = new Statement[ga + 1], 0, ga);
        System.arraycopy(unregStats1, 0, unregStats1 = new Statement[(u1 > 3) ? (u1 + 1) : u1], 0, u1);
        // no role instance found means: return false:
        hasStats1[h1] = gen.returnStatement(gen.booleanLiteral(false));
        // no duplicate means: return first_result;
        getStats1[g1] = gen.returnStatement(gen.singleNameReference(FIRST_RESULT));
        getAStats1[ga] = gen
                .returnStatement(gen.messageSend(gen.singleNameReference(FIRST_RESULT), TO_ARRAY, null));
        // no duplicate means: if found remove from first_cache;
        if (u1 > 3)
            unregStats1[u1] = createRemoveIfFound(gen2, weavingScheme); // if u1 <= 3 this would not be reachable due to definite null
        hasRole1.setStatements(hasStats1);
        getRole1.setStatements(getStats1);
        getARoles1.setStatements(getAStats1);
        unregRole1.setStatements(unregStats1);
        checkedAddMethod(teamDecl, hasRole1);
        checkedAddMethod(teamDecl, getRole1);
        checkedAddMethod(teamDecl, getARoles1);
        checkedAddMethod(teamDecl, unregRole1);
    }
    if (m2 > 0 || needsAllMethods) {
        System.arraycopy(hasStats2, 0, hasStats2 = new Statement[m2 + 1], 0, m2);
        System.arraycopy(getStats2, 0, getStats2 = new Statement[m2 + 1], 0, m2);
        System.arraycopy(unregStats2, 0, unregStats2 = new Statement[u2 + 1], 0, u2);
        // role class not found means: illegal argument:
        hasStats2[m2] = createThrowNoSuchRole(gen);
        getStats2[m2] = createThrowNoSuchRole(gen);
        unregStats2[u2] = createThrowNoSuchRole(gen);
        hasRole2.setStatements(hasStats2);
        getRole2.setStatements(getStats2);
        unregRole2.setStatements(unregStats2);
        checkedAddMethod(teamDecl, hasRole2);
        checkedAddMethod(teamDecl, getRole2);
        checkedAddMethod(teamDecl, unregRole2);
    }
    if (g2 > 2 || needsAllMethods) {
        System.arraycopy(getAStats2, 0, getAStats2 = new Statement[g2], 0, g2);
        getARoles2.setStatements(getAStats2);
        checkedAddMethod(teamDecl, getARoles2);
    }
}

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

License:Open Source License

/**
 * Create the code that combines team anchor comparison and a regulare instanceof.
 * @param exprType//from  ww  w.  j a  va2  s .c o m
 * @param castType
 */
public static Expression createRoleInstanceOfCheck(BlockScope scope, InstanceOfExpression expr,
        ReferenceBinding exprType, DependentTypeBinding castType) {

    AstGenerator gen = new AstGenerator(expr.sourceStart, expr.sourceEnd);
    Expression teamInstanceComparison;
    if (RoleTypeBinding.isRoleWithExplicitAnchor(exprType)) {
        teamInstanceComparison = createAnchorEqualCheck(scope, (RoleTypeBinding) exprType, castType,
                expr.sourceStart, expr.sourceEnd);
    } else {
        BinaryExpression teamCheck = genTeamCheck(gen, OperatorIds.EQUAL_EQUAL,
                gen.resolvedCastExpression(expr.expression, // FIXME(SH): avoid double evaluation of expression!
                        // but how can we store a value without a statement?
                        // use a byte-code hack (cf. Lowering.{Pushing,Pop}Expression!)
                        castType.getRealType(), CastExpression.RAW),
                createTeamAnchorReference(scope, castType, gen), expr.type.dimensions());

        // manually resolve:
        MessageSend msg = (MessageSend) teamCheck.left;
        msg.binding = castType.getMethod(scope, IOTConstants._OT_GETTEAM);
        if (msg.binding == null) {
            // add a fake method, assuming it was not created due to errors:
            msg.binding = new MethodBinding(AccPublic, IOTConstants._OT_GETTEAM, scope.getOrgObjectteamsITeam(),
                    Binding.NO_PARAMETERS, Binding.NO_EXCEPTIONS, castType);
            assert castType.roleModel.isIgnoreFurtherInvestigation();
        }
        msg.actualReceiverType = castType.getRealType();
        //         msg.resolvedType = msg.binding.returnType;
        msg.constant = Constant.NotAConstant;
        teamCheck.right.constant = Constant.NotAConstant;
        teamCheck.constant = Constant.NotAConstant;
        teamCheck.resolvedType = TypeBinding.BOOLEAN;

        teamInstanceComparison = teamCheck;
    }

    TypeReference castTypeRef = gen.typeReference(castType.getRealType());
    castTypeRef.resolvedType = castType.getRealType();
    castTypeRef.constant = Constant.NotAConstant;
    expr.expression.resolvedType = exprType.getRealClass();
    expr.expression.constant = Constant.NotAConstant;
    InstanceOfExpression origCheckClone = gen.setPos(new InstanceOfExpression(expr.expression, castTypeRef));
    origCheckClone.bits = expr.bits; // includes operator
    origCheckClone.resolvedType = TypeBinding.BOOLEAN;
    origCheckClone.constant = Constant.NotAConstant;

    AND_AND_Expression andAnd = gen
            .setPos(new AND_AND_Expression(origCheckClone, teamInstanceComparison, OperatorIds.AND_AND));
    andAnd.resolvedType = TypeBinding.BOOLEAN;
    andAnd.constant = Constant.NotAConstant;
    return andAnd;
}