org.eclipse.xtext.validation.EObjectDiagnosticImpl Java Examples

The following examples show how to use org.eclipse.xtext.validation.EObjectDiagnosticImpl. 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: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void _computeTypes(XInstanceOfExpression object, ITypeComputationState state) {
	ITypeComputationState expressionState = state.withExpectation(state.getReferenceOwner().newReferenceToObject());
	expressionState.computeTypes(object.getExpression());
	JvmTypeReference type = object.getType();
	if (isReferenceToTypeParameter(type)) {
		LightweightTypeReference lightweightReference = state.getReferenceOwner().toLightweightTypeReference(type);
		LightweightTypeReference rawTypeRef = lightweightReference.getRawTypeReference();
		state.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR,
				IssueCodes.INVALID_USE_OF_TYPE_PARAMETER,
				"Cannot perform instanceof check against type parameter "+lightweightReference.getHumanReadableName()+". Use its erasure "+rawTypeRef.getHumanReadableName()+" instead since further generic type information will be erased at runtime.",
				object.getType(),
				null,
				-1,
				new String[] { 
				}));
	}
	LightweightTypeReference bool = getRawTypeForName(Boolean.TYPE, state);
	state.acceptActualType(bool);
}
 
Example #2
Source File: SARLTypeComputer.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void computeTypes(XExpression expression, ITypeComputationState state) {
	if (expression instanceof SarlBreakExpression) {
		_computeTypes((SarlBreakExpression) expression, state);
	} else if (expression instanceof SarlContinueExpression) {
		_computeTypes((SarlContinueExpression) expression, state);
	} else if (expression instanceof SarlAssertExpression) {
		_computeTypes((SarlAssertExpression) expression, state);
	} else if (expression instanceof SarlCastedExpression) {
		_computeTypes((SarlCastedExpression) expression, state);
	} else {
		try {
			super.computeTypes(expression, state);
		} catch (Throwable exception) {
			final Throwable cause = Throwables.getRootCause(exception);
			state.addDiagnostic(new EObjectDiagnosticImpl(
					Severity.ERROR,
					IssueCodes.INTERNAL_ERROR,
					cause.getLocalizedMessage(),
					expression,
					null,
					-1,
					null));
		}
	}
}
 
Example #3
Source File: CompilationUnitImpl.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public Object evaluate(final XExpression expression, final JvmTypeReference expectedType) {
  try {
    final Object result = this.interpreter.evaluate(expression, expectedType);
    return this.translate(result);
  } catch (final Throwable _t) {
    if (_t instanceof ConstantExpressionEvaluationException) {
      final ConstantExpressionEvaluationException e = (ConstantExpressionEvaluationException)_t;
      String _message = e.getMessage();
      final EObjectDiagnosticImpl error = new EObjectDiagnosticImpl(Severity.ERROR, "constant_expression_evaluation_problem", _message, expression, null, (-1), null);
      expression.eResource().getErrors().add(error);
      return null;
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
}
 
Example #4
Source File: ProblemSupportTests.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testErrorOnDerivedElement() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("class MyClass {");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("String foo = \'foo\'");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final Procedure1<CompilationUnitImpl> _function = (CompilationUnitImpl it) -> {
    final MutableClassDeclaration derived = it.getTypeLookup().findClass("MyClass");
    it.getProblemSupport().addError(derived, "error on derived element");
    Assert.assertEquals("error on derived element", IterableExtensions.<Resource.Diagnostic>head(it.getXtendFile().eResource().getErrors()).getMessage());
    Resource.Diagnostic _head = IterableExtensions.<Resource.Diagnostic>head(it.getXtendFile().eResource().getErrors());
    Assert.assertEquals(IterableExtensions.<XtendTypeDeclaration>head(it.getXtendFile().getXtendTypes()), ((EObjectDiagnosticImpl) _head).getProblematicObject());
  };
  this.asCompilationUnit(this.validFile(_builder), _function);
}
 
Example #5
Source File: ProblemSupportTests.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testErrorOnSource() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("class MyClass {");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("String foo = \'foo\'");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final Procedure1<CompilationUnitImpl> _function = (CompilationUnitImpl it) -> {
    it.getProblemSupport().addError(IterableExtensions.head(it.getSourceTypeDeclarations()), "error on source");
    Assert.assertEquals("error on source", IterableExtensions.<Resource.Diagnostic>head(it.getXtendFile().eResource().getErrors()).getMessage());
    Resource.Diagnostic _head = IterableExtensions.<Resource.Diagnostic>head(it.getXtendFile().eResource().getErrors());
    Assert.assertEquals(IterableExtensions.<XtendTypeDeclaration>head(it.getXtendFile().getXtendTypes()), ((EObjectDiagnosticImpl) _head).getProblematicObject());
  };
  this.asCompilationUnit(this.validFile(_builder), _function);
}
 
Example #6
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 #7
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 #8
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 #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: 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 #11
Source File: LogicalContainerAwareReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
/* @Nullable */
protected JvmTypeReference doGetTypeReference(XComputedTypeReferenceImplCustom context) {
	try {
		resolvedTypes.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR, 
				IssueCodes.TOO_LITTLE_TYPE_INFORMATION, 
				"Cannot infer type",
				typeResolver.getSourceElement(member), 
				null, 
				-1, 
				null));
		return TypesFactory.eINSTANCE.createJvmAnyTypeReference();
	} finally {
		context.unsetTypeProviderWithoutNotification();
	}
}
 
Example #12
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 #13
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 #14
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 #15
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void _computeTypes(XSynchronizedExpression expr, ITypeComputationState state) {
	ITypeComputationState paramState = state.withExpectation(state.getReferenceOwner().newReferenceToObject());
	ITypeComputationResult paramType = paramState.computeTypes(expr.getParam());
	LightweightTypeReference actualParamType = paramType.getActualExpressionType();
	if (actualParamType != null && (actualParamType.isPrimitive() || actualParamType.isAny())) {
		state.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR,
				IssueCodes.INCOMPATIBLE_TYPES,
				actualParamType.getHumanReadableName() +  " is not a valid type's argument for the synchronized expression.",
				expr.getParam(),
				null,
				-1,
				new String[] { 
				}));
	}
	state.computeTypes(expr.getExpression());
}
 
Example #16
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void checkValidReturnExpression(XExpression returnValue, ITypeComputationState expressionState) {
	ITypeComputationResult result = expressionState.computeTypes(returnValue);
	LightweightTypeReference actualType = result.getActualExpressionType();
	int conformanceFlags = result.getConformanceFlags();
	if (actualType.isPrimitiveVoid() && (conformanceFlags & ConformanceFlags.NO_IMPLICIT_RETURN) != 0) {
		String message = "Invalid return's expression.";
		if (returnValue instanceof XReturnExpression) {
			// when the return's expression is directory a return
			// we provide a more detailed error
			message = "Return cannot be nested.";
		}
		expressionState.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR,
				IssueCodes.INVALID_RETURN,
				message,
				returnValue,
				null,
				-1,
				new String[] { 
				}));
	}
}
 
Example #17
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void checkValidReturn(XReturnExpression object, ITypeComputationState state) {
	// if the expectation comes from a method's return type
	// then it is legal, thus we must check if the return is
	// contained in a throw expression
	if (hasThrowableExpectation(state) &&
			EcoreUtil2.getContainerOfType(object, XThrowExpression.class) != null) {
		state.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR,
				IssueCodes.INVALID_RETURN,
				"Invalid return inside throw.",
				object,
				null,
				-1,
				new String[] { 
				}));
	}
}
 
Example #18
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 #19
Source File: GamlResource.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doLinking() {
	// If the imports are not correctly updated, we cannot proceed
	final EObject faulty = GamlResourceIndexer.updateImports(this);
	if (faulty != null) {
		System.out.println(getURI() + " cannot import " + faulty);
		final EAttribute attribute = getContents().get(0) instanceof Model ? GamlPackage.Literals.IMPORT__IMPORT_URI
				: GamlPackage.Literals.HEADLESS_EXPERIMENT__IMPORT_URI;
		getErrors().add(new EObjectDiagnosticImpl(Severity.ERROR, IGamlIssue.IMPORT_ERROR,
				"Impossible to locate import", faulty, attribute, -1, null));
		return;
	}
	super.doLinking();
}
 
Example #20
Source File: ProblemSupportImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void addWarning(final Element element, final String message) {
  this.checkCanceled();
  this.checkValidationAllowed();
  final Pair<Resource, EObject> resAndObj = this.getResourceAndEObject(element);
  EList<Resource.Diagnostic> _warnings = resAndObj.getKey().getWarnings();
  EObject _value = resAndObj.getValue();
  EStructuralFeature _significantFeature = this.getSignificantFeature(resAndObj.getValue());
  EObjectDiagnosticImpl _eObjectDiagnosticImpl = new EObjectDiagnosticImpl(Severity.WARNING, "user.issue", message, _value, _significantFeature, (-1), null);
  _warnings.add(_eObjectDiagnosticImpl);
}
 
Example #21
Source File: ProblemSupportImpl.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void addError(final Element element, final String message) {
  this.checkCanceled();
  this.checkValidationAllowed();
  final Pair<Resource, EObject> resAndObj = this.getResourceAndEObject(element);
  EList<Resource.Diagnostic> _errors = resAndObj.getKey().getErrors();
  EObject _value = resAndObj.getValue();
  EStructuralFeature _significantFeature = this.getSignificantFeature(resAndObj.getValue());
  EObjectDiagnosticImpl _eObjectDiagnosticImpl = new EObjectDiagnosticImpl(Severity.ERROR, "user.issue", message, _value, _significantFeature, (-1), null);
  _errors.add(_eObjectDiagnosticImpl);
}
 
Example #22
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks if the given thrownexcpetion is handled (as in "taken care of by compiler").
 * 
 * @param thrownException the exception to validate
 * @param object the object in which context the exception should be validated
 * @param feature which causes the exception
 * @param state bearing the expected exceptions
 * @param message function to specify the exception message
 * 
 * @since 2.18
 */
protected void validateUnhandledException(
		LightweightTypeReference thrownException,
		XExpression object,
		EStructuralFeature feature,
		ITypeComputationState state,
		Function<? super JvmType, ? extends String> message) {
	if (!state.isIgnored(IssueCodes.UNHANDLED_EXCEPTION) && thrownException.isSubtypeOf(Throwable.class)
			&& !thrownException.isSubtypeOf(RuntimeException.class) && !thrownException.isSubtypeOf(Error.class)) {
		boolean declarationFound = false;
		for (LightweightTypeReference declaredException : state.getExpectedExceptions())
			if (declaredException.isAssignableFrom(thrownException)) {
				declarationFound = true;
				break;
			}
		if (!declarationFound) {
			JvmType exceptionType = thrownException.getNamedType().getType();
			state.addDiagnostic(new EObjectDiagnosticImpl(
					state.getSeverity(IssueCodes.UNHANDLED_EXCEPTION),
					IssueCodes.UNHANDLED_EXCEPTION,
					message.apply(exceptionType),
					object,
					feature,
					-1,
					new String[] { 
						EcoreUtil.getURI(exceptionType).toString(),
						EcoreUtil.getURI(object).toString()
					}));
		}
	}
}
 
Example #23
Source File: XtendReentrantTypeResolver.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected JvmTypeReference handleReentrantInvocation(XComputedTypeReferenceImplCustom context) {
	resolvedTypes.addDiagnostic(new EObjectDiagnosticImpl(
			Severity.WARNING,
			IssueCodes.TOO_LITTLE_TYPE_INFORMATION,
			"Cannot infer type from recursive usage. Type 'Object' is used.",
			typeResolver.getSourceElement(operation),
			null,
			-1,
			null));
	AnyTypeReference result = resolvedTypes.getReferenceOwner().newAnyTypeReference();
	return typeResolver.toJavaCompliantTypeReference(result, session);
}
 
Example #24
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private void checkTypeParameterNotAllowedAsLiteral(EObject ctx, JvmType type, ITypeComputationState state) {
	if (type instanceof JvmTypeParameter) {
		state.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR,
				IssueCodes.INVALID_USE_OF_TYPE_PARAMETER,
				"Illegal class literal for the type parameter " + type.getSimpleName()+".",
				ctx,
				null,
				-1,
				new String[] { 
				}));
	}
}
 
Example #25
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 #26
Source File: AbstractTypeComputationState.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void addLocalToCurrentScope(QualifiedName elementName, JvmIdentifiableElement element, boolean raiseIssueIfShadowing) {
	if (getResolver().isDisallowedName(elementName)) {
		resolvedTypes.addDiagnostic(new EObjectDiagnosticImpl(
				Severity.ERROR,
				IssueCodes.VARIABLE_NAME_DISALLOWED, 
				"'" + elementName + "' is not a valid name", 
				getResolver().getSourceElement(element),
				element.eClass().getEStructuralFeature("name"),
				-1,
				null));
		return;
	}
	if (getResolver().isDiscouragedName(elementName)) {
		if (!isIgnored(IssueCodes.VARIABLE_NAME_DISCOURAGED)) {
			resolvedTypes.addDiagnostic(new EObjectDiagnosticImpl(
					getSeverity(IssueCodes.VARIABLE_NAME_DISCOURAGED),
					IssueCodes.VARIABLE_NAME_DISCOURAGED, 
					"'" + elementName + "' is a discouraged name", 
					getResolver().getSourceElement(element),
					element.eClass().getEStructuralFeature("name"),
					-1,
					null));
		}
	}
	if (raiseIssueIfShadowing) {
		IEObjectDescription existingElement = featureScopeSession.getLocalElement(elementName);
		if (existingElement != null) {
			resolvedTypes.addDiagnostic(new EObjectDiagnosticImpl(
					Severity.ERROR,
					IssueCodes.VARIABLE_NAME_SHADOWING, 
					"Duplicate local variable " + elementName, 
					getResolver().getSourceElement(element),
					element.eClass().getEStructuralFeature("name"),
					-1,
					null));
		}
	}
	featureScopeSession = featureScopeSession.addLocalElement(elementName, element, getReferenceOwner());
}
 
Example #27
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 #28
Source File: LogicalContainerAwareReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected JvmTypeReference handleReentrantInvocation(XComputedTypeReferenceImplCustom context) {
	EObject sourceElement = getSourceElement(member);
	EStructuralFeature feature = sourceElement.eClass().getEStructuralFeature("name");
	resolvedTypes.addDiagnostic(new EObjectDiagnosticImpl(
			Severity.WARNING, 
			IssueCodes.TOO_LITTLE_TYPE_INFORMATION, 
			"Cannot infer type from recursive usage. Type 'Object' is used.",
			sourceElement, 
			feature, 
			-1, 
			null));
	AnyTypeReference result = resolvedTypes.getReferenceOwner().newAnyTypeReference();
	return toJavaCompliantTypeReference(result, session);
}
 
Example #29
Source File: SARLTypeComputer.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Compute the type of a casted expression.
 *
 * @param cast the expression.
 * @param state the state of the type resolver.
 */
@SuppressWarnings("checkstyle:nestedifdepth")
protected void _computeTypes(SarlCastedExpression cast, ITypeComputationState state) {
	if (state instanceof AbstractTypeComputationState) {
		final JvmTypeReference type = cast.getType();
		if (type != null) {
			state.withNonVoidExpectation().computeTypes(cast.getTarget());
			// Set the linked feature
			try {
				final AbstractTypeComputationState computationState = (AbstractTypeComputationState) state;
				final CastedExpressionTypeComputationState astate = new CastedExpressionTypeComputationState(
						cast,
						computationState,
						this.castOperationValidator);
				astate.resetFeature(cast);
				if (astate.isCastOperatorLinkingEnabled(cast)) {
					final List<? extends ILinkingCandidate> candidates = astate.getLinkingCandidates(cast);
					if (!candidates.isEmpty()) {
						final ILinkingCandidate best = getBestCandidate(candidates);
						if (best != null) {
							best.applyToModel(computationState.getResolvedTypes());
						}
					}
				}
			} catch (Throwable exception) {
				final Throwable cause = Throwables.getRootCause(exception);
				state.addDiagnostic(new EObjectDiagnosticImpl(
						Severity.ERROR,
						IssueCodes.INTERNAL_ERROR,
						cause.getLocalizedMessage(),
						cast,
						null,
						-1,
						null));
			}
			state.acceptActualType(state.getReferenceOwner().toLightweightTypeReference(type));
		} else {
			state.computeTypes(cast.getTarget());
		}
	} else {
		super._computeTypes(cast, state);
	}
}
 
Example #30
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;
}