org.eclipse.xtext.linking.lazy.LazyLinkingResource Java Examples

The following examples show how to use org.eclipse.xtext.linking.lazy.LazyLinkingResource. 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: CheckConfigurationStoreService.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the language for the given object.
 *
 * @param context
 *          object
 * @return the language the corresponding resource was parsed from, may be {@code null}
 */
private String getLanguage(final Object context) {
  if (context instanceof EObject) {
    Resource resource = ((EObject) context).eResource();
    if (resource instanceof LazyLinkingResource) {
      return ((LazyLinkingResource) resource).getLanguageName();
    }
  } else if (context instanceof Issue && !LANGUAGE_AGNOSTIC_DIAGNOSTICS.contains(((Issue) context).getCode())) {
    URI uri = ((Issue) context).getUriToProblem();
    if (uri != null) {
      Registry registry = IResourceServiceProvider.Registry.INSTANCE;
      IResourceServiceProvider resourceServiceProvider = registry.getResourceServiceProvider(uri);
      if (resourceServiceProvider != null) {
        return resourceServiceProvider.get(Injector.class).getInstance(Key.get(String.class, Names.named(Constants.LANGUAGE_NAME)));
      } else {
        LOGGER.error("Could not fetch a ResourceServiceProvider for URI: " + uri); //$NON-NLS-1$
      }
    } else {
      LOGGER.warn("Could not fetch eResource from issue: URI to problem is null"); //$NON-NLS-1$
    }
  }

  return null;
}
 
Example #2
Source File: AbstractSmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void doParseAndCheckForSmokeWithoutResourceSet(final String model) throws Exception {
	try {
		LazyLinkingResource resource = createResource(model);
		// simulate closed editor
		ResourceSet resourceSet = resource.getResourceSet();
		resourceSet.eSetDeliver(false);
		resourceSet.getResources().clear();
		resourceSet.eAdapters().clear();
		checkForSmoke(model, resource);
	} catch (Throwable e) {
		e.printStackTrace();
		assertEquals(e.getMessage()+" : Model was : \n\n"+model, model, "");
		// just to make sure we fail for empty model, too
		fail(e.getMessage()+" : Model was : \n\n"+model);
	}
}
 
Example #3
Source File: DotHtmlLabelQuickfixDelegator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private XtextResource getXtextResource(String model) {
	StringInputStream in = new StringInputStream(
			Strings.emptyIfNull(model));

	// creating an in-memory EMF Resource
	URI uri = URI.createURI(""); //$NON-NLS-1$
	Resource resource = injector.getInstance(IResourceFactory.class)
			.createResource(uri);
	new XtextResourceSet().getResources().add(resource);
	try {
		resource.load(in, null);
	} catch (IOException e) {
		e.printStackTrace();
	}
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource)
				.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return (XtextResource) resource;
}
 
Example #4
Source File: DotEditorUtils.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private static XtextResource doGetResource(Injector injector,
		InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = injector.getInstance(XtextResourceSet.class);
	rs.setClasspathURIContext(DotEditorUtils.class);
	XtextResource resource = (XtextResource) injector
			.getInstance(IResourceFactory.class).createResource(uri);
	rs.getResources().add(resource);
	resource.load(in, null);
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource)
				.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return resource;
}
 
Example #5
Source File: AbstractQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected XtextResource getXtextResource(String model) {
	StringInputStream in = new StringInputStream(Strings.emptyIfNull(model));
	URI uri = URI.createURI(""); // creating an in-memory EMF Resource

	ResourceSet resourceSet = resourceSetProvider.get(project);
	Resource resource = injector.getInstance(IResourceFactory.class).createResource(uri);
	resourceSet.getResources().add(resource);

	try {
		resource.load(in, null);
		if (resource instanceof LazyLinkingResource) {
			((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
		} else {
			EcoreUtil.resolveAll(resource);
		}
		return (XtextResource) resource;
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #6
Source File: AbstractStreamingFingerprintComputer.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generate a fingerprint for the target object using its URI.
 *
 * @param target
 *          The target object
 * @param context
 *          The object containing the reference
 * @param hasher
 *          hasher to stream to
 */
private void fingerprintEObject(final EObject target, final EObject context, final Hasher hasher) {
  if (target == null) {
    hasher.putUnencodedChars(NULL_STRING);
  } else if (target.eIsProxy()) {
    if (context.eResource() instanceof LazyLinkingResource) {
      final URI proxyUri = ((InternalEObject) target).eProxyURI();
      if (!((LazyLinkingResource) context.eResource()).getEncoder().isCrossLinkFragment(context.eResource(), proxyUri.fragment())) {
        hasher.putUnencodedChars(proxyUri.toString());
        return;
      }
    }
    hasher.putUnencodedChars(UNRESOLVED_STRING);
  } else {
    hasher.putUnencodedChars(EcoreUtil.getURI(target).toString());
  }
}
 
Example #7
Source File: AbstractFingerprintComputer.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generate a fingerprint for the target object using its URI.
 *
 * @param target
 *          The target object
 * @param context
 *          The object containing the reference
 * @return Its fingerprint.
 */
private CharSequence fingerprintEObject(final EObject target, final EObject context) {
  if (target == null) {
    return NULL_STRING;
  } else if (target.eIsProxy()) {
    if (context.eResource() instanceof LazyLinkingResource) {
      final URI proxyUri = ((InternalEObject) target).eProxyURI();
      if (!((LazyLinkingResource) context.eResource()).getEncoder().isCrossLinkFragment(context.eResource(), proxyUri.fragment())) {
        return proxyUri.toString();
      }
    }
    return UNRESOLVED_STRING;
  } else {
    return EcoreUtil.getURI(target).toString();
  }
}
 
Example #8
Source File: ParseTreeUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source text assigned to the given feature of the given object. Does not work for multi-valued features. Optionally also converts the source
 * text using the corresponding value converter. Conversion is only performed for keywords, rule call or cross reference grammar rules.
 * <p>
 * This method does not perform a check to make sure the feature matches the given object.
 *
 * @param object
 *          the semantic object
 * @param feature
 *          the feature to be considered when parsing the parse tree model
 * @param convert
 *          {@code true} if the parsed string needs conversion using its value converter
 * @return the parsed string from the node model
 */
public static String getParsedStringUnchecked(final EObject object, final EStructuralFeature feature, final boolean convert) {
  INode node = Iterables.getFirst(NodeModelUtils.findNodesForFeature(object, feature), null);
  if (node != null) {
    if (convert) {
      final LazyLinkingResource res = (LazyLinkingResource) object.eResource();
      EObject grammarElement = node.getGrammarElement();
      if (res != null && (grammarElement instanceof Keyword || grammarElement instanceof RuleCall || grammarElement instanceof CrossReference)) {
        final DefaultLinkingService linkingService = (DefaultLinkingService) res.getLinkingService();
        return linkingService.getCrossRefNodeAsString(node);
      }
    }
    // result may contain escape sequences or quotes
    return NodeModelUtils.getTokenText(node);
  }
  return null;
}
 
Example #9
Source File: AbstractUnresolvableReferenceWithNode.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void applyToModel(IResolvedTypes resolvedTypes) {
	Resource resource = getExpression().eResource();
	if (resource instanceof LazyLinkingResource) {
		LazyLinkingResource lazyLinkingResource = (LazyLinkingResource) resource;
		
		TypeAwareLinkingDiagnosticContext context = new TypeAwareLinkingDiagnosticContext(this, resolvedTypes);
		DiagnosticMessage message = lazyLinkingResource.getDiagnosticMessageProvider()
				.getUnresolvedProxyMessage(context);
		if (message != null) {
			List<Resource.Diagnostic> diagnostics = getDiagnosticList(lazyLinkingResource, message);
			Diagnostic diagnostic = createDiagnostic(message);
			diagnostics.add(diagnostic);
		}
		EObject referenced = (InternalEObject) getExpression().eGet(getReference(), false);
		lazyLinkingResource.markUnresolvable(referenced);
	}
}
 
Example #10
Source File: ResourceDescription2.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create EObjectDescriptions for exported objects.
 *
 * @param resource
 *          LazyLinkingResource
 * @return list of object descriptions
 */
protected List<IEObjectDescription> createDescriptions(final LazyLinkingResource resource) {
  final ImmutableList.Builder<IEObjectDescription> exportedEObjects = ImmutableList.builder();
  IAcceptor<IEObjectDescription> acceptor = decorateExportedObjectsAcceptor(exportedEObjects::add);
  TreeIterator<EObject> allProperContents = EcoreUtil.getAllProperContents(resource, false);
  while (allProperContents.hasNext()) {
    EObject content = allProperContents.next();
    if (!strategy.createEObjectDescriptions(content, acceptor)) {
      allProperContents.prune();
    }
  }
  return exportedEObjects.build();
}
 
Example #11
Source File: ResourceDescription2.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected List<IEObjectDescription> computeExportedObjects() {
  if (!getResource().isLoaded()) {
    try {
      getResource().load(null);
    } catch (IOException e) {
      LOG.error(e.getMessage(), e);
      return Collections.emptyList();
    }
  }
  // Maybe we need to install the derived state first. Installing/discarding the derived state will clear the resource cache, so we must
  // make sure at least that the resource description is re-added.
  LazyLinkingResource resource = (LazyLinkingResource) getResource();
  boolean doInitialize = (resource instanceof ILazyLinkingResource2) && !((ILazyLinkingResource2) resource).isInitialized();
  final ResourceDescription2 self = this;
  try {
    if (doInitialize) {
      resource.eSetDeliver(false);
      ((ILazyLinkingResource2) resource).installDerivedState(BuildPhases.isIndexing(resource));
      // Make sure we have at least this resource description itself in the resource cache.
      resource.getCache().get(AbstractCachingResourceDescriptionManager.CACHE_KEY, resource, () -> self);
    }
    return createDescriptions(resource);

  } finally {
    if (doInitialize) {
      // DerivedStateAwareResourceManager does discard the state. Should we do so, too?
      resource.eSetDeliver(true);
      // Make sure we have at least this resource description itself in the resource cache.
      resource.getCache().get(AbstractCachingResourceDescriptionManager.CACHE_KEY, resource, () -> self);
    }
  }
}
 
Example #12
Source File: BuilderIntegrationFragment.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Set<Binding> getGuiceBindingsRt(final Grammar grammar) {
  final Set<Binding> bindings = super.getGuiceBindingsRt(grammar);
  final BindFactory factory = new BindFactory();
  factory.addTypeToType(IContainer.Manager.class.getName(), "com.avaloq.tools.ddk.xtext.builder.CachingStateBasedContainerManager");
  factory.addTypeToType(LazyLinkingResource.class.getName(), LazyLinkingResource2.class.getName());
  factory.addTypeToType(LazyURIEncoder.class.getName(), FastLazyURIEncoder.class.getName());
  final Set<Binding> result = factory.getBindings();
  result.addAll(bindings);
  return result;
}
 
Example #13
Source File: RenameElementHandler.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
private NamedElement findInStatechart(NamedElement fakeElement) {
	Resource resource = fakeElement.eResource();
	// only do something if element is really from fake resource
	if (resource instanceof LazyLinkingResource) {
		Statechart sct = utils.getStatechart((LazyLinkingResource) resource);
		EObject elem = utils.findElement(fakeElement, sct);
		if (elem instanceof NamedElement) {
			return (NamedElement) elem;
		}
	}
	return fakeElement;
}
 
Example #14
Source File: ContainerQuery.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute the query on containers visible from a certain resource, and caches the results on that resource. The results will grouped by
 * container and in the order of
 * {@link IContainer.Manager#getVisibleContainers(org.eclipse.xtext.resource.IResourceDescription, org.eclipse.xtext.resource.IResourceDescriptions)}. The
 * result does <em>not</em> apply
 * any name shadowing.
 *
 * @param resource
 *          The resource.
 * @return The query results
 */
@SuppressWarnings("nls")
public Iterable<IEObjectDescription> execute(final Resource resource) {
  if (!(resource instanceof LazyLinkingResource)) {
    throw new IllegalStateException("Resource is not a LazyLinkingResource " + (resource != null ? resource.getURI() : ""));
  }
  final IScopeProvider scopeProvider = EObjectUtil.getScopeProviderByResource((LazyLinkingResource) resource);
  if (!(scopeProvider instanceof AbstractPolymorphicScopeProvider)) {
    throw new IllegalStateException("Scope provider is not an AbstractPolymorphicScopeProvider scope provider.");
  }
  return execute(((AbstractPolymorphicScopeProvider) scopeProvider).getVisibleContainers((LazyLinkingResource) resource));
}
 
Example #15
Source File: AbstractXtextTests.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource doGetResource(InputStream in, URI uri) throws Exception {
	XtextResourceSet rs = get(XtextResourceSet.class);
	rs.setClasspathURIContext(getClasspathURIContext());
	XtextResource resource = (XtextResource) getResourceFactory().createResource(uri);
	rs.getResources().add(resource);
	resource.load(in, null);
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return resource;
}
 
Example #16
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource getResourceFromString(String model, String uriString, XtextResourceSet rs) throws IOException {
	rs.setClasspathURIContext(getClasspathURIContext());
	XtextResource resource = (XtextResource) getResourceFactory().createResource(URI.createURI(uriString));
	rs.getResources().add(resource);
	resource.load(getAsStream(model), null);
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
	} else {
		EcoreUtil.resolveAll(resource);
	}
	return resource;
}
 
Example #17
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If the given resource is a {@link LazyLinkingResource} the implementation delegates
 * to {@link LazyLinkingResource#resolveLazyCrossReferences(CancelIndicator)} otherwise to
 * {@link EcoreUtil2#resolveAll(Resource, CancelIndicator)}.
 */
public static void resolveLazyCrossReferences(Resource resource, CancelIndicator monitor) {
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).resolveLazyCrossReferences(monitor);
	} else {
		resolveAll(resource, monitor);
	}
}
 
Example #18
Source File: AbstractCleaningLinker.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void beforeModelLinked(EObject model, IDiagnosticConsumer diagnosticsConsumer) {
	Resource resource = model.eResource();
	if (resource instanceof LazyLinkingResource) {
		((LazyLinkingResource) resource).clearLazyProxyInformation();
	}
	ImportedNamesAdapter adapter = ImportedNamesAdapter.find(resource);
	if (adapter!=null)
		adapter.clear();
}
 
Example #19
Source File: LinkingErrorTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertNoExceptions(EObject object) {
	Resource resource = object.eResource();
	if (resource instanceof LazyLinkingResource)
		((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
	List<Diagnostic> errors = object.eResource().getErrors();
	for(Diagnostic error: errors) {
		if (error instanceof ExceptionDiagnostic) {
			((ExceptionDiagnostic) error).getException().printStackTrace();
		}
		assertFalse(error.toString(), error instanceof ExceptionDiagnostic);
	}
	validateWithoutException((XtextResource) resource);
}
 
Example #20
Source File: AbstractSmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected LazyLinkingResource createResource(final String model) throws IOException {
	if (logger.isTraceEnabled()) {
		logger.trace("createResource: " + model);
	}
	XtextResourceSet set = getResourceSet();
	typeProviderFactory.findOrCreateTypeProvider(set);
	LazyLinkingResource resource = (LazyLinkingResource) resourceFactory.createResource(URI.createURI("Test.xtend"));
	set.getResources().add(resource);
	resource.load(new StringInputStream(model), null);
	resource.resolveLazyCrossReferences(CancelIndicator.NullImpl);
	return resource;
}
 
Example #21
Source File: ResolveLazyComponent.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
public void invoke(IWorkflowContext ctx) {
	Set<String> names = ctx.getSlotNames();
	for (String slotName : names) {

		Object slotContent = ctx.get(slotName);
		if (slotContent instanceof Iterable) {
			Iterator<?> iter = ((Iterable<?>) slotContent).iterator();
			while (iter.hasNext()) {
				Object o = iter.next();
				if (o instanceof Resource) {
					Resource r = ((Resource) o);
					if(!r.isLoaded())
						try {
							r.load(null);
						} catch (IOException e) {
							throw new RuntimeException("Error loading slot "+ slotName, e);
						} 

					if(r instanceof LazyLinkingResource)
						ctx.put(slotName, r.getContents());
				}
			}
		}

	}

}
 
Example #22
Source File: AbstractUnresolvableReferenceWithNode.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected List<Diagnostic> getDiagnosticList(LazyLinkingResource resource, /* @Nullable */ DiagnosticMessage message) throws AssertionError {
	if (message != null) {
		switch (message.getSeverity()) {
			case ERROR:
				return resource.getErrors();
			case WARNING:
				return resource.getWarnings();
			default:
				throw new AssertionError("Unexpected severity: " + message.getSeverity());
		}
	}
	return Collections.emptyList();
}
 
Example #23
Source File: SmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void checkNoErrorsInTypeProvider(LazyLinkingResource resource) {
	typeResolver.resolveTypes(resource);
	
	Iterator<Object> contents = EcoreUtil.getAllContents(resource, true);
	while(contents.hasNext()) {
		Object object = contents.next();
		if (object instanceof JvmWildcardTypeReference) {
			assertTrue(((JvmWildcardTypeReference) object).eContainer() instanceof JvmTypeReference);
		}
	}
}
 
Example #24
Source File: SmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void checkForSmoke(final String model, LazyLinkingResource resource) {
	checkNodeModelInvariant(resource);
	cache.clear(resource);
	checkNoErrorsInTypeProvider(resource);
	cache.clear(resource);
	checkNoErrorsInValidator(model, resource);
}
 
Example #25
Source File: FollowUpError.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyToModel(IResolvedTypes resolvedTypes) {
	Resource resource = getExpression().eResource();
	if (resource instanceof LazyLinkingResource) {
		LazyLinkingResource lazyLinkingResource = (LazyLinkingResource) resource;
		EObject referenced = (InternalEObject) getExpression().eGet(getReference(), false);
		lazyLinkingResource.markUnresolvable(referenced);
	}
}
 
Example #26
Source File: TypeInsteadOfConstructorLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyToModel(IResolvedTypes resolvedTypes) {
	Resource resource = getExpression().eResource();
	if (resource instanceof LazyLinkingResource) {
		LazyLinkingResource lazyLinkingResource = (LazyLinkingResource) resource;
		EObject referenced = (InternalEObject) getExpression().eGet(XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR, false);
		lazyLinkingResource.markUnresolvable(referenced);
	}
}
 
Example #27
Source File: SmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testResourceUpdateSkipCharacterInBetween() throws Exception {
	for(String string: smokeTestModels) {
		LazyLinkingResource resource = createResource(string.substring(1));
		for (int i = 0; i < string.length() - 1; i++) {
			logProgress(i);
			compareWithNewResource(resource, i, 1, String.valueOf(string.charAt(i)));
		}
	}
}
 
Example #28
Source File: ErrorTreeAppendable.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected LazyURIEncoder getOrCreateURIEncoder() {
	Resource resource = getState().getResource();
	if (resource instanceof LazyLinkingResource) {
		return ((LazyLinkingResource) resource).getEncoder();
	}
	return new LazyURIEncoder();
}
 
Example #29
Source File: SmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testResourceUpdateSkipFirstCharacters() throws Exception {
	for(String string: smokeTestModels) {
		LazyLinkingResource resource = createResource("");
		for (int i = string.length() - 1; i >= 0; i--) {
			logProgress(i);
			compareWithNewResource(resource, 0, 0, String.valueOf(string.charAt(i)));
		}
	}
}
 
Example #30
Source File: SmokeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testResourceUpdateSkipLastCharacters() throws Exception {
	for(String string: smokeTestModels) {
		LazyLinkingResource resource = createResource("");
		for (int i = 0; i < string.length(); i++) {
			logProgress(i);
			compareWithNewResource(resource, i, 0, String.valueOf(string.charAt(i)));
		}
	}
}