Search in sources :

Example 26 with MetaborgException

use of org.metaborg.core.MetaborgException in project spoofax by metaborg.

the class JSGLRCompletionService method recursiveCompletions.

private Collection<? extends ICompletion> recursiveCompletions(Iterable<IStrategoTerm> leftRecursive, Iterable<IStrategoTerm> rightRecursive, String languageName, ILanguageComponent component, FileObject location) throws MetaborgException {
    Collection<ICompletion> completions = Lists.newLinkedList();
    // call Stratego part of the framework to compute change
    final HybridInterpreter runtime = strategoRuntimeService.runtime(component, location, false);
    final ITermFactory termFactory = termFactoryService.get(component, null, false);
    for (IStrategoTerm term : leftRecursive) {
        IStrategoTerm sort = termFactory.makeString(ImploderAttachment.getSort(term));
        final IStrategoTerm strategoInput = termFactory.makeTuple(sort, term);
        IStrategoTerm proposals = null;
        try {
            proposals = strategoCommon.invoke(runtime, strategoInput, "get-proposals-left-recursive-" + languageName);
        } catch (Exception e) {
            logger.error("Getting proposals for {} failed", term);
            continue;
        }
        if (proposals == null) {
            logger.error("Getting proposals for {} failed", term);
            continue;
        }
        for (IStrategoTerm proposalTerm : proposals) {
            final IStrategoTuple tuple = (IStrategoTuple) proposalTerm;
            if (tuple.getSubtermCount() != 5 || !(tuple.getSubterm(0) instanceof IStrategoString) || !(tuple.getSubterm(1) instanceof IStrategoString) || !(tuple.getSubterm(2) instanceof IStrategoString) || !(tuple.getSubterm(3) instanceof IStrategoAppl) || !(tuple.getSubterm(4) instanceof IStrategoString)) {
                logger.error("Unexpected proposal term {}, skipping", proposalTerm);
                continue;
            }
            final String name = Tools.asJavaString(tuple.getSubterm(0));
            final String text = Tools.asJavaString(tuple.getSubterm(1));
            final String additionalInfo = Tools.asJavaString(tuple.getSubterm(2));
            final StrategoAppl change = (StrategoAppl) tuple.getSubterm(3);
            final String prefix = Tools.asJavaString(tuple.getSubterm(4));
            if (change.getConstructor().getName().contains("REPLACE_TERM")) {
                final ICompletion completion = createCompletionReplaceTerm(name, text, additionalInfo, change, false, prefix, "");
                if (completion == null) {
                    logger.error("Unexpected proposal term {}, skipping", proposalTerm);
                    continue;
                }
                completions.add(completion);
            }
        }
    }
    for (IStrategoTerm term : rightRecursive) {
        IStrategoTerm sort = termFactory.makeString(ImploderAttachment.getSort(term));
        final IStrategoTerm strategoInput = termFactory.makeTuple(sort, term);
        IStrategoTerm proposals = null;
        try {
            proposals = strategoCommon.invoke(runtime, strategoInput, "get-proposals-right-recursive-" + languageName);
        } catch (Exception e) {
            logger.error("Getting proposals for {} failed", term);
            continue;
        }
        if (proposals == null) {
            logger.error("Getting proposals for {} failed", term);
            continue;
        }
        for (IStrategoTerm proposalTerm : proposals) {
            final IStrategoTuple tuple = (IStrategoTuple) proposalTerm;
            if (tuple.getSubtermCount() != 5 || !(tuple.getSubterm(0) instanceof IStrategoString) || !(tuple.getSubterm(1) instanceof IStrategoString) || !(tuple.getSubterm(2) instanceof IStrategoString) || !(tuple.getSubterm(3) instanceof IStrategoAppl) || !(tuple.getSubterm(4) instanceof IStrategoString)) {
                logger.error("Unexpected proposal term {}, skipping", proposalTerm);
                continue;
            }
            final String name = Tools.asJavaString(tuple.getSubterm(0));
            final String text = Tools.asJavaString(tuple.getSubterm(1));
            final String additionalInfo = Tools.asJavaString(tuple.getSubterm(2));
            final StrategoAppl change = (StrategoAppl) tuple.getSubterm(3);
            final String suffix = Tools.asJavaString(tuple.getSubterm(4));
            if (change.getConstructor().getName().contains("REPLACE_TERM")) {
                final ICompletion completion = createCompletionReplaceTerm(name, text, additionalInfo, change, false, "", suffix);
                if (completion == null) {
                    logger.error("Unexpected proposal term {}, skipping", proposalTerm);
                    continue;
                }
                completions.add(completion);
            }
        }
    }
    return completions;
}
Also used : ICompletion(org.metaborg.core.completion.ICompletion) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) HybridInterpreter(org.strategoxt.HybridInterpreter) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) IStrategoTuple(org.spoofax.interpreter.terms.IStrategoTuple) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) ITermFactory(org.spoofax.interpreter.terms.ITermFactory) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) StrategoAppl(org.spoofax.terms.StrategoAppl) MetaborgException(org.metaborg.core.MetaborgException)

Example 27 with MetaborgException

use of org.metaborg.core.MetaborgException in project spoofax by metaborg.

the class JSGLRCompletionService method fromTokens.

// TODO: Do these strategies need to be specific for a language
@Nullable
protected ISourceLocation fromTokens(IStrategoTerm fragment, HybridInterpreter runtime, ITermFactory termFactory, int position, String languageName, Map<IStrategoTerm, Boolean> leftRecursiveTerms, Map<IStrategoTerm, Boolean> rightRecursiveTerms) {
    final FileObject resource = SourceAttachment.getResource(fragment, resourceService);
    final IToken left = ImploderAttachment.getLeftToken(fragment);
    final IToken right = ImploderAttachment.getRightToken(fragment);
    ITokens tokenizer = ImploderAttachment.getTokenizer(fragment);
    IToken leftmostValid = left;
    IToken rightmostValid = right;
    boolean isList = (fragment instanceof IStrategoList) ? true : false;
    boolean isOptional = false;
    String sort = ImploderAttachment.getSort(fragment);
    IStrategoTerm input = termFactory.makeString(sort);
    boolean isLeftRecursive = false;
    if (fragment instanceof IStrategoAppl && position > right.getEndOffset()) {
        try {
            isLeftRecursive = strategoCommon.invoke(runtime, input, "is-left-recursive") != null;
        } catch (MetaborgException e) {
            logger.error("Failed to check recursivity for term {} of sort {} - syntactic completion not activated for this language, please import the completion stratego library", fragment, sort);
        }
    }
    boolean isRightRecursive = false;
    if (fragment instanceof IStrategoAppl && position <= left.getStartOffset()) {
        try {
            isRightRecursive = strategoCommon.invoke(runtime, input, "is-right-recursive") != null;
        } catch (MetaborgException e) {
            logger.error("Failed to check recursivity for term {} of sort {} - syntactic completion not activated for this language, please import the completion stratego library", fragment, sort);
        }
    }
    if (isLeftRecursive) {
        leftRecursiveTerms.put(fragment, true);
    }
    if (isRightRecursive) {
        rightRecursiveTerms.put(fragment, true);
    }
    if (left == null || right == null) {
        return null;
    }
    if (!isList && left == right && left.getEndOffset() < left.getStartOffset()) {
        isOptional = true;
    }
    // if it's a list or a node that is empty make the element includes the surrounding layout tokens
    if (left.getStartOffset() > right.getEndOffset() || isList || isOptional || (isLeftRecursive && isRightRecursive)) {
        for (int i = left.getIndex() - 1; i >= 0; i--) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                leftmostValid = tokenizer.getTokenAt(i);
            } else {
                break;
            }
        }
        for (int i = right.getIndex() + 1; i < tokenizer.getTokenCount(); i++) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_EOF || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                rightmostValid = tokenizer.getTokenAt(i);
            } else {
                break;
            }
        }
    // if it is left recursive include the layout only on the right
    } else if (isLeftRecursive) {
        for (int i = left.getIndex(); i < right.getIndex(); i++) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                leftmostValid = tokenizer.getTokenAt(i + 1);
            } else {
                break;
            }
        }
        for (int i = right.getIndex() + 1; i < tokenizer.getTokenCount(); i++) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_EOF || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                rightmostValid = tokenizer.getTokenAt(i);
            } else {
                break;
            }
        }
    // if it is right recursive include the layout only on the left
    } else if (isRightRecursive) {
        for (int i = left.getIndex() - 1; i >= 0; i--) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                leftmostValid = tokenizer.getTokenAt(i);
            } else {
                break;
            }
        }
        for (int i = right.getIndex(); i > left.getIndex(); i--) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_EOF || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                rightmostValid = tokenizer.getTokenAt(i - 1);
            } else {
                break;
            }
        }
    } else // if not make it stripes the surrounding layout tokens
    {
        for (int i = left.getIndex(); i < right.getIndex(); i++) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                leftmostValid = tokenizer.getTokenAt(i + 1);
            } else {
                break;
            }
        }
        for (int i = right.getIndex(); i > left.getIndex(); i--) {
            if (tokenizer.getTokenAt(i).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(i).getKind() == IToken.TK_EOF || tokenizer.getTokenAt(i).getKind() == IToken.TK_ERROR) {
                rightmostValid = tokenizer.getTokenAt(i - 1);
            } else {
                break;
            }
        }
    }
    final ISourceRegion region = JSGLRSourceRegionFactory.fromTokensLayout(leftmostValid, rightmostValid, (isOptional || isList || isLeftRecursive || isRightRecursive));
    return new SourceLocation(region, resource);
}
Also used : SourceLocation(org.metaborg.core.source.SourceLocation) ISourceLocation(org.metaborg.core.source.ISourceLocation) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) IToken(org.spoofax.jsglr.client.imploder.IToken) MetaborgException(org.metaborg.core.MetaborgException) ISourceRegion(org.metaborg.core.source.ISourceRegion) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) IStrategoList(org.spoofax.interpreter.terms.IStrategoList) FileObject(org.apache.commons.vfs2.FileObject) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) ITokens(org.spoofax.jsglr.client.imploder.ITokens) Nullable(javax.annotation.Nullable)

Example 28 with MetaborgException

use of org.metaborg.core.MetaborgException in project spoofax by metaborg.

the class LanguageComponentFactory method request.

private IComponentCreationConfigRequest request(FileObject root) throws MetaborgException {
    final Collection<String> errors = Lists.newLinkedList();
    final Collection<Throwable> exceptions = Lists.newLinkedList();
    final ConfigRequest<ILanguageComponentConfig> configRequest = componentConfigService.get(root);
    if (!configRequest.valid()) {
        for (IMessage message : configRequest.errors()) {
            errors.add(message.message());
            final Throwable exception = message.exception();
            if (exception != null) {
                exceptions.add(exception);
            }
        }
    }
    final ILanguageComponentConfig config = configRequest.config();
    if (config == null) {
        final String message = logger.format("Cannot retrieve language component configuration at {}", root);
        errors.add(message);
        return new ComponentFactoryRequest(root, errors, exceptions);
    }
    final IStrategoAppl esvTerm;
    try {
        final FileObject esvFile = root.resolveFile("target/metaborg/editor.esv.af");
        if (!esvFile.exists()) {
            esvTerm = null;
        } else {
            esvTerm = esvTerm(root, esvFile);
        }
    } catch (ParseError | IOException | MetaborgException e) {
        exceptions.add(e);
        return new ComponentFactoryRequest(root, errors, exceptions);
    }
    SyntaxFacet syntaxFacet = null;
    StrategoRuntimeFacet strategoRuntimeFacet = null;
    if (esvTerm != null) {
        try {
            syntaxFacet = SyntaxFacetFromESV.create(esvTerm, root);
            if (syntaxFacet != null) {
                Iterables.addAll(errors, syntaxFacet.available());
            }
        } catch (FileSystemException e) {
            exceptions.add(e);
        }
        try {
            strategoRuntimeFacet = StrategoRuntimeFacetFromESV.create(esvTerm, root);
            if (strategoRuntimeFacet != null) {
                Iterables.addAll(errors, strategoRuntimeFacet.available(resourceService));
            }
        } catch (IOException e) {
            exceptions.add(e);
        }
    }
    final ComponentFactoryRequest request;
    if (errors.isEmpty() && exceptions.isEmpty()) {
        request = new ComponentFactoryRequest(root, config, esvTerm, syntaxFacet, strategoRuntimeFacet);
    } else {
        request = new ComponentFactoryRequest(root, errors, exceptions);
    }
    return request;
}
Also used : SyntaxFacet(org.metaborg.spoofax.core.syntax.SyntaxFacet) IMessage(org.metaborg.core.messages.IMessage) MetaborgException(org.metaborg.core.MetaborgException) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) IOException(java.io.IOException) FileSystemException(org.apache.commons.vfs2.FileSystemException) ParseError(org.spoofax.terms.ParseError) FileObject(org.apache.commons.vfs2.FileObject) ILanguageComponentConfig(org.metaborg.core.config.ILanguageComponentConfig) StrategoRuntimeFacet(org.metaborg.spoofax.core.stratego.StrategoRuntimeFacet)

Example 29 with MetaborgException

use of org.metaborg.core.MetaborgException in project spoofax by metaborg.

the class LanguageComponentFactory method requestAllInDirectory.

@Override
public Collection<IComponentCreationConfigRequest> requestAllInDirectory(FileObject directory) throws MetaborgException {
    final Set<IComponentCreationConfigRequest> requests = Sets.newHashSet();
    try {
        if (!directory.exists()) {
            throw new MetaborgException("Cannot scan directory " + directory + ", it does not exist");
        }
        if (!directory.isFolder()) {
            throw new MetaborgException("Cannot scan " + directory + ", it is not a directory");
        }
        final Iterable<FileObject> files = ResourceUtils.find(directory, new LanguageFileScanSelector());
        for (FileObject file : files) {
            final IComponentCreationConfigRequest request;
            if (file.isFolder()) {
                request = requestFromDirectory(file);
            } else {
                request = requestFromArchive(file);
            }
            requests.add(request);
        }
    } catch (FileSystemException e) {
        throw new MetaborgException("Cannot scan " + directory + ", unexpected I/O error", e);
    }
    return requests;
}
Also used : FileSystemException(org.apache.commons.vfs2.FileSystemException) MetaborgException(org.metaborg.core.MetaborgException) IComponentCreationConfigRequest(org.metaborg.core.language.IComponentCreationConfigRequest) FileObject(org.apache.commons.vfs2.FileObject)

Example 30 with MetaborgException

use of org.metaborg.core.MetaborgException in project spoofax by metaborg.

the class LanguageDiscoveryService method request.

@Deprecated
@Override
public Iterable<ILanguageDiscoveryRequest> request(FileObject location) throws MetaborgException {
    final Collection<ILanguageDiscoveryRequest> requests = Lists.newLinkedList();
    final FileObject[] configFiles;
    try {
        configFiles = location.findFiles(new FileSelector() {

            @Override
            public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception {
                final String baseName = fileInfo.getFile().getName().getBaseName();
                return !baseName.equals("bin") && !baseName.equals("target");
            }

            @Override
            public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
                return fileInfo.getFile().getName().getBaseName().equals(MetaborgConstants.FILE_COMPONENT_CONFIG);
            }
        });
    } catch (FileSystemException e) {
        throw new MetaborgException("Searching for language components failed unexpectedly", e);
    }
    if (configFiles == null || configFiles.length == 0) {
        return requests;
    }
    for (FileObject configFile : configFiles) {
        try {
            final FileObject directory = configFile.getParent().getParent();
            final IComponentCreationConfigRequest request = componentFactory.requestFromDirectory(directory);
            requests.add(request);
        } catch (FileSystemException e) {
            logger.error("Could not resolve parent directory of config file {}, skipping", e, configFile);
            continue;
        }
    }
    return requests;
}
Also used : FileSystemException(org.apache.commons.vfs2.FileSystemException) FileSelector(org.apache.commons.vfs2.FileSelector) MetaborgException(org.metaborg.core.MetaborgException) ILanguageDiscoveryRequest(org.metaborg.core.language.ILanguageDiscoveryRequest) IComponentCreationConfigRequest(org.metaborg.core.language.IComponentCreationConfigRequest) FileObject(org.apache.commons.vfs2.FileObject) FileSelectInfo(org.apache.commons.vfs2.FileSelectInfo)

Aggregations

MetaborgException (org.metaborg.core.MetaborgException)49 FileObject (org.apache.commons.vfs2.FileObject)25 IStrategoTerm (org.spoofax.interpreter.terms.IStrategoTerm)19 ILanguageImpl (org.metaborg.core.language.ILanguageImpl)17 HybridInterpreter (org.strategoxt.HybridInterpreter)14 IProject (org.metaborg.core.project.IProject)12 IStrategoString (org.spoofax.interpreter.terms.IStrategoString)11 IOException (java.io.IOException)9 IContext (org.metaborg.core.context.IContext)9 ITermFactory (org.spoofax.interpreter.terms.ITermFactory)9 Nullable (javax.annotation.Nullable)8 AnalysisException (org.metaborg.core.analysis.AnalysisException)8 FileSystemException (org.apache.commons.vfs2.FileSystemException)7 MetaborgRuntimeException (org.metaborg.core.MetaborgRuntimeException)7 ISpoofaxAnalyzeResults (org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults)6 SpoofaxAnalyzeResults (org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults)6 IStrategoAppl (org.spoofax.interpreter.terms.IStrategoAppl)6 ILanguage (org.metaborg.core.language.ILanguage)5 ISourceRegion (org.metaborg.core.source.ISourceRegion)5 ISpoofaxParseUnit (org.metaborg.spoofax.core.unit.ISpoofaxParseUnit)5