Search in sources :

Example 6 with SimpleScope

use of org.eclipse.xtext.scoping.impl.SimpleScope in project xtext-eclipse by eclipse.

the class XbaseProposalProvider method createLocalVariableAndImplicitProposals.

protected void createLocalVariableAndImplicitProposals(EObject context, IExpressionScope.Anchor anchor, ContentAssistContext contentAssistContext, ICompletionProposalAcceptor acceptor) {
    String prefix = contentAssistContext.getPrefix();
    if (prefix.length() > 0) {
        if (!Character.isJavaIdentifierStart(prefix.charAt(0))) {
            if (prefix.length() > 1) {
                if (prefix.charAt(0) == '^' && !Character.isJavaIdentifierStart(prefix.charAt(1))) {
                    return;
                }
            }
        }
    }
    // long time = System.currentTimeMillis();
    Function<IEObjectDescription, ICompletionProposal> proposalFactory = getProposalFactory(getFeatureCallRuleName(), contentAssistContext);
    IResolvedTypes resolvedTypes = context != null ? typeResolver.resolveTypes(context) : typeResolver.resolveTypes(contentAssistContext.getResource());
    IExpressionScope expressionScope = resolvedTypes.getExpressionScope(context, anchor);
    // TODO use the type name information
    IScope scope = expressionScope.getFeatureScope();
    getCrossReferenceProposalCreator().lookupCrossReference(scope, context, XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, acceptor, getFeatureDescriptionPredicate(contentAssistContext), proposalFactory);
    // System.out.printf("XbaseProposalProvider.createLocalVariableAndImplicitProposals = %d\n", System.currentTimeMillis() - time);
    // time = System.currentTimeMillis();
    // TODO use the type name information
    proposeDeclaringTypeForStaticInvocation(context, null, /* ignore */
    contentAssistContext, acceptor);
    // System.out.printf("XbaseProposalProvider.proposeDeclaringTypeForStaticInvocation = %d\n", System.currentTimeMillis() - time);
    if (context != null && !(context instanceof XMemberFeatureCall)) {
        Iterable<JvmFeature> featuresToImport = getFavoriteStaticFeatures(context, input -> true);
        // Create StaticFeatureDescription instead of SimpleIdentifiableElementDescription since we want the Proposal to show parameters
        Iterable<IEObjectDescription> scopedFeatures = Iterables.transform(featuresToImport, feature -> {
            QualifiedName qualifiedName = QualifiedName.create(feature.getSimpleName());
            return new StaticFeatureDescription(qualifiedName, feature, 0, true);
        });
        // Scope for all static features
        IScope staticMemberScope = new SimpleScope(IScope.NULLSCOPE, scopedFeatures);
        proposeFavoriteStaticFeatures(context, contentAssistContext, acceptor, staticMemberScope);
    }
}
Also used : IResolvedTypes(org.eclipse.xtext.xbase.typesystem.IResolvedTypes) SimpleScope(org.eclipse.xtext.scoping.impl.SimpleScope) QualifiedName(org.eclipse.xtext.naming.QualifiedName) IExpressionScope(org.eclipse.xtext.xbase.typesystem.IExpressionScope) StyledString(org.eclipse.jface.viewers.StyledString) StaticFeatureDescription(org.eclipse.xtext.xbase.scoping.batch.StaticFeatureDescription) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) JvmFeature(org.eclipse.xtext.common.types.JvmFeature) XMemberFeatureCall(org.eclipse.xtext.xbase.XMemberFeatureCall) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IScope(org.eclipse.xtext.scoping.IScope)

Example 7 with SimpleScope

use of org.eclipse.xtext.scoping.impl.SimpleScope in project xtext-eclipse by eclipse.

the class XbaseProposalProvider method completeXMemberFeatureCall_Feature.

@Override
public void completeXMemberFeatureCall_Feature(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
    if (model instanceof XMemberFeatureCall) {
        XExpression memberCallTarget = ((XMemberFeatureCall) model).getMemberCallTarget();
        IResolvedTypes resolvedTypes = typeResolver.resolveTypes(memberCallTarget);
        LightweightTypeReference memberCallTargetType = resolvedTypes.getActualType(memberCallTarget);
        Iterable<JvmFeature> featuresToImport = getFavoriteStaticFeatures(model, input -> {
            if (input instanceof JvmOperation && input.isStatic()) {
                List<JvmFormalParameter> parameters = ((JvmOperation) input).getParameters();
                if (parameters.size() > 0) {
                    JvmFormalParameter firstParam = parameters.get(0);
                    JvmTypeReference parameterType = firstParam.getParameterType();
                    if (parameterType != null) {
                        LightweightTypeReference lightweightTypeReference = memberCallTargetType.getOwner().toLightweightTypeReference(parameterType);
                        if (lightweightTypeReference != null) {
                            return memberCallTargetType.isAssignableFrom(lightweightTypeReference);
                        }
                    }
                }
            }
            return false;
        });
        // Create StaticExtensionFeatureDescriptionWithImplicitFirstArgument instead of SimpleIdentifiableElementDescription since we want the Proposal to show parameters
        Iterable<IEObjectDescription> scopedFeatures = Iterables.transform(featuresToImport, feature -> {
            QualifiedName qualifiedName = QualifiedName.create(feature.getSimpleName());
            return new StaticExtensionFeatureDescriptionWithImplicitFirstArgument(qualifiedName, feature, memberCallTarget, memberCallTargetType, 0, true);
        });
        // Scope for all static features
        IScope staticMemberScope = new SimpleScope(IScope.NULLSCOPE, scopedFeatures);
        proposeFavoriteStaticFeatures(model, context, acceptor, staticMemberScope);
        // Regular proposals
        createReceiverProposals(((XMemberFeatureCall) model).getMemberCallTarget(), (CrossReference) assignment.getTerminal(), context, acceptor);
    } else if (model instanceof XAssignment) {
        createReceiverProposals(((XAssignment) model).getAssignable(), (CrossReference) assignment.getTerminal(), context, acceptor);
    }
}
Also used : LightweightTypeReference(org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference) StaticExtensionFeatureDescriptionWithImplicitFirstArgument(org.eclipse.xtext.xbase.scoping.batch.StaticExtensionFeatureDescriptionWithImplicitFirstArgument) IResolvedTypes(org.eclipse.xtext.xbase.typesystem.IResolvedTypes) SimpleScope(org.eclipse.xtext.scoping.impl.SimpleScope) QualifiedName(org.eclipse.xtext.naming.QualifiedName) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) JvmOperation(org.eclipse.xtext.common.types.JvmOperation) JvmFeature(org.eclipse.xtext.common.types.JvmFeature) JvmFormalParameter(org.eclipse.xtext.common.types.JvmFormalParameter) XMemberFeatureCall(org.eclipse.xtext.xbase.XMemberFeatureCall) JvmTypeReference(org.eclipse.xtext.common.types.JvmTypeReference) IScope(org.eclipse.xtext.scoping.IScope) CrossReference(org.eclipse.xtext.CrossReference) XExpression(org.eclipse.xtext.xbase.XExpression) XAssignment(org.eclipse.xtext.xbase.XAssignment)

Example 8 with SimpleScope

use of org.eclipse.xtext.scoping.impl.SimpleScope in project dsl-devkit by dsldevkit.

the class ValidScopeProvider method createEClassScope.

/**
 * Creates the Eclass scope provider (all EClasses from the parent classifiers, referenced by their fully qualified (::) names.
 *
 * @param parent
 *          the parent
 * @param classifiers
 *          the classifiers
 * @return the i scope
 */
private IScope createEClassScope(final IScope parent, final Iterable<EClassifier> classifiers) {
    final Iterable<EClass> classes = Iterables.filter(classifiers, EClass.class);
    Iterable<IEObjectDescription> elements = EObjectDescriptions.all(classes, EcorePackage.Literals.ENAMED_ELEMENT__NAME);
    elements = Iterables.concat(elements, EObjectDescriptions.all(classes, new AbstractNameFunction() {

        public QualifiedName apply(final EObject from) {
            final EClass param = (EClass) from;
            return QualifiedName.create(param.getEPackage().getNsPrefix(), param.getName());
        }
    }));
    return new SimpleScope(parent, elements);
}
Also used : AbstractNameFunction(com.avaloq.tools.ddk.xtext.scoping.AbstractNameFunction) EClass(org.eclipse.emf.ecore.EClass) SimpleScope(org.eclipse.xtext.scoping.impl.SimpleScope) EObject(org.eclipse.emf.ecore.EObject) QualifiedName(org.eclipse.xtext.naming.QualifiedName) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription)

Example 9 with SimpleScope

use of org.eclipse.xtext.scoping.impl.SimpleScope in project dsl-devkit by dsldevkit.

the class EPackageScopeProvider method scope_EPackage.

/**
 * Scope for {@link EPackage}. These are read from the registry as well as from the {@link Grammar Xtext grammar} corresponding
 * to the scope model (if any).
 *
 * @param context
 *          context scope DSL model (usually the root element, but any object will do)
 * @param reference
 *          context reference (unused for the time being)
 * @return scope with all available {@link EPackage EPackages} with {@link EPackage#getNsURI()} as name
 */
// CHECKSTYLE:OFF
public IScope scope_EPackage(final EObject context, final EReference reference) {
    // CHECKSTYLE:ON
    Resource rsc = context.eResource();
    IScope result = IScope.NULLSCOPE;
    // Add packages from the registry first.
    final Registry packageRegistry = EPackage.Registry.INSTANCE;
    result = new AbstractScope(result, false) {

        @Override
        protected IEObjectDescription getSingleLocalElementByName(final QualifiedName name) {
            return getEPackage(nameConverter.toString(name));
        }

        @Override
        protected Iterable<IEObjectDescription> getAllLocalElements() {
            return Iterables.filter(Iterables.transform(Sets.newHashSet(packageRegistry.keySet()), this::getEPackage), Predicates.notNull());
        }

        private IEObjectDescription getEPackage(final String nsURI) {
            try {
                EPackage ePackage = packageRegistry.getEPackage(nsURI);
                return ePackage != null ? EObjectDescription.create(QualifiedName.create(nsURI), ePackage) : null;
            // CHECKSTYLE:OFF
            } catch (Exception e) {
                // CHECKSTYLE:ON
                // $NON-NLS-1$
                LOG.warn("could not load package " + nsURI, e);
                return null;
            }
        }
    };
    // Add the index
    IResourceDescriptions descriptions = descriptionsProvider.getResourceDescriptions(context.eResource());
    if (descriptions != null) {
        result = SelectableBasedScope.createScope(result, descriptions, EcorePackage.Literals.EPACKAGE, false);
    }
    // Add the global scope
    result = SelectableBasedScope.createScope(result, new ScopeBasedSelectable(globalScopeProvider.getScope(rsc, reference, null)), EcorePackage.Literals.EPACKAGE, false);
    // Now add all packages from the grammar
    final URI grammarUri = rsc.getURI().trimFileExtension().appendFileExtension(XTEXT_EXTENSION);
    final ResourceSet resourceSet = rsc.getResourceSet();
    final URIConverter uriConverter = resourceSet.getURIConverter();
    if (uriConverter.exists(grammarUri, null)) {
        final Resource grammarResource = resourceSet.getResource(grammarUri, true);
        if (grammarResource != null && !grammarResource.getContents().isEmpty()) {
            final Grammar grammar = (Grammar) grammarResource.getContents().get(0);
            final IScope parent = result;
            result = new SimpleScope(parent, Iterables.transform(Iterables.filter(getGrammarEPackages(grammar), Predicates.notNull()), new Function<EPackage, IEObjectDescription>() {

                @Override
                public IEObjectDescription apply(final EPackage param) {
                    return EObjectDescription.create(param.getNsURI(), param);
                }
            }));
        }
    }
    return result;
}
Also used : AbstractScope(org.eclipse.xtext.scoping.impl.AbstractScope) SimpleScope(org.eclipse.xtext.scoping.impl.SimpleScope) QualifiedName(org.eclipse.xtext.naming.QualifiedName) Resource(org.eclipse.emf.ecore.resource.Resource) Registry(org.eclipse.emf.ecore.EPackage.Registry) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) Grammar(org.eclipse.xtext.Grammar) URI(org.eclipse.emf.common.util.URI) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) EPackage(org.eclipse.emf.ecore.EPackage) ScopeBasedSelectable(org.eclipse.xtext.scoping.impl.ScopeBasedSelectable) IResourceDescriptions(org.eclipse.xtext.resource.IResourceDescriptions) IScope(org.eclipse.xtext.scoping.IScope) URIConverter(org.eclipse.emf.ecore.resource.URIConverter)

Example 10 with SimpleScope

use of org.eclipse.xtext.scoping.impl.SimpleScope in project xtext-eclipse by eclipse.

the class JavaTypeQuickfixes method getImportedTypesScope.

protected IScope getImportedTypesScope(EObject model, final String misspelled, final IScope actualScope, IJavaSearchScope scope) {
    if (scope == null) {
        return IScope.NULLSCOPE;
    }
    try {
        final Set<String> visiblePackages = importsConfiguration.getImplicitlyImportedPackages((XtextResource) model.eResource());
        final Set<String> importedTypes = Sets.newHashSet();
        final Set<String> seen = Sets.newHashSet();
        XImportSection importSection = importsConfiguration.getImportSection((XtextResource) model.eResource());
        if (importSection != null) {
            parseImportSection(importSection, new IAcceptor<String>() {

                @Override
                public void accept(String t) {
                    visiblePackages.add(t);
                }
            }, new IAcceptor<String>() {

                @Override
                public void accept(String t) {
                    importedTypes.add(t);
                }
            });
        }
        SearchEngine searchEngine = new SearchEngine();
        final List<IEObjectDescription> validProposals = Lists.newArrayList();
        for (String importedType : importedTypes) {
            if (validProposals.size() <= 5 && seen.add(importedType)) {
                int dot = importedType.lastIndexOf('.');
                if (dot != -1) {
                    importedType = importedType.substring(dot + 1);
                }
                if (isSimilarTypeName(misspelled, importedType)) {
                    QualifiedName qualifiedName = qualifiedNameConverter.toQualifiedName(importedType);
                    for (IEObjectDescription element : actualScope.getElements(qualifiedName)) {
                        validProposals.add(new AliasedEObjectDescription(qualifiedName, element));
                        break;
                    }
                }
            }
        }
        try {
            for (String visiblePackage : visiblePackages) {
                if (validProposals.size() <= 5) {
                    searchEngine.searchAllTypeNames(visiblePackage.toCharArray(), SearchPattern.R_EXACT_MATCH, null, SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.TYPE, scope, new TypeNameRequestor() {

                        @Override
                        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
                            StringBuilder typeNameBuilder = new StringBuilder(simpleTypeName.length);
                            for (char[] enclosingType : enclosingTypeNames) {
                                typeNameBuilder.append(enclosingType);
                                typeNameBuilder.append('.');
                            }
                            typeNameBuilder.append(simpleTypeName);
                            String typeName = typeNameBuilder.toString();
                            if (isSimilarTypeName(misspelled, typeName)) {
                                String fqNameAsString = getQualifiedTypeName(packageName, enclosingTypeNames, simpleTypeName);
                                if (seen.add(fqNameAsString)) {
                                    QualifiedName qualifiedName = qualifiedNameConverter.toQualifiedName(typeName);
                                    for (IEObjectDescription element : actualScope.getElements(qualifiedName)) {
                                        validProposals.add(new AliasedEObjectDescription(qualifiedName, element));
                                        break;
                                    }
                                }
                            }
                        }
                    }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor() {

                        @Override
                        public boolean isCanceled() {
                            return validProposals.size() > 5;
                        }
                    });
                }
            }
        } catch (OperationCanceledException exc) {
        // enough proposals
        }
        return new SimpleScope(validProposals);
    } catch (JavaModelException jme) {
        return IScope.NULLSCOPE;
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) AliasedEObjectDescription(org.eclipse.xtext.resource.impl.AliasedEObjectDescription) JavaModelException(org.eclipse.jdt.core.JavaModelException) XImportSection(org.eclipse.xtext.xtype.XImportSection) SimpleScope(org.eclipse.xtext.scoping.impl.SimpleScope) QualifiedName(org.eclipse.xtext.naming.QualifiedName) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) TypeNameRequestor(org.eclipse.jdt.core.search.TypeNameRequestor)

Aggregations

SimpleScope (org.eclipse.xtext.scoping.impl.SimpleScope)11 IEObjectDescription (org.eclipse.xtext.resource.IEObjectDescription)10 IScope (org.eclipse.xtext.scoping.IScope)8 QualifiedName (org.eclipse.xtext.naming.QualifiedName)5 FilteringScope (org.eclipse.xtext.scoping.impl.FilteringScope)3 EClass (org.eclipse.emf.ecore.EClass)2 EObject (org.eclipse.emf.ecore.EObject)2 Resource (org.eclipse.emf.ecore.resource.Resource)2 Grammar (org.eclipse.xtext.Grammar)2 JvmFeature (org.eclipse.xtext.common.types.JvmFeature)2 XMemberFeatureCall (org.eclipse.xtext.xbase.XMemberFeatureCall)2 IResolvedTypes (org.eclipse.xtext.xbase.typesystem.IResolvedTypes)2 IGeneratorDescriptor (org.yakindu.sct.generator.core.extensions.IGeneratorDescriptor)2 GeneratorModel (org.yakindu.sct.model.sgen.GeneratorModel)2 AbstractNameFunction (com.avaloq.tools.ddk.xtext.scoping.AbstractNameFunction)1 Function (com.google.common.base.Function)1 ArrayList (java.util.ArrayList)1 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)1 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)1 EList (org.eclipse.emf.common.util.EList)1