Java Code Examples for org.eclipse.xtext.diagnostics.Severity#ERROR

The following examples show how to use org.eclipse.xtext.diagnostics.Severity#ERROR . 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: 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 2
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 3
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 4
Source File: QuickFixXpectMethod.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Example: {@code // XPECT quickFixList  at 'a.<|>method' --> 'import A','do other things' }
 *
 * @param expectation
 *            comma separated strings, which are proposed as quick fix
 * @param resource
 *            injected xtext-file
 * @param offset
 *            cursor position at '<|>'
 * @param checkType
 *            'display': verify list of provided proposals comparing their user-displayed strings.
 * @param selected
 *            which proposal to pick
 * @param mode
 *            modus of operation
 * @param offset2issue
 *            mapping of offset(!) to issues.
 * @throws Exception
 *             if failing
 */
@Xpect
@ParameterParser(syntax = "('at' (arg2=STRING (arg3=ID  (arg4=STRING)?  (arg5=ID)? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixList(
		@CommaSeparatedValuesExpectation(quoted = true, ordered = true) ICommaSeparatedValuesExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2
		String checkType, // arg3
		String selected, // arg4
		String mode, // arg5
		@IssuesByLine Multimap<Integer, Issue> offset2issue) throws Exception {

	List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);

	List<String> resolutionNames = Lists.newArrayList();
	for (IssueResolution resolution : resolutions) {
		resolutionNames.add(resolution.getLabel());
	}

	expectation.assertEquals(resolutionNames);
}
 
Example 5
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 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: LinkingDiagnosticMessageProvider.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public DiagnosticMessage getUnresolvedProxyMessage(ILinkingDiagnosticContext context) {
	String linkText = "";
	try {
		linkText = context.getLinkText();
	} catch (IllegalNodeException e) {
		linkText = e.getNode().getText();
	}

	String format = "Could not find declaration of %s '%s'";
	String type = context.getReference().getEReferenceType().getName();
	String message = String.format(format, "", linkText);
	if (!type.equals("EObject")) {
		message = String.format(format, type, linkText);
	}
	return new DiagnosticMessage(message, Severity.ERROR, Diagnostic.LINKING_DIAGNOSTIC);
}
 
Example 8
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 9
Source File: FeatureLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Severity getUnhandledExceptionSeverity(JvmExecutable executable) {
	if (getFeature() instanceof JvmConstructor) {
		return Severity.ERROR;
	}
	return super.getUnhandledExceptionSeverity(executable);
}
 
Example 10
Source File: LinkingDiagnosticMessageProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public DiagnosticMessage getViolatedBoundsConstraintMessage(ILinkingDiagnosticContext context, int size) {
	String message = "Too many matches for reference to '" + context.getLinkText() + "'. " 
			+ "Feature " + context.getReference().getName() + " can only hold " + context.getReference().getUpperBound()
			+ " reference" + (context.getReference().getUpperBound() != 1 ? "s" : "") + " but found " + size + " candidate" +
			(size!=1 ? "s" : "");
	return new DiagnosticMessage(message, Severity.ERROR, Diagnostic.LINKING_DIAGNOSTIC);
}
 
Example 11
Source File: LinkingDiagnosticMessageProvider.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public DiagnosticMessage getUnresolvedProxyMessage(ILinkingDiagnosticContext context) {
	EClass referenceType = context.getReference().getEReferenceType();
	String linkText = "";
	try {
		linkText = context.getLinkText();
	} catch (IllegalNodeException e){
		linkText = e.getNode().getText();
	}
	String msg = "Couldn't resolve reference to " + referenceType.getName() + " '" + linkText + "'.";
	return new DiagnosticMessage(msg, Severity.ERROR, Diagnostic.LINKING_DIAGNOSTIC);
}
 
Example 12
Source File: IssueCodeBasedEObjectDescription.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Instantiates a new {@link IssueCodeBasedEObjectDescription} with the given issue message and code. */
public IssueCodeBasedEObjectDescription(IEObjectDescription delegate, String message, String issueCode) {
	super(delegate);
	this.issueCode = issueCode;
	this.message = message;
	this.severity = Severity.ERROR;
}
 
Example 13
Source File: XtextEditorErrorTickUpdater.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void updateEditorImage(XtextEditor xtextEditor) {
	Severity severity = getSeverity(xtextEditor);
	if (severity != null && severity != Severity.INFO) {
		ImageDescriptor descriptor = severity == Severity.ERROR ? XtextPluginImages.DESC_OVR_ERROR
				: XtextPluginImages.DESC_OVR_WARNING;
		DecorationOverlayIcon decorationOverlayIcon = new DecorationOverlayIcon(defaultImage, descriptor,
				IDecoration.BOTTOM_LEFT);
		scheduleUpdateEditor(decorationOverlayIcon);
	} else {
		scheduleUpdateEditor(defaultImage);
	}
}
 
Example 14
Source File: ValidValidatorFragment.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the valid model.
 *
 * @param grammar
 *          the grammar
 * @return the valid model
 */
private ValidModel getValidModel(final Grammar grammar) {
  if (model != null) {
    return model;
  }

  Resource resource = null;
  final String name = GrammarUtil.getSimpleName(grammar) + '.' + XTEXT_EXTENSION;
  URI uri;
  for (final Resource res : grammar.eResource().getResourceSet().getResources()) {
    if (res.getURI() != null && name.equals(EmfResourceUtil.getFileName(res.getURI()))) {
      resource = res;
      break;
    }
  }
  if (getValidURI() == null) {
    Assert.isNotNull(resource, NLS.bind(Messages.RESOURCE_NOT_FOUND, name));
    uri = resource.getURI().trimFileExtension().appendFileExtension(VALID_EXTENSION);
  } else {
    uri = URI.createURI(getValidURI());
  }

  resource = resource.getResourceSet().getResource(uri, true);

  final List<Issue> issues = VALIDATOR.validate(resource, LOGGER);
  for (final Issue issue : issues) {
    if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) {
      throw new WorkflowInterruptedException(NLS.bind(Messages.ERROR_FOUND, uri.toString()));
    }
  }
  model = (ValidModel) resource.getContents().get(0);
  return model;
}
 
Example 15
Source File: LinkingDiagnosticMessageProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public DiagnosticMessage getViolatedUniqueConstraintMessage(ILinkingDiagnosticContext context) {
	String message = "Cannot refer to '" + context.getLinkText() + "' more than once.";
	return new DiagnosticMessage(message, Severity.ERROR, Diagnostic.LINKING_DIAGNOSTIC);
}
 
Example 16
Source File: GamlLinkingErrorMessageProvider.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public DiagnosticMessage getViolatedUniqueConstraintMessage(final ILinkingDiagnosticContext context) {
	final String message = "Cannot refer to '" + context.getLinkText() + "' more than once.";
	return new DiagnosticMessage(message, Severity.ERROR, Diagnostic.LINKING_DIAGNOSTIC);
}
 
Example 17
Source File: ExportFragment.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get the export model that we have to process.
 *
 * @param grammar
 *          The grammar
 * @return The model
 */
private synchronized ExportModel getModel(final Grammar grammar) { // NOPMD NPathComplexity by wth on 24.11.10 08:22
  if (modelLoaded) {
    return model;
  }
  modelLoaded = true;
  Resource resource = grammar.eResource();
  if (resource == null) {
    return null;
  }

  final ResourceSet resourceSet = resource.getResourceSet();
  URI uri = null;
  if (getExportFileURI() != null) {
    uri = URI.createURI(getExportFileURI());
  } else {
    uri = grammar.eResource().getURI().trimFileExtension().appendFileExtension(EXPORT_FILE_EXTENSION);
  }
  try {
    resource = resourceSet.getResource(uri, true);
    final List<Issue> issues = VALIDATOR.validate(resource, LOGGER);

    for (final Issue issue : issues) {
      if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) {
        throw new WorkflowInterruptedException(NLS.bind(Messages.ExportFragment_EXPORT_ERRORS, uri));
      }
    }
    if (resource.getContents().size() == 0) {
      return null;
    }
    model = (ExportModel) resource.getContents().get(0);
    return model;
  } catch (final ClasspathUriResolutionException e) {
    // Resource does not exist.
    if (getExportFileURI() != null) {
      // Explicit file specified, but not found: stop the workflow.
      throw new WorkflowInterruptedException(NLS.bind(Messages.ExportFragment_NO_EXPORT_FILE, uri)); // NOPMD PreserveStackTrace by wth on 24.11.10 08:27
    }
    // No file found at implicit location: work with a null model, generating code that implements the default behavior.
    return null;
  }
}
 
Example 18
Source File: OrganizeImportXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Give the result as a multiline diff. If cancellation due to multiple possible resolution is expected, provide the
 * expected Exception with 'XPECT organizeImports ambiguous "Exception-Message" -->'.
 *
 * If the parameter is not provided, always the first computed solution in the list will be taken
 *
 * @param ambiguous
 *            - String Expectation in {@link BreakException}
 */
@ParameterParser(syntax = "('ambiguous' arg0=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void organizeImports(
		String ambiguous, // arg0
		@StringDiffExpectation(whitespaceSensitive = false, allowSingleSegmentDiff = false, allowSingleLineDiff = false) IStringDiffExpectation expectation,
		@ThisResource XtextResource resource) throws Exception {

	logger.info("organize imports ...");
	boolean bAmbiguityCheck = ambiguous != null && ambiguous.trim().length() > 0;
	Interaction iaMode = bAmbiguityCheck ? Interaction.breakBuild : Interaction.takeFirst;

	try {

		if (expectation == null /* || expectation.isEmpty() */) {
			// TODO throw exception if empty.
			// Hey, I want to ask the expectation if it's empty.
			// Cannot access the region which could be asked for it's length.
			throw new AssertionFailedError(
					"The test is missing a diff: // XPECT organizeImports --> [old string replaced|new string expected] ");
		}

		// capture text for comparison:
		String beforeApplication = resource.getParseResult().getRootNode().getText();

		N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper
				.createTestBuilderForResource(resource);

		IXtextDocument xtextDoc = fixture.getDocument(resource, beforeApplication);

		// in case of cross-file hyperlinks, we have to make sure the target resources are fully resolved
		final ResourceSet resSet = resource.getResourceSet();
		for (Resource currRes : new ArrayList<>(resSet.getResources())) {
			N4JSResource.postProcess(currRes);
		}

		// Calling organize imports
		Display.getDefault().syncExec(
				() -> imortsOrganizer.unsafeOrganizeDocument(xtextDoc, iaMode));

		if (bAmbiguityCheck) {
			// should fail if here
			assertEquals("Expected ambiguous resolution to break the organize import command.", ambiguous, "");
		}

		// checking that no errors are left.
		String textAfterApplication = xtextDoc.get();

		// compare with expectation, it's a multiline-diff expectation.
		String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
		String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);

		expectation.assertDiffEquals(before, after);
	} catch (Exception exc) {
		if (exc instanceof RuntimeException && exc.getCause() instanceof BreakException) {
			String breakMessage = exc.getCause().getMessage();
			assertEquals(ambiguous, breakMessage);
		} else {
			throw exc;
		}
	}
}
 
Example 19
Source File: ContentAssistXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Application of a content assist. The right hand side describes the expected modifications.
 *
 * Up to now only single-line changes are supported.
 *
 * @param expectation
 *            injected Applicaiton
 * @param resource
 *            injected xtext resource
 * @param offset
 *            parsed arg2 - Cursorposition and Selection
 * @param kind
 *            parsed arg3 - named kind of assistence-provider 'recommenders',...
 * @param selected
 *            parsed arg4 - string of things to select in proposal list.
 * @param mode
 *            parsed arg5 - mode modifier
 * @throws Exception
 *             in junit-error case
 */
@Xpect
@ParameterParser(syntax = "( ('kind' arg3=STRING)? 'at' (arg2=STRING  ('apply' arg4=STRING)?  (arg5=ID)? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void contentAssist(
		IStringExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		RegionWithCursor offset, // arg2 //@ThisOffset is obsolete
		String kind, // arg3
		String selected, // arg4
		String mode // arg5
) throws Exception {

	N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper
			.createTestBuilderForResource(resource);
	ICompletionProposal proposal = exactlyMatchingProposal(offset, fixture, selected);
	String before = resource.getParseResult().getRootNode().getText();

	// apply:
	// so working with the fixture cannot get any selection information since these are mocked away.
	IXtextDocument document = fixture.getDocument(resource, before);

	Optional<String> optionalMode = Optional.ofNullable(mode);
	if (optionalMode.isPresent() && optionalMode.get().trim() == "override") {

		// TODO mode override: needs to have a real selectionprovider in the fixture.
		// currently there is a mockup which doesn't support selection
		// see org.eclipse.xtext.ui.testing.ContentAssistProcessorTestBuilder.getSourceViewer(String,
		// IXtextDocument)

		// val sv = fixture.getSourceViewer(null, document)

		// sv.selectionProvider.selection = new TextSelection(..)
	}

	String after = applyProposal(proposal, document);

	final boolean isMultiLineExpectation = getExpectationString(expectation).contains("\n");
	if (isMultiLineExpectation) {
		assertMultiLineExpectation(expectation, after);
		return;
	}

	// Expecting change only in single line:
	ChangeInfo changedLines = extractSingleChangedLine(before, after);
	if (changedLines.isMoreThanOne()) {
		throw new AssertionError("more then one line changed: " + changedLines.asString());
	} else if (changedLines.isEmpty()) {
		throw new AssertionError("Nothing changed.");
	}
	String exp = changedLines.first().getAfter();

	Point selection = proposal.getSelection(document);
	if (selection != null) {
		IExpectationRegion region = ((AbstractExpectation) expectation).getRegion();
		if (CursorMarkerHelper.exists(region.getRegionText(), CursorMarkerHelper.markerCursor)) {
			int newPos = selection.x - changedLines.first().getAfterOffset();
			exp = new StringBuilder(exp).insert(newPos, CursorMarkerHelper.markerCursor).toString();
		}
	}
	// Single changed line:
	expectation.assertEquals(exp);

	// TODO up to now this only removes the locations for the cursor but doesn't check the location.
	// TODO multilines must be supported.
	// // before = replaceXPECT(before);
	// // after = replaceXPECT(after);
	// expectation.assertEquals(after)
	// expectation.assertDiffEquals("a", "b - not implemented yet")
}
 
Example 20
Source File: IEObjectDescriptionWithError.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * {@link Severity#ERROR} by default.
 *
 * @return the issue severity
 */
public default Severity getSeverity() {
	return Severity.ERROR;
}