org.eclipse.xtext.resource.DerivedStateAwareResource Java Examples

The following examples show how to use org.eclipse.xtext.resource.DerivedStateAwareResource. 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: InferredModelAssociator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new acceptor for the given resource.
 *
 * @param resource
 *          resource, must not be {@code null}
 * @return new acceptor, never {@code null}
 */
protected IAcceptor<EObject> createAcceptor(final DerivedStateAwareResource resource) {
  return new IAcceptor<EObject>() {
    private InferenceContainer container;

    @Override
    public void accept(final EObject t) {
      if (t != null) {
        if (container == null) {
          container = ModelInferenceFactory.eINSTANCE.createInferenceContainer();
          resource.getContents().add(container);
        }
        container.getContents().add(t);
      }
    }
  };
}
 
Example #2
Source File: InferredModelAssociator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public final void installDerivedState(final DerivedStateAwareResource resource, final boolean isPreLinkingPhase) {
  if (resource.getContents().isEmpty()) {
    return;
  }
  EObject eObject = resource.getContents().get(0);
  Deque<Resource> inferenceStack = getInferenceStack();
  inferenceStack.push(resource);
  try {
    inferTargetModel(eObject, createAcceptor(resource), isPreLinkingPhase);
    // CHECKSTYLE:OFF
  } catch (RuntimeException e) {
    // CHECKSTYLE:ON
    LOGGER.error("Failed to install derived state for resource " + resource.getURI(), e); //$NON-NLS-1$
  } finally {
    inferenceStack.pop();
  }
}
 
Example #3
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * copies contents of a resource set into a new one
 */
public static <T extends ResourceSet> T clone(T target, ResourceSet source) {
	EList<Resource> resources = source.getResources();
	EcoreUtil.Copier copier = new EcoreUtil.Copier();
	for (Resource resource : resources) {
		Resource targetResource = target.createResource(resource.getURI());
		targetResource.getContents().addAll(copier.copyAll(resource.getContents()));
		// mark all resources as fully initialized
		if (resource instanceof DerivedStateAwareResource && targetResource instanceof DerivedStateAwareResource) {
			((DerivedStateAwareResource) targetResource).setFullyInitialized(((DerivedStateAwareResource) resource)
					.isFullyInitialized());
		}
	}
	copier.copyReferences();
	return target;
}
 
Example #4
Source File: GrammarResource.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void installDerivedState(DerivedStateAwareResource resource, boolean preLinkingPhase) {
	if (preLinkingPhase)
		return;
	GrammarResource castedResource = (GrammarResource)resource;
	castedResource.superDoLinking();
}
 
Example #5
Source File: ScriptBuilderImpl.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Finalize the script.
 *
 * <p>The finalization includes: <ul>
 * <li>The import section is created.</li>
 * </ul>
 */
public void finalizeScript() {
	if (this.isFinalized) {
		throw new IllegalStateException("already finalized");
	}
	this.isFinalized = true;
	ImportManager concreteImports = new ImportManager(true);
	XImportSection importSection = getScript().getImportSection();
	if (importSection != null) {
		for (XImportDeclaration decl : importSection.getImportDeclarations()) {
			concreteImports.addImportFor(decl.getImportedType());
		}
	}
	for (String importName : getImportManager().getImports()) {
		JvmType type = findType(getScript(), importName).getType();
		if (concreteImports.addImportFor(type) && type instanceof JvmDeclaredType) {
			XImportDeclaration declaration = XtypeFactory.eINSTANCE.createXImportDeclaration();
			declaration.setImportedType((JvmDeclaredType) type);
			if (importSection == null) {
				importSection = XtypeFactory.eINSTANCE.createXImportSection();
				getScript().setImportSection(importSection);
			}
			importSection.getImportDeclarations().add(declaration);
		}
	}
	Resource resource = getScript().eResource();
	if (resource instanceof DerivedStateAwareResource) {
		((DerivedStateAwareResource) resource).discardDerivedState();
	}
}
 
Example #6
Source File: AbstractBuilder.java    From sarl with Apache License 2.0 5 votes vote down vote up
protected <T> T getAssociatedElement(Class<T> expectedType, EObject dslObject, Resource resource) {
	for (final EObject obj : this.associations.getJvmElements(dslObject)) {
		if (expectedType.isInstance(obj)) {
			return expectedType.cast(obj);
		}
	}
	if (resource instanceof DerivedStateAwareResource) {
		((DerivedStateAwareResource) resource).discardDerivedState();
		resource.getContents();
		return getAssociatedElement(expectedType, dslObject, null);
	}
	throw new IllegalStateException("No JvmFormalParameter associated to " + dslObject + " in " + dslObject.eContainer());
}
 
Example #7
Source File: FixedHighlightingReconciler.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @since 2.8
 */
@Override
protected void beforeRefresh(final XtextResource resource, final CancelIndicator cancelIndicator) {
  if (resource instanceof DerivedStateAwareResource) {
    resource.getContents(); // trigger derived state computation
  }
  if (resource instanceof IBatchLinkableResource) {
    ((IBatchLinkableResource) resource).linkBatched(cancelIndicator);
  }
}
 
Example #8
Source File: InferredModelAssociator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void discardDerivedState(final DerivedStateAwareResource resource) {
  List<EObject> derived = newArrayList();
  EList<EObject> resourcesContentsList = resource.getContents();
  for (int i = 1; i < resourcesContentsList.size(); i++) {
    EObject eObject = resourcesContentsList.get(i);
    unloader.unloadRoot(eObject);
    derived.add(eObject);
  }
  resourcesContentsList.removeAll(derived);
  getSourceToInferredModelMap(resource).clear();
  getInferredModelToSourceMap(resource).clear();
}
 
Example #9
Source File: ContentAssistContextFactory.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public ContentAssistContext[] create(String document, ITextRegion selection, int offset, XtextResource resource) {
	this.document = document;
	this.selection = selection;
	this.resource = resource;
	//This is called to make sure late initialization is done.
	if (resource instanceof DerivedStateAwareResource) {
		resource.getContents();
	}
	this.parseResult = resource.getParseResult();
	if (parseResult == null)
		throw new NullPointerException("parseResult is null");
	return doCreateContexts(offset);
}
 
Example #10
Source File: EcoreUtil2Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testClone_2() throws Exception {
	ResourceSetImpl sourceSet = new DerivedStateAwareResourceSet();
	DerivedStateAwareResource resource = (DerivedStateAwareResource) sourceSet.createResource(URI
			.createURI("http://derived.res"));
	boolean stateToCheck = !resource.isFullyInitialized();
	resource.setFullyInitialized(stateToCheck);
	
	Resource targetRes = EcoreUtil2.clone(new DerivedStateAwareResourceSet(), sourceSet).getResources().get(0);
	
	assertTrue(targetRes instanceof DerivedStateAwareResource);
	assertEquals("FullyInitialized flag not copied ", stateToCheck, ((DerivedStateAwareResource) targetRes).isFullyInitialized());
}
 
Example #11
Source File: LogicalContainerAwareBatchTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void validateResourceState(Resource resource) {
	super.validateResourceState(resource);
	if (resource instanceof DerivedStateAwareResource && ((DerivedStateAwareResource) resource).isInitializing()) {
		LOG.error("Discouraged attempt to compute types during model inference. Resource was : "+resource.getURI(), new Exception());
	}
	if (resource instanceof JvmMemberInitializableResource && ((JvmMemberInitializableResource) resource).isInitializingJvmMembers()) {
		LOG.error("Discouraged attempt to compute types during JvmMember initialization. Resource was : "+resource.getURI(), new Exception());
	}
}
 
Example #12
Source File: TypeDeclarationAwareBatchTypeResolver.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks the internal state of the resource and logs if type resolution was triggered unexpectedly.
 * If such a condition is detected, an {@link IllegalStateException exception} is thrown.
 * 
 * @throws IllegalStateException if the resource is in an unexpected state.
 */
@Override
protected void validateResourceState(Resource resource) {
	if (resource instanceof StorageAwareResource && ((StorageAwareResource) resource).isLoadedFromStorage()) {
		throw new IllegalStateException("Discouraged attempt to compute types for resource that was loaded from storage. Resource was : "+resource.getURI());
	}
	if (resource instanceof DerivedStateAwareResource && ((DerivedStateAwareResource) resource).isInitializing()) {
		throw new IllegalStateException("Discouraged attempt to compute types during model inference. Resource was : "+resource.getURI());
	}
	if (resource instanceof JvmMemberInitializableResource && ((JvmMemberInitializableResource) resource).isInitializingJvmMembers()) {
		throw new IllegalStateException("Discouraged attempt to compute types during JvmMember initialization. Resource was : "+resource.getURI());
	}
}
 
Example #13
Source File: XtendResourceSetBasedResourceDescriptionsTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUnloadedInstallDerivedStateThrowsException() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo class ClassA extends bar.ClassB {}");
    Pair<String, String> _mappedTo = Pair.<String, String>of("foo/ClassA.xtend", _builder.toString());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package bar class ClassB { public foo.ClassA myField }");
    Pair<String, String> _mappedTo_1 = Pair.<String, String>of("bar/ClassB.xtend", _builder_1.toString());
    final ResourceSet resourceSet = this.compiler.unLoadedResourceSet(_mappedTo, _mappedTo_1);
    final List<? extends Resource> resources = resourceSet.getResources();
    ArrayList<Resource> _arrayList = new ArrayList<Resource>(resources);
    for (final Resource res : _arrayList) {
      {
        Assert.assertFalse(res.isLoaded());
        try {
          ((DerivedStateAwareResource) res).installDerivedState(true);
          Assert.fail("expected exception");
        } catch (final Throwable _t) {
          if (_t instanceof IllegalStateException) {
          } else {
            throw Exceptions.sneakyThrow(_t);
          }
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #14
Source File: DefaultJvmModelRenameStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void setInferredJvmElementName(String name, EObject renamedElement) {
	// This only works if the elements keep their EObject fragment on rename.
	// 
	// In case you modified the IFragmentProvider or if you did something bad in 
	// createDeclarationChange, you must implement this method without discarding 
	// the inferred model.
	if (renamedElement.eResource() instanceof DerivedStateAwareResource) {
		DerivedStateAwareResource resource = (DerivedStateAwareResource) renamedElement.eResource();
		resource.discardDerivedState();
		resource.installDerivedState(false);
	}
}
 
Example #15
Source File: HighlightingReconciler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.8
 */
protected void beforeRefresh(XtextResource resource, CancelIndicator cancelIndicator) {
	if (resource instanceof DerivedStateAwareResource)
		resource.getContents(); // trigger derived state computation
	if (resource instanceof IBatchLinkableResource)
		((IBatchLinkableResource) resource).linkBatched(cancelIndicator);
}
 
Example #16
Source File: ParserBasedContentAssistContextFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ContentAssistContext[] create(ITextViewer viewer, int offset, XtextResource resource)
		throws BadLocationException {
	this.viewer = viewer;
	this.resource = resource;
	//This is called to make sure late initialization is done.
	if (resource instanceof DerivedStateAwareResource) {
		resource.getContents();
	}
	this.parseResult = resource.getParseResult();
	if (parseResult == null)
		throw new NullPointerException("parseResult is null");
	return doCreateContexts(offset);
}
 
Example #17
Source File: SerializerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSerialize_ExtrasIssue164_02() throws Exception {
	DerivedStateAwareResource resource = (DerivedStateAwareResource) newResource("org.eclipse.xtext.xbase.tests.serializer.SerializerTest.Demo.getDemo2(1)");
	XMemberFeatureCall call = (XMemberFeatureCall) resource.getContents().get(0);
	ISerializer serializer = get(ISerializer.class);
	call.eAdapters().clear();
	String string = serializer.serialize(call);
	assertEquals("org.eclipse.xtext.xbase.tests.serializer.SerializerTest.Demo.getDemo2(1)", string);
}
 
Example #18
Source File: SerializerTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSerialize_ExtrasIssue164() throws Exception {
	DerivedStateAwareResource resource = (DerivedStateAwareResource) newResource("org.eclipse.xtext.xbase.tests.serializer.SerializerTest.Demo.demo");
	XMemberFeatureCall call = (XMemberFeatureCall) resource.getContents().get(0);
	ISerializer serializer = get(ISerializer.class);
	call.eAdapters().clear();
	String string = serializer.serialize(call);
	assertEquals("org.eclipse.xtext.xbase.tests.serializer.SerializerTest.Demo.demo", string);
}
 
Example #19
Source File: DerivedStateAwareResourceValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void validate(Resource resource, CheckMode mode, CancelIndicator monitor, IAcceptor<Issue> acceptor) {
	getOperationCanceledManager().checkCanceled(monitor);
	if (resource instanceof DerivedStateAwareResource) {
		List<EObject> contents = resource.getContents();
		if (!contents.isEmpty()) {
			validate(resource, contents.get(0), mode, monitor, acceptor);
		}
	} else {
		super.validate(resource, mode, monitor, acceptor);
	}
}
 
Example #20
Source File: GrammarResource.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void discardDerivedState(DerivedStateAwareResource resource) {
}
 
Example #21
Source File: UnloadingTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testProperUnloading() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class B {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def void foo() {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("new A(this)");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String fileB = _builder.toString();
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("class A {");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("new (B b) {");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("}");
    _builder_1.newLine();
    _builder_1.append("}");
    _builder_1.newLine();
    final List<XtendFile> parsedFiles = IterableExtensions.<XtendFile>toList(this.files(true, _builder_1.toString(), fileB));
    Resource _eResource = parsedFiles.get(1).eResource();
    final DerivedStateAwareResource resource = ((DerivedStateAwareResource) _eResource);
    final Resource resourceA = IterableExtensions.<XtendFile>head(parsedFiles).eResource();
    resource.reparse(fileB);
    EObject _head = IterableExtensions.<EObject>head(resourceA.getContents());
    final XtendFile file = ((XtendFile) _head);
    XtendTypeDeclaration _head_1 = IterableExtensions.<XtendTypeDeclaration>head(file.getXtendTypes());
    XtendMember _head_2 = IterableExtensions.<XtendMember>head(((XtendClass) _head_1).getMembers());
    Assert.assertNotNull(IterableExtensions.<XtendParameter>head(((XtendConstructor) _head_2).getParameters()).getParameterType().getType().eResource());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #22
Source File: EcoreUtil2Test.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Resource createResource(URI uri) {
	DerivedStateAwareResource result = new DerivedStateAwareResource();
	getResources().add(result);
	return result;
}
 
Example #23
Source File: JvmModelAssociator.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
public JvmDeclaredTypeAcceptor(DerivedStateAwareResource resource) {
	this.resource = resource;
}
 
Example #24
Source File: JvmModelAssociator.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void discardDerivedState(DerivedStateAwareResource resource) {
	cleanAssociationState(resource);
}