Search in sources :

Example 31 with TModule

use of org.eclipse.n4js.ts.types.TModule in project n4js by eclipse.

the class ScriptApiTracker method interfaceApiSupertypeWalker.

/**
 * This methods takes an API-Element and pulls the projectComparisons along the suptertype chain.
 *
 * Does nothing if apiElement is null.
 *
 * @param filter
 *            applied to each encountered projectComparison
 * @param actionProvider
 *            function to apply on filtered ProjectComparinsonEntries.
 * @param apiElement
 *            concrete API element to start from.
 */
public <T extends TClassifier> void interfaceApiSupertypeWalker(Predicate<? super ProjectComparisonEntry> filter, Function<T, Consumer<? super ProjectComparisonEntry>> actionProvider, ProjectComparisonAdapter projectComparisonAdapter, /* ProjectComparisonEntry compareEntry, */
T apiElement, Class<T> castGuard) {
    if (apiElement == null) {
        // from projects
        return;
    }
    LinkedHashSet<T> toBeProcessedSuperInterfaces = new LinkedHashSet<>();
    LinkedHashSet<T> processedSuperInterfaces = new LinkedHashSet<>();
    // Yes it is correct ~Not correct~, since we need VirtualMethods for the direct missing parts:: //
    toBeProcessedSuperInterfaces.add(apiElement);
    while (!toBeProcessedSuperInterfaces.isEmpty()) {
        Iterator<T> iter = toBeProcessedSuperInterfaces.iterator();
        T pivot = iter.next();
        iter.remove();
        // do not process built-in types
        if (TypeUtils.isBuiltIn(pivot)) {
            continue;
        }
        // collect to be processed:
        includeAdditionsSuperInterfaces2(toBeProcessedSuperInterfaces, processedSuperInterfaces, pivot, castGuard);
        // go over methods.
        // Is the superInterface from the same Project ? If not it cannot be an API problem of this
        // implementation.
        TModule superModule = pivot.getContainingModule();
        if (superModule != null) {
            ProjectComparisonEntry useCompareEntry = projectComparisonAdapter.getEntryFor(superModule);
            if (useCompareEntry == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("No comparison found for pivot = " + pivot.getName());
                }
            } else {
                // Is there an API entry at all ? --> If not it was just a normal implementation of some library ?
                ProjectComparisonEntry superInterfaceCompareEntry = useCompareEntry.getChildForElementAPI(pivot);
                if (superInterfaceCompareEntry != null) {
                    // Is there a difference between this API and the implementations ?
                    if (superInterfaceCompareEntry.hasChildren()) {
                        // get the ones which are missing implementations; others are real errors and will not be
                        // touched!
                        superInterfaceCompareEntry.allChildren().filter(filter).forEach(actionProvider.apply(pivot));
                    }
                }
            // end if superInterfaceCompareEntry != null
            }
        } else // end if null-check for module...
        {
            if (logger.isDebugEnabled()) {
                logger.debug("-#- could not get module for super-classifier: " + pivot.getName() + " of type " + pivot.getTypeAsString() + " providedByRuntime=" + pivot.isProvidedByRuntime());
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TModule(org.eclipse.n4js.ts.types.TModule) ProjectComparisonEntry(org.eclipse.n4js.compare.ProjectComparisonEntry)

Example 32 with TModule

use of org.eclipse.n4js.ts.types.TModule in project n4js by eclipse.

the class EditorContentExtractor method getDescriptorForSemanticElement.

/**
 * Optionally returns with the semantic AST node element (given as the element URI) as a {@link StyledTextDescriptor
 * styled text descriptor}. If the element cannot be resolved or the styled text cannot be computed this method
 * returns with and {@link Optional#absent() absent} instance but never {@code null}.
 *
 * @param uri
 *            the URI of the semantic element in the AST.
 * @return a styled text descriptor representing the extracted code for the semantic AST node given with its unique
 *         URI.
 */
public Optional<StyledTextDescriptor> getDescriptorForSemanticElement(final URI uri) {
    if (null == uri) {
        return absent();
    }
    final URI trimmedUri = uri.hasFragment() ? uri.trimFragment() : uri;
    final IN4JSProject project = core.findProject(trimmedUri).orNull();
    if (project == null) {
        return absent();
    }
    final ResourceSet resSet = core.createResourceSet(Optional.of(project));
    final IResourceDescriptions index = core.getXtextIndex(resSet);
    final IResourceDescription resDesc = index.getResourceDescription(trimmedUri);
    if (null == resDesc) {
        return absent();
    }
    final TModule module = core.loadModuleFromIndex(resSet, resDesc, false);
    if (null == module || null == module.eResource() || null == module.eResource().getResourceSet()) {
        return absent();
    }
    final URI moduleUri = module.eResource().getURI();
    final IFile file = getWorkspace().getRoot().getFile(new Path(moduleUri.toPlatformString(true)));
    if (null == file || !file.exists()) {
        return absent();
    }
    final FileEditorInput editorInput = new FileEditorInput(file);
    try {
        docProvider.connect(editorInput);
    } catch (final CoreException e) {
        LOGGER.error("Error while connecting editor input with document provider: " + e);
        return absent();
    }
    final IDocument doc = docProvider.getDocument(editorInput);
    if (null == doc) {
        return absent();
    }
    final XtextResource xtextResource = (XtextResource) module.eResource();
    final ResourceSet resourceSet = xtextResource.getResourceSet();
    final EObject object = resourceSet.getEObject(uri, true);
    if (null == object) {
        return absent();
    }
    final ITextRegion textRegion = locationInFileProvider.getFullTextRegion(object);
    if (null == textRegion) {
        return absent();
    }
    try {
        final int lineOfOffset = doc.getLineOfOffset(textRegion.getOffset());
        final int lineOffset = doc.getLineOffset(lineOfOffset);
        final int offset = lineOffset;
        final int length = textRegion.getLength() + (textRegion.getOffset() - lineOffset);
        final String text = doc.get(offset, length);
        final IPresentationRepairer repairer = repairerProvider.get();
        final IPresentationDamager damager = damagerProvider.get();
        for (final String contentType : partitionTypeMapper.getSupportedPartitionTypes()) {
            reconciler.setRepairer(repairer, contentType);
            repairer.setDocument(doc);
            reconciler.setDamager(damager, contentType);
            damager.setDocument(doc);
        }
        final Region region = new Region(offset, length);
        final TextPresentation textPresentation = reconciler.createRepairDescription(region, doc);
        final Iterator<?> rangeItr = textPresentation.getAllStyleRangeIterator();
        final Collection<StyleRange> ranges = newLinkedList();
        while (rangeItr.hasNext()) {
            final Object next = rangeItr.next();
            if (next instanceof StyleRange) {
                ranges.add((StyleRange) next);
            }
        }
        final Range<Integer> textRange = Range.closed(offset, offset + length);
        for (final Iterator<StyleRange> itr = ranges.iterator(); itr.hasNext(); ) /* nothing */
        {
            final StyleRange range = itr.next();
            if (!textRange.contains(range.start) || !textRange.contains(range.start + range.length)) {
                itr.remove();
            } else {
                range.start = range.start - offset;
            }
        }
        return fromNullable(new StyledTextDescriptorImpl(text, ranges));
    } catch (final BadLocationException e) {
        LOGGER.error("Error while trying to extract text from document.", e);
        return absent();
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) StyleRange(org.eclipse.swt.custom.StyleRange) XtextResource(org.eclipse.xtext.resource.XtextResource) URI(org.eclipse.emf.common.util.URI) IPresentationRepairer(org.eclipse.jface.text.presentation.IPresentationRepairer) IN4JSProject(org.eclipse.n4js.projectModel.IN4JSProject) EObject(org.eclipse.emf.ecore.EObject) TModule(org.eclipse.n4js.ts.types.TModule) IPresentationDamager(org.eclipse.jface.text.presentation.IPresentationDamager) TextPresentation(org.eclipse.jface.text.TextPresentation) Path(org.eclipse.core.runtime.Path) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) CoreException(org.eclipse.core.runtime.CoreException) ITextRegion(org.eclipse.xtext.util.ITextRegion) IResourceDescriptions(org.eclipse.xtext.resource.IResourceDescriptions) FileEditorInput(org.eclipse.ui.part.FileEditorInput) Region(org.eclipse.jface.text.Region) ITextRegion(org.eclipse.xtext.util.ITextRegion) EObject(org.eclipse.emf.ecore.EObject) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 33 with TModule

use of org.eclipse.n4js.ts.types.TModule in project n4js by eclipse.

the class ProjectCompareHelper method createEntries.

// may be made public later
private ProjectComparisonEntry createEntries(ProjectComparison root, IN4JSProject api, IN4JSProject[] impls, ResourceSet resourceSet, IResourceDescriptions index) {
    final ProjectComparisonEntry entry = new ProjectComparisonEntry(root, api, impls);
    for (IN4JSSourceContainer currSrcConti : api.getSourceContainers()) {
        for (URI uri : currSrcConti) {
            final String uriStr = uri.toString();
            if (uriStr.endsWith("." + N4JSGlobals.N4JS_FILE_EXTENSION) || uriStr.endsWith("." + N4JSGlobals.N4JSD_FILE_EXTENSION)) {
                final IResourceDescription resDesc = index.getResourceDescription(uri);
                final TModule moduleApi = getModuleFrom(resourceSet, resDesc);
                if (moduleApi != null) {
                    final TModule[] moduleImpls = new TModule[impls.length];
                    for (int idx = 0; idx < impls.length; idx++) {
                        final IN4JSProject projectImpl = impls[idx];
                        if (projectImpl != null)
                            moduleImpls[idx] = findImplementation(moduleApi, projectImpl, resourceSet, index);
                        else
                            moduleImpls[idx] = null;
                    }
                    createEntries(entry, -1, moduleApi, moduleImpls, false);
                }
            }
        }
    }
    return entry;
}
Also used : IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) IN4JSProject(org.eclipse.n4js.projectModel.IN4JSProject) TModule(org.eclipse.n4js.ts.types.TModule) URI(org.eclipse.emf.common.util.URI) IN4JSSourceContainer(org.eclipse.n4js.projectModel.IN4JSSourceContainer)

Example 34 with TModule

use of org.eclipse.n4js.ts.types.TModule in project n4js by eclipse.

the class N4JSResource method performPostProcessing.

@Override
public void performPostProcessing(CancelIndicator cancelIndicator) {
    // make sure post-processing is never performed in pre-linking phase
    // FIXME should never happen -> better throw an exception here if isPreLinkingPhase===true?
    final TModule module = getModule();
    final boolean isPreLinkingPhase = module != null && module.isPreLinkingPhase();
    if (!isPreLinkingPhase) {
        super.performPostProcessing(cancelIndicator);
    }
}
Also used : TModule(org.eclipse.n4js.ts.types.TModule)

Example 35 with TModule

use of org.eclipse.n4js.ts.types.TModule in project n4js by eclipse.

the class N4JSResource method demandLoadResource.

/**
 * Discards the current content of the resource, sets the parser result as first slot, installs derived state (this
 * will build up the second slot again) and sends notifications that proxies have been resolved. The resource will
 * be even loaded if its already marked as loaded.
 *
 * If the second slot, that is the TModule, was already loaded and we just resolved the AST, then the existing
 * TModule is kept in the resource and rewired to the resolved AST.
 *
 * @param object
 *            the object which resource should be loaded
 * @return the loaded/resolved object
 */
private EObject demandLoadResource(EObject object) {
    TModule oldModule = null;
    EObject oldScript = null;
    ModuleAwareContentsList myContents = ((ModuleAwareContentsList) contents);
    try {
        oldModule = discardStateFromDescription(false);
        if (!myContents.isEmpty()) {
            oldScript = myContents.basicGet(0);
            myContents.sneakyClear();
        }
        // now everything is removed from the resource and contents is empty
        // stop sending notifications
        eSetDeliver(false);
        if (isLoaded) {
            // Loads the resource even its marked as being already loaded
            isLoaded = false;
        }
        superLoad(null);
        // manually send the notification
        eSetDeliver(true);
        EObject result = getParseResult().getRootASTElement();
        if (myContents.isEmpty()) {
            myContents.sneakyAdd(0, result);
            if (oldModule != null) {
                myContents.sneakyAdd(oldModule);
            }
            forceInstallDerivedState(false);
        } else {
            if (myContents.size() == 1) {
                if (oldModule != null) {
                    myContents.sneakyAdd(oldModule);
                }
            }
            installDerivedState(false);
        }
        if (oldScript != null) {
            notifyProxyResolved(0, oldScript);
        }
        fullyPostProcessed = false;
        return result;
    } catch (IOException | IllegalStateException ioe) {
        if (myContents.isEmpty()) {
            myContents.sneakyAdd(oldScript);
            myContents.sneakyAdd(oldModule);
        }
        Throwable cause = ioe.getCause();
        if (cause instanceof CoreException) {
            IStatus status = ((CoreException) cause).getStatus();
            if (IResourceStatus.RESOURCE_NOT_FOUND == status.getCode()) {
                return object;
            }
        }
        logger.error("Error in demandLoadResource for " + getURI(), ioe);
        return object;
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) CoreException(org.eclipse.core.runtime.CoreException) EObject(org.eclipse.emf.ecore.EObject) InternalEObject(org.eclipse.emf.ecore.InternalEObject) IOException(java.io.IOException) TModule(org.eclipse.n4js.ts.types.TModule)

Aggregations

TModule (org.eclipse.n4js.ts.types.TModule)48 EObject (org.eclipse.emf.ecore.EObject)12 Resource (org.eclipse.emf.ecore.resource.Resource)8 URI (org.eclipse.emf.common.util.URI)7 Type (org.eclipse.n4js.ts.types.Type)7 TMember (org.eclipse.n4js.ts.types.TMember)6 IResourceDescription (org.eclipse.xtext.resource.IResourceDescription)5 InternalEObject (org.eclipse.emf.ecore.InternalEObject)4 ENotificationImpl (org.eclipse.emf.ecore.impl.ENotificationImpl)4 Script (org.eclipse.n4js.n4JS.Script)4 IN4JSProject (org.eclipse.n4js.projectModel.IN4JSProject)4 IEObjectDescription (org.eclipse.xtext.resource.IEObjectDescription)4 N4JSResource (org.eclipse.n4js.resource.N4JSResource)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 CoreException (org.eclipse.core.runtime.CoreException)2 XMIResource (org.eclipse.emf.ecore.xmi.XMIResource)2 XMIResourceImpl (org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl)2 ImportDeclaration (org.eclipse.n4js.n4JS.ImportDeclaration)2 ContainerType (org.eclipse.n4js.ts.types.ContainerType)2