Search in sources :

Example 1 with N4JSResource

use of org.eclipse.n4js.resource.N4JSResource in project n4js by eclipse.

the class FindReferencesXpectMethod method findReferences.

/**
 * This Xpect methods compares all computed references at a given EObject to the expected references. The expected
 * references include the line number.
 */
@Xpect
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
public void findReferences(@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation, IEObjectCoveringRegion offset) {
    // When you write Xpect test methods, ALWAYS retrieve eObject via IEObjectCoveringRegion to get the right
    // eObject!
    // Do NOT use EObject arg1!
    EObject context = offset.getEObject();
    EObject argEObj = offsetHelper.resolveElementAt((XtextResource) context.eResource(), offset.getOffset());
    // If not a cross-reference element, use context instead
    if (argEObj == null)
        argEObj = context;
    EObject eObj = argEObj;
    if (argEObj instanceof ParameterizedTypeRef)
        eObj = ((ParameterizedTypeRef) argEObj).getDeclaredType();
    List<EObject> refs = findReferenceHelper.findReferences(eObj);
    ArrayList<String> result = Lists.newArrayList();
    for (EObject ref : refs) {
        if (ref instanceof PropertyNameOwner)
            ref = ((PropertyNameOwner) ref).getDeclaredName();
        ICompositeNode srcNode = NodeModelUtils.getNode(ref);
        int line = srcNode.getStartLine();
        String moduleName;
        if (ref.eResource() instanceof N4JSResource) {
            N4JSResource n4jsResource = (N4JSResource) ref.eResource();
            moduleName = n4jsResource.getModule().getQualifiedName();
        } else {
            moduleName = "(unknown resource)";
        }
        String text = NodeModelUtils.getTokenText(srcNode);
        if (ref instanceof GenericDeclaration)
            text = ((GenericDeclaration) ref).getDefinedType().getName();
        String resultText = moduleName + " - " + text + " - " + line;
        result.add(resultText);
    }
    expectation.assertEquals(result);
}
Also used : ParameterizedTypeRef(org.eclipse.n4js.ts.typeRefs.ParameterizedTypeRef) PropertyNameOwner(org.eclipse.n4js.n4JS.PropertyNameOwner) EObject(org.eclipse.emf.ecore.EObject) N4JSResource(org.eclipse.n4js.resource.N4JSResource) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) GenericDeclaration(org.eclipse.n4js.n4JS.GenericDeclaration) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 2 with N4JSResource

use of org.eclipse.n4js.resource.N4JSResource in project n4js by eclipse.

the class EcmaScriptSubGenerator method internalDoGenerate.

@Override
protected void internalDoGenerate(Resource resource, GeneratorOption[] options, IFileSystemAccess fsa) {
    if (!(resource instanceof N4JSResource)) {
        if (IN4JSProject.N4MF_MANIFEST.equals(resource.getURI().lastSegment())) {
            return;
        }
        throw new IllegalArgumentException("Given resource is not an N4JSResource. " + resource);
    }
    final N4JSResource resourceCasted = (N4JSResource) resource;
    if (resourceCasted.getModule().isStaticPolyfillModule()) {
        // do not transpile static polyfill modules (i.e. the fillers)
        return;
    }
    Measurement measurement = this.collector.getMeasurement(resource.getURI().toString());
    /*
		 * In addition to here, check for cancellation is done also on file-emit boundaries, see fsa.generateFile().
		 */
    CancelIndicator monitor = ciExtractor.extractCancelIndicator(fsa);
    // if the transpile-conditions are all met, then transpile:
    if (shouldBeCompiled(resource, monitor)) {
        final String compiledFileExtension = getCompiledFileExtension(resource);
        final String filename = getTargetFileName(resource, compiledFileExtension);
        final String sourceMapFileExtension = getCompiledFileSourceMapExtension(resource);
        final String sourceMapFileName = getTargetFileName(resource, sourceMapFileExtension);
        // used within the file-content to refer to sibling-file:
        final String simpleSourceMapFileName = new File(sourceMapFileName).toPath().getFileName().toString();
        final String simpleCompiledFileName = new File(filename).toPath().getFileName().toString();
        // the next two variables store the navigation-prefix to get to the sources
        final Path relativeNavigationToSrc = calculateNavigationFromOutputToSourcePath(fsa, getCompilerID(), resourceCasted);
        final Path explicitNavigationToSrc = Paths.get("/sources");
        // true use explicitNavigationToSrc | false use relativeNavigationToSrc
        boolean useExplicitSourceRef = true;
        boolean createSourceMap = true;
        if (filename != null) {
            final EObject root = rootElement(resource);
            if (root != null) {
                final Writer buffCode = new StringWriter();
                Optional<SourceMapInfo> optSourceMapData = Optional.absent();
                if (createSourceMap) {
                    SourceMapInfo sourceMapDataInstance = getTranspiler().new SourceMapInfo();
                    sourceMapDataInstance.sourceMapBuff = new StringWriter();
                    sourceMapDataInstance.simpleSourceMapFileName = simpleSourceMapFileName;
                    sourceMapDataInstance.simpleCompiledFileName = simpleCompiledFileName;
                    sourceMapDataInstance.isExplicitSourceRef = useExplicitSourceRef;
                    sourceMapDataInstance.explicitNavigationToSrc = explicitNavigationToSrc;
                    sourceMapDataInstance.n4jsFilePath = relativeNavigationToSrc.resolve(resourceCasted.getURI().lastSegment()).toString();
                    sourceMapDataInstance.sourceMapFileExtension = sourceMapFileExtension;
                    optSourceMapData = Optional.of(sourceMapDataInstance);
                }
                getTranspiler().transpile(resourceCasted, options, buffCode, optSourceMapData);
                fsa.generateFile(filename, COMPILER_ID, buffCode.toString());
                if (createSourceMap) {
                    fsa.generateFile(sourceMapFileName, COMPILER_ID, optSourceMapData.get().sourceMapBuff.toString());
                }
            }
        }
    }
    measurement.end();
}
Also used : Measurement(org.eclipse.n4js.smith.Measurement) Path(java.nio.file.Path) SourceMapInfo(org.eclipse.n4js.transpiler.AbstractTranspiler.SourceMapInfo) StringWriter(java.io.StringWriter) EObject(org.eclipse.emf.ecore.EObject) N4JSResource(org.eclipse.n4js.resource.N4JSResource) CancelIndicator(org.eclipse.xtext.util.CancelIndicator) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 3 with N4JSResource

use of org.eclipse.n4js.resource.N4JSResource in project n4js by eclipse.

the class N4JSDirtyStateEditorSupport method collectTransitivelyDependentResources.

private List<Resource> collectTransitivelyDependentResources(XtextResource resource, Set<URI> deltaURIs) {
    List<Resource> result = Lists.newArrayList();
    ResourceSet resourceSet = resource.getResourceSet();
    for (Resource candidate : resourceSet.getResources()) {
        if (candidate != resource) {
            URI uri = candidate.getURI();
            if (deltaURIs.contains(uri)) {
                // the candidate is contained in the delta list
                // schedule it for unloading
                result.add(candidate);
            } else if (candidate instanceof N4JSResource) {
                // schedule it for unloading
                if (canLoadFromDescriptionHelper.dependsOnAny(candidate, deltaURIs)) {
                    result.add(candidate);
                }
            }
        }
    }
    return result;
}
Also used : XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSResource(org.eclipse.n4js.resource.N4JSResource) Resource(org.eclipse.emf.ecore.resource.Resource) N4JSResource(org.eclipse.n4js.resource.N4JSResource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) URI(org.eclipse.emf.common.util.URI)

Example 4 with N4JSResource

use of org.eclipse.n4js.resource.N4JSResource in project n4js by eclipse.

the class MarkedProject method unloadASTAndClearCaches.

/**
 * Unload the ASTs and clear the resource scope caches of all resources that belong to this marked project.
 */
public void unloadASTAndClearCaches() {
    Iterables.filter(resources, resource -> resource.isLoaded()).forEach(resource -> {
        if (resource instanceof N4JSResource) {
            N4JSResource n4jsResource = (N4JSResource) resource;
            n4jsResource.unloadAST();
        }
    });
}
Also used : HashSet(java.util.HashSet) N4JSResource(org.eclipse.n4js.resource.N4JSResource) Iterables(com.google.common.collect.Iterables) URI(org.eclipse.emf.common.util.URI) Optional(com.google.common.base.Optional) IN4JSProject(org.eclipse.n4js.projectModel.IN4JSProject) Resource(org.eclipse.emf.ecore.resource.Resource) Set(java.util.Set) ResourceDescriptionsData(org.eclipse.xtext.resource.impl.ResourceDescriptionsData) LinkedHashSet(java.util.LinkedHashSet) TreeSet(java.util.TreeSet) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) N4JSResource(org.eclipse.n4js.resource.N4JSResource)

Example 5 with N4JSResource

use of org.eclipse.n4js.resource.N4JSResource in project n4js by eclipse.

the class N4HeadlessCompiler method postProcessResources.

/*
	 * ===============================================================================================================
	 *
	 * PROJECT POST-PROCESSING
	 *
	 * ===============================================================================================================
	 */
/**
 * Post processing on the whole project. While validations can trigger post processing in a lazy way, they do not
 * guarantee that all resources will be fully processed. This is an issue in larger project graphs. Unlike in the
 * IDE which can at any point load AST on demand based on the TModel, the HLC does not allow to access AST after
 * unloading therefore we explicitly post process all N4JS resources in the given project.
 *
 * @param markedProject
 *            project to trigger post process.
 */
private void postProcessResources(MarkedProject markedProject) {
    if (logger.isCreateDebugOutput())
        logger.debug(" PostProcessing " + markedProject);
    Iterables.filter(markedProject.resources, resource -> resource.isLoaded()).forEach(resource -> {
        if (resource instanceof N4JSResource) {
            N4JSResource n4jsResource = (N4JSResource) resource;
            // Make sure the resource is fully postprocessed before unloading the AST. Otherwise, resolving
            // cross references to the elements inside the resources from dependent projects will fail.
            n4jsResource.performPostProcessing();
        }
    });
}
Also used : Arrays(java.util.Arrays) SortedSet(java.util.SortedSet) ListIterator(java.util.ListIterator) Inject(com.google.inject.Inject) FileUtils(org.eclipse.n4js.utils.io.FileUtils) IN4JSCore(org.eclipse.n4js.projectModel.IN4JSCore) IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) IN4JSSourceContainer(org.eclipse.n4js.projectModel.IN4JSSourceContainer) HashMultimap(com.google.common.collect.HashMultimap) TreeMultimap(com.google.common.collect.TreeMultimap) Optional(com.google.common.base.Optional) Map(java.util.Map) Path(java.nio.file.Path) Collections2(org.eclipse.n4js.utils.collections.Collections2) N4JSModel(org.eclipse.n4js.internal.N4JSModel) BiMap(com.google.common.collect.BiMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) IN4JSProject(org.eclipse.n4js.projectModel.IN4JSProject) Set(java.util.Set) IHeadlessLogger(org.eclipse.n4js.generator.headless.logging.IHeadlessLogger) ResourceDescriptionsData(org.eclipse.xtext.resource.impl.ResourceDescriptionsData) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) DelegatingIAllContainerAdapter(org.eclipse.xtext.resource.containers.DelegatingIAllContainerAdapter) List(java.util.List) FileBasedWorkspace(org.eclipse.n4js.internal.FileBasedWorkspace) Resource(org.eclipse.emf.ecore.resource.Resource) ResourceType(org.eclipse.n4js.utils.ResourceType) CheckMode(org.eclipse.xtext.validation.CheckMode) Joiner(com.google.common.base.Joiner) Iterables(com.google.common.collect.Iterables) URI(org.eclipse.emf.common.util.URI) IResourceServiceProvider(org.eclipse.xtext.resource.IResourceServiceProvider) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) N4JSProject(org.eclipse.n4js.internal.N4JSProject) TreeSet(java.util.TreeSet) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) HashSet(java.util.HashSet) JavaIoFileSystemAccess(org.eclipse.xtext.generator.JavaIoFileSystemAccess) ImmutableList(com.google.common.collect.ImmutableList) CancelIndicator(org.eclipse.xtext.util.CancelIndicator) LinkedList(java.util.LinkedList) GeneratorException(org.eclipse.n4js.generator.GeneratorException) XtextResource(org.eclipse.xtext.resource.XtextResource) Severity(org.eclipse.xtext.diagnostics.Severity) N4FilebasedWorkspaceResourceSetContainerState(org.eclipse.n4js.internal.N4FilebasedWorkspaceResourceSetContainerState) DecimalFormat(java.text.DecimalFormat) Lazy(org.eclipse.n4js.utils.Lazy) IResourceValidator(org.eclipse.xtext.validation.IResourceValidator) IOException(java.io.IOException) File(java.io.File) N4JSResource(org.eclipse.n4js.resource.N4JSResource) HashBiMap(com.google.common.collect.HashBiMap) Provider(com.google.inject.Provider) Issue(org.eclipse.xtext.validation.Issue) OrderedResourceDescriptionsData(org.eclipse.n4js.resource.OrderedResourceDescriptionsData) Collections(java.util.Collections) XtextResourceSet(org.eclipse.xtext.resource.XtextResourceSet) N4JSResource(org.eclipse.n4js.resource.N4JSResource)

Aggregations

N4JSResource (org.eclipse.n4js.resource.N4JSResource)21 Resource (org.eclipse.emf.ecore.resource.Resource)10 URI (org.eclipse.emf.common.util.URI)8 EObject (org.eclipse.emf.ecore.EObject)6 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)5 Script (org.eclipse.n4js.n4JS.Script)4 IN4JSProject (org.eclipse.n4js.projectModel.IN4JSProject)3 TModule (org.eclipse.n4js.ts.types.TModule)3 Optional (com.google.common.base.Optional)2 Iterables (com.google.common.collect.Iterables)2 File (java.io.File)2 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 Writer (java.io.Writer)2 Path (java.nio.file.Path)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 TreeSet (java.util.TreeSet)2 QualifiedName (org.eclipse.xtext.naming.QualifiedName)2 XtextResource (org.eclipse.xtext.resource.XtextResource)2