Search in sources :

Example 16 with XtextResource

use of org.eclipse.xtext.resource.XtextResource in project n4js by eclipse.

the class OutlineXpectMethod method skipNodesInBetween.

private void skipNodesInBetween(Script script) throws Exception {
    if (script != null) {
        XtextResource resource = (XtextResource) script.eResource();
        ICompositeNode rootNode = resource.getParseResult().getRootNode();
        ReplaceRegion region = null;
        for (INode node : rootNode.getAsTreeIterable()) {
            if (node instanceof ICompositeNode && !(node instanceof SyntheticCompositeNode)) {
                ICompositeNode casted = (ICompositeNode) node;
                int offset = node.getTotalOffset();
                int length = node.getTotalLength();
                if (length != 0) {
                    if (casted.getFirstChild().equals(casted.getLastChild())) {
                        if (region == null || region.getOffset() != offset || region.getLength() != length) {
                            region = new ReplaceRegion(offset, length, "");
                            StringBuilder builder = new StringBuilder(rootNode.getText());
                            region.applyTo(builder);
                            processFile(builder.toString(), "skipNodesInBetween");
                        }
                    }
                }
            }
        }
    }
}
Also used : SyntheticCompositeNode(org.eclipse.xtext.nodemodel.impl.SyntheticCompositeNode) INode(org.eclipse.xtext.nodemodel.INode) ReplaceRegion(org.eclipse.xtext.util.ReplaceRegion) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) XtextResource(org.eclipse.xtext.resource.XtextResource)

Example 17 with XtextResource

use of org.eclipse.xtext.resource.XtextResource in project n4js by eclipse.

the class ProposalXpectMethod method checkProposals.

/**
 * Iterates over all proposed completion entries at the given offset and checks whether its application would cause
 * validation issues in the resource.
 *
 * @param expectation
 *            the expected proposals causing validation errors
 * @param resource
 *            the resource under test
 * @param offset
 *            the offset of where to invoke content assist (note: it must be named arg2 as Xpect injects the
 *            parameter values by position)
 * @throws Exception
 *             some exception
 */
@ParameterParser(syntax = "'at' arg2=STRING")
@Xpect
public void checkProposals(@CommaSeparatedValuesExpectation ICommaSeparatedValuesExpectation expectation, @ThisResource XtextResource resource, RegionWithCursor offset) throws Exception {
    N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    ICompletionProposal[] computeCompletionProposals = allProposalsAt(offset, fixture);
    List<String> proposalsWithError = Lists.newArrayList();
    for (int proposal = 0; proposal < computeCompletionProposals.length; proposal++) {
        fixture = fixture.reset();
        String content = resource.getParseResult().getRootNode().getText();
        fixture = fixture.append(content);
        IXtextDocument document = fixture.getDocument(resource, content);
        int index = proposal;
        String newContent = applyProposal(computeCompletionProposals[index], document);
        IXtextDocument newXtextDocument = fixture.getDocument(getNewResource(newContent, resource.getURI()), content);
        newXtextDocument.readOnly(new IUnitOfWork<Object, XtextResource>() {

            @Override
            public Object exec(XtextResource state) throws Exception {
                EcoreUtil.resolveAll(state);
                if (!state.getErrors().isEmpty()) {
                    proposalsWithError.add(computeCompletionProposals[index].getDisplayString());
                } else if (!state.validateConcreteSyntax().isEmpty()) {
                    proposalsWithError.add(computeCompletionProposals[index].getDisplayString());
                }
                return null;
            }
        });
    }
    expectation.assertEquals(proposalsWithError);
}
Also used : ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) XtextResource(org.eclipse.xtext.resource.XtextResource) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 18 with XtextResource

use of org.eclipse.xtext.resource.XtextResource 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 19 with XtextResource

use of org.eclipse.xtext.resource.XtextResource in project n4js by eclipse.

the class LinkingXpectMethod method linkedPathname.

/**
 * Similar to {@link #linkedName(IStringExpectation, ICrossEReferenceAndEObject)} but concatenating the fully
 * qualified name again instead of using the qualified name provider, as the latter may not create a valid name for
 * non-globally available elements.
 * <p>
 * The qualified name created by retrieving all "name" properties of the target and its containers, using '/' as
 * separator.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void linkedPathname(@StringExpectation IStringExpectation expectation, ICrossEReferenceAndEObject arg1) {
    EObject targetObject = (EObject) arg1.getEObject().eGet(arg1.getCrossEReference());
    if (targetObject == null) {
        Assert.fail("Reference is null");
        // to avoid warnings in the following
        return;
    }
    if (targetObject.eIsProxy())
        Assert.fail("Reference is a Proxy: " + ((InternalEObject) targetObject).eProxyURI());
    Resource targetResource = targetObject.eResource();
    if (targetResource instanceof TypeResource)
        targetResource = arg1.getEObject().eResource();
    if (!(targetResource instanceof XtextResource))
        Assert.fail("Referenced EObject is not in an XtextResource.");
    Deque<String> segments = new ArrayDeque<>();
    do {
        EStructuralFeature nameFeature = targetObject.eClass().getEStructuralFeature("name");
        if (nameFeature != null) {
            Object obj = targetObject.eGet(nameFeature);
            if (obj instanceof String) {
                segments.push((String) obj);
            }
        } else {
            if (targetObject instanceof NamedElement) {
                segments.push(((NamedElement) targetObject).getName());
            }
        }
        targetObject = targetObject.eContainer();
    } while (targetObject != null);
    String pathname = Joiner.on('/').join(segments);
    expectation.assertEquals(pathname);
}
Also used : TypeResource(org.eclipse.xtext.common.types.access.TypeResource) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) ICrossEReferenceAndEObject(org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject) XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) TypeResource(org.eclipse.xtext.common.types.access.TypeResource) EStructuralFeature(org.eclipse.emf.ecore.EStructuralFeature) XtextResource(org.eclipse.xtext.resource.XtextResource) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) ICrossEReferenceAndEObject(org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject) NamedElement(org.eclipse.n4js.n4JS.NamedElement) ArrayDeque(java.util.ArrayDeque) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 20 with XtextResource

use of org.eclipse.xtext.resource.XtextResource in project n4js by eclipse.

the class OrganizeImportXpectMethod method organizeImports.

/**
 * 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(// arg0
String ambiguous, @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() */
        {
            // 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;
        }
    }
}
Also used : Interaction(org.eclipse.n4js.ui.organize.imports.Interaction) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSResource(org.eclipse.n4js.resource.N4JSResource) Resource(org.eclipse.emf.ecore.resource.Resource) ArrayList(java.util.ArrayList) BreakException(org.eclipse.n4js.ui.organize.imports.BreakException) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) AssertionFailedError(junit.framework.AssertionFailedError) BreakException(org.eclipse.n4js.ui.organize.imports.BreakException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Aggregations

XtextResource (org.eclipse.xtext.resource.XtextResource)627 Test (org.junit.Test)367 Resource (org.eclipse.emf.ecore.resource.Resource)107 EObject (org.eclipse.emf.ecore.EObject)99 XtextResourceSet (org.eclipse.xtext.resource.XtextResourceSet)67 StringInputStream (org.eclipse.xtext.util.StringInputStream)67 URI (org.eclipse.emf.common.util.URI)62 Diagnostic (org.eclipse.emf.common.util.Diagnostic)55 IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)55 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)46 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)40 Grammar (org.eclipse.xtext.Grammar)32 IUnitOfWork (org.eclipse.xtext.util.concurrent.IUnitOfWork)31 XtextEditor (org.eclipse.xtext.ui.editor.XtextEditor)30 IFile (org.eclipse.core.resources.IFile)29 Issue (org.eclipse.xtext.validation.Issue)29 StringConcatenation (org.eclipse.xtend2.lib.StringConcatenation)28 List (java.util.List)26 XtendFile (org.eclipse.xtend.core.xtend.XtendFile)26 INode (org.eclipse.xtext.nodemodel.INode)23