org.eclipse.xtext.resource.IResourceDescriptions Java Examples

The following examples show how to use org.eclipse.xtext.resource.IResourceDescriptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractCachingResourceDescriptionManager.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Bulk method to return all resources (managed by this manager) which are affected by the given set of deltas.
 *
 * @param deltas
 *          deltas
 * @param candidates
 *          candidates
 * @param context
 *          context index
 * @return collection of affected resources
 */
public Collection<URI> getAffectedResources(final Collection<Delta> deltas, final Collection<URI> candidates, final IResourceDescriptions context) {
  // Don't filter by isInterestedIn() in this bulk method. First, isInterestedIn() is based on file extensions, which may or may not
  // work precisely. Second, it filters by haveEObjectdescriptionsChanged(), but the MonitoredClusteringBuilderState already ensures that
  // the delta does not contain unchanged resource descriptions.
  //
  // By not pre-filtering the deltas, we can also ensure that resource description managers for different languages will end up making
  // identical queries to findAllReferencingResources() and findExactReferencingResources(), which is crucial to make the cache in
  // MonitoredClusteringBuilderState be effective.
  //
  // See also the comment on MonitoredClusteringBuilderState.FindReferenceCachingState.
  if (deltas.isEmpty() || candidates.isEmpty()) {
    return Collections.emptySet();
  }

  return getAffectedResources(deltas, uri -> candidates.contains(uri) && isManagerFor(uri), (IResourceDescriptions2) context);
}
 
Example #2
Source File: SimpleResourceDescriptionsBasedContainerManager.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: LinkingService.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Register a name as imported.
 *
 * @param context
 *          context object within which a reference is being set to some object, must not be {@code null}
 * @param target
 *          the associated target eObject. Its exported name is recorded as imported, must not be {@code null}
 * @param type
 *          the lookup type, may be {@code null}
 */
public void importObject(final EObject context, final EObject target, final EClass type) {
  Resource eResource = target.eResource();
  QualifiedName targetName = null;
  if (eResource instanceof LazyLinkingResource2) {
    IQualifiedNameProvider nameProvider = ((LazyLinkingResource2) eResource).getService(IQualifiedNameProvider.class);
    if (nameProvider != null) {
      targetName = nameProvider.getFullyQualifiedName(target);
    }
  } else {
    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()) {
    registerNamedType(context, targetName.toLowerCase(), type); // NOPMD targetName not a String!
  }
}
 
Example #4
Source File: ExternalIndexSynchronizer.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns a map that maps the names of projects as they can be found in the index to their locations and versions.
 */
public Map<N4JSProjectName, Pair<FileURI, String>> findNpmsInIndex() {
	// keep map of all NPMs that were discovered in the index
	Map<N4JSProjectName, Pair<FileURI, String>> discoveredNpmsInIndex = new HashMap<>();

	final ResourceSet resourceSet = core.createResourceSet(Optional.absent());
	final IResourceDescriptions index = core.getXtextIndex(resourceSet);

	for (IResourceDescription resourceDescription : index.getAllResourceDescriptions()) {
		boolean isExternal = resourceDescription.getURI().isFile();
		if (isExternal) {
			addToIndex(discoveredNpmsInIndex, resourceDescription);
		}
	}

	return discoveredNpmsInIndex;
}
 
Example #5
Source File: ExternalLibraryBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Deletes all entries in the Xtext index that start with one of the given project URIs will be cleaned from the
 * index.
 *
 * @param toBeWiped
 *            URIs of project roots
 */
public void wipeURIsFromIndex(IProgressMonitor monitor, Collection<FileURI> toBeWiped) {
	Set<String> toBeWipedStrings = new HashSet<>();
	for (FileURI toWipe : toBeWiped) {
		toBeWipedStrings.add(toWipe.toString());
		N4JSProjectName projectName = toWipe.getProjectName();
		validatorExtension.clearAllMarkersOfExternalProject(projectName);
	}

	ResourceSet resourceSet = core.createResourceSet(Optional.absent());
	IResourceDescriptions index = core.getXtextIndex(resourceSet);

	Set<URI> toBeRemoved = new HashSet<>();
	for (IResourceDescription res : index.getAllResourceDescriptions()) {
		URI resUri = res.getURI();
		String resUriString = resUri.toString();
		for (String toWipeProject : toBeWipedStrings) {
			if (resUriString.startsWith(toWipeProject)) {
				toBeRemoved.add(resUri);
				break;
			}
		}
	}

	builderState.clean(toBeRemoved, monitor);
}
 
Example #6
Source File: ValidationJobSchedulerTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testOutgoingReferencesToAnotherResourceWithBuilderStateNoAffection() {
	String exportedName = "exportedName";
	String importedName = "importedName";
	testMe.setBuilderStateProvider(Providers.<IResourceDescriptions>of(new MyBuilderState(exportedName)));
	documentResource.importedName = importedName;
	documentURI = URI.createURI("document");
	targetURI = URI.createURI("target");
	ReferenceDescriptionImpl reference = (ReferenceDescriptionImpl) BuilderStateFactory.eINSTANCE.createReferenceDescription();
	reference.setTargetEObjectUri(URI.createURI("anothertarget"));
	referenceDescriptions.add(reference);
	noDocumentDescription = false;
	announceDirtyStateChanged();
	validationScheduled = false;
	testMe.scheduleInitialValidation(document);
	assertFalse(validationScheduled);
}
 
Example #7
Source File: DefaultUniqueNameContext.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Context tryGetContext(Resource resource, CancelIndicator cancelIndicator) {
	IResourceDescriptions index = getIndex(resource);
	if (index == null) {
		return null;
	}
	IResourceDescription description = getResourceDescription(resource);
	if (description == null) {
		return null;
	}
	IContainer container = containerManager.getContainer(description, index);
	return new DefaultUniqueNameContext(description, container, getCaseInsensitivityHelper(), cancelIndicator);
}
 
Example #8
Source File: QueryParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected JavaSearchHelper createSearchHelper(ISearchRequestor requestor) {
	JavaSearchHelper searchHelper = javaSearchHelperProvider.get();
	IResourceDescriptions descriptionsToSearch = resourceDescriptionsProvider.get();
	if(descriptionsToSearch.isEmpty()) {
		waitForBuild();
		descriptionsToSearch = resourceDescriptionsProvider.get();
	}
	searchHelper.init(requestor, descriptionsToSearch);
	return searchHelper;
}
 
Example #9
Source File: TestDiscoveryHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Low-level method to collect all test modules, i.e. N4JS files containing classes containing at least one method
 * annotated with &#64;Test, as {@link IResourceDescription}s.
 */
private List<URI> collectDistinctTestLocations(Function<? super URI, ? extends ResourceSet> resourceSetAccess,
		List<URI> locations) {
	return locations.stream().flatMap(loc -> {
		ResourceSet resSet = resourceSetAccess.apply(loc);
		IResourceDescriptions index = n4jsCore.getXtextIndex(resSet);
		return collectTestLocations(index, resSet, loc);
	}).distinct().collect(Collectors.toList());
}
 
Example #10
Source File: FastReferenceSearchResultContentProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Inject
public FastReferenceSearchResultContentProvider(final IResourceDescriptions resourceDescriptions) {
  super(resourceDescriptions);
  this.resourceDescriptions = resourceDescriptions;
  if (resourceDescriptions instanceof IResourceDescription.Event.Source) {
    ((IResourceDescription.Event.Source) resourceDescriptions).addListener(this);
  }
}
 
Example #11
Source File: ModelSequencerTest.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() {
	Module m = new Module() {
		@Override
		public void configure(Binder binder) {
			binder.bind(INamingService.class).to(DefaultNamingService.class);
			binder.bind(IQualifiedNameProvider.class).to(SGraphNameProvider.class);
			binder.bind(ITypeSystem.class).toInstance(GenericTypeSystem.getInstance());
			binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class);
			binder.bind(String.class).annotatedWith(Names.named("Separator")).toInstance("_");
		}
	};
	Injector injector = Guice.createInjector(m);
	injector.injectMembers(this);
}
 
Example #12
Source File: BuilderUtil.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
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;
}
 
Example #13
Source File: N4JSTestedProjectWizardPage.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a new tested project wizard page.
 *
 * @param projectInfo
 *            The N4JSProjectInfo to use as model
 * @param resourceDescriptions
 *            A {@link IResourceDescriptions} implementation.
 */
public N4JSTestedProjectWizardPage(N4JSProjectInfo 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");
}
 
Example #14
Source File: Bug334456Test.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testNoCopiedResourceDescription() throws Exception {
	createPluginProject("foo");
	build();
	IResourceDescriptions descriptions = BuilderUtil.getBuilderState();
	assertFalse(Iterables.isEmpty(descriptions.getAllResourceDescriptions()));
	for(IResourceDescription description: descriptions.getAllResourceDescriptions()) {
		if (description instanceof CopiedResourceDescription) {
			fail("Did not expect an instance of copied resource description in builder state");
		}
	}
}
 
Example #15
Source File: ResourceSetBasedAllContainersStateProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected ResourceSet getResourceSet(IResourceDescriptions context) {
	if (context instanceof IResourceSetAware)
		return ((IResourceSetAware) context).getResourceSet();
	String contextType = context == null ? "null" : context.getClass().getName();
	throw new IllegalStateException("Passed " + contextType + " is not based on a resource set");
}
 
Example #16
Source File: IndexAwareNameEnvironment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public IndexAwareNameEnvironment(Resource resource, ClassLoader classLoader,
		IResourceDescriptions resourceDescriptions, EObjectDescriptionBasedStubGenerator stubGenerator,
		ClassFileCache classFileCache) {
	this.resource = resource;
	this.classLoader = classLoader;
	this.resourceDescriptions = resourceDescriptions;
	this.stubGenerator = stubGenerator;
	this.classFileCache = classFileCache;
}
 
Example #17
Source File: DefaultReferenceFinder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public DefaultReferenceFinder(IResourceDescriptions indexData,
		IResourceServiceProvider.Registry serviceProviderRegistry, 
		TargetURIConverter converter) {
	super(serviceProviderRegistry);
	this.indexData = indexData;
	this.converter = converter;
}
 
Example #18
Source File: ProjectDescriptionBasedContainerManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<IContainer> getVisibleContainers(IResourceDescription desc,
		IResourceDescriptions resourceDescriptions) {
	ChunkedResourceDescriptions descriptions = getChunkedResourceDescriptions(resourceDescriptions);
	if (descriptions == null)
		throw new IllegalArgumentException("Expected " + ChunkedResourceDescriptions.class.getName());
	ProjectDescription projectDescription = ProjectDescription.findInEmfObject(descriptions.getResourceSet());
	List<IContainer> allContainers = new ArrayList<>();
	allContainers.add(createContainer(resourceDescriptions, descriptions, projectDescription.getName()));
	for (String name : projectDescription.getDependencies())
		allContainers.add(createContainer(resourceDescriptions, descriptions, name));
	return allContainers;
}
 
Example #19
Source File: OpenAssociationHierarchyHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IHierarchyBuilder createHierarchyBuilder(EObject target) {
	AssociationHierarchyBuilder xtextCallHierarchyBuilder = globalServiceProvider.findService(target,
			AssociationHierarchyBuilder.class);
	xtextCallHierarchyBuilder.setResourceAccess(resourceAccess);
	xtextCallHierarchyBuilder.setIndexData(globalServiceProvider.findService(target, IResourceDescriptions.class));
	DeferredHierarchyBuilder deferredHierarchyBuilder = globalServiceProvider.findService(target, DeferredHierarchyBuilder.class);
	deferredHierarchyBuilder.setHierarchyBuilder(xtextCallHierarchyBuilder);
	return deferredHierarchyBuilder;
}
 
Example #20
Source File: AbstractScopeResourceDescriptionsTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertLiveModelScopeLocal(boolean enabled) throws IOException {
	final URI resourceURI = URI.createPlatformResourceURI("test/assertLiveModelScopeLocal." + fileExt.getPrimaryFileExtension(), true);
	Resource resource = resourceSet.createResource(resourceURI);
	resource.load(new StringInputStream("stuff foo"), null);
	Stuff stuffFoo = ((File) resource.getContents().get(0)).getStuff().get(0);
	if (enabled) {
		assertExportedObject(resource, "foo");
		stuffFoo.setName("bar");
		assertExportedObject(resource, "bar");
	} else {
		IResourceDescriptions resourceDescriptions = resourceDescriptionsProvider.getResourceDescriptions(resource);
		IResourceDescription resourceDescription = resourceDescriptions.getResourceDescription(resource.getURI());
		assertNull(resourceDescription);
	}
}
 
Example #21
Source File: StateBasedContainerManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: ProjectCompareHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: BuilderIntegrationFragment.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Set<Binding> getGuiceBindingsUi(final Grammar grammar) {
  final Set<Binding> bindings = super.getGuiceBindingsUi(grammar);
  final BindFactory factory = new BindFactory();
  factory.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("
      + "com.avaloq.tools.ddk.xtext.builder.CurrentDescriptions2.ResourceSetAware.class)");
  final Set<Binding> result = factory.getBindings();
  result.addAll(bindings);
  return result;
}
 
Example #24
Source File: XtextLinkingService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: AbstractNoJdtTestLanguageRuntimeModule.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public void configureIResourceDescriptions(Binder binder) {
	binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class);
}
 
Example #26
Source File: AbstractMyDslUiModule.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
public void configureIResourceDescriptionsPersisted(Binder binder) {
	binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(IBuilderState.class);
}
 
Example #27
Source File: ResourceDescriptionsUtil.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Find all {@link IResourceDescription}s of all resources containing cross-references to any of the objects.
 *
 * @param descriptions
 *          {@link IResourceDescriptions} to find the references in.
 * @param targetResources
 *          Target objects.
 * @param matchPolicy
 *          match policy
 * @return An {@link Iterable} of all {@link IResourceDescription}s that reference any of the objects.
 */
@SuppressWarnings("PMD.NPathComplexity")
public static Iterable<IResourceDescription> findReferencesToResources(final IResourceDescriptions descriptions, final Set<IResourceDescription> targetResources, final ReferenceMatchPolicy matchPolicy) {
  if (targetResources.isEmpty()) {
    return ImmutableSet.of();
  }

  final boolean matchNames = matchPolicy.includes(ReferenceMatchPolicy.IMPORTED_NAMES)
      || matchPolicy.includes(ReferenceMatchPolicy.UNRESOLVED_IMPORTED_NAMES);
  final Set<URI> targetUris = Sets.newHashSetWithExpectedSize(targetResources.size());
  final Set<QualifiedName> exportedNames = Sets.newHashSet();
  for (IResourceDescription res : targetResources) {
    targetUris.add(res.getURI());
    if (matchNames) {
      for (IEObjectDescription obj : res.getExportedObjects()) {
        if (matchPolicy.includes(ReferenceMatchPolicy.IMPORTED_NAMES)) {
          exportedNames.add(obj.getName().toLowerCase());
        }
        if (matchPolicy.includes(ReferenceMatchPolicy.UNRESOLVED_IMPORTED_NAMES)) {
          exportedNames.add(QualifiedNames.toUnresolvedName(obj.getName().toLowerCase()));
        }
      }
    }
  }

  return Iterables.filter(descriptions.getAllResourceDescriptions(), input -> {
    if (matchNames) {
      for (QualifiedName name : input.getImportedNames()) {
        if (exportedNames.contains(name.toLowerCase())) { // NOPMD
          return true;
        }
      }
    }
    if (matchPolicy.includes(ReferenceMatchPolicy.REFERENCES)) {
      for (IReferenceDescription ref : input.getReferenceDescriptions()) {
        if (targetUris.contains(ref.getTargetEObjectUri().trimFragment())) {
          return true;
        }
      }
    }
    return false;
  });
}
 
Example #28
Source File: AbstractGamlRuntimeModule.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public void configureIResourceDescriptions(Binder binder) {
	binder.bind(IResourceDescriptions.class).to(ResourceSetBasedResourceDescriptions.class);
}
 
Example #29
Source File: AbstractSARLRuntimeModule.java    From sarl with Apache License 2.0 4 votes vote down vote up
public void configureIResourceDescriptionsPersisted(Binder binder) {
	binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(ResourceSetBasedResourceDescriptions.class);
}
 
Example #30
Source File: AbstractRuleEngineUiModule.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public void configureIResourceDescriptionsBuilderScope(Binder binder) {
	binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE)).to(CurrentDescriptions.ResourceSetAware.class);
}