org.eclipse.xtext.diagnostics.AbstractDiagnostic Java Examples

The following examples show how to use org.eclipse.xtext.diagnostics.AbstractDiagnostic. 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: AbstractValidationTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Persist list diagnostics into string to display the list of issue codes.
 *
 * @param diagnostics
 *          list of diagnostics
 * @param displayPathToTargetObject
 *          if true, the path through the object hierarchy is printed out up to the root node
 * @return
 *         string with list of issue codes, separated with a line break
 */
// TODO (ACF-4153) generalize for all kinds of errors and move to AbstractXtextTest
private String diagnosticsToString(final List<Resource.Diagnostic> diagnostics, final boolean displayPathToTargetObject) {
  StringBuilder sb = new StringBuilder();
  for (Resource.Diagnostic diagnostic : diagnostics) {
    if (diagnostic instanceof AbstractDiagnostic) {
      AbstractDiagnostic diag = (AbstractDiagnostic) diagnostic;
      sb.append("    ");
      sb.append(diag.getCode());
      if (displayPathToTargetObject) {
        sb.append(" at line: ");
        sb.append(diag.getLine());
        sb.append(" on \n");
        sb.append("      ");
        sb.append(diag.getUriToProblem());
      }
      sb.append(LINE_BREAK);
    }
  }
  return sb.toString();
}
 
Example #2
Source File: DiagnosticConverterImpl.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void convertResourceDiagnostic(Diagnostic diagnostic, Severity severity,	IAcceptor<Issue> acceptor) {
	IssueImpl issue = new Issue.IssueImpl();
	issue.setSyntaxError(diagnostic instanceof XtextSyntaxDiagnostic);
	issue.setSeverity(severity);
	issue.setLineNumber(diagnostic.getLine());
	issue.setColumn(diagnostic.getColumn());
	issue.setMessage(diagnostic.getMessage());

	if (diagnostic instanceof org.eclipse.xtext.diagnostics.Diagnostic) {
		org.eclipse.xtext.diagnostics.Diagnostic xtextDiagnostic = (org.eclipse.xtext.diagnostics.Diagnostic) diagnostic;
		issue.setOffset(xtextDiagnostic.getOffset());
		issue.setLength(xtextDiagnostic.getLength());
	}
	if (diagnostic instanceof AbstractDiagnostic) {
		AbstractDiagnostic castedDiagnostic = (AbstractDiagnostic)diagnostic;
		issue.setUriToProblem(castedDiagnostic.getUriToProblem());
		issue.setCode(castedDiagnostic.getCode());
		issue.setData(castedDiagnostic.getData());
		issue.setLineNumberEnd(castedDiagnostic.getLineEnd());
		issue.setColumnEnd(castedDiagnostic.getColumnEnd());
	}
	issue.setType(CheckType.FAST);
	acceptor.accept(issue);
}
 
Example #3
Source File: TypeInsteadOfConstructorLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	JvmType type = (JvmType) description.getElementOrProxy();
	String typeKind = "";
	if (type instanceof JvmPrimitiveType || type instanceof JvmVoid) {
		typeKind = "primitive type";
	} else if (type instanceof JvmAnnotationType) {
		typeKind = "annotation type";
	} else if (type instanceof JvmEnumerationType) {
		typeKind = "enum type";
	} else if (type instanceof JvmGenericType && ((JvmGenericType) type).isInterface()) {
		typeKind = "interface type";
	} else if (type instanceof JvmTypeParameter) {
		typeKind = "type parameter";
	}
	String message = String.format("Cannot instantiate the %s %s", typeKind, type.getSimpleName());
	AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
			IssueCodes.ILLEGAL_CLASS_INSTANTIATION, message, getExpression(),
			XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR, -1, null);
	result.accept(diagnostic);
	return false;
}
 
Example #4
Source File: RootResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected AbstractDiagnostic createTypeDiagnostic(XExpression expression, LightweightTypeReference actualType, LightweightTypeReference expectedType) {
	if (!expectedType.isAny()) {
		String actualName = actualType.getSimpleName();
		String expectedName = expectedType.getSimpleName();
		if (actualName.equals(expectedName)) {
			if (expectedType.isAssignableFrom(actualType)) {
				return null;
			}
		}
		if (expression.eContainingFeature() == XbasePackage.Literals.XABSTRACT_FEATURE_CALL__IMPLICIT_FIRST_ARGUMENT) {
			return new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.INCOMPATIBLE_TYPES, String.format(
					"Type mismatch: cannot convert implicit first argument from %s to %s", actualType.getHumanReadableName(), expectedType.getHumanReadableName()),
					expression, null, -1, null);
		} else {
			return new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.INCOMPATIBLE_TYPES, String.format(
					"Type mismatch: cannot convert from %s to %s", actualType.getHumanReadableName(), expectedType.getHumanReadableName()),
					expression, null, -1, null);
		}
	} else {
		return new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.INCOMPATIBLE_TYPES, String.format(
				"Type mismatch: type %s is not applicable at this location", actualType.getHumanReadableName()), expression, null, -1,
				null);
	}
}
 
Example #5
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean validateTypeArity(IAcceptor<? super AbstractDiagnostic> result) {
	if (getTypeArityMismatch() != 0) {
		String message = String.format("Invalid number of type arguments. The %1$s %2$s%3$s is not applicable for the type arguments %4$s",
				getFeatureTypeName(), 
				getSimpleFeatureName(), 
				getFeatureTypeParametersAsString(true),
				getTypeArgumentsAsString(getSyntacticTypeArguments()));
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				Severity.ERROR, 
				IssueCodes.INVALID_NUMBER_OF_TYPE_ARGUMENTS, 
				message, 
				getExpression(), 
				getDefaultValidationFeature(), -1, null);
		result.accept(diagnostic);
		return false;
	}
	return true;
}
 
Example #6
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean validateArity(IAcceptor<? super AbstractDiagnostic> result) {
	if (getArityMismatch() != 0) {
		String message; 
		if (getArguments().isEmpty()) {
			message = String.format("Invalid number of arguments. The %1$s %2$s%3$s is not applicable without arguments" , 
					getFeatureTypeName(), 
					getSimpleFeatureName(), 
					getFeatureParameterTypesAsString());
		} else {
			message = String.format("Invalid number of arguments. The %1$s %2$s%3$s is not applicable for the arguments %4$s" , 
					getFeatureTypeName(), 
					getSimpleFeatureName(), 
					getFeatureParameterTypesAsString(), 
					getArgumentTypesAsString());
		}
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				Severity.ERROR, 
				IssueCodes.INVALID_NUMBER_OF_ARGUMENTS, 
				message, 
				getExpression(), 
				getInvalidArgumentsValidationFeature(), -1, null);
		result.accept(diagnostic);
		return false;
	}
	return true;
}
 
Example #7
Source File: ConstructorLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	JvmDeclaredType declaringType = getConstructor().getDeclaringType();
	if (declaringType.isAbstract()) {
		String message = "Cannot instantiate the abstract type " + declaringType.getSimpleName();
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				Severity.ERROR, 
				IssueCodes.ABSTRACT_CLASS_INSTANTIATION, 
				message, 
				getExpression(), 
				getDefaultValidationFeature(), -1, null);
		result.accept(diagnostic);
		return false;
	}
	return super.validate(result);
}
 
Example #8
Source File: SuspiciouslyOverloadedCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	if (chosenCandidate.validate(result)) {
		StringBuilder messageBuilder = new StringBuilder("Suspiciously overloaded method.\n");
		messageBuilder.append("The ").append(getFeatureTypeName()).append("\n\t");
		appendCandidate(chosenCandidate, messageBuilder);
		messageBuilder.append("\noverloads the ").append(getFeatureTypeName()).append("\n\t");
		appendCandidate(rejectedCandidate, messageBuilder);
		messageBuilder.append(".");
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(chosenCandidate.getSeverity(IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE),
				IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE, messageBuilder.toString(), getExpression(),
				XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
		result.accept(diagnostic);
	}
	return false;
}
 
Example #9
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean validateVisibility(IAcceptor<? super AbstractDiagnostic> result) {
	if (!isVisible()) {
		String message = String.format("The %1$s %2$s%3$s is not visible", 
				getFeatureTypeName(),
				getSimpleFeatureName(),
				getFeatureParameterTypesAsString());
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				Severity.ERROR, 
				IssueCodes.FEATURE_NOT_VISIBLE, 
				message, 
				getExpression(), 
				getDefaultValidationFeature(), -1, null);
		result.accept(diagnostic);
		return false;
	}
	return true;
}
 
Example #10
Source File: ImplicitFirstArgument.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	if (!getState().isInstanceContext()) {
		JvmIdentifiableElement implicitFeature = getFeature();
		if (implicitFeature instanceof JvmType) {
			JvmIdentifiableElement feature = getState().getResolvedTypes().getLinkedFeature(getOwner());
			if (feature == null || feature.eIsProxy() || !(feature instanceof JvmFeature))
				return true;
			String message = "Cannot make an implicit reference to this from a static context";
			AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(Severity.ERROR,
					IssueCodes.STATIC_ACCESS_TO_INSTANCE_MEMBER, message, getOwner(),
					XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
			result.accept(diagnostic);
			return false;
		}
	}
	return super.validate(result);
}
 
Example #11
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Validates this linking candidate and adds respective diagnostics to the given queue.
 * 
 * This checks the following criteria:
 * <ol>
 * <li>{@link #validateVisibility(IAcceptor) visibility},</li>
 * <li>{@link #validateArity(IAcceptor) arity},</li>
 * <li>{@link #validateTypeArity(IAcceptor) type arity},</li>
 * <li>{@link #validateTypeArgumentConformance(IAcceptor) type arguments},</li>
 * <li>{@link #validateUnhandledExceptions(IAcceptor) unhandled excptions},</li>
 * </ol>
 */
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	if (!validateVisibility(result)) {
		return false;
	}
	if (!validateArity(result)) {
		return false;
	}
	if (!validateTypeArity(result)) {
		return false;
	}
	if (!validateTypeArgumentConformance(result)) {
		return false;
	}
	if (!validateUnhandledExceptions(result)) {
		return false;
	}
	return true;
}
 
Example #12
Source File: RootResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void addDiagnostics(final Resource resource) {
	if (resource instanceof XtextResource) {
		if (((XtextResource) resource).isValidationDisabled())
			return;
	}
	class DiagnosticAcceptor implements IAcceptor<AbstractDiagnostic> {

		@Override
		public void accept(/* @Nullable */ AbstractDiagnostic diagnostic) {
			if (diagnostic instanceof EObjectDiagnosticImpl) {
				Severity severity = ((EObjectDiagnosticImpl) diagnostic).getSeverity();
				if (severity == Severity.ERROR) {
					resource.getErrors().add(diagnostic);
				} else if (severity == Severity.WARNING) {
					resource.getWarnings().add(diagnostic);
				}
			} else {
				resource.getErrors().add(diagnostic);
			}
		}
		
	}
	DiagnosticAcceptor acceptor = new DiagnosticAcceptor();
	addQueuedDiagnostics(acceptor);
	addLinkingDiagnostics(acceptor);
	addTypeDiagnostics(acceptor);
}
 
Example #13
Source File: SuspiciousOverloadedCastOperatorLinkingCandidate.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	final CastOperatorLinkingCandidate ccandidate = getChosenCandidate();
	if (ccandidate.validate(result)) {
		final String message = MessageFormat.format(
				Messages.SuspiciousOverloadedCastOperatorLinkingCandidate_0,
				ccandidate.getValidationDescription(), getRejectedCandidate().toString());
		final AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				ccandidate.getState().getSeverity(IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE),
				IssueCodes.SUSPICIOUSLY_OVERLOADED_FEATURE, message, getExpression(),
				XbasePackage.Literals.XABSTRACT_FEATURE_CALL__FEATURE, -1, null);
		result.accept(diagnostic);
	}
	return false;
}
 
Example #14
Source File: RootResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void addTypeDiagnostics(IAcceptor<? super AbstractDiagnostic> acceptor) {
	for(Map.Entry<XExpression, List<TypeData>> entry: basicGetExpressionTypes().entrySet()) {
		XExpression expression = entry.getKey();
		if (!isPropagatedType(expression))
			addTypeDiagnostic(expression, mergeTypeData(expression, entry.getValue(), false, false), acceptor);
	}
}
 
Example #15
Source File: FeatureLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected boolean validateArity(IAcceptor<? super AbstractDiagnostic> result) {
	if (getFeatureCall() instanceof XFeatureCall) {
		XExpression implicitReceiver = getImplicitReceiver();
		if (implicitReceiver instanceof XFeatureCall) {
			JvmIdentifiableElement feature = ((XFeatureCall) implicitReceiver).getFeature();
			if (feature instanceof JvmType && !getState().isInstanceContext()) {
				return false;
			}
		}
	}
	return super.validateArity(result);
}
 
Example #16
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean validateTypeArgumentConformance(IAcceptor<? super AbstractDiagnostic> result) {
	if (getTypeArgumentConformanceFailures(result) == 0) {
		// TODO use early exit computation
		List<XExpression> arguments = getSyntacticArguments();
		for(int i = 0; i < arguments.size(); i++) {
			XExpression argument = arguments.get(i);
			if (isDefiniteEarlyExit(argument)) {
				XExpression errorOn = getExpression();
				String message = "Unreachable code.";
				EStructuralFeature errorFeature = null;
				if (i < arguments.size() - 1) {
					errorOn = arguments.get(i + 1);
				} else {
					errorFeature = getDefaultValidationFeature();
					if (errorOn instanceof XBinaryOperation) {
						message = "Unreachable code. The right argument expression does not complete normally.";
					} else {
						message = "Unreachable code. The last argument expression does not complete normally.";
					}
				}
				AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
						Severity.ERROR, 
						IssueCodes.UNREACHABLE_CODE, 
						message, 
						errorOn, 
						errorFeature, 
						-1, null);
				result.accept(diagnostic);
				return false;
			}
		}
	} else {
		return false;
	}
	return true;
}
 
Example #17
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean validateUnhandledExceptions(IAcceptor<? super AbstractDiagnostic> result) {
	if (getFeature() instanceof JvmExecutable) {
		JvmExecutable executable = (JvmExecutable) getFeature();
		if (getUnhandledExceptionSeverity(executable) != Severity.IGNORE) {
			if (!executable.getExceptions().isEmpty()) {
				return validateUnhandledExceptions(executable, result);
			}
		}
	}
	return true;
}
 
Example #18
Source File: ResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public void addDiagnostic(AbstractDiagnostic diagnostic) {
	if (diagnostics == null) {
		diagnostics = Sets.newLinkedHashSet();
	}
	if (!diagnostics.add(diagnostic)) {
		throw new IllegalStateException("Duplicate diagnostic: " + diagnostic);
	}
}
 
Example #19
Source File: N4JSDiagnosticConverter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void convertResourceDiagnostic(Diagnostic diagnostic, Severity severity, IAcceptor<Issue> acceptor) {
	// START: Following copied from super method
	LSPIssue issue = new LSPIssue(); // Changed
	issue.setSyntaxError(diagnostic instanceof XtextSyntaxDiagnostic);
	issue.setSeverity(severity);
	issue.setLineNumber(diagnostic.getLine());
	issue.setColumn(diagnostic.getColumn());
	issue.setMessage(diagnostic.getMessage());

	if (diagnostic instanceof org.eclipse.xtext.diagnostics.Diagnostic) {
		org.eclipse.xtext.diagnostics.Diagnostic xtextDiagnostic = (org.eclipse.xtext.diagnostics.Diagnostic) diagnostic;
		issue.setOffset(xtextDiagnostic.getOffset());
		issue.setLength(xtextDiagnostic.getLength());
	}
	if (diagnostic instanceof AbstractDiagnostic) {
		AbstractDiagnostic castedDiagnostic = (AbstractDiagnostic) diagnostic;
		issue.setUriToProblem(castedDiagnostic.getUriToProblem());
		issue.setCode(castedDiagnostic.getCode());
		issue.setData(castedDiagnostic.getData());

		// START: Changes here
		INode node = ReflectionUtils.getMethodReturn(AbstractDiagnostic.class, "getNode", diagnostic);
		int posEnd = castedDiagnostic.getOffset() + castedDiagnostic.getLength();
		LineAndColumn lineAndColumn = NodeModelUtils.getLineAndColumn(node, posEnd);
		issue.setLineNumberEnd(lineAndColumn.getLine());
		issue.setColumnEnd(lineAndColumn.getColumn());
		// END: Changes here
	}
	issue.setType(CheckType.FAST);
	acceptor.accept(issue);
	// END: Following copied from super method
}
 
Example #20
Source File: CompoundReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Collection<AbstractDiagnostic> getQueuedDiagnostics() {
	List<AbstractDiagnostic> result = Lists.newArrayList();
	for(IResolvedTypes delegate: this) {
		result.addAll(delegate.getQueuedDiagnostics());
	}
	return result;
}
 
Example #21
Source File: ExpectedExceptionsStackedResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void addDiagnostic(AbstractDiagnostic diagnostic) {
	getParent().addDiagnostic(diagnostic);
}
 
Example #22
Source File: AbstractValidationTest.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Check if the given issue code is found among issue codes for the object, located at the given position.
 *
 * @param root
 *          root object of the document
 * @param pos
 *          position to locate the target object
 */
@Override
public void apply(final EObject root, final Integer pos) {
  Iterable<Resource.Diagnostic> diagnostics = null;
  switch (expectedSeverity) {
  case Diagnostic.ERROR:
    diagnostics = root.eResource().getErrors();
    break;
  case Diagnostic.WARNING:
    diagnostics = root.eResource().getWarnings();
    break;
  case SEVERITY_UNDEFINED:
    diagnostics = Iterables.concat(root.eResource().getErrors(), root.eResource().getWarnings());
    break;
  }
  final List<Resource.Diagnostic> diagnosticsOnTargetPosition = Lists.newArrayList();
  boolean issueFound = false;
  int actualSeverity = expectedSeverity;
  boolean expectedMessageMatches = false;
  String actualMessage = "";

  for (AbstractDiagnostic diag : Iterables.filter(diagnostics, AbstractDiagnostic.class)) {
    if (diagnosticPositionEquals(pos, diag)) {
      // Add issue to the list of issues at the given position
      diagnosticsOnTargetPosition.add(diag);
      if (diag.getCode().equals(issueCode)) {
        issueFound = true;
        if (expectedSeverity == SEVERITY_UNDEFINED) {
          actualSeverity = root.eResource().getErrors().contains(diag) ? Diagnostic.ERROR : Diagnostic.WARNING;
        }
        actualMessage = diag.getMessage();
        // True if message matches with actual message or message is null
        expectedMessageMatches = message == null || actualMessage.equals(message);
        // Don't need to display error messages
        if (issueMustBeFound) {
          // Remove the diagnostic from the list of non-expected diagnostics
          getUnexpectedResourceDiagnostics().remove(diag);
          // Don't need to display error messages
          if (expectedMessageMatches) {
            return;
          }
        }
      }
    }
  }

  // Create error message
  createErrorMessage(pos, diagnosticsOnTargetPosition, issueFound, true, actualSeverity, expectedMessageMatches, actualMessage);
}
 
Example #23
Source File: AbstractClosureTypeHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	return true;
}
 
Example #24
Source File: ForwardingResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Collection<AbstractDiagnostic> getQueuedDiagnostics() {
	return delegate().getQueuedDiagnostics();
}
 
Example #25
Source File: ReassigningStackedResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void addDiagnostic(AbstractDiagnostic diagnostic) {
	getParent().addDiagnostic(diagnostic);
}
 
Example #26
Source File: IResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Collection<AbstractDiagnostic> getQueuedDiagnostics() {
	return Collections.emptyList();
}
 
Example #27
Source File: ResolvedTypes.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Collection<AbstractDiagnostic> getQueuedDiagnostics() {
	if (diagnostics == null)
		return Collections.emptyList();
	return diagnostics;
}
 
Example #28
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean validateUnhandledExceptions(JvmExecutable executable, IAcceptor<? super AbstractDiagnostic> result) {
	TypeParameterSubstitutor<?> substitutor = createArgumentTypeSubstitutor();
	List<LightweightTypeReference> unhandledExceptions = null;
	List<LightweightTypeReference> expectedExceptions = getState().getExpectedExceptions();
	ITypeReferenceOwner referenceOwner = getState().getReferenceOwner();
	outer: for(JvmTypeReference typeReference: executable.getExceptions()) {
		LightweightTypeReference exception = referenceOwner.toLightweightTypeReference(typeReference);
		LightweightTypeReference resolvedException = substitutor.substitute(exception);
		if (resolvedException.isSubtypeOf(Throwable.class) && !resolvedException.isSubtypeOf(RuntimeException.class) && !resolvedException.isSubtypeOf(Error.class)) {
			for (LightweightTypeReference expectedException : expectedExceptions) {
				if (expectedException.isAssignableFrom(resolvedException)) {
					continue outer;
				}
			}
			if (unhandledExceptions == null) {
				unhandledExceptions = Lists.newArrayList(resolvedException);
			} else {
				unhandledExceptions.add(resolvedException);
			}
		}
	}
	if (unhandledExceptions != null) {
		String message = null;
		int count = unhandledExceptions.size();
		if (count > 1) {
			message = String.format("Unhandled exception types %s and %s", 
					IterableExtensions.join(unhandledExceptions.subList(0, count - 1), ", "),
					unhandledExceptions.get(count - 1));
		} else {
			message = String.format("Unhandled exception type %s", unhandledExceptions.get(0).getHumanReadableName());
		}
		String[] data = new String[unhandledExceptions.size() + 1];
		for(int i = 0; i < data.length - 1; i++) {
			LightweightTypeReference unhandled = unhandledExceptions.get(i);
			data[i] = EcoreUtil.getURI(unhandled.getType()).toString();
		}
		data[data.length - 1] = EcoreUtil.getURI(getExpression()).toString();
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				getUnhandledExceptionSeverity(executable), 
				IssueCodes.UNHANDLED_EXCEPTION,
				message, 
				getExpression(),
				getDefaultValidationFeature(), 
				-1, 
				data);
		result.accept(diagnostic);
		return false;
	}
	return true;
}
 
Example #29
Source File: AbstractUnresolvableReference.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean validate(IAcceptor<? super AbstractDiagnostic> result) {
	// nothing to do
	return true;
}
 
Example #30
Source File: CompoundTypeComputationState.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void addDiagnostic(AbstractDiagnostic diagnostic) {
	for (int i = 0; i < components.length; i++) {
		components[i].addDiagnostic(diagnostic);
	}
}