Example usage for org.eclipse.jdt.core.dom IVariableBinding getName

List of usage examples for org.eclipse.jdt.core.dom IVariableBinding getName

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom IVariableBinding getName.

Prototype

@Override
public String getName();

Source Link

Document

Returns the name of the field or local variable declared in this binding.

Usage

From source file:astview.Binding.java

License:Open Source License

@Override
public String getLabel() {
    StringBuffer buf = new StringBuffer(fLabel);
    buf.append(": "); //$NON-NLS-1$
    if (fBinding != null) {
        switch (fBinding.getKind()) {
        case IBinding.VARIABLE:
            IVariableBinding variableBinding = (IVariableBinding) fBinding;
            if (!variableBinding.isField()) {
                buf.append(variableBinding.getName());
            } else {
                if (variableBinding.getDeclaringClass() == null) {
                    buf.append("<some array type>"); //$NON-NLS-1$
                } else {
                    buf.append(variableBinding.getDeclaringClass().getName());
                }/* w w w  . j  a  v  a 2  s . co  m*/
                buf.append('.');
                buf.append(variableBinding.getName());
            }
            break;
        case IBinding.PACKAGE:
            IPackageBinding packageBinding = (IPackageBinding) fBinding;
            buf.append(packageBinding.getName());
            break;
        case IBinding.TYPE:
            ITypeBinding typeBinding = (ITypeBinding) fBinding;
            appendAnnotatedQualifiedName(buf, typeBinding);
            break;
        case IBinding.METHOD:
            IMethodBinding methodBinding = (IMethodBinding) fBinding;
            buf.append(methodBinding.getDeclaringClass().getName());
            buf.append('.');
            buf.append(methodBinding.getName());
            buf.append('(');
            ITypeBinding[] parameters = methodBinding.getParameterTypes();
            for (int i = 0; i < parameters.length; i++) {
                if (i > 0) {
                    buf.append(", "); //$NON-NLS-1$
                }
                ITypeBinding parameter = parameters[i];
                buf.append(parameter.getName());
            }
            buf.append(')');
            break;
        case IBinding.ANNOTATION:
        case IBinding.MEMBER_VALUE_PAIR:
            buf.append(fBinding.toString());
            break;
        }

    } else {
        buf.append("null"); //$NON-NLS-1$
    }
    return buf.toString();

}

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

private IDSModel processComponent(TypeDeclaration type, ITypeBinding typeBinding, Annotation annotation,
        IAnnotationBinding annotationBinding, Collection<DSAnnotationProblem> problems) {
    HashMap<String, Object> params = new HashMap<String, Object>();
    for (IMemberValuePairBinding pair : annotationBinding.getDeclaredMemberValuePairs()) {
        params.put(pair.getName(), pair.getValue());
    }//from   w  ww. j a  v  a2  s . c  o  m

    boolean requiresV12 = false;

    String implClass = typeBinding.getBinaryName();

    String name = implClass;
    Object value;
    if ((value = params.get("name")) instanceof String) { //$NON-NLS-1$
        name = (String) value;
        validateComponentName(annotation, name, problems);
    }

    Collection<String> services;
    if ((value = params.get("service")) instanceof Object[]) { //$NON-NLS-1$
        Object[] elements = (Object[]) value;
        services = new LinkedHashSet<String>(elements.length);
        Map<String, Integer> serviceDuplicates = errorLevel.isNone() ? null : new HashMap<String, Integer>();
        for (int i = 0; i < elements.length; ++i) {
            ITypeBinding serviceType = (ITypeBinding) elements[i];
            String serviceName = serviceType.getBinaryName();
            if (!errorLevel.isNone()) {
                if (serviceDuplicates.containsKey(serviceName)) {
                    reportProblem(annotation, "service", i, problems, //$NON-NLS-1$
                            Messages.AnnotationProcessor_duplicateServiceDeclaration, serviceName);
                    Integer pos = serviceDuplicates.put(serviceName, null);
                    if (pos != null)
                        reportProblem(annotation, "service", pos.intValue(), problems, //$NON-NLS-1$
                                Messages.AnnotationProcessor_duplicateServiceDeclaration, serviceName);
                } else {
                    serviceDuplicates.put(serviceName, i);
                }
            }

            services.add(serviceName);
            validateComponentService(annotation, typeBinding, serviceType, i, problems);
        }
    } else {
        ITypeBinding[] serviceTypes = typeBinding.getInterfaces();
        services = new ArrayList<String>(serviceTypes.length);
        for (int i = 0; i < serviceTypes.length; ++i) {
            services.add(serviceTypes[i].getBinaryName());
        }
    }

    String factory = null;
    if ((value = params.get("factory")) instanceof String) { //$NON-NLS-1$
        factory = (String) value;
        validateComponentFactory(annotation, factory, problems);
    }

    Boolean serviceFactory = null;
    if ((value = params.get("servicefactory")) instanceof Boolean) { //$NON-NLS-1$
        serviceFactory = (Boolean) value;
    }

    Boolean enabled = null;
    if ((value = params.get("enabled")) instanceof Boolean) { //$NON-NLS-1$
        enabled = (Boolean) value;
    }

    Boolean immediate = null;
    if ((value = params.get("immediate")) instanceof Boolean) { //$NON-NLS-1$
        immediate = (Boolean) value;
    }

    String[] properties;
    if ((value = params.get("property")) instanceof Object[]) { //$NON-NLS-1$
        Object[] elements = (Object[]) value;
        ArrayList<String> list = new ArrayList<String>(elements.length);
        for (int i = 0; i < elements.length; ++i) {
            if (elements[i] instanceof String)
                list.add((String) elements[i]);
        }

        properties = list.toArray(new String[list.size()]);
    } else {
        properties = new String[0];
    }

    String[] propertyFiles;
    if ((value = params.get("properties")) instanceof Object[]) { //$NON-NLS-1$
        Object[] elements = (Object[]) value;
        ArrayList<String> list = new ArrayList<String>(elements.length);
        for (int i = 0; i < elements.length; ++i) {
            if (elements[i] instanceof String)
                list.add((String) elements[i]);
        }

        propertyFiles = list.toArray(new String[list.size()]);
        validateComponentPropertyFiles(annotation,
                ((IType) typeBinding.getJavaElement()).getJavaProject().getProject(), propertyFiles, problems);
    } else {
        propertyFiles = new String[0];
    }

    String configPolicy = null;
    if ((value = params.get("configurationPolicy")) instanceof IVariableBinding) { //$NON-NLS-1$
        IVariableBinding configPolicyBinding = (IVariableBinding) value;
        ConfigurationPolicy configPolicyLiteral = ConfigurationPolicy.valueOf(configPolicyBinding.getName());
        if (configPolicyLiteral != null)
            configPolicy = configPolicyLiteral.toString();
    }

    String configPid = null;
    if ((value = params.get("configurationPid")) instanceof String) { //$NON-NLS-1$
        configPid = (String) value;
        validateComponentConfigPID(annotation, configPid, problems);
        requiresV12 = true;
    }

    DSModel model = new DSModel(new Document(), false);
    IDSComponent component = model.getDSComponent();

    if (name != null)
        component.setAttributeName(name);

    if (factory != null)
        component.setFactory(factory);

    if (enabled != null)
        component.setEnabled(enabled.booleanValue());

    if (immediate != null)
        component.setImmediate(immediate.booleanValue());

    if (configPolicy != null)
        component.setConfigurationPolicy(configPolicy);

    if (configPid != null)
        component.setXMLAttribute("configuration-pid", configPid); //$NON-NLS-1$

    IDSDocumentFactory dsFactory = component.getModel().getFactory();
    IDSImplementation impl = dsFactory.createImplementation();
    component.setImplementation(impl);
    impl.setClassName(implClass);

    if (!services.isEmpty()) {
        IDSService service = dsFactory.createService();
        component.setService(service);
        for (String serviceName : services) {
            IDSProvide provide = dsFactory.createProvide();
            service.addProvidedService(provide);
            provide.setInterface(serviceName);
        }

        if (serviceFactory != null)
            service.setServiceFactory(serviceFactory.booleanValue());
    }

    if (properties.length > 0) {
        HashMap<String, IDSProperty> map = new HashMap<String, IDSProperty>(properties.length);
        for (int i = 0; i < properties.length; ++i) {
            String propertyStr = properties[i];
            String[] pair = propertyStr.split("=", 2); //$NON-NLS-1$
            int colon = pair[0].indexOf(':');
            String propertyName, propertyType;
            if (colon == -1) {
                propertyName = pair[0];
                propertyType = null;
            } else {
                propertyName = pair[0].substring(0, colon);
                propertyType = pair[0].substring(colon + 1);
            }

            String propertyValue = pair.length > 1 ? pair[1].trim() : null;

            IDSProperty property = map.get(propertyName);
            if (property == null) {
                // create a new property
                property = dsFactory.createProperty();
                component.addPropertyElement(property);
                map.put(propertyName, property);
                property.setPropertyName(propertyName);
                property.setPropertyType(propertyType);
                property.setPropertyValue(propertyValue);
                validateComponentProperty(annotation, propertyName, propertyType, propertyValue, i, problems);
            } else {
                // property exists; make it multi-valued
                String content = property.getPropertyElemBody();
                if (content == null) {
                    content = property.getPropertyValue();
                    property.setPropertyElemBody(content);
                    property.setPropertyValue(null);
                }

                if (!errorLevel.isNone()) {
                    String expected = property.getPropertyType() == null || property.getPropertyType().isEmpty()
                            || String.class.getSimpleName().equals(property.getPropertyType())
                                    ? Messages.AnnotationProcessor_stringOrEmpty
                                    : property.getPropertyType();
                    String actual = propertyType == null || String.class.getSimpleName().equals(propertyType)
                            ? Messages.AnnotationProcessor_stringOrEmpty
                            : propertyType;
                    if (!actual.equals(expected))
                        reportProblem(annotation, "property", i, problems, //$NON-NLS-1$
                                NLS.bind(Messages.AnnotationProcessor_inconsistentComponentPropertyType, actual,
                                        expected),
                                actual);
                    else
                        validateComponentProperty(annotation, propertyName, propertyType, propertyValue, i,
                                problems);
                }

                if (propertyValue != null)
                    property.setPropertyElemBody(content + "\n" + pair[1]); //$NON-NLS-1$
            }
        }
    }

    if (propertyFiles.length > 0) {
        for (String propertyFile : propertyFiles) {
            IDSProperties propertiesElement = dsFactory.createProperties();
            component.addPropertiesElement(propertiesElement);
            propertiesElement.setEntry(propertyFile);
        }
    }

    String activate = null;
    Annotation activateAnnotation = null;
    String deactivate = null;
    Annotation deactivateAnnotation = null;
    String modified = null;
    Annotation modifiedAnnotation = null;

    ArrayList<IDSReference> references = new ArrayList<IDSReference>();
    HashMap<String, Annotation> referenceNames = new HashMap<String, Annotation>();

    for (MethodDeclaration method : type.getMethods()) {
        for (Object modifier : method.modifiers()) {
            if (!(modifier instanceof Annotation))
                continue;

            Annotation methodAnnotation = (Annotation) modifier;
            IAnnotationBinding methodAnnotationBinding = methodAnnotation.resolveAnnotationBinding();
            if (methodAnnotationBinding == null) {
                if (debug.isDebugging())
                    debug.trace(
                            String.format("Unable to resolve binding for annotation: %s", methodAnnotation)); //$NON-NLS-1$

                continue;
            }

            String annotationName = methodAnnotationBinding.getAnnotationType().getQualifiedName();

            if (ACTIVATE_ANNOTATION.equals(annotationName)) {
                if (activate == null) {
                    activate = method.getName().getIdentifier();
                    activateAnnotation = methodAnnotation;
                    validateLifeCycleMethod(methodAnnotation, "activate", method, problems); //$NON-NLS-1$
                } else if (!errorLevel.isNone()) {
                    reportProblem(methodAnnotation, null, problems,
                            Messages.AnnotationProcessor_duplicateActivateMethod,
                            method.getName().getIdentifier());
                    if (activateAnnotation != null) {
                        reportProblem(activateAnnotation, null, problems,
                                Messages.AnnotationProcessor_duplicateActivateMethod, activate);
                        activateAnnotation = null;
                    }
                }

                continue;
            }

            if (DEACTIVATE_ANNOTATION.equals(annotationName)) {
                if (deactivate == null) {
                    deactivate = method.getName().getIdentifier();
                    deactivateAnnotation = methodAnnotation;
                    validateLifeCycleMethod(methodAnnotation, "deactivate", method, problems); //$NON-NLS-1$
                } else if (!errorLevel.isNone()) {
                    reportProblem(methodAnnotation, null, problems,
                            Messages.AnnotationProcessor_duplicateDeactivateMethod,
                            method.getName().getIdentifier());
                    if (deactivateAnnotation != null) {
                        reportProblem(deactivateAnnotation, null, problems,
                                Messages.AnnotationProcessor_duplicateDeactivateMethod, deactivate);
                        deactivateAnnotation = null;
                    }
                }

                continue;
            }

            if (MODIFIED_ANNOTATION.equals(annotationName)) {
                if (modified == null) {
                    modified = method.getName().getIdentifier();
                    modifiedAnnotation = methodAnnotation;
                    validateLifeCycleMethod(methodAnnotation, "modified", method, problems); //$NON-NLS-1$
                } else if (!errorLevel.isNone()) {
                    reportProblem(methodAnnotation, null, problems,
                            Messages.AnnotationProcessor_duplicateModifiedMethod,
                            method.getName().getIdentifier());
                    if (modifiedAnnotation != null) {
                        reportProblem(modifiedAnnotation, null, problems,
                                Messages.AnnotationProcessor_duplicateModifiedMethod, modified);
                        modifiedAnnotation = null;
                    }
                }

                continue;
            }

            if (REFERENCE_ANNOTATION.equals(annotationName)) {
                IMethodBinding methodBinding = method.resolveBinding();
                if (methodBinding == null) {
                    if (debug.isDebugging())
                        debug.trace(String.format("Unable to resolve binding for method: %s", method)); //$NON-NLS-1$
                } else {
                    requiresV12 |= processReference(method, methodBinding, methodAnnotation,
                            methodAnnotationBinding, dsFactory, references, referenceNames, problems);
                }

                continue;
            }
        }
    }

    if (activate != null)
        component.setActivateMethod(activate);

    if (deactivate != null)
        component.setDeactivateMethod(deactivate);

    if (modified != null)
        component.setModifiedeMethod(modified);

    if (!references.isEmpty()) {
        // references must be declared in ascending lexicographical order of their names
        Collections.sort(references, REF_NAME_COMPARATOR);
        for (IDSReference reference : references) {
            component.addReference(reference);
        }
    }

    String xmlns = null;
    if ((value = params.get("xmlns")) instanceof String) { //$NON-NLS-1$
        xmlns = (String) value;
        validateComponentXMLNS(annotation, xmlns, requiresV12, problems);
    } else if (requiresV12) {
        xmlns = NAMESPACE_1_2;
    }

    if (xmlns != null)
        component.setNamespace(xmlns);

    return model;
}

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

private boolean processReference(MethodDeclaration method, IMethodBinding methodBinding, Annotation annotation,
        IAnnotationBinding annotationBinding, IDSDocumentFactory factory, Collection<IDSReference> collector,
        Map<String, Annotation> names, Collection<DSAnnotationProblem> problems) {
    HashMap<String, Object> params = new HashMap<String, Object>();
    for (IMemberValuePairBinding pair : annotationBinding.getDeclaredMemberValuePairs()) {
        params.put(pair.getName(), pair.getValue());
    }//from w  w  w  .  j  a v a2s  .com

    boolean requiresV12 = false;

    ITypeBinding[] argTypes = methodBinding.getParameterTypes();

    ITypeBinding serviceType;
    Object value;
    if ((value = params.get("service")) instanceof ITypeBinding) { //$NON-NLS-1$
        serviceType = (ITypeBinding) value;
        if (!errorLevel.isNone() && argTypes.length > 0) {
            ITypeBinding[] typeArgs;
            if (!(ServiceReference.class.getName().equals(argTypes[0].getErasure().getQualifiedName())
                    && ((typeArgs = argTypes[0].getTypeArguments()).length == 0
                            || serviceType.isAssignmentCompatible(typeArgs[0])))
                    && !serviceType.isAssignmentCompatible(argTypes[0]))
                reportProblem(annotation, "service", problems, //$NON-NLS-1$
                        NLS.bind(Messages.AnnotationProcessor_invalidReferenceService, argTypes[0].getName(),
                                serviceType.getName()),
                        serviceType.getName());
        }
    } else if (argTypes.length > 0) {
        if (ServiceReference.class.getName().equals(argTypes[0].getErasure().getQualifiedName())) {
            ITypeBinding[] typeArgs = argTypes[0].getTypeArguments();
            if (typeArgs.length > 0)
                serviceType = typeArgs[0];
            else
                serviceType = null;
        } else {
            serviceType = argTypes[0].isPrimitive() ? getObjectType(method.getAST(), argTypes[0]) : argTypes[0];
        }
    } else {
        serviceType = null;
    }

    if (serviceType == null) {
        reportProblem(annotation, null, problems, Messages.AnnotationProcessor_invalidReferenceServiceUnknown);

        serviceType = method.getAST().resolveWellKnownType(Object.class.getName());
    }

    validateReferenceBindMethod(annotation, serviceType, methodBinding, problems);

    String service = serviceType == null ? null : serviceType.getBinaryName();

    String methodName = methodBinding.getName();
    String name;
    if ((value = params.get("name")) instanceof String) { //$NON-NLS-1$
        name = (String) value;
    } else if (methodName.startsWith("bind")) { //$NON-NLS-1$
        name = methodName.substring("bind".length()); //$NON-NLS-1$
    } else if (methodName.startsWith("set")) { //$NON-NLS-1$
        name = methodName.substring("set".length()); //$NON-NLS-1$
    } else if (methodName.startsWith("add")) { //$NON-NLS-1$
        name = methodName.substring("add".length()); //$NON-NLS-1$
    } else {
        name = methodName;
    }

    if (!errorLevel.isNone()) {
        if (names.containsKey(name)) {
            reportProblem(annotation, "name", problems, //$NON-NLS-1$
                    NLS.bind(Messages.AnnotationProcessor_duplicateReferenceName, name), name);
            Annotation duplicate = names.put(name, null);
            if (duplicate != null)
                reportProblem(duplicate, "name", problems, //$NON-NLS-1$
                        NLS.bind(Messages.AnnotationProcessor_duplicateReferenceName, name), name);
        } else {
            names.put(name, annotation);
        }
    }

    String cardinality = null;
    if ((value = params.get("cardinality")) instanceof IVariableBinding) { //$NON-NLS-1$
        IVariableBinding cardinalityBinding = (IVariableBinding) value;
        ReferenceCardinality cardinalityLiteral = ReferenceCardinality.valueOf(cardinalityBinding.getName());
        if (cardinalityLiteral != null)
            cardinality = cardinalityLiteral.toString();
    }

    String policy = null;
    if ((value = params.get("policy")) instanceof IVariableBinding) { //$NON-NLS-1$
        IVariableBinding policyBinding = (IVariableBinding) value;
        ReferencePolicy policyLiteral = ReferencePolicy.valueOf(policyBinding.getName());
        if (policyLiteral != null)
            policy = policyLiteral.toString();
    }

    String target = null;
    if ((value = params.get("target")) instanceof String) { //$NON-NLS-1$
        target = (String) value;
        validateReferenceTarget(annotation, target, problems);
    }

    String unbind;
    if ((value = params.get("unbind")) instanceof String) { //$NON-NLS-1$
        String unbindValue = (String) value;
        if ("-".equals(unbindValue)) { //$NON-NLS-1$
            unbind = null;
        } else {
            unbind = unbindValue;
            if (!errorLevel.isNone() && serviceType != null) {
                IMethodBinding unbindMethod = findReferenceMethod(methodBinding.getDeclaringClass(),
                        serviceType, unbind);
                if (unbindMethod == null)
                    reportProblem(annotation, "unbind", problems, //$NON-NLS-1$
                            NLS.bind(Messages.AnnotationProcessor_invalidReferenceUnbind, unbind), unbind);
            }
        }
    } else if (serviceType != null) {
        String unbindCandidate;
        if (methodName.startsWith("add")) { //$NON-NLS-1$
            unbindCandidate = "remove" + methodName.substring("add".length()); //$NON-NLS-1$ //$NON-NLS-2$
        } else {
            unbindCandidate = "un" + methodName; //$NON-NLS-1$
        }

        IMethodBinding unbindMethod = findReferenceMethod(methodBinding.getDeclaringClass(), serviceType,
                unbindCandidate);
        if (unbindMethod == null)
            unbind = null;
        else
            unbind = unbindMethod.getName();
    } else {
        unbind = null;
    }

    String policyOption = null;
    if ((value = params.get("policyOption")) instanceof IVariableBinding) { //$NON-NLS-1$
        IVariableBinding policyOptionBinding = (IVariableBinding) value;
        ReferencePolicyOption policyOptionLiteral = ReferencePolicyOption
                .valueOf(policyOptionBinding.getName());
        if (policyOptionLiteral != null) {
            policyOption = policyOptionLiteral.toString();
            requiresV12 = true;
        }
    }

    String updated;
    if ((value = params.get("updated")) instanceof String) { //$NON-NLS-1$
        String updatedValue = (String) value;
        if ("-".equals(updatedValue)) { //$NON-NLS-1$
            updated = null;
        } else {
            updated = updatedValue;
            if (!errorLevel.isNone() && serviceType != null) {
                IMethodBinding updatedMethod = findReferenceMethod(methodBinding.getDeclaringClass(),
                        serviceType, updated);
                if (updatedMethod == null)
                    reportProblem(annotation, "updated", problems, //$NON-NLS-1$
                            NLS.bind(Messages.AnnotationProcessor_invalidReferenceUpdated, updated), updated);
            }
        }

        requiresV12 = true;
    } else if (serviceType != null) {
        String updatedCandidate;
        if (methodName.startsWith("bind")) { //$NON-NLS-1$
            updatedCandidate = "updated" + methodName.substring("bind".length()); //$NON-NLS-1$ //$NON-NLS-2$
        } else if (methodName.startsWith("set")) { //$NON-NLS-1$
            updatedCandidate = "updated" + methodName.substring("set".length()); //$NON-NLS-1$ //$NON-NLS-2$
        } else if (methodName.startsWith("add")) { //$NON-NLS-1$
            updatedCandidate = "updated" + methodName.substring("add".length()); //$NON-NLS-1$ //$NON-NLS-2$
        } else {
            updatedCandidate = "updated" + methodName; //$NON-NLS-1$
        }

        IMethodBinding updatedMethod = findReferenceMethod(methodBinding.getDeclaringClass(), serviceType,
                updatedCandidate);
        if (updatedMethod == null)
            updated = null;
        else
            updated = updatedMethod.getName();
    } else {
        updated = null;
    }

    IDSReference reference = factory.createReference();
    collector.add(reference);

    reference.setReferenceBind(methodName);

    if (name != null)
        reference.setReferenceName(name);

    if (service != null)
        reference.setReferenceInterface(service);

    if (cardinality != null)
        reference.setReferenceCardinality(cardinality);

    if (policy != null)
        reference.setReferencePolicy(policy);

    if (target != null)
        reference.setReferenceTarget(target);

    if (unbind != null)
        reference.setReferenceUnbind(unbind);

    if (policyOption != null)
        reference.setXMLAttribute("policy-option", policyOption); //$NON-NLS-1$

    if (updated != null)
        reference.setXMLAttribute("updated", updated); //$NON-NLS-1$

    return requiresV12;
}

From source file:ca.mcgill.cs.swevo.jayfx.ASTCrawler.java

License:Open Source License

/**
 * Converts a variable binding to a field element.
 * //from w ww . j  a  va2s.  c  o  m
 * @param pBinding
 *            The binding to convert. Cannot be null.
 * @return A field element representing this binding. Cannot be null.
 */
private static IElement convertBinding(final IVariableBinding pBinding) {
    ASTCrawler.checkForNull(pBinding);
    ITypeBinding declaringClass = pBinding.getDeclaringClass();

    if (declaringClass != null) { // it's a field.
        final String lFieldID = ASTCrawler.convertBinding(declaringClass).getId() + "." + pBinding.getName();
        return FlyweightElementFactory.getElement(Category.FIELD, lFieldID);
    } else // not a field.
        throw new IllegalArgumentException(pBinding.getName() + " is not a field.");
}

From source file:ca.mcgill.cs.swevo.ppa.inference.FieldInferenceStrategy.java

License:Open Source License

public void makeSafe(ASTNode node, TypeFact typeFact) {
    SimpleName sName = (SimpleName) node;
    PPATypeRegistry typeRegistry = ppaEngine.getRegistry();
    PPADefaultBindingResolver resolver = getResolver(sName);

    // The field's type changed.
    if (typeFact.getIndex().equals(getMainIndex(node))) {
        IVariableBinding varBinding = (IVariableBinding) sName.resolveBinding();
        ITypeBinding newType = typeFact.getNewType();
        IVariableBinding newBinding = typeRegistry.getFieldBindingWithType(varBinding.getName(),
                varBinding.getDeclaringClass(), newType, resolver);

        resolver.fixFieldBinding(sName, newBinding);
    }//from   ww  w. ja  v  a2s  .  c  o m
    // The field's container changed.
    //      else {
    //         
    //         //
    //
    //      }
}

From source file:ca.mcgill.cs.swevo.ppa.inference.FieldInferenceStrategy.java

License:Open Source License

public void makeSafeSecondary(ASTNode node, TypeFact typeFact) {
    SimpleName sName = (SimpleName) node;
    PPATypeRegistry typeRegistry = ppaEngine.getRegistry();
    PPADefaultBindingResolver resolver = getResolver(sName);
    ASTNode newContainerNode = PPAASTUtil.getFieldContainer(node, true, false);
    ITypeBinding newContainer = PPABindingsUtil.getTypeBinding(newContainerNode);

    if (newContainer == null) {
        return;/*from   www . java2  s .  c  om*/
    }

    IVariableBinding varBinding = (IVariableBinding) sName.resolveBinding();
    IVariableBinding newFieldBinding = null;

    if (PPABindingsUtil.isMissingType(newContainer)) {
        newFieldBinding = typeRegistry.getFieldBinding(varBinding.getName(), newContainer, varBinding.getType(),
                resolver);
    } else {
        // Maybe we can find the field declaration
        newFieldBinding = PPABindingsUtil.findFieldHierarchy(newContainer, sName.getFullyQualifiedName());
        if (newFieldBinding == null) {
            // We did not find the field in the container, try to find a suitable container (missing type)
            ITypeBinding tempContainer = PPABindingsUtil.getFirstMissingSuperType(newContainer);
            if (tempContainer != null) {
                newContainer = tempContainer;
                newFieldBinding = typeRegistry.getFieldBinding(varBinding.getName(), newContainer,
                        varBinding.getType(), resolver);
            } else {
                newFieldBinding = typeRegistry.getFieldBinding(varBinding.getName(), newContainer,
                        varBinding.getType(), resolver);
            }
        } else {
            // In case we found the field in a super type of the container.
            newContainer = newFieldBinding.getDeclaringClass();
        }
    }

    // Check field type
    ITypeBinding newFieldType = newFieldBinding.getType();
    ITypeBinding oldFieldType = varBinding.getType();
    if (!newFieldType.isEqualTo(oldFieldType)) {
        if (PPABindingsUtil.isSafer(newFieldType, oldFieldType)) {
            resolver.fixFieldBinding(sName, newFieldBinding);
            TypeFact tFact = new TypeFact(indexer.getMainIndex(sName), oldFieldType, TypeFact.UNKNOWN,
                    newFieldType, TypeFact.EQUALS, TypeFact.FIELD_STRATEGY);
            ppaEngine.reportTypeFact(tFact);

        } else if (!PPABindingsUtil.isMissingType(newContainer)) {
            resolver.fixFieldBinding(sName, newFieldBinding);
            // This is the case where we found the field declaration and the field is "less" safe than the previous type.
            // XXX The oldType = Unknown is to ensure that the new type will be pushed.
            TypeFact tFact = new TypeFact(indexer.getMainIndex(sName), typeRegistry.getUnknownBinding(resolver),
                    TypeFact.UNKNOWN, newFieldType, TypeFact.EQUALS, TypeFact.FIELD_STRATEGY);
            ppaEngine.reportTypeFact(tFact);
        } else {
            // This is an odd case: we found a ppa generated field, but the type we got before was safer.
            newFieldBinding = typeRegistry.getFieldBindingWithType(varBinding.getName(), newContainer,
                    varBinding.getType(), resolver);
            resolver.fixFieldBinding(sName, newFieldBinding);
        }
    } else {
        resolver.fixFieldBinding(sName, newFieldBinding);
    }

}

From source file:ca.mcgill.cs.swevo.ppa.ui.ASTUtil.java

License:Open Source License

private static void getFieldBindingHandle(IBinding binding, boolean augmented, StringBuffer handle) {
    IVariableBinding vBinding = (IVariableBinding) binding;
    handle.append(FIELD_KIND);//from   w w w. ja v a  2 s.c  o m
    if (augmented) {
        handle.append(AUGMENTED_HANDLE_SEPARATOR);
        if (vBinding.isEnumConstant()) {
            handle.append(ENUM_VALUE_KIND);
        } else {
            handle.append(FIELD_KIND);
        }
    }
    handle.append(HANDLE_SEPARATOR);
    handle.append(getNonEmptyTypeString(getTypeString(vBinding.getDeclaringClass())));
    handle.append(HANDLE_SEPARATOR);
    handle.append(getNonEmptyTypeString(getTypeString(vBinding.getType())));
    handle.append(HANDLE_SEPARATOR);
    handle.append(getNonEmptyName(vBinding.getName()));
}

From source file:ca.mcgill.cs.swevo.ppa.ui.NameMapVisitor.java

License:Open Source License

private String addBindingText(IBinding binding, ASTNode node, boolean isDeclaration) {
    String bindingText = "";
    if (binding != null) {
        if (binding instanceof IMethodBinding) {
            IMethodBinding mBinding = (IMethodBinding) binding;
            String methodName = mBinding.getName();
            if (!filterUnknown || methodName == null || !methodName.equals(SnippetUtil.SNIPPET_METHOD)) {
                if (encoded) {
                    bindingText = ASTUtil.getHandle(binding, augmented);
                } else {
                    bindingText = PPABindingsUtil.getFullMethodSignature(mBinding);

                }/* ww w.ja  v a 2  s  .  com*/
                bindings.add(bindingText);
                bindingsType.add(METHOD_TYPE);
                declarations.add(isDeclaration);
                nodes.add(node);
            }
        } else if (binding instanceof IVariableBinding) {
            IVariableBinding vBinding = (IVariableBinding) binding;
            if (vBinding.isField()) {
                if (encoded) {
                    bindingText = ASTUtil.getHandle(binding, augmented);
                } else {
                    String type = "nil";
                    if (vBinding.getType() != null) {
                        type = PPABindingsUtil.getTypeString(vBinding.getType());
                    }

                    String decType = "nil";
                    if (vBinding.getDeclaringClass() != null) {
                        decType = PPABindingsUtil.getTypeString(vBinding.getDeclaringClass());
                    }
                    bindingText = type + " " + decType + ":" + vBinding.getName();
                }
                bindings.add(bindingText);
                bindingsType.add(FIELD_TYPE);
                declarations.add(isDeclaration);
                nodes.add(node);
            }
        } else if (binding instanceof ITypeBinding) {
            ITypeBinding typeBinding = (ITypeBinding) binding;
            bindingText = typeBinding.getName();
            // TODO Change SNIPPET FOR SOMETHING THAT WON't BREAK ANYTHING
            // AND HANDLE
            // SUPERSNIPPET!!!
            if (!filterUnknown || (!bindingText.contains(PPATypeRegistry.UNKNWON_CLASS)
                    && !bindingText.contains(SnippetUtil.SNIPPET_CLASS)
                    && !bindingText.contains(SnippetUtil.SNIPPET_SUPER_CLASS))) {
                if (encoded) {
                    bindingText = ASTUtil.getHandle(binding, augmented);
                }
                bindings.add(bindingText);
                bindingsType.add(TYPE_TYPE);
                declarations.add(isDeclaration);
                nodes.add(node);
            }
        }
    }
    return bindingText;
}

From source file:changetypes.ASTVisitorAtomicChange.java

License:Open Source License

private static String getQualifiedName(IVariableBinding ivb) {
    try {/* ww  w  . j  a  va 2s . co  m*/
        String name = ivb.getName();
        return getQualifiedName(ivb.getDeclaringClass()) + "#" + name;
    } catch (NullPointerException localNullPointerException) {
    }
    return "";
}

From source file:changetypes.ASTVisitorAtomicChange.java

License:Open Source License

public boolean visit(TypeDeclaration node) {
    ITypeBinding itb = node.resolveBinding();
    this.itbStack.push(itb);
    try {/*from   ww w .  j a  va  2s  .  c om*/
        this.facts.add(Fact.makeTypeFact(getQualifiedName(itb), getSimpleName(itb), itb.getPackage().getName(),
                itb.isInterface() ? "interface" : "class"));
    } catch (Exception localException1) {
        System.err.println("Cannot resolve bindings for class " + node.getName().toString());
    }
    ITypeBinding localITypeBinding1;
    ITypeBinding i2;
    try {
        ITypeBinding itb2 = itb.getSuperclass();
        if (itb.getSuperclass() != null) {
            this.facts.add(Fact.makeSubtypeFact(getQualifiedName(itb2), getQualifiedName(itb)));
            this.facts.add(Fact.makeExtendsFact(getQualifiedName(itb2), getQualifiedName(itb)));
        }
        ITypeBinding[] arrayOfITypeBinding;
        int i;
        if (node.isInterface()) {
            i = (arrayOfITypeBinding = itb.getInterfaces()).length;
            for (localITypeBinding1 = 0; localITypeBinding1 < i; localITypeBinding1++) {
                ITypeBinding i2 = arrayOfITypeBinding[localITypeBinding1];
                this.facts.add(Fact.makeSubtypeFact(getQualifiedName(i2), getQualifiedName(itb)));
                this.facts.add(Fact.makeExtendsFact(getQualifiedName(i2), getQualifiedName(itb)));
            }
        } else {
            i = (arrayOfITypeBinding = itb.getInterfaces()).length;
            for (localITypeBinding1 = 0; localITypeBinding1 < i; localITypeBinding1++) {
                i2 = arrayOfITypeBinding[localITypeBinding1];
                this.facts.add(Fact.makeSubtypeFact(getQualifiedName(i2), getQualifiedName(itb)));
                this.facts.add(Fact.makeImplementsFact(getQualifiedName(i2), getQualifiedName(itb)));
            }
        }
    } catch (Exception localException2) {
        System.err.println("Cannot resolve super class bindings for class " + node.getName().toString());
    }
    Object localObject;
    try {
        localITypeBinding1 = (localObject = itb.getDeclaredFields()).length;
        for (i2 = 0; i2 < localITypeBinding1; i2++) {
            IVariableBinding ivb = localObject[i2];
            String visibility = getModifier(ivb);
            String fieldStr = ivb.toString();

            String[] tokens = fieldStr.split(" ");
            String[] arrayOfString1;
            int k = (arrayOfString1 = tokens).length;
            for (int j = 0; j < k; j++) {
                String token = arrayOfString1[j];
                if (this.allowedFieldMods_.contains(token)) {
                    this.facts.add(Fact.makeFieldModifierFact(getQualifiedName(ivb), token));
                }
            }
            this.facts.add(Fact.makeFieldFact(getQualifiedName(ivb), ivb.getName(), getQualifiedName(itb),
                    visibility));
            if (!ivb.getType().isParameterizedType()) {
                this.facts.add(Fact.makeFieldTypeFact(getQualifiedName(ivb), getQualifiedName(ivb.getType())));
            } else {
                this.facts.add(Fact.makeFieldTypeFact(getQualifiedName(ivb), makeParameterizedName(ivb)));
            }
        }
    } catch (Exception localException3) {
        System.err.println("Cannot resolve field bindings for class " + node.getName().toString());
    }
    try {
        ITypeBinding localITypeBinding2 = (localObject = node.getTypes()).length;
        for (i2 = 0; i2 < localITypeBinding2; i2++) {
            TypeDeclaration t = localObject[i2];
            ITypeBinding intb = t.resolveBinding();
            this.facts.add(Fact.makeTypeInTypeFact(getQualifiedName(intb), getQualifiedName(itb)));
        }
    } catch (Exception localException4) {
        System.err.println("Cannot resolve inner type bindings for class " + node.getName().toString());
    }
    return true;
}