Search in sources :

Example 11 with XtextResource

use of org.eclipse.xtext.resource.XtextResource in project xtext-core by eclipse.

the class AbstractXtextResourceSetTest method testResourcesAreClearedWithNormalizedURI_01.

@Test
public void testResourcesAreClearedWithNormalizedURI_01() {
    final XtextResourceSet rs = this.createEmptyResourceSet();
    Assert.assertEquals(0, rs.getURIResourceMap().size());
    final XtextResource resource = new XtextResource();
    resource.setURI(URI.createURI("/a/../foo"));
    EList<Resource> _resources = rs.getResources();
    ArrayList<Resource> _newArrayList = CollectionLiterals.<Resource>newArrayList(resource);
    Iterables.<Resource>addAll(_resources, _newArrayList);
    Assert.assertEquals(2, rs.getURIResourceMap().size());
    rs.getResources().clear();
    Assert.assertTrue(resource.eAdapters().isEmpty());
    Assert.assertEquals(0, rs.getURIResourceMap().size());
}
Also used : XtextResourceSet(org.eclipse.xtext.resource.XtextResourceSet) XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) XtextResource(org.eclipse.xtext.resource.XtextResource) AbstractResourceSetTest(org.eclipse.xtext.resource.AbstractResourceSetTest) Test(org.junit.Test)

Example 12 with XtextResource

use of org.eclipse.xtext.resource.XtextResource in project xtext-core by eclipse.

the class AbstractXtextResourceSetTest method testResourcesAreInMapWithNormalizedURI_02.

@Test
public void testResourcesAreInMapWithNormalizedURI_02() {
    final XtextResourceSet rs = this.createEmptyResourceSet();
    Assert.assertEquals(0, rs.getURIResourceMap().size());
    final XtextResource resource = new XtextResource();
    resource.setURI(URI.createURI("/a/../foo"));
    EList<Resource> _resources = rs.getResources();
    ArrayList<Resource> _newArrayList = CollectionLiterals.<Resource>newArrayList(resource);
    Iterables.<Resource>addAll(_resources, _newArrayList);
    Assert.assertEquals(2, rs.getURIResourceMap().size());
    rs.getResources().remove(resource);
    Assert.assertTrue(resource.eAdapters().isEmpty());
    Assert.assertEquals(0, rs.getURIResourceMap().size());
}
Also used : XtextResourceSet(org.eclipse.xtext.resource.XtextResourceSet) XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) XtextResource(org.eclipse.xtext.resource.XtextResource) AbstractResourceSetTest(org.eclipse.xtext.resource.AbstractResourceSetTest) Test(org.junit.Test)

Example 13 with XtextResource

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

the class PolyfillValidatorFragment method holdsSinglePolyfillSource.

/**
 * Constraints 129 (Applying Polyfills) No member must be filled by more than one polyfill.
 */
private boolean holdsSinglePolyfillSource(PolyfillValidationState state) {
    EList<TMember> myPolyMember = state.polyType.getOwnedMembers();
    // a) find references to the filled type
    // b) check, that they are in the same Project
    // c) search for clashing contributions.
    XtextResource res = (XtextResource) state.polyType.eResource();
    IResourceDescriptions index = resourceDescriptionsProvider.getResourceDescriptions(res);
    // a+b) all polyfills to same calssifier in same project:
    IContainer container = containerManager.getContainer(res.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(res), index);
    // Iterable over all exported Polyfills
    Iterable<IEObjectDescription> iterEObj = container.getExportedObjects(TypesPackage.Literals.TCLASSIFIER, N4TSQualifiedNameProvider.getPolyfillFQN(state.filledType, qualifiedNameProvider), false);
    // collection of involved TModules for each Member.
    ListMultimap<TMember, TModule> clashProviders = LinkedListMultimap.create();
    for (IEObjectDescription pivotObjectDescription : iterEObj) {
        EObject eob = pivotObjectDescription.getEObjectOrProxy();
        // Resolve
        if (eob.eIsProxy()) {
            eob = EcoreUtil.resolve(eob, res);
        }
        if (eob == state.polyType) {
            // saw myself .-.
            continue;
        }
        EList<TMember> pivotPolyMember = ((TClassifier) eob).getOwnedMembers();
        ListMultimap<TMember, TMember> clashing = findClashingMembersByName(myPolyMember, pivotPolyMember);
        for (TMember myMember : clashing.keySet()) {
            // only interested in the module, so first is sufficient
            clashProviders.put(myMember, clashing.get(myMember).get(0).getContainingModule());
        }
    }
    List<TMember> sortedMembers = clashProviders.keySet().stream().sorted().collect(Collectors.toList());
    for (TMember myMember : sortedMembers) {
        // Combine list of Modules involved in the polyfill clash.
        String uris = Stream.concat(Stream.of(myMember.getContainingModule()), clashProviders.get(myMember).stream()).map(u -> u.getQualifiedName().toString()).sorted().reduce("", (a, b) -> a + PREFIX_LIST + b);
        if (uris.startsWith(PREFIX_LIST))
            uris = uris.substring(PREFIX_LIST.length());
        int lastPrefix_idx = uris.lastIndexOf(PREFIX_LIST);
        if (lastPrefix_idx >= 0) {
            StringBuffer sb = new StringBuffer(uris);
            uris = sb.replace(lastPrefix_idx, lastPrefix_idx + PREFIX_LIST.length(), " and ").toString();
        }
        // give Qualified name filled in Property.
        String memberAxis = myMember.getContainingType().getName() + "." + myMember.getName();
        // Issue on filled Member-name declaration:
        String msg = IssueCodes.getMessageForCLF_POLYFILL_MULTIPOLYFILLS_MEMBER_CONFLICT(uris, memberAxis);
        state.host.addIssue(msg, myMember.getAstElement(), N4JSPackage.Literals.PROPERTY_NAME_OWNER__DECLARED_NAME, IssueCodes.CLF_POLYFILL_MULTIPOLYFILLS_MEMBER_CONFLICT);
    }
    return true;
}
Also used : TClassifier(org.eclipse.n4js.ts.types.TClassifier) XtextResource(org.eclipse.xtext.resource.XtextResource) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) IResourceDescriptions(org.eclipse.xtext.resource.IResourceDescriptions) EObject(org.eclipse.emf.ecore.EObject) TMember(org.eclipse.n4js.ts.types.TMember) IContainer(org.eclipse.xtext.resource.IContainer) TModule(org.eclipse.n4js.ts.types.TModule)

Example 14 with XtextResource

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

the class XpectN4JSES5TranspilerHelper method doCompileAndExecute.

/**
 * Compile provided resource, execute in Node.js and return execution output.
 *
 * @param resource
 *            Script to execute
 * @param init
 *            xpect setup-init
 * @param fileSetupContext
 *            xpect injected
 * @param decorateStdStreams
 *            false-just connect stdout+stderr or errors to resulting string, true - decorate the streams with "<==
 *            stdout: ..."
 * @param resourceTweaker
 *            - resource-modifier like QuickFix application, can be null
 * @param systemLoader
 *            the system loader to use (SYSTEM_JS[default], COMMON_JS,...)
 * @return output streams concatenated
 */
public String doCompileAndExecute(final XtextResource resource, org.eclipse.xpect.setup.ISetupInitializer<Object> init, FileSetupContext fileSetupContext, boolean decorateStdStreams, ResourceTweaker resourceTweaker, GeneratorOption[] options, SystemLoaderInfo systemLoader) throws IOException {
    // Apply some modification to the resource here.
    if (resourceTweaker != null) {
        resourceTweaker.tweak(resource);
    }
    loadXpectConfiguration(init, fileSetupContext);
    File artificialRoot = Files.createTempDirectory("n4jsXpect").toFile();
    RunConfiguration runConfig;
    // && (((ReadOutWorkspaceConfiguration) readOutConfiguration).getXpectConfiguredWorkspace() == null)
    if (Platform.isRunning()) {
        // If we are in the IDE, execute the test the same as for "Run in Node.js" and this way avoid
        // the effort of calculating dependencies etc.
        final String implementationId = chooseImplHelper.chooseImplementationIfRequired(NodeRunner.ID, resource.getURI().trimFileExtension());
        boolean replaceQuotes = false;
        // We have to generate JS code for the resource. Because if Xpect test is quickfixAndRun the resource
        // contains errors and hence no generated JS code is available for execution.
        // Then sneak in the path to the generated JS code.
        Script script = (Script) resource.getContents().get(0);
        createTempJsFileWithScript(artificialRoot.toPath(), script, options, replaceQuotes);
        runConfig = runnerFrontEnd.createConfiguration(NodeRunner.ID, (implementationId == ChooseImplementationHelper.CANCEL) ? null : implementationId, systemLoader.getId(), resource.getURI().trimFileExtension(), artificialRoot.getAbsolutePath().toString());
    } else {
        // In the non-GUI case, we need to calculate dependencies etc. manually
        final Iterable<Resource> dependencies = from(getDependentResources());
        boolean replaceQuotes = false;
        // compile all file resources
        StringBuilder errorResult = new StringBuilder();
        Script testScript = (Script) resource.getContents().get(0);
        // replace n4jsd resource with provided js resource
        for (final Resource dep : from(dependencies).filter(r -> !r.getURI().equals(resource.getURI()))) {
            if ("n4jsd".equalsIgnoreCase(dep.getURI().fileExtension())) {
                compileImplementationOfN4JSDFile(artificialRoot.toPath(), errorResult, dep, options, replaceQuotes);
            } else if (xpectGenerator.isCompilable(dep, errorResult)) {
                final Script script = (Script) dep.getContents().get(0);
                createTempJsFileWithScript(artificialRoot.toPath(), script, options, replaceQuotes);
            }
        }
        if (errorResult.length() != 0) {
            return errorResult.toString();
        }
        // No error so far
        // determine module to run
        createTempJsFileWithScript(artificialRoot.toPath(), testScript, options, replaceQuotes);
        String fileToRun = jsModulePathToRun(testScript);
        // Not in UI case, hence manually set up the resources
        runConfig = runnerFrontEnd.createXpectOutputTestConfiguration(NodeRunner.ID, fileToRun, systemLoader, artificialRoot.toPath().toString() + "/" + testScript.getModule().getProjectId());
    }
    return configRunner.executeWithConfig(runConfig, decorateStdStreams);
}
Also used : Script(org.eclipse.n4js.n4JS.Script) RunConfiguration(org.eclipse.n4js.runner.RunConfiguration) XtextResource(org.eclipse.xtext.resource.XtextResource) Resource(org.eclipse.emf.ecore.resource.Resource) File(java.io.File)

Example 15 with XtextResource

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

the class HyperlinkXpectMethod method hyperlinks.

/**
 * @param expectation
 *            a list of expected URIs to jump to by this hyperlink
 * @param resource
 *            the resource under test
 * @param region
 *            the offset where hyperlinking should be invoked
 * @throws Exception
 *             some exceptions
 */
@ParameterParser(syntax = "('at' arg2=STRING)?")
@Xpect
public void hyperlinks(// arg0
@CommaSeparatedValuesExpectation ICommaSeparatedValuesExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2
RegionWithCursor region) throws Exception {
    ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    String currentModelToParse = resource.getParseResult().getRootNode().getText();
    IXtextDocument xtextDocument = fixture.getDocument(resource, currentModelToParse);
    // 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);
    ITextViewer sourceViewer = fixture.getSourceViewer(currentModelToParse, xtextDocument);
    IHyperlink[] hyperlinks = hyperlinkDetector.detectHyperlinks(sourceViewer, new Region(region.getGlobalCursorOffset(), 0), true);
    // cleaned up resource, otherwise #createTestBuilder() above will fail next time this method is called
    XtextResourceCleanUtil.cleanXtextResource(resource);
    ArrayList<String> result = Lists.newArrayList();
    if (hyperlinks != null) {
        for (IHyperlink hyperlink : hyperlinks) {
            result.add(getTargetDescription(resource, hyperlink));
        }
    }
    expectation.assertEquals(result);
}
Also used : ContentAssistProcessorTestBuilder(org.eclipse.xtext.ui.testing.ContentAssistProcessorTestBuilder) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) 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) Region(org.eclipse.jface.text.Region) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) ITextViewer(org.eclipse.jface.text.ITextViewer) 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