/** * 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) { 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; }
@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); } }
/** * 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()); } }
/** * 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(); } }
/** * 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; }
/** * Also adds the Object.fj resource * @see org.eclipse.xtext.junit.AbstractXtextTests#doGetResource(java.io.InputStream, org.eclipse.emf.common.util.URI) */ @Override protected XtextResource doGetResource(InputStream in, URI uri) throws Exception { XtextResourceSet rs = get(XtextResourceSet.class); rs.getResource(URI.createURI(FJTestLoader.OBJECT_FJ_URI), true); rs.setClasspathURIContext(getClass()); 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; }
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(); }
@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); } }
@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); } }
protected LazyURIEncoder getOrCreateURIEncoder() { Resource resource = getState().getResource(); if (resource instanceof LazyLinkingResource) { return ((LazyLinkingResource) resource).getEncoder(); } return new LazyURIEncoder(); }
protected XtextResource doGetResource(InputStream in, URI uri) throws Exception { XtextResourceSet rs = get(XtextResourceSet.class); rs.setClasspathURIContext(getClass()); 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; }
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(); }
/** * 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); } }
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; }
@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; }
@Override protected List<IEObjectDescription> computeExportedObjects() { if (!getResource().isLoaded()) { try { getResource().load(null); } catch (IOException e) { LOG.error(e.getMessage(), e); return ImmutableList.of(); } } // 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 createDecriptions(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); } } }
/** * Create EObjectDescriptions for exported objects. * * @param resource * LazyLinkingResource * @return list of object descriptions */ protected List<IEObjectDescription> createDecriptions(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(); }
private NamedElement findElementForFakeInStatechart(NamedElement fakeElement) { Resource resource = fakeElement.eResource(); // only do something if element is really from fake resource if (resource instanceof LazyLinkingResource) { Statechart sct = getStatechartFromFakeResource((LazyLinkingResource)resource); EList<Scope> scopes = sct.getScopes(); for (Scope scope : scopes) { // check all declarations EList<Declaration> declarations = scope.getDeclarations(); for (Declaration decl : declarations) { if (decl.eClass().getName().equals(fakeElement.eClass().getName()) && decl.getName().equals(fakeElement.getName())) { return decl; } } // check scope itself it is a named one if (scope instanceof NamedElement) { NamedElement namedScope = (NamedElement) scope; if (namedScope.eClass().getName().equals(fakeElement.eClass().getName()) && namedScope.getName().equals(fakeElement.getName())) { return namedScope; } } } } return fakeElement; }
protected Statechart getStatechartFromFakeResource(LazyLinkingResource resource) { for (Adapter adapter : resource.eAdapters()) { if (adapter instanceof ContextElementAdapter) { EObject elem = ((ContextElementAdapter)adapter).getElement(); if (elem instanceof Statechart) { return (Statechart) elem; } } } return null; }
@Test public void testParse() throws Exception { final DefaultContext context = new DefaultContext(); final SrcGen4JFile dir = new SrcGen4JFile("src/test/resources"); final SrcGen4JFile file = new SrcGen4JFile(dir, "xtext-test-config.xml"); final JAXBContext jaxbContext = JAXBContext.newInstance( SrcGen4JConfig.class, XtextParserConfig.class, EMFGeneratorConfig.class, SrcGen4JFile.class); final SrcGen4JConfig srcGen4JConfig = new JaxbHelper().create( file.toFile(), jaxbContext); srcGen4JConfig.init(context, new File(".")); final ParserConfig config = srcGen4JConfig.getParsers().getList() .get(0); final List<SrcGen4JFile> srcDirs = new ArrayList<SrcGen4JFile>(); srcDirs.add(dir); final XtextParser testee = new XtextParser(); testee.initialize(context, config); // TEST final ResourceSet resourceSet = testee.parse(); // VERIFY assertThat(resourceSet).isNotNull(); final TreeIterator<Notifier> it = resourceSet.getAllContents(); assertThat(it.next()).isInstanceOf(LazyLinkingResource.class); assertThat(it.next()).isInstanceOf(ModelImpl.class); final Notifier notifier = it.next(); assertThat(notifier).isInstanceOf(GreetingImpl.class); final Greeting greeting = (Greeting) notifier; assertThat(greeting.getName()).isEqualTo("World"); }
private void assertResolvingCrossReferencesThrowsNoException(String input) throws Exception { XExpression expression = expression(input); // throws CCE otherwise ((LazyLinkingResource) expression.eResource()).resolveLazyCrossReferences(CancelIndicator.NullImpl); }
public Class<? extends XtextResource> bindXtextResource() { return LazyLinkingResource.class; }
@Test public void testGetMultiValuedLinkText() throws Exception { with(LazyLinkingTestLanguageStandaloneSetup.class); crossRefSerializer = get(ICrossReferenceSerializer.class); final LazyLinkingTestLanguageGrammarAccess g = (LazyLinkingTestLanguageGrammarAccess) get(IGrammarAccess.class); final XtextResource r = CrossRefTest.this.getResourceFromStringAndExpect("type TypeA {} type TypeB { TypeA TypeC TypeB p1; }", 1); LogCapture log = LoggingTester.captureLogging(Level.ERROR, LazyLinkingResource.class, new Runnable() { @Override public void run() { Model model = (Model) r.getContents().get(0); assertEquals(2, model.getTypes().size()); org.eclipse.xtext.linking.lazy.lazyLinking.Type type = model.getTypes().get(1); assertEquals("TypeB", type.getName()); assertEquals(1, type.getProperties().size()); Property prop = type.getProperties().get(0); assertEquals("p1", prop.getName()); assertEquals(3, prop.getType().size()); org.eclipse.xtext.linking.lazy.lazyLinking.Type propType = prop.getType().get(0); assertFalse(propType.eIsProxy()); String linkText = crossRefSerializer.serializeCrossRef(prop,g.getPropertyAccess().getTypeTypeCrossReference_0_0(), propType, null); assertEquals("TypeA", linkText); propType = prop.getType().get(1); assertTrue(propType.eIsProxy()); INode node = getCrossReferenceNode(prop, GrammarUtil.getReference(g.getPropertyAccess().getTypeTypeCrossReference_0_0()), propType); linkText = crossRefSerializer.serializeCrossRef(prop,g.getPropertyAccess().getTypeTypeCrossReference_0_0(), propType, node); assertEquals("TypeC", linkText); propType = prop.getType().get(2); assertFalse(propType.eIsProxy()); node = getCrossReferenceNode(prop, GrammarUtil.getReference(g.getPropertyAccess().getTypeTypeCrossReference_0_0()), propType); linkText = crossRefSerializer.serializeCrossRef(prop,g.getPropertyAccess().getTypeTypeCrossReference_0_0(), propType, null); assertEquals("TypeB", linkText); Adapter adapter = (Adapter) NodeModelUtils.getNode(prop); prop.eAdapters().remove(adapter); propType = prop.getType().get(1); assertTrue(propType.eIsProxy()); linkText = crossRefSerializer.serializeCrossRef(prop,g.getPropertyAccess().getTypeTypeCrossReference_0_0(), propType, null); assertNull(linkText); } }); log.assertNumberOfLogEntries(2); }
/** * Execute the query on containers visible from an object in a certain resource, but cache the results on originalResource. 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 context * An object in the context resource. * @param originalResource * The original resource. * @return The query results */ @SuppressWarnings("nls") public Iterable<IEObjectDescription> execute(final EObject context, final Resource originalResource) { if (!(originalResource instanceof LazyLinkingResource)) { throw new IllegalStateException("Resource is not a LazyLinkingResource " + (originalResource != null ? originalResource.getURI() : "")); } final IScopeProvider scopeProvider = EObjectUtil.getScopeProviderByResource((LazyLinkingResource) originalResource); if (!(scopeProvider instanceof AbstractPolymorphicScopeProvider)) { throw new IllegalStateException("Scope provider is not an AbstractPolymorphicScopeProvider scope provider."); } return execute(((AbstractPolymorphicScopeProvider) scopeProvider).getVisibleContainers(originalResource.getContents().get(0), originalResource)); }
/** * Gets the scope provider given an object part of a {@link org.eclipse.xtext.linking.lazy.LazyLinkingResource * LazyLinkingResource}. * * @param object * the object * @return the scope provider by e object */ public static IScopeProvider getScopeProviderByEObject(final EObject object) { if (object.eResource() instanceof LazyLinkingResource) { return getScopeProviderByResource((LazyLinkingResource) object.eResource()); } else { throw new IllegalArgumentException("Scope provider can only be returned if given a LazyLinkingResource"); //$NON-NLS-1$ } }
/** * Returns a scope provider given a {@link org.eclipse.xtext.linking.lazy.LazyLinkingResource LazyLinkingResource}. * * @param resource * the resource * @return the scope provider by resource */ public static IScopeProvider getScopeProviderByResource(final LazyLinkingResource resource) { return ((DefaultLinkingService) resource.getLinkingService()).getScopeProvider(); }
/** * * @return Root model at the resource set */ public TranslationUnit getModel() { return (TranslationUnit) ((LazyLinkingResource) model).getContents().get(0); }
protected abstract LazyLinkingResource createResource(String string);