Java 类org.eclipse.xtext.resource.IResourceDescriptions 实例源码

项目:n4js    文件:N4JSResourceDescriptionManager.java   
/**
 * {@inheritDoc}
 *
 * This marks {@code n4js} as affected if the manifest of the project changes. In turn, they will be revalidated and
 * taken into consideration for the code generation step.
 */
@Override
public boolean isAffected(Collection<IResourceDescription.Delta> deltas, IResourceDescription candidate,
        IResourceDescriptions context) {
    boolean result = basicIsAffected(deltas, candidate);
    if (!result) {
        for (IResourceDescription.Delta delta : deltas) {
            URI uri = delta.getUri();
            if (IN4JSProject.N4MF_MANIFEST.equalsIgnoreCase(uri.lastSegment())) {
                URI prefixURI = uri.trimSegments(1).appendSegment("");
                if (candidate.getURI().replacePrefix(prefixURI, prefixURI) != null) {
                    return true;
                }
            }
        }
    }
    return result;
}
项目:dsl-devkit    文件:CachingStateBasedContainerManager.java   
@Override
protected synchronized IContainer createContainer(final String handle, final IResourceDescriptions resourceDescriptions) {
  final IResourceDescriptions descriptionsKey = resourceDescriptions instanceof CurrentDescriptions2.ResourceSetAware
      ? ((CurrentDescriptions2.ResourceSetAware) resourceDescriptions).getDelegate()
      : resourceDescriptions;

  Map<String, WeakReference<IContainer>> containersMap = descriptionsContainersCache.get(descriptionsKey);
  if (containersMap == null) {
    containersMap = new HashMap<String, WeakReference<IContainer>>();
    descriptionsContainersCache.put(descriptionsKey, containersMap);
  }

  WeakReference<IContainer> containerRef = containersMap.get(handle);
  IContainer container = containerRef != null ? containerRef.get() : null;
  if (container == null) {
    final IContainerState containerState = new ContainerState(handle, getStateProvider().get(descriptionsKey));
    container = new StateBasedContainerWithHandle(descriptionsKey, containerState, handle);
    new CacheInvalidator(descriptionsKey, handle, containerState);
    containerRef = new WeakReference<IContainer>(container);
    containersMap.put(handle, containerRef);
  }

  return container;
}
项目:xtext-extras    文件:BuilderIntegrationFragment.java   
@Override
public Set<Binding> getGuiceBindingsUi(Grammar grammar) {
    return new BindFactory()
        .addConfiguredBinding(
                IResourceDescriptions.class.getName() + "BuilderScope",
                "binder.bind(" + IResourceDescriptions.class.getName() + ".class"
                        + ").annotatedWith(com.google.inject.name.Names.named("
                        + ResourceDescriptionsProvider.class.getName() + ".NAMED_BUILDER_SCOPE)).to("
                        + "org.eclipse.xtext.builder.clustering.CurrentDescriptions.ResourceSetAware.class)")
        .addTypeToType("org.eclipse.xtext.ui.editor.IXtextEditorCallback", "org.eclipse.xtext.builder.nature.NatureAddingEditorCallback")
        .addTypeToType("org.eclipse.xtext.generator.IContextualOutputConfigurationProvider", "org.eclipse.xtext.builder.EclipseOutputConfigurationProvider")
        .addConfiguredBinding(
                IResourceDescriptions.class.getName() + "Persisted",
                "binder.bind("+ IResourceDescriptions.class.getName() + ".class"
                        + ").annotatedWith(com.google.inject.name.Names.named("
                        + "org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to("
                        + "org.eclipse.xtext.builder.builderState.IBuilderState.class)")
        .addTypeToType("org.eclipse.xtext.ui.editor.DocumentBasedDirtyResource", "org.eclipse.xtext.builder.impl.PersistentDataAwareDirtyResource")
        .getBindings();
}
项目:xtext-extras    文件:IndexedJvmTypeAccess.java   
public EObject getIndexedJvmType(QualifiedName qualifiedName, String fragment, ResourceSet resourceSet, boolean throwShadowedException) throws UnknownNestedTypeException {
    if (resourceSet != null) {
        IResourceDescriptions descriptions = resourceDescriptionsProvider.getResourceDescriptions(resourceSet);
        Iterable<IEObjectDescription> candidates = descriptions.getExportedObjects(TypesPackage.Literals.JVM_TYPE, qualifiedName, false);
        Iterator<IEObjectDescription> iterator = candidates.iterator();
        if (iterator.hasNext()) {
            EObject result = findAccessibleType(fragment, resourceSet, iterator);
            if (result != null) {
                return result;
            }
        }
        if (throwShadowedException && descriptions instanceof IShadowedResourceDescriptions) {
            if (((IShadowedResourceDescriptions) descriptions).isShadowed(TypesPackage.Literals.JVM_TYPE, qualifiedName, false)) {
                throw new ShadowedTypeException("The type '"+qualifiedName+"' is locally shadowed.");
            }
        }
    }
    return null;
}
项目:xtext-core    文件:AbstractLiveContainerTest.java   
@Test
public void testContainerAddRemove() throws Exception {
    ResourceSet resourceSet = new XtextResourceSet();
    Resource res = parse("local", resourceSet).eResource();
    parse("other", resourceSet);
    IResourceDescription resourceDescription = descriptionManager.getResourceDescription(res);
    IResourceDescriptions resourceDescriptions = descriptionsProvider.getResourceDescriptions(res);
    List<IContainer> containers = containerManager.getVisibleContainers(resourceDescription, resourceDescriptions);
    assertEquals(1, containers.size());
    IContainer container = containers.get(0);

    assertEquals("local, other", format(container.getExportedObjects()));

    Resource foo = parse("foo", resourceSet).eResource();
    assertEquals("foo, local, other", format(container.getExportedObjects()));

    resourceSet.getResources().remove(foo);
    assertEquals("local, other", format(container.getExportedObjects()));
}
项目:xtext-core    文件:WorkspaceSymbolService.java   
public List<? extends SymbolInformation> getSymbols(final String query, final IReferenceFinder.IResourceAccess resourceAccess, final IResourceDescriptions indexData, final CancelIndicator cancelIndicator) {
  final LinkedList<SymbolInformation> result = CollectionLiterals.<SymbolInformation>newLinkedList();
  Iterable<IResourceDescription> _allResourceDescriptions = indexData.getAllResourceDescriptions();
  for (final IResourceDescription resourceDescription : _allResourceDescriptions) {
    {
      this.operationCanceledManager.checkCanceled(cancelIndicator);
      final IResourceServiceProvider resourceServiceProvider = this._registry.getResourceServiceProvider(resourceDescription.getURI());
      DocumentSymbolService _get = null;
      if (resourceServiceProvider!=null) {
        _get=resourceServiceProvider.<DocumentSymbolService>get(DocumentSymbolService.class);
      }
      final DocumentSymbolService documentSymbolService = _get;
      if ((documentSymbolService != null)) {
        List<? extends SymbolInformation> _symbols = documentSymbolService.getSymbols(resourceDescription, query, resourceAccess, cancelIndicator);
        Iterables.<SymbolInformation>addAll(result, _symbols);
      }
    }
  }
  return result;
}
项目:xtext-core    文件:StateBasedContainerManager.java   
@Override
public IContainer getContainer(IResourceDescription desc, IResourceDescriptions resourceDescriptions) {
    if (delegate.shouldUseProjectDescriptionBasedContainers(resourceDescriptions)) {
        return delegate.getContainer(desc, resourceDescriptions);
    }
    String root = internalGetContainerHandle(desc, resourceDescriptions);
    if (root == null) {
        if (log.isDebugEnabled())
            log.debug("Cannot find IContainer for: " + desc.getURI());
        return IContainer.NULL_CONTAINER;
    }
    IContainer result = createContainer(root, resourceDescriptions);
    if (!result.hasResourceDescription(desc.getURI())) {
        // desc has not been saved -> merge containers
        result = new DescriptionAddingContainer(desc, result);
    }
    return result;
}
项目:xtext-core    文件:StateBasedContainerManager.java   
@Override
public List<IContainer> getVisibleContainers(IResourceDescription desc, IResourceDescriptions resourceDescriptions) {
    if (delegate.shouldUseProjectDescriptionBasedContainers(resourceDescriptions)) {
        return delegate.getVisibleContainers(desc, resourceDescriptions);
    }
    String root = internalGetContainerHandle(desc, resourceDescriptions);
    if (root == null) {
        if (log.isDebugEnabled())
            log.debug("Cannot find IContainer for: " + desc.getURI());
        return Collections.emptyList();
    }
    List<String> handles = getState(resourceDescriptions).getVisibleContainerHandles(root);
    List<IContainer> result = getVisibleContainers(handles, resourceDescriptions);
    if (!result.isEmpty()) {
        IContainer first = result.get(0);
        if (!first.hasResourceDescription(desc.getURI())) {
            first = new DescriptionAddingContainer(desc, first);
            result.set(0, first);
        }
    }
    return result;
}
项目:xtext-core    文件:SimpleResourceDescriptionsBasedContainerManager.java   
@Override
public IContainer getContainer(IResourceDescription desc, IResourceDescriptions resourceDescriptions) {
    if (delegate.shouldUseProjectDescriptionBasedContainers(resourceDescriptions)) {
        return delegate.getContainer(desc, resourceDescriptions);
    }
    ResourceDescriptionsBasedContainer result = new ResourceDescriptionsBasedContainer(resourceDescriptions) {
        // this used to be the default implementation, which is wrong.
        // we fixed the orginal and moved the wrong impl here since old clients might see much worse performance with the new impl. 
        @Override
        public boolean hasResourceDescription(URI uri) {
            return true;
        }
    };
    result.setUriToDescriptionCacheEnabled(false);
    return result;
}
项目:dsl-devkit    文件:CachingStateBasedContainerManager.java   
CacheInvalidator(final IResourceDescriptions resourceDescriptions, final String handle, final IContainerState containerState) {
  this.resourceDescriptions = resourceDescriptions;
  this.handle = handle;
  this.containerState = containerState;
  if (resourceDescriptions instanceof IResourceDescription.Event.Source) {
    ((IResourceDescription.Event.Source) resourceDescriptions).addListener(this);
  }
}
项目:xtext-core    文件:ReferenceFinder.java   
protected void doFindReferencesWith(final IReferenceFinder referenceFinder, final TargetURIs targetURIs, final URI candidate,
        IResourceAccess resourceAccess, IResourceDescriptions descriptions, final Acceptor acceptor,
        final IProgressMonitor monitor) {
    IResourceDescription resourceDescription = null;
    if (!targetURIs.getTargetResourceURIs().contains(candidate) && (resourceDescription = descriptions.getResourceDescription(candidate)) != null) {
        referenceFinder.findReferences(targetURIs, resourceDescription, resourceAccess, acceptor, monitor);
    } else if (resourceAccess != null) {
        resourceAccess.readOnly(candidate, new IUnitOfWork.Void<ResourceSet>() {
            @Override
            public void process(final ResourceSet state) throws Exception {
                Resource resource = state.getResource(candidate, false);
                if (resource != null) {
                    referenceFinder.findReferences(targetURIs, resource, acceptor, monitor);
                }
            }
        });
    }
}
项目:xtext-core    文件:DefaultGlobalScopeProvider.java   
protected List<IContainer> getVisibleContainers(Resource resource) {
    IResourceDescription description = descriptionManager.getResourceDescription(resource);
    IResourceDescriptions resourceDescriptions = getResourceDescriptions(resource);
    String cacheKey = getCacheKey("VisibleContainers", resource.getResourceSet());
    OnChangeEvictingCache.CacheAdapter cache = new OnChangeEvictingCache().getOrCreate(resource);
    List<IContainer> result = null;
    result = cache.get(cacheKey);
    if (result == null) {
        result = containerManager.getVisibleContainers(description, resourceDescriptions);
        // SZ: I'ld like this dependency to be moved to the implementation of the
        // container manager, but it is not aware of a CacheAdapter
        if (resourceDescriptions instanceof IResourceDescription.Event.Source) {
            IResourceDescription.Event.Source eventSource = (Source) resourceDescriptions;
            DelegatingEventSource delegatingEventSource = new DelegatingEventSource(eventSource);
            delegatingEventSource.addListeners(Lists.newArrayList(Iterables.filter(result, IResourceDescription.Event.Listener.class)));
            delegatingEventSource.initialize();
            cache.addCacheListener(delegatingEventSource);
        }
        cache.set(cacheKey, result);
    }
    return result;
}
项目:xtext-core    文件:ProjectDescriptionBasedContainerManager.java   
protected IContainer createContainer(final IResourceDescriptions resourceDescriptions, final ChunkedResourceDescriptions chunkedResourceDescriptions, final String projectName) {
  IContainer _xifexpression = null;
  if ((resourceDescriptions instanceof LiveShadowedChunkedResourceDescriptions)) {
    _xifexpression = new LiveShadowedChunkedContainer(((LiveShadowedChunkedResourceDescriptions)resourceDescriptions), projectName);
  } else {
    ResourceDescriptionsData _elvis = null;
    ResourceDescriptionsData _container = chunkedResourceDescriptions.getContainer(projectName);
    if (_container != null) {
      _elvis = _container;
    } else {
      Set<IResourceDescription> _emptySet = CollectionLiterals.<IResourceDescription>emptySet();
      ResourceDescriptionsData _resourceDescriptionsData = new ResourceDescriptionsData(_emptySet);
      _elvis = _resourceDescriptionsData;
    }
    _xifexpression = new ResourceDescriptionsBasedContainer(_elvis);
  }
  return _xifexpression;
}
项目:xtext-core    文件:PortableURIs.java   
/**
 * @return a portable URI fragment, or <code>null</code> if the give EObject isn't itself or is not contained in an exported EObjectDescription
 */
protected String getPortableURIFragment(final EObject obj) {
  final IResourceDescriptions descriptions = this.resourceDescriptionsProvider.getResourceDescriptions(obj.eResource());
  final IResourceDescription desc = descriptions.getResourceDescription(obj.eResource().getURI());
  if ((desc == null)) {
    return null;
  }
  final Function1<IEObjectDescription, Boolean> _function = (IEObjectDescription it) -> {
    boolean _xblockexpression = false;
    {
      final EObject possibleContainer = EcoreUtil.resolve(it.getEObjectOrProxy(), obj.eResource());
      _xblockexpression = (Objects.equal(obj, possibleContainer) || EcoreUtil.isAncestor(obj, possibleContainer));
    }
    return Boolean.valueOf(_xblockexpression);
  };
  final IEObjectDescription containerDesc = IterableExtensions.<IEObjectDescription>findFirst(desc.getExportedObjects(), _function);
  if ((containerDesc != null)) {
    final PortableURIs.PortableFragmentDescription fragmentDescription = this.createPortableFragmentDescription(containerDesc, obj);
    return this.toFragmentString(fragmentDescription);
  }
  return null;
}
项目:xtext-core    文件:LiveShadowedChunkedResourceDescriptions.java   
@Override
public void setContext(final Notifier ctx) {
  IResourceDescriptions _localDescriptions = this.getLocalDescriptions();
  final Procedure1<ResourceSetBasedResourceDescriptions> _function = (ResourceSetBasedResourceDescriptions it) -> {
    it.setContext(ctx);
    it.setData(null);
  };
  ObjectExtensions.<ResourceSetBasedResourceDescriptions>operator_doubleArrow(((ResourceSetBasedResourceDescriptions) _localDescriptions), _function);
  final ResourceSet resourceSet = EcoreUtil2.getResourceSet(ctx);
  this.setGlobalDescriptions(ChunkedResourceDescriptions.findInEmfObject(resourceSet));
  IProjectConfig _projectConfig = null;
  if (this.projectConfigProvider!=null) {
    _projectConfig=this.projectConfigProvider.getProjectConfig(resourceSet);
  }
  IWorkspaceConfig _workspaceConfig = null;
  if (_projectConfig!=null) {
    _workspaceConfig=_projectConfig.getWorkspaceConfig();
  }
  this.workspaceConfig = _workspaceConfig;
}
项目:n4js    文件:AbstractBuilderTest.java   
private void assertXtextIndexIsValidInternal() {
    final IResourceDescriptions index = getXtextIndex();
    final StringBuilder sb = new StringBuilder();
    for (IResourceDescription desc : index.getAllResourceDescriptions()) {
        if (desc instanceof ResourceDescriptionWithoutModuleUserData) {
            sb.append("\n");
            sb.append(IResourceDescription.class.getSimpleName());
            sb.append(" in index must not be an instance of ");
            sb.append(ResourceDescriptionWithoutModuleUserData.class.getSimpleName());
            sb.append(" but it was. URI: ");
            sb.append(desc.getURI());
        }
    }
    assertTrue(sb.toString(), 0 == sb.length());
}
项目:n4js    文件:BuilderUtil.java   
/***/
public static String toString(IResourceDescriptions index) {
    StringBuffer buff = new StringBuffer();
    for (IResourceDescription desc : index.getAllResourceDescriptions()) {
        buff.append(EmfFormatter.objToStr(desc, new EStructuralFeature[0]));
    }
    return buff.toString();
}
项目:n4js    文件:BuilderUtil.java   
/***/
public static boolean indexContainsElement(final String fileUri, final String eObjectName) {
    IResourceDescriptions descriptions = getBuilderState();
    URI uri = URI.createURI("platform:/resource" + fileUri);
    IResourceDescription description = descriptions.getResourceDescription(uri);
    if (description != null) {
        return description
                .getExportedObjects(EcorePackage.Literals.EOBJECT, QualifiedName.create(eObjectName), false)
                .iterator().hasNext();
    }
    return false;
}
项目:n4js    文件:TestDiscoveryHelper.java   
private Map<URI, TModule> loadModules(final Iterable<URI> moduleUris, final IResourceDescriptions index,
        final ResourceSet resSet) {

    final Map<URI, TModule> uri2Modules = newHashMap();
    for (final URI moduleUri : moduleUris) {
        final IResourceDescription resDesc = index.getResourceDescription(moduleUri);
        uri2Modules.put(moduleUri, n4jsCore.loadModuleFromIndex(resSet, resDesc, false));
    }
    return uri2Modules;
}
项目:n4js    文件:ProjectCompareHelper.java   
/**
 * First step in comparing API and implementation projects. This method will collect all API projects, the types
 * declared there and their members and relate them to the corresponding types and members in all available
 * implementation projects.
 * <p>
 * The second step of comparison is to compare an individual type/member to a corresponding type/member of a
 * particular implementation via method {@link #compareApiImpl(ProjectComparisonEntry, int)}.
 * <p>
 * Usually, this second step is performed lazily when method <code>#compareApiImpl()</code> is invoked; however, by
 * setting <code>fullCompare</code> to <code>true</code>, this is performed up-front here causing all results to be
 * stored in a cache in the entries, and then subsequent calls to <code>#compareApiImpl()</code> will just read from
 * that cache.
 * <p>
 * Returns <code>null</code> in case of error and adds human-readable error messages to the given list.
 */
public ProjectComparison createComparison(boolean fullCompare, List<String> addErrorMessagesHere) {
    final ResourceSet resourceSet = n4jsCore.createResourceSet(Optional.absent());
    final IResourceDescriptions index = n4jsCore.getXtextIndex(resourceSet);

    final ApiImplMapping mapping = ApiImplMapping.of(n4jsCore);
    if (mapping.hasErrors()) {
        if (addErrorMessagesHere != null)
            addErrorMessagesHere.addAll(mapping.getErrorMessages());
        return null;
    }

    final List<String> allImplIds = mapping.getAllImplIds();
    final int implCount = allImplIds.size();

    final ProjectComparison root = new ProjectComparison(allImplIds.toArray(new String[implCount]));

    for (String currApiId : mapping.getApiIds()) {
        final IN4JSProject currApi = mapping.getApi(currApiId);
        final IN4JSProject[] currImpls = new IN4JSProject[implCount];
        for (int idx = 0; idx < implCount; idx++) {
            final String currImplId = allImplIds.get(idx);
            currImpls[idx] = mapping.getImpl(currApiId, currImplId);
        }
        createEntries(root, currApi, currImpls, resourceSet, index);
    }

    // compare all implementations in all entries and store in cache (if requested)
    if (fullCompare) {
        root.getAllEntries().forEach(currE -> {
            for (int implIdx = 0; implIdx < implCount; implIdx++)
                compareApiImpl(currE, implIdx);
        });
    }

    return root;
}
项目:n4js    文件:ProjectCompareHelper.java   
private ProjectComparisonEntry createEntries(
        ProjectComparison root,
        IN4JSProject api, IN4JSProject[] impls,
        ResourceSet resourceSet, IResourceDescriptions index) {

    final ProjectComparisonEntry entry = new ProjectComparisonEntry(root, api, impls);

    for (IN4JSSourceContainer currSrcConti : api.getSourceContainers()) {
        for (URI uri : currSrcConti) {
            final String uriStr = uri.toString();
            if (uriStr.endsWith("." + N4JSGlobals.N4JS_FILE_EXTENSION)
                    || uriStr.endsWith("." + N4JSGlobals.N4JSD_FILE_EXTENSION)) {
                final IResourceDescription resDesc = index.getResourceDescription(uri);
                final TModule moduleApi = getModuleFrom(resourceSet, resDesc);
                if (moduleApi != null) {
                    final TModule[] moduleImpls = new TModule[impls.length];
                    for (int idx = 0; idx < impls.length; idx++) {
                        final IN4JSProject projectImpl = impls[idx];
                        if (projectImpl != null)
                            moduleImpls[idx] = findImplementation(moduleApi, projectImpl, resourceSet, index);
                        else
                            moduleImpls[idx] = null;
                    }
                    createEntries(entry, -1, moduleApi, moduleImpls, false);
                }
            }
        }
    }

    return entry;
}
项目:n4js    文件:ProjectCompareHelper.java   
private TModule findImplementation(TModule moduleApi, IN4JSProject projectImpl,
        ResourceSet resourceSet, IResourceDescriptions index) {
    final String fqnStr = moduleApi.getQualifiedName();
    final URI uri = projectUtils.findArtifact(projectImpl, fqnStr, Optional.of(N4JSGlobals.N4JS_FILE_EXTENSION));
    if (uri == null)
        return null;
    final IResourceDescription resDesc = index.getResourceDescription(uri);
    if (resDesc == null)
        return null;
    final TModule moduleImpl = getModuleFrom(resourceSet, resDesc);
    return moduleImpl;
}
项目:n4js    文件:N4MFWizardTestedProjectPage.java   
/**
 * Create a new tested project wizard page.
 *
 * @param projectInfo
 *            The N4MFProjectInfo to use as model
 * @param resourceDescriptions
 *            A {@link IResourceDescriptions} implementation.
 */
public N4MFWizardTestedProjectPage(N4MFProjectInfo projectInfo, IResourceDescriptions resourceDescriptions) {
    super("Select projects to be tested");
    this.resourceDescriptions = resourceDescriptions;
    this.projectInfo = projectInfo;

    this.setTitle("Select projects to be tested");
    this.setMessage("Select projects to be tested in your new test project");
}
项目:lcdsl    文件:LcDslProvider.java   
@Override
public Set<LcDslLaunchObject> getLaunchObjects() {
    IResourceDescriptions index = LcDslHelper.getInjector().getInstance(IResourceDescriptions.class);
    ResourceSet set = LcDslHelper.getInjector().getInstance(ResourceSet.class);

    Set<LcDslLaunchObject> result = new TreeSet<>();
    Iterable<IEObjectDescription> descs = index.getExportedObjectsByType(LcDslPackage.eINSTANCE.getLaunchConfig());
    for (IEObjectDescription obj : descs) {
        EObject lc = EcoreUtil2.resolve(obj.getEObjectOrProxy(), set);
        if (lc instanceof LaunchConfig) {
            LaunchConfig l = (LaunchConfig) lc;
            if (l.isAbstract()) {
                continue;
            }

            LcDslLaunchObject o = new LcDslLaunchObject((LaunchConfig) lc);
            if (o.getType() == null) { // unsupported type
                continue;
            }

            // only hide manual if there is no other object it would be (properly) hiding
            if (hideManual && l.isManual() && findLaunchConfiguration(o.getType(), generator.fullName(l)) == null) {
                continue;
            }

            result.add(o);
        }
    }

    return result;
}
项目:dsl-devkit    文件:CachingStateBasedContainerManager.java   
@Override
public List<IContainer> getVisibleContainers(final IResourceDescription desc, final IResourceDescriptions resourceDescriptions) {
  String root = internalGetContainerHandle(desc, resourceDescriptions);
  if (root == null) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Cannot find IContainer for: " + desc.getURI()); //$NON-NLS-1$
    }
    return Collections.emptyList();
  }
  List<String> handles = getState(resourceDescriptions).getVisibleContainerHandles(root);
  return getContainersForHandlesAndResource(handles, desc, resourceDescriptions);
}
项目:xtext-extras    文件:StandaloneBuilderModule.java   
@Override
protected void configure() {
  this.<IResourceDescriptions>bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE)).to(ResourceSetBasedResourceDescriptions.class);
  this.<IResourceDescriptions>bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.LIVE_SCOPE)).to(ResourceSetBasedResourceDescriptions.class);
  this.<IResourceDescriptions>bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class);
  this.<IResourceDescriptions>bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class);
  this.<IIssueHandler>bind(IIssueHandler.class).to(this.bindIIssueHandler());
  this.<AbstractFileSystemAccess>bind(AbstractFileSystemAccess.class).to(this.bindJavaIoFileSystemAccess());
  this.<IJavaCompiler>bind(IJavaCompiler.class).to(this.bindIJavaCompiler());
  this.<IEncodingProvider>bind(IEncodingProvider.class).to(this.bindIEncodingProvider());
}
项目:xtext-extras    文件:JavaResourceDescriptionManager.java   
@Override
public boolean isAffected(final Collection<IResourceDescription.Delta> deltas, final IResourceDescription candidate, final IResourceDescriptions context) throws IllegalArgumentException {
  Collection<QualifiedName> importedNames = IterableExtensions.<QualifiedName>toSet(candidate.getImportedNames());
  for (final IResourceDescription.Delta delta : deltas) {
    boolean _hasChanges = this.hasChanges(delta, candidate);
    if (_hasChanges) {
      if ((this.isAffected(importedNames, delta.getNew()) || this.isAffected(importedNames, delta.getOld()))) {
        return true;
      }
    }
  }
  return false;
}
项目:xtext-core    文件:AbstractLiveContainerTest.java   
@Test
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=382555
public void testNonNormalizedURIs() throws Exception {
    ResourceSet resourceSet = new XtextResourceSet();
    parser.parse("B", URI.createURI("a." + parser.fileExtension), resourceSet);
    parser.parse("B", URI.createURI("b." + parser.fileExtension), resourceSet);
    IResourceDescriptions index = descriptionsProvider.getResourceDescriptions(resourceSet);
    IResourceDescription rd = index.getResourceDescription(URI.createURI("a." + parser.fileExtension));
    List<IContainer> containers = containerManager.getVisibleContainers(rd, index);
    List<IEObjectDescription> objects = Lists.newArrayList();
    EClass type = (EClass) grammarAccess.getGrammar().getRules().get(0).getType().getClassifier();
    for (IContainer container : containers)
        Iterables.addAll(objects, container.getExportedObjects(type, QualifiedName.create("B"), false));
    assertEquals(2, objects.size());
}
项目:dsl-devkit    文件:AbstractPolymorphicScopeProvider.java   
/**
 * Return the visible containers given a context object.
 *
 * @param context
 *          The context object
 * @param originalResource
 *          the original resource
 * @return The list of visible containers.
 */
protected List<IContainer> getVisibleContainers(final EObject context, final Resource originalResource) { // NOPMD by WTH on 26.01.11 09:26 (NPath
                                                                                                          // complexity...)
  final Resource ctxRsc = originalResource == null ? context.eResource() : originalResource;
  if (!(ctxRsc instanceof XtextResource)) {
    LOGGER.error(MessageFormat.format("Context {0} is not in an Xtext resource: {1}", context, ctxRsc != null ? ctxRsc.getURI() : "null")); //$NON-NLS-1$ //$NON-NLS-2$
    throw new IllegalStateException();
  }
  final XtextResource rsc = (XtextResource) ctxRsc;
  // Cache these container lists, they're expensive to create
  final String key = "CONTAINERCACHE&" + rsc.getURI().toString(); //$NON-NLS-1$
  List<IContainer> result = null;
  final ResourceCache<String, List<IContainer>> cache = CacheManager.getInstance().getOrCreateResourceCache("AbstractPolymorphicScopeProvider#cache", rsc); //$NON-NLS-1$
  if (cache != null) {
    result = cache.get(key);
    if (result != null) {
      return result;
    }
  }

  final EObject ctx = ctxRsc != context.eResource() ? ctxRsc.getContents().get(0) : context;
  // We need to get the container manager dynamically, otherwise we may end up using the wrong ResourceDescriptions if
  // the context object in actually from another resource.
  final IResourceServiceProvider resourceServiceProvider = rsc.getResourceServiceProvider();
  final IResourceDescription.Manager descriptionManager = resourceServiceProvider.getResourceDescriptionManager();
  final IContainer.Manager containerManager = resourceServiceProvider.getContainerManager();

  final IResourceDescription description = descriptionManager.getResourceDescription(ctx.eResource());
  final IResourceDescriptions resourceDescriptions = getResourceDescriptions(ctx.eResource());
  result = containerManager.getVisibleContainers(description, resourceDescriptions);
  if (cache != null) {
    cache.set(key, result);
  }
  return result;
}
项目:dsl-devkit    文件:IBuildSorter.java   
/** {@inheritDoc} */
@Override
public List<List<URI>> sort(final Collection<URI> uris, final IResourceDescriptions oldState) {
  List<List<URI>> sortedCopy = Lists.newLinkedList();
  sortedCopy.add(Lists.newLinkedList(uris));// Make a copy
  return sortedCopy;
}
项目:xtext-core    文件:DocumentSymbolService.java   
public List<? extends Location> getReferences(final Document document, final XtextResource resource, final ReferenceParams params, final IReferenceFinder.IResourceAccess resourceAccess, final IResourceDescriptions indexData, final CancelIndicator cancelIndicator) {
  final int offset = document.getOffSet(params.getPosition());
  List<? extends Location> _xifexpression = null;
  boolean _isIncludeDeclaration = params.getContext().isIncludeDeclaration();
  if (_isIncludeDeclaration) {
    _xifexpression = this.getDefinitions(resource, offset, resourceAccess, cancelIndicator);
  } else {
    _xifexpression = CollectionLiterals.emptyList();
  }
  final List<? extends Location> definitions = _xifexpression;
  final List<? extends Location> references = this.getReferences(resource, offset, resourceAccess, indexData, cancelIndicator);
  final Iterable<Location> result = Iterables.<Location>concat(definitions, references);
  return IterableExtensions.<Location>toList(result);
}
项目:xtext-core    文件:XtextLinkingService.java   
private EPackage findPackageInAllDescriptions(EObject context, QualifiedName packageNsURI) {
    IResourceDescriptions descriptions = descriptionsProvider.getResourceDescriptions(context.eResource());
    if (descriptions != null) {
        Iterable<IEObjectDescription> exported = descriptions.getExportedObjects(EcorePackage.Literals.EPACKAGE, packageNsURI, false);
        for(IEObjectDescription candidate: exported) {
            if (isNsUriIndexEntry(candidate)) {
                EPackage result = getResolvedEPackage(candidate, context);
                if (result != null)
                    return result;
            }
        }
    }
    return null;
}
项目:xtext-core    文件:GenericResourceDescriptionManager.java   
@Override
public boolean isAffected(Collection<Delta> deltas, IResourceDescription candidate, IResourceDescriptions context)
        throws IllegalArgumentException {
    Set<URI> outgoingReferences = descriptionUtils.collectOutgoingReferences(candidate);
    if (!outgoingReferences.isEmpty()) {
        for (IResourceDescription.Delta delta : deltas)
            if (delta.haveEObjectDescriptionsChanged() && outgoingReferences.contains(delta.getUri()))
                return true;
    }
    return false;
}
项目:xtext-core    文件:ResourceSetBasedAllContainersStateProvider.java   
@Override
public IAllContainersState get(IResourceDescriptions context) {
    ResourceSet resourceSet = getResourceSet(context);
    IAllContainersState adapter = (IAllContainersState) EcoreUtil.getAdapter(resourceSet.eAdapters(),
            IAllContainersState.class);
    if (adapter == null) {
        return handleAdapterNotFound(resourceSet);
    }
    return adapter;
}
项目:xtext-core    文件:ResourceSetBasedAllContainersStateProvider.java   
/**
 * @since 2.4
 */
protected ResourceSet getResourceSet(IResourceDescriptions context) {
    if (context instanceof ResourceSetBasedResourceDescriptions) 
        return ((ResourceSetBasedResourceDescriptions) context).getResourceSet();
    else if (context instanceof EagerResourceSetBasedResourceDescriptions) 
        return ((EagerResourceSetBasedResourceDescriptions) context).getResourceSet();
    String contextType = context == null ? "null" : context.getClass().getName();
    throw new IllegalStateException("Passed " + contextType + " is not based on a resource set");
}
项目:xtext-core    文件:StateBasedContainerManager.java   
protected IContainer createContainer(String handle, IResourceDescriptions resourceDescriptions) {
    IAllContainersState state = getState(resourceDescriptions);
    IContainerState containerState = new ContainerState(handle, state);
    StateBasedContainer result = new StateBasedContainer(resourceDescriptions, containerState);
    if (state instanceof FlatResourceSetBasedAllContainersState)
        result.setUriToDescriptionCacheEnabled(false);
    return result;
}
项目:xtext-core    文件:StateBasedContainerManager.java   
protected List<IContainer> getVisibleContainers(List<String> handles, IResourceDescriptions resourceDescriptions) {
    if (handles.isEmpty())
        return Collections.emptyList();
    List<IContainer> result = Lists.newArrayListWithExpectedSize(handles.size());
    for(String handle: handles) {
        IContainer container = createContainer(handle, resourceDescriptions);
        if (!container.isEmpty() || result.isEmpty())
            result.add(container);
    }
    return result;
}
项目:dsl-devkit    文件:AbstractCachingResourceDescriptionManager.java   
/** {@inheritDoc} */
@Override
public boolean isAffected(final Collection<Delta> deltas, final IResourceDescription candidate, final IResourceDescriptions context) { // NOPMD(NPathComplexity)
  final Collection<Delta> filteredDeltas = getInterestingDeltas(deltas);
  if (filteredDeltas.isEmpty()) {
    return false;
  }

  final List<IContainer> containers = getContainerManager().getVisibleContainers(candidate, context);
  for (final Delta delta : filteredDeltas) {
    final URI deltaURI = delta.getUri();// NOPMD - potentially could be lost due to call on getNew() after
    // deleted resources are no longer visible resources so we test them, too.
    if (delta.getNew() == null && isReferencedBy(delta, candidate, context)) {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(candidate.getURI() + " is affected by " + delta.getUri()); //$NON-NLS-1$
      }
      return true;
    }
    for (IContainer container : containers) {
      if (container.getResourceDescription(deltaURI) != null) {
        if (isReferencedBy(delta, candidate, context)) {
          if (LOGGER.isDebugEnabled()) { // NOPMD AvoidDeeplyNestedIfStmts
            LOGGER.debug(candidate.getURI() + " is affected by " + delta.getUri()); //$NON-NLS-1$
          }
          return true;
        }
        break;
      }
    }
  }
  return false;
}
项目:dsl-devkit    文件:CachingStateBasedContainerManager.java   
/**
 * Returns the containers for the given handles, where one of the containers will also include {@code desc} when appropriate.
 * 
 * @param handles
 *          handles to get containers for, must not be {@code null}
 * @param desc
 *          description to add, must not be {@code null}
 * @param resourceDescriptions
 *          resource descriptions, must not be {@code null}
 * @return list of containers, never {@code null}
 */
protected List<IContainer> getContainersForHandlesAndResource(final List<String> handles, final IResourceDescription desc, final IResourceDescriptions resourceDescriptions) {
  List<IContainer> result = getVisibleContainers(handles, resourceDescriptions);
  if (!result.isEmpty()) {
    URI descURI = desc.getURI();
    for (int i = 0; i < result.size(); i++) {
      if (result.get(i).getResourceDescription(descURI) != null) {
        return result;
      }
    }
    // Do *not* add the context resource description itself if we're in the first phase of a build: 'desc' itself
    // may not be in any consistent state, and adding it to the containers may result in recursive invocations of
    // getEObjectDescriptions(), leading to a stack overflow since it may in turn invoke getVisibleContainers() again.
    if (desc instanceof DefaultResourceDescription) {
      DefaultResourceDescription d = (DefaultResourceDescription) desc;
      if (BuildPhases.isIndexing(d.getResource())) {
        return result;
      }
    }
    // the IResourceDescription was found nowhere, add it to the first one that matches the description's domain.
    IDomain descDomain = mapper.map(descURI);
    IContainer wrappedContainer = null;
    int index = 0;
    for (int i = 0; i < result.size(); i++) {
      IContainer container = result.get(i);
      IDomain containerDomain = mapper.map(container);
      if (containerDomain != null && containerDomain.equals(descDomain)) {
        wrappedContainer = new DescriptionAddingContainer(desc, container);
        result.set(index, wrappedContainer);
        return result;
      }
      index++;
    }
    // If we get here, we found no container with a matching domain. Add to the first, but use a DescriptionAddingContainer that
    // will add the description at the end.
    wrappedContainer = new DescriptionAtEndAddingContainer(desc, result.get(0));
    result.set(0, wrappedContainer);
  }
  return result;
}
项目:dsl-devkit    文件:LinkingService.java   
/**
 * Register a name as imported.
 *
 * @param context
 *          context object within which a reference is being set to some object using "name" for the lookup, must not be {@code null}
 * @param name
 *          the lookup name, may be {@code null}
 * @param type
 *          the lookup type, may be {@code null}
 * @param target
 *          the associated target eObject. If not {@code null} then all names for this eObject are also recorded
 *          as imported, provided they're not the same as the {@code name} parameter. May be {@code null}
 */
public void importObject(final EObject context, final String name, final EObject target, final EClass type) {
  // import exported name for resolved references
  ImportedNamesTypesAdapter adapter = getImportedNamesAdapter(context);
  if (target != null) {
    QualifiedName targetName = null;
    final IResourceDescriptions resourceDescriptions = provider.getResourceDescriptions(context.eResource());
    Iterator<IEObjectDescription> exports = resourceDescriptions.getExportedObjectsByObject(target).iterator();
    if (exports.hasNext()) {
      targetName = exports.next().getName();
      if (targetName != null && !targetName.isEmpty()) {
        final QualifiedName lowerCaseName = targetName.toLowerCase();// NOPMD targetName not a String!
        adapter.getImportedNames().add(lowerCaseName);
        if (adapter.getImportedNamesTypes().containsKey(lowerCaseName)) {
          adapter.getImportedNamesTypes().get(lowerCaseName).add(type);
        } else {
          adapter.getImportedNamesTypes().put(lowerCaseName, Sets.newHashSet(type));
        }

      }
    }
  } else if (name != null && name.length() > 0) { // import parsed string for unresolved references
    QualifiedName unresolvedName = crossRefHelper.toUnresolvedReferenceName(name);
    adapter.getImportedNames().add(unresolvedName);
    if (adapter.getImportedNamesTypes().containsKey(unresolvedName)) {
      adapter.getImportedNamesTypes().get(unresolvedName).add(type);
    } else {
      adapter.getImportedNamesTypes().put(unresolvedName, Sets.newHashSet(type));
    }
  }
}