Search in sources :

Example 21 with Issue

use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.

the class XpectN4JSES5GeneratorHelper method registerErrors.

private boolean registerErrors(Resource dep, StringBuilder errorResult) {
    boolean hasErrors = false;
    List<Issue> issues = resourceValidator.validate(dep, CheckMode.ALL, CancelIndicator.NullImpl);
    List<Issue> errorIssues = new ArrayList<>();
    for (Issue issue : issues) {
        if (Severity.ERROR == issue.getSeverity()) {
            errorIssues.add(issue);
        }
    }
    hasErrors = !errorIssues.isEmpty();
    if (hasErrors) {
        errorResult.append("Couldn't compile resource " + dep.getURI() + " because it contains errors: ");
        for (Issue errorIssue : errorIssues) {
            errorResult.append(NL + errorIssue.getMessage() + " at line " + errorIssue.getLineNumber());
        }
    }
    return hasErrors;
}
Also used : Issue(org.eclipse.xtext.validation.Issue) ArrayList(java.util.ArrayList)

Example 22 with Issue

use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.

the class N4JSValidationTestHelper method assertNoIssuesExcept.

/**
 * Asserts the given model to not have any issues except the ones specified by the exception issue codes parameter.
 *
 * @param model
 *            The model
 * @param exceptionIssueCodes
 *            Issue codes which should be ignored
 */
public void assertNoIssuesExcept(EObject model, String... exceptionIssueCodes) {
    Resource resource = model.eResource();
    final List<Issue> issues = validate(resource);
    if (removeIssuesWithCode(issues, exceptionIssueCodes).size() > 0) {
        fail("Expected no issues, but got :" + getIssuesAsString(resource, issues, new StringBuilder()));
    }
}
Also used : Issue(org.eclipse.xtext.validation.Issue) Resource(org.eclipse.emf.ecore.resource.Resource)

Example 23 with Issue

use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.

the class QuickFixXpectMethod method quickFix.

/**
 * Choose quick fix and apply
 *
 * @param expectation
 *            from right hand side - expected changes to code, especially cursor position.
 * @param resource
 *            injected resource under test
 * @param offset
 *            parsed arg2 offset cursor position
 * @param selected
 *            parsed arg3 - chosen quick fix to apply
 * @param mode
 *            parsed arg4 if 'fileValid' additional validation check after application
 *
 * @param specifiedResourcePath
 *            Specifies the relative path of the resource in which the quickfix applies
 *
 * @param reparseResource
 *            Specifies if the resource is reset after application of the quick fix or not.
 *
 *            Note: In case of passing false the caller has to reset the resource on its own as it is essential for
 *            the following quick fix xpect method calls.
 *
 * @throws Exception
 *             in test failure.
 */
private void quickFix(IStringDiffExpectation expectation, XtextResource resource, RegionWithCursor offset, String selected, String mode, String specifiedResourcePath, Multimap<Integer, Issue> offset2issue, boolean reparseResource) throws Exception {
    Optional<XtextEditor> editor = Optional.empty();
    // Optional<XtextEditor> specifiedResourceEditor = Optional.empty();
    try {
        List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);
        IssueResolution res = QuickFixTestHelper.selectSingleOrFail(resolutions, selected);
        String beforeApplication;
        URI targetResourceUri = resource.getURI();
        // Get the content of the specified resource
        if (specifiedResourcePath != null && !specifiedResourcePath.isEmpty()) {
            URI specifiedURI = resource.getURI().trimSegments(1).appendSegments(specifiedResourcePath.split("/"));
            targetResourceUri = specifiedURI;
            beforeApplication = getContentForResourceUri(specifiedURI);
        } else {
            // capture text for comparison from disk:
            // 
            beforeApplication = getContentForResourceUri(resource.getURI());
        // beforeApplication = resource.getParseResult().getRootNode().getText();
        }
        Display.getDefault().syncExec(() -> res.apply());
        // obtain new text from editor and reparse it into the resource, otherwise the resource is outdated.
        // necessary if the resource is further used in compilation after this QF-Application.
        editor = EditorsUtil.openXtextEditor(targetResourceUri, N4JSActivator.ORG_ECLIPSE_N4JS_N4JS);
        assertTrue("No editor for provided resource " + targetResourceUri.path(), editor.isPresent());
        String textAfterApplication = editor.get().getDocument().get();
        // as it would replace the test code with the specified resource
        if (specifiedResourcePath == null || specifiedResourcePath.isEmpty()) {
            // reparse the text into the resource.
            resource.reparse(textAfterApplication);
            // in case of @IssuesByLine our Validator is of type:
            TestingResourceValidator trVal = (TestingResourceValidator) resource.getResourceServiceProvider().getResourceValidator();
            // Check for no other Issues
            if ("fileValid".equals(mode)) {
                List<Issue> remainingIssues = trVal.validateDelegate(resource, CheckMode.ALL, CancelIndicator.NullImpl, null);
                assertEquals("Expecting all issues resolved, but got still left: " + remainingIssues, 0, remainingIssues.size());
            }
        }
        if (reparseResource) {
            // Reset resource after quick fix application
            resource.reparse(getContentForResourceUri(resource.getURI()));
        }
        if (expectation != null) {
            // TODO assert cursor position after application.
            String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
            String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);
            if ("whitespaceSensitive".equals(mode)) {
                LineBasedTokenizer tokenizer = new LineBasedTokenizer();
                expectation.assertDiffEquals(tokenizer.apply(before), tokenizer.apply(after), new WSAwareTokenAdapter());
            } else {
                expectation.assertDiffEquals(before, after);
            }
        }
    } finally {
        // TODO initial state aware context
        /*
			 * If editor was created it should be closed, but if it was opened before running tests, we should only undo
			 * changes (and get rid of dirty state), but we should not close editor
			 */
        editor.ifPresent(e -> EditorsUtil.forceCloseAllEditors());
    // editor.ifPresent(e -> EditorsUtil.forceCloseEditor(e));
    }
}
Also used : TestingResourceValidator(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.TestingResourceValidator) Issue(org.eclipse.xtext.validation.Issue) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) IssueResolution(org.eclipse.xtext.ui.editor.quickfix.IssueResolution) URI(org.eclipse.emf.common.util.URI)

Example 24 with Issue

use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.

the class QuickFixXpectMethod method quickFixAndRun.

/*-
	contentAssistList kind 'smart' at 'a.<|>methodA'       display   'methodA2'            --> 'methodA2(): any - A'
	quickFix                       at 'a.<|>method'        apply     'methodA2'  fileValid --> a.<|>methodA2();
	quickFixAndRun                 at 'a.<|>method'        apply     'methodHelloWorld' --> Hello World
	                        kind        offset             checkType  selected    mode
	                                    arg2                          arg3
	 */
/**
 * Apply quick fix, compile and run the result. Compares the generated stdout-result to the expectation on the right
 * hand side.
 *
 * @param expectation
 *            - expected output of running script, just stdout no error-stream. Expecting the error-stream to be
 *            empty.
 * @param resource
 *            - injected resource
 * @param offset
 *            - parsed arg2 - cursor position
 * @param selected
 *            - parsed arg3 - selection from list of expectations
 * @param offset2issue
 *            - injected Map of issues
 * @param init
 *            - injected xpect-initizalizer
 * @param fileSetupContext
 *            - injected xpect meta-info about file under test.
 * @throws Exception
 *             in failure case
 */
@Xpect
@ParameterParser(syntax = "('at' arg2=STRING)? ('apply'  arg3=STRING )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixAndRun(// arg0
@StringExpectation(caseSensitive = true) IStringExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2
RegionWithCursor offset, // arg3
String selected, @IssuesByLine Multimap<Integer, Issue> offset2issue, ISetupInitializer<Object> init, FileSetupContext fileSetupContext) throws Exception {
    try {
        long timeStart = System.currentTimeMillis();
        logger.info("Execution started: " + new Date(timeStart));
        // System.out.println(
        // "##-Qr-## we got it selected='" + selected + "' at " + offset + " in " + resource.toString() + "");
        String executionResult;
        ExecutionResult exRes = new ExecutionResult();
        ResourceTweaker resourceTweaker = resourceToTweak -> {
            try {
                quickFix(null, resourceToTweak, offset, selected, "fileValid", "", offset2issue, false);
            } catch (Exception e) {
                Exceptions.sneakyThrow(e);
            }
        };
        Display.getDefault().syncExec(() -> exRes.result = compileAndExecute(resource, init, fileSetupContext, resourceTweaker));
        executionResult = exRes.result;
        long timeEnd = System.currentTimeMillis();
        logger.info("Execution finished: " + new Date(timeEnd));
        logger.info("Execution took " + (timeEnd - timeStart + 0.0) / 1000.0 + " seconds.");
        expectation.assertEquals(executionResult);
        // Reset resource after quick fix application and code execution
        resource.reparse(getContentForResourceUri(resource.getURI()));
    } finally {
        logger.info("Closing all editors");
        EditorsUtil.forceCloseAllEditors();
    }
    logger.info("Successful End of Execution");
}
Also used : VarDef(org.eclipse.n4js.xpect.config.VarDef) EditorsUtil(org.eclipse.n4js.tests.util.EditorsUtil) Exceptions(org.eclipse.xtext.xbase.lib.Exceptions) ISetupInitializer(org.eclipse.xpect.setup.ISetupInitializer) Date(java.util.Date) IssueResolutionProvider(org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider) Inject(com.google.inject.Inject) ICommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.ICommaSeparatedValuesExpectation) IStringDiffExpectation(org.eclipse.xpect.expectation.IStringDiffExpectation) ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) N4JSActivator(org.eclipse.n4js.ui.internal.N4JSActivator) Logger(org.apache.log4j.Logger) Config(org.eclipse.n4js.xpect.config.Config) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) StringDiffExpectation(org.eclipse.xpect.expectation.StringDiffExpectation) RegionWithCursor(org.eclipse.n4js.xpect.ui.methods.contentassist.RegionWithCursor) EObject(org.eclipse.emf.ecore.EObject) Display(org.eclipse.swt.widgets.Display) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) IssueResolution(org.eclipse.xtext.ui.editor.quickfix.IssueResolution) TestingResourceValidator(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.TestingResourceValidator) List(java.util.List) XpEnvironmentData(org.eclipse.n4js.xpect.config.XpEnvironmentData) Path(org.eclipse.core.runtime.Path) Optional(java.util.Optional) Xpect(org.eclipse.xpect.runner.Xpect) CheckMode(org.eclipse.xtext.validation.CheckMode) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) URI(org.eclipse.emf.common.util.URI) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) ResourceTweaker(org.eclipse.n4js.xpect.common.ResourceTweaker) StringExpectation(org.eclipse.xpect.expectation.StringExpectation) IssuesByLine(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.IssuesByLine) Multimap(com.google.common.collect.Multimap) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) ValidationTestModuleSetup(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup) Lists(com.google.common.collect.Lists) CancelIndicator(org.eclipse.xtext.util.CancelIndicator) IFile(org.eclipse.core.resources.IFile) QuickFixTestHelper(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper) XpectImport(org.eclipse.xpect.XpectImport) ParameterParser(org.eclipse.xpect.parameter.ParameterParser) CommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.CommaSeparatedValuesExpectation) GeneratorOption(org.eclipse.n4js.generator.GeneratorOption) XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSOffsetAdapter(org.eclipse.n4js.xpect.common.N4JSOffsetAdapter) Severity(org.eclipse.xtext.diagnostics.Severity) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) XpectN4JSES5TranspilerHelper(org.eclipse.n4js.xpect.ui.common.XpectN4JSES5TranspilerHelper) XpectCommentRemovalUtil(org.eclipse.n4js.xpect.common.XpectCommentRemovalUtil) Issue(org.eclipse.xtext.validation.Issue) FileSetupContext(org.eclipse.xpect.xtext.lib.setup.FileSetupContext) ITokenAdapter(org.eclipse.xpect.expectation.IStringDiffExpectation.ITokenAdapter) Collections(java.util.Collections) IStringExpectation(org.eclipse.xpect.expectation.IStringExpectation) Assert.assertEquals(org.junit.Assert.assertEquals) SystemLoaderInfo(org.eclipse.n4js.runner.SystemLoaderInfo) ResourceTweaker(org.eclipse.n4js.xpect.common.ResourceTweaker) Date(java.util.Date) IOException(java.io.IOException) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 25 with Issue

use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.

the class QuickFixXpectMethod method collectAllResolutions.

/**
 * CollectAll resolutions under the cursor at offset.
 */
List<IssueResolution> collectAllResolutions(XtextResource resource, RegionWithCursor offset, Multimap<Integer, Issue> offset2issue) {
    EObject script = resource.getContents().get(0);
    ICompositeNode scriptNode = NodeModelUtils.getNode(script);
    ILeafNode offsetNode = NodeModelUtils.findLeafNodeAtOffset(scriptNode, offset.getGlobalCursorOffset());
    int offStartLine = offsetNode.getTotalStartLine();
    List<Issue> allIssues = QuickFixTestHelper.extractAllIssuesInLine(offStartLine, offset2issue);
    List<IssueResolution> resolutions = Lists.newArrayList();
    for (Issue issue : allIssues) {
        if (issue.getLineNumber() == offsetNode.getStartLine() && issue.getLineNumber() <= offsetNode.getEndLine()) {
            Display.getDefault().syncExec(() -> resolutions.addAll(quickfixProvider.getResolutions(issue)));
        }
    }
    return resolutions;
}
Also used : ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) Issue(org.eclipse.xtext.validation.Issue) EObject(org.eclipse.emf.ecore.EObject) IssueResolution(org.eclipse.xtext.ui.editor.quickfix.IssueResolution) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode)

Aggregations

Issue (org.eclipse.xtext.validation.Issue)105 Test (org.junit.Test)38 XtextResource (org.eclipse.xtext.resource.XtextResource)33 Resource (org.eclipse.emf.ecore.resource.Resource)21 IResourceValidator (org.eclipse.xtext.validation.IResourceValidator)18 URI (org.eclipse.emf.common.util.URI)16 List (java.util.List)14 XtextResourceSet (org.eclipse.xtext.resource.XtextResourceSet)12 IssueResolution (org.eclipse.xtext.ui.editor.quickfix.IssueResolution)12 XtendFile (org.eclipse.xtend.core.xtend.XtendFile)11 ArrayList (java.util.ArrayList)9 Severity (org.eclipse.xtext.diagnostics.Severity)9 IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)9 EObject (org.eclipse.emf.ecore.EObject)8 IOException (java.io.IOException)7 CoreException (org.eclipse.core.runtime.CoreException)7 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)7 StringInputStream (org.eclipse.xtext.util.StringInputStream)7 Diagnostic (org.eclipse.emf.ecore.resource.Resource.Diagnostic)6 IssueResolutionAcceptor (org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor)6