org.eclipse.xtext.diagnostics.ExceptionDiagnostic Java Examples

The following examples show how to use org.eclipse.xtext.diagnostics.ExceptionDiagnostic. 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: ExceptionAnalyser.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<Diagnostic> getScriptErrors(Script script) {
	EcoreUtil.resolveAll(script.eResource());
	List<Diagnostic> diagnostics = super.getScriptErrors(script);
	Iterator<TypableElement> typableASTNodes = Iterators.filter(EcoreUtil2.eAll(script), TypableElement.class);
	List<Diagnostic> result = Lists.<Diagnostic> newArrayList(Iterables.filter(diagnostics,
			ExceptionDiagnostic.class));
	while (typableASTNodes.hasNext()) {
		TypableElement typableASTNode = typableASTNodes.next();
		RuleEnvironment ruleEnvironment = RuleEnvironmentExtensions.newRuleEnvironment(typableASTNode);
		try {
			typeSystem.type(ruleEnvironment, typableASTNode);
		} catch (Throwable cause) {
			if (cause instanceof Exception) {
				result.add(new ExceptionDiagnostic((Exception) cause));
			} else {
				throw new RuntimeException(cause);
			}
		}
	}
	validator.validate(script.eResource(), CheckMode.ALL, CancelIndicator.NullImpl);
	return result;
}
 
Example #2
Source File: AbstractXtextTests.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
	XtextResource resource = doGetResource(in, uri);
	checkNodeModel(resource);
	if (expectedErrors != UNKNOWN_EXPECTATION) {
		if (expectedErrors == EXPECT_ERRORS)
			assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
		else
			assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
	}
	for(Diagnostic d: resource.getErrors()) {
		if (d instanceof ExceptionDiagnostic)
			fail(d.getMessage());
	}
	if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
		SerializerTestHelper tester = get(SerializerTestHelper.class);
		EObject obj = resource.getContents().get(0);
		tester.assertSerializeWithNodeModel(obj);
		tester.assertSerializeWithoutNodeModel(obj);
	}
	return resource;
}
 
Example #3
Source File: AbstractXtextTests.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
	XtextResource resource = doGetResource(in, uri);
	checkNodeModel(resource);
	if (expectedErrors != UNKNOWN_EXPECTATION) {
		if (expectedErrors == EXPECT_ERRORS)
			assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
		else
			assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
	}
	for(Diagnostic d: resource.getErrors()) {
		if (d instanceof ExceptionDiagnostic)
			fail(d.getMessage());
	}
	if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
		SerializerTester tester = get(SerializerTester.class);
		EObject obj = resource.getContents().get(0);
		tester.assertSerializeWithNodeModel(obj);
		tester.assertSerializeWithoutNodeModel(obj);
	}
	return resource;
}
 
Example #4
Source File: XtextLinker.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void linkModel(EObject model, IDiagnosticConsumer consumer) {
	if (model instanceof Grammar) {
		final Xtext2EcoreTransformer transformer = createTransformer((Grammar) model, consumer);
		//TODO duplicate
		transformer.removeGeneratedPackages();
		super.linkModel(model, consumer);
		updateOverriddenRules((Grammar) model);
		try {
			transformer.transform();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			consumer.consume(new ExceptionDiagnostic(e), Severity.ERROR);
		}
		if (!model.eResource().eAdapters().contains(packageRemover))
			model.eResource().eAdapters().add(packageRemover);
	} else {
		super.linkModel(model, consumer);
	}
}
 
Example #5
Source File: LazyLinkingResource.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public synchronized EObject getEObject(String uriFragment) {
	try {
		if (getEncoder().isCrossLinkFragment(this, uriFragment)) {
			Triple<EObject, EReference, INode> triple = getEncoder().decode(this, uriFragment);
			return getEObject(uriFragment, triple);
		}
	} catch (RuntimeException e) {
		operationCanceledManager.propagateAsErrorIfCancelException(e);
		getErrors().add(new ExceptionDiagnostic(e));
		log.error("resolution of uriFragment '" + uriFragment + "' failed.", e);
		// wrapped because the javaDoc of this method states that WrappedExceptions are thrown
		// logged because EcoreUtil.resolve will ignore any exceptions.
		throw new WrappedException(e);
	}
	return super.getEObject(uriFragment);
}
 
Example #6
Source File: AbstractXtextTests.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
	XtextResource resource = doGetResource(in, uri);
	checkNodeModel(resource);
	if (expectedErrors != UNKNOWN_EXPECTATION) {
		if (expectedErrors == EXPECT_ERRORS)
			assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
		else
			assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
	}
	for(Diagnostic d: resource.getErrors()) {
		if (d instanceof ExceptionDiagnostic)
			fail(d.getMessage());
	}
	if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
		SerializerTestHelper tester = get(SerializerTestHelper.class);
		EObject obj = resource.getContents().get(0);
		tester.assertSerializeWithNodeModel(obj);
		tester.assertSerializeWithoutNodeModel(obj);
	}
	return resource;
}
 
Example #7
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNoException_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals import \'http://www.eclipse.org/emf/2002/Ecore\' as ecore generate test \'http://test\'");
  _builder.newLine();
  _builder.append("CompositeModel: (model+=Model)+;");
  _builder.newLine();
  _builder.append("Model: id=NestedModelId (\':\' value=Fraction)? (\'#\' vector=Vector)? (\'+\' dots=Dots)? \';\'");
  _builder.newLine();
  _builder.append("ModelId returns ecore::EString: ID \'.\' ID;");
  _builder.newLine();
  _builder.append("NestedModelId : ModelId \'.\' ModelId;");
  _builder.newLine();
  _builder.append("Fraction returns EBigDecimal: INT (\'/\' INT)?;");
  _builder.newLine();
  _builder.append("Vector : \'(\' INT I");
  String grammar = _builder.toString();
  final XtextResource resource = this.getResourceFromStringAndExpect(grammar, 10);
  EList<Resource.Diagnostic> _errors = resource.getErrors();
  for (final Resource.Diagnostic d : _errors) {
    Assert.assertFalse((d instanceof ExceptionDiagnostic));
  }
}
 
Example #8
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNoException_02() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals generate test \'http://test\'");
  _builder.newLine();
  _builder.append("Model: (children+=Element)*;");
  _builder.newLine();
  _builder.append("Element returns Type: Item ( { Item.items+=current } items+=Item );");
  _builder.newLine();
  _builder.append("Item returns Type:\t{ T");
  String grammar = _builder.toString();
  final XtextResource resource = this.getResourceFromStringAndExpect(grammar, 1);
  EList<Resource.Diagnostic> _errors = resource.getErrors();
  for (final Resource.Diagnostic d : _errors) {
    Assert.assertFalse((d instanceof ExceptionDiagnostic));
  }
}
 
Example #9
Source File: BaseAnalyser.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
// TODO after java update bring back null analysis
// protected StringBuilder agregateDiagnosticsToStringBuilder(@Nonnull final List<Diagnostic> issues) {
protected StringBuilder aggregateDiagnosticsToStringBuilder(String codeName, final List<Diagnostic> issues) {
	StringBuilder result = new StringBuilder(codeName).append('\n');
	for (Diagnostic diagnostic : issues) {
		if (diagnostic instanceof ExceptionDiagnostic) {
			((ExceptionDiagnostic) diagnostic).getException().printStackTrace();
		}
		result.append(" - line: " + diagnostic.getLine() + ", message: " + diagnostic.getMessage() + "\n");
	}
	return result;
}
 
Example #10
Source File: BatchLinkableResource.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * Delegates to the {@link BatchLinkingService} if the requested reference is 
 * {@link BatchLinkingService#isBatchLinkable(EReference) linkeable in batch mode}.
 * 
 * Implementation detail: This specialization of {@link #getEObject(String) getEObject}
 * synchronizes on the {@link #getLock() lock} which is exposed by the synchronizable
 * resource rather than on the resource directly. This guards against reentrant resolution
 * from different threads that could block each other.
 * 
 * Usually one would want to lock only in the {@link BatchLinkingService} but we could
 * have intermixed {@link LazyURIEncoder#isCrossLinkFragment(org.eclipse.emf.ecore.resource.Resource, String)
 * lazy cross reference} and vanilla EMF cross references which again could lead to a
 * dead lock.
 */
@Override
public EObject getEObject(String uriFragment) {
	synchronized (getLock()) {
		try {
			if (getEncoder().isCrossLinkFragment(this, uriFragment) && !isLoadedFromStorage()) {
				if (!getUnresolvableURIFragments().contains(uriFragment)) {
					Triple<EObject, EReference, INode> triple = getEncoder().decode(this, uriFragment);
					if (batchLinkingService.isBatchLinkable(triple.getSecond())) {
						if (compilerPhases.isIndexing(this))
							log.error("Don't resolve expressions during indexing!", new IllegalStateException("Resource URI : "+getURI()+", fragment : "+uriFragment));
						return batchLinkingService.resolveBatched(triple.getFirst(), triple.getSecond(), uriFragment);
					}
					return getEObject(uriFragment, triple);
				} else {
					return null;
				}
			}
			return super.getEObject(uriFragment);
		} catch (RuntimeException e) {
			operationCanceledManager.propagateAsErrorIfCancelException(e);
			getErrors().add(new ExceptionDiagnostic(e));
			log.error("resolution of uriFragment '" + uriFragment + "' failed.", e);
			// wrapped because the javaDoc of this method states that WrappedExceptions are thrown
			// logged because EcoreUtil.resolve will ignore any exceptions.
			throw new WrappedException(e);
		}
	}
}
 
Example #11
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 #12
Source File: ResourceLoadTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void assertNoExceptionDiagnostic(Resource r, String model) throws Exception {
	for (Diagnostic d : r.getErrors()) {
		if (d instanceof ExceptionDiagnostic) {
			throw new Exception(model, ((ExceptionDiagnostic) d).getException());
		}
	}
}
 
Example #13
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug_272566_3() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate test \'http://test\'");
  _builder.newLine();
  _builder.append("Model:");
  _builder.newLine();
  _builder.append("   ");
  _builder.append("test=Test");
  _builder.newLine();
  _builder.append(";");
  _builder.newLine();
  _builder.newLine();
  _builder.append("Test:");
  _builder.newLine();
  _builder.append("   ");
  _builder.append("\"keyword\" MyEnum name=ID");
  _builder.newLine();
  _builder.append(";");
  _builder.newLine();
  _builder.append("enum MyEnum:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("A | B;");
  _builder.newLine();
  String grammar = _builder.toString();
  final XtextResource resource = this.getResourceFromStringAndExpect(grammar, 1);
  Assert.assertFalse(resource.getErrors().toString(), resource.getErrors().isEmpty());
  EList<Resource.Diagnostic> _errors = resource.getErrors();
  for (final Resource.Diagnostic d : _errors) {
    Assert.assertFalse((d instanceof ExceptionDiagnostic));
  }
}
 
Example #14
Source File: ExceptionTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private void assertNoException(String model, int expectedErrors) throws Exception {
	Resource r = getResourceFromStringAndExpect(model, expectedErrors);
	Iterable<ExceptionDiagnostic> filtered = Iterables.filter(r.getErrors(), ExceptionDiagnostic.class);
	assertNotNull(filtered);
	assertFalse(filtered.iterator().hasNext());
}
 
Example #15
Source File: LazyLinkingResource2.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public synchronized EObject getEObject(final String uriFragment) {
  try {
    final EObject result = super.getEObject(uriFragment);
    if (result == null && getEncoder().isCrossLinkFragment(this, uriFragment)) {
      final ResourceSet rs = getResourceSet();
      if (rs.getLoadOptions().get(MARK_UNRESOLVABLE_XREFS) == Boolean.FALSE) {
        Triple<EObject, EReference, INode> refInfo = getEncoder().decode(this, uriFragment);
        EReference reference = refInfo.getSecond();
        EObject context = refInfo.getFirst();
        LOGGER.warn("Failed unexpected attempt to resolve reference during indexing " + context.eClass().getName() + "#" //$NON-NLS-1$ //$NON-NLS-2$
            + reference.getName() + " for object " + EcoreUtil.getURI(context), new RuntimeException()); //$NON-NLS-1$
        rs.getLoadOptions().put(MARK_UNRESOLVABLE_XREFS, Boolean.TRUE);
      }
    }
    return result;
  } catch (FastLazyURIEncoder.DecodingError err) {
    RuntimeException cause = err.getCause();
    getErrors().add(new ExceptionDiagnostic(cause));
    throw new WrappedException(cause);
  } catch (WrappedException e) {
    boolean logged = false;
    try {
      if (getEncoder().isCrossLinkFragment(this, uriFragment)) {
        Triple<EObject, EReference, INode> triple = getEncoder().decode(this, uriFragment);
        INode node = triple.getThird();
        final String nodeName = getLinkingHelper().getCrossRefNodeAsString(node, true);
        LOGGER.error("Resolution of uriFragment '" + uriFragment + "' in the resource '" + this.getURI() + "' node_name " + nodeName //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            + " line " + node.getStartLine() + " offset " + node.getOffset() + " failed.", e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        logged = true;
      }
      // CHECKSTYLE:OFF
    } catch (RuntimeException e1) {
      // CHECKSTYLE:ON
      // ignore
    }
    if (!logged) {
      LOGGER.error("Resolution of uriFragment '" + uriFragment + "' in the resource '" + this.getURI() + "' failed.", e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }
    throw e;
  }
}