Search in sources :

Example 26 with IStrategoAppl

use of org.spoofax.interpreter.terms.IStrategoAppl in project spoofax by metaborg.

the class Typesmart method extractSortType.

private SortType extractSortType(IStrategoTerm sort) {
    String kind = ((IStrategoAppl) sort).getName();
    if (kind.equals("SortList") || kind.equals("SortListTl") || kind.equals("SortVar")) {
        logger.error("Unsupported Stratego signature: " + sort);
        return TAny.instance;
    } else if (kind.equals("SortTuple")) {
        IStrategoTerm[] kids = sort.getSubterm(0).getAllSubterms();
        SortType[] sorts = new SortType[kids.length];
        for (int i = 0; i < kids.length; i++) {
            sorts[i] = extractSortType(kids[i]);
        }
        return new TTuple(sorts);
    }
    if (sort.getSubterm(0).getTermType() != IStrategoTerm.STRING) {
        throw new IllegalArgumentException("Found type in unexpected format " + sort);
    }
    String sortName = ((IStrategoString) sort.getSubterm(0)).stringValue();
    if (kind.equals("SortNoArgs") && sortName.equals(SortType.LEXICAL_SORT)) {
        return TLexical.instance;
    } else if (kind.equals("SortNoArgs") && sortName.equals(SortType.ANY_SORT)) {
        return TAny.instance;
    } else if (kind.equals("SortNoArgs")) {
        return new TSort(sortName);
    } else if (kind.equals("Sort") && sortName.equals("List")) {
        SortType t = extractSortType(sort.getSubterm(1).getSubterm(0));
        return t == null ? null : new TList(t);
    } else if (kind.equals("Sort") && sortName.equals("Option")) {
        SortType t = extractSortType(sort.getSubterm(1).getSubterm(0));
        return t == null ? null : new TOption(t);
    } else if (kind.equals("SortVar")) {
        return null;
    } else {
        throw new IllegalArgumentException("Found type in unexpected format " + sort);
    }
}
Also used : SortType(org.spoofax.terms.typesmart.types.SortType) TList(org.spoofax.terms.typesmart.types.TList) TOption(org.spoofax.terms.typesmart.types.TOption) TSort(org.spoofax.terms.typesmart.types.TSort) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) TTuple(org.spoofax.terms.typesmart.types.TTuple) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) IStrategoString(org.spoofax.interpreter.terms.IStrategoString)

Example 27 with IStrategoAppl

use of org.spoofax.interpreter.terms.IStrategoAppl in project spoofax by metaborg.

the class TaskEngineAnalyzer method analyzeAll.

private ISpoofaxAnalyzeResults analyzeAll(Iterable<ISpoofaxParseUnit> inputs, IContext context, HybridInterpreter runtime, String strategy, ITermFactory termFactory) throws AnalysisException {
    final Map<String, ISpoofaxParseUnit> inputsPerSource = Maps.newHashMap();
    int detachedCounter = 0;
    final Collection<IStrategoAppl> analysisInputs = Lists.newArrayList();
    for (ISpoofaxParseUnit input : inputs) {
        if (!input.valid()) {
            logger.warn("Parse result for {} is invalid, cannot analyze", input.source());
            continue;
        }
        final String pathString;
        if (input.detached()) {
            pathString = "detached-source-" + detachedCounter++;
            logger.debug("Parse input is detached, using '{}' as path", pathString);
        } else {
            pathString = input.source().getName().getURI();
        }
        inputsPerSource.put(pathString, input);
        final IStrategoString pathTerm = termFactory.makeString(pathString);
        final IStrategoReal durationTerm = termFactory.makeReal(input.duration());
        analysisInputs.add(termFactory.makeAppl(fileCons, pathTerm, input.ast(), durationTerm));
    }
    final IStrategoTerm inputTerm = termFactory.makeList(analysisInputs);
    logger.trace("Invoking {} strategy", strategy);
    final IStrategoTerm resultTerm;
    try {
        resultTerm = strategoCommon.invoke(runtime, inputTerm, strategy);
    } catch (MetaborgException e) {
        final String message = analysisCommon.analysisFailedMessage(runtime);
        throw new AnalysisException(context, message, e);
    }
    if (resultTerm == null) {
        final String message = analysisCommon.analysisFailedMessage(runtime);
        throw new AnalysisException(context, message);
    }
    if (!(resultTerm instanceof IStrategoAppl) || resultTerm.getSubtermCount() != 5) {
        final String message = logger.format("Unexpected results from analysis {}, expected 5-tuple", resultTerm);
        throw new AnalysisException(context, message);
    }
    final IStrategoTerm resultsTerm = resultTerm.getSubterm(0);
    final IStrategoTerm updateResultsTerm = resultTerm.getSubterm(1);
    final Collection<ISpoofaxAnalyzeUnit> fileResults = Lists.newArrayListWithCapacity(resultsTerm.getSubtermCount());
    for (IStrategoTerm result : resultsTerm) {
        // HACK: analysis duration per parse unit is unknown, pass -1 as duration.
        final ISpoofaxAnalyzeUnit fileResult = result(result, inputsPerSource, context, -1);
        if (fileResult == null) {
            continue;
        }
        fileResults.add(fileResult);
    }
    final Collection<ISpoofaxAnalyzeUnitUpdate> updateResults = Lists.newArrayListWithCapacity(updateResultsTerm.getSubtermCount());
    for (IStrategoTerm result : updateResultsTerm) {
        final ISpoofaxAnalyzeUnitUpdate updateResult = updateResult(result, context);
        if (updateResult == null) {
            continue;
        }
        updateResults.add(updateResult);
    }
    return new SpoofaxAnalyzeResults(fileResults, updateResults, context);
}
Also used : ISpoofaxParseUnit(org.metaborg.spoofax.core.unit.ISpoofaxParseUnit) ISpoofaxAnalyzeResults(org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults) SpoofaxAnalyzeResults(org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) ISpoofaxAnalyzeUnitUpdate(org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnitUpdate) MetaborgException(org.metaborg.core.MetaborgException) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) IStrategoReal(org.spoofax.interpreter.terms.IStrategoReal) AnalysisException(org.metaborg.core.analysis.AnalysisException) ISpoofaxAnalyzeUnit(org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit)

Example 28 with IStrategoAppl

use of org.spoofax.interpreter.terms.IStrategoAppl in project spoofax by metaborg.

the class JSGLRCompletionService method createCompletionInsertBefore.

private ICompletion createCompletionInsertBefore(String name, String text, String additionalInfo, StrategoAppl change) {
    final StrategoTerm oldNode = (StrategoTerm) change.getSubterm(0);
    final StrategoTerm newNode = (StrategoTerm) change.getSubterm(1);
    // expect two terms and 1st should be an element of a list
    final StrategoTerm oldList = (StrategoTerm) ParentAttachment.getParent(oldNode);
    if (change.getSubtermCount() != 2 || !(oldNode instanceof IStrategoAppl) || !(newNode instanceof IStrategoList) || !(oldList instanceof IStrategoList)) {
        return null;
    }
    final String sort = ImploderAttachment.getSort(oldNode);
    int insertionPoint, suffixPoint;
    ITokens tokenizer = ImploderAttachment.getTokenizer(oldNode);
    IStrategoTerm[] subterms = oldList.getAllSubterms();
    int indexOfElement;
    for (indexOfElement = 0; indexOfElement < subterms.length; indexOfElement++) {
        if (subterms[indexOfElement] == oldNode)
            break;
    }
    // if inserted element is first (only two elements)
    if (indexOfElement == 0) {
        // insert after the first non-layout token before the leftmost token of the
        // completion node
        final ImploderAttachment oldNodeIA = oldNode.getAttachment(ImploderAttachment.TYPE);
        int tokenPosition = oldNodeIA.getLeftToken().getIndex() - 1 > 0 ? oldNodeIA.getLeftToken().getIndex() - 1 : 0;
        while ((tokenizer.getTokenAt(tokenPosition).getKind() == IToken.TK_LAYOUT || tokenizer.getTokenAt(tokenPosition).getKind() == IToken.TK_ERROR) && tokenPosition > 0) tokenPosition--;
        insertionPoint = tokenizer.getTokenAt(tokenPosition).getEndOffset();
    } else {
        // if inserted element is not first
        // insert after at end offset of the rightmost token of the element before the
        // completion
        StrategoTerm elementBefore = (StrategoTerm) oldList.getSubterm(indexOfElement - 1);
        insertionPoint = elementBefore.getAttachment(ImploderAttachment.TYPE).getRightToken().getEndOffset();
    }
    // if completion is separated by a newline, preserve indentation of the subsequent node
    // else separation follows from the grammar
    String separator = "";
    for (int i = text.length() - 1; i >= 0; i--) {
        if (text.charAt(i) == additionalInfo.charAt(additionalInfo.length() - 1)) {
            break;
        }
        separator = text.charAt(i) + separator;
    }
    IToken checkToken = oldNode.getAttachment(ImploderAttachment.TYPE).getLeftToken();
    int checkTokenIdx = oldNode.getAttachment(ImploderAttachment.TYPE).getLeftToken().getIndex();
    suffixPoint = insertionPoint;
    if (separator.contains("\n")) {
        for (; checkTokenIdx >= 0; checkTokenIdx--) {
            checkToken = tokenizer.getTokenAt(checkTokenIdx);
            if (tokenizer.toString(checkToken, checkToken).contains("\n")) {
                break;
            }
            suffixPoint = checkToken.getStartOffset();
        }
    } else {
        suffixPoint = checkToken.getStartOffset();
    }
    return new Completion(name, sort, text, additionalInfo, insertionPoint + 1, suffixPoint, CompletionKind.expansion);
}
Also used : IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) ICompletion(org.metaborg.core.completion.ICompletion) Completion(org.metaborg.core.completion.Completion) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) StrategoTerm(org.spoofax.terms.StrategoTerm) IToken(org.spoofax.jsglr.client.imploder.IToken) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) IStrategoList(org.spoofax.interpreter.terms.IStrategoList) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) ImploderAttachment(org.spoofax.jsglr.client.imploder.ImploderAttachment) ListImploderAttachment(org.spoofax.jsglr.client.imploder.ListImploderAttachment) ITokens(org.spoofax.jsglr.client.imploder.ITokens)

Example 29 with IStrategoAppl

use of org.spoofax.interpreter.terms.IStrategoAppl in project spoofax by metaborg.

the class JSGLRCompletionService method optionalCompletions.

public Collection<ICompletion> optionalCompletions(Iterable<IStrategoTerm> optionals, boolean blankLineCompletion, String languageName, ILanguageComponent component, FileObject location) throws MetaborgException {
    Collection<ICompletion> completions = Lists.newLinkedList();
    final ITermFactory termFactory = termFactoryService.get(component, null, false);
    for (IStrategoTerm optional : optionals) {
        ImploderAttachment attachment = optional.getAttachment(ImploderAttachment.TYPE);
        String sort = attachment.getSort().substring(0, attachment.getSort().length());
        String placeholderName = sort + "-Plhdr";
        IStrategoAppl optionalPlaceholder = termFactory.makeAppl(termFactory.makeConstructor(placeholderName, 0));
        final IStrategoTerm strategoInput = termFactory.makeTuple(termFactory.makeString(sort), optional, optionalPlaceholder);
        // call Stratego part of the framework to compute change
        final HybridInterpreter runtime = strategoRuntimeService.runtime(component, location, false);
        final IStrategoTerm proposalsOptional = strategoCommon.invoke(runtime, strategoInput, "get-proposals-optional-" + languageName);
        if (proposalsOptional == null) {
            logger.error("Getting proposals for {} failed", strategoInput);
            continue;
        }
        for (IStrategoTerm proposalTerm : proposalsOptional) {
            if (!(proposalTerm instanceof IStrategoTuple)) {
                logger.error("Unexpected proposal term {}, skipping", proposalTerm);
                continue;
            }
            final IStrategoTuple tuple = (IStrategoTuple) proposalTerm;
            if (tuple.getSubtermCount() != 4 || !(tuple.getSubterm(0) instanceof IStrategoString) || !(tuple.getSubterm(1) instanceof IStrategoString) || !(tuple.getSubterm(2) instanceof IStrategoString) || !(tuple.getSubterm(3) instanceof IStrategoAppl)) {
                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);
            if (change.getConstructor().getName().contains("REPLACE_TERM")) {
                final ICompletion completion = createCompletionReplaceTerm(name, text, additionalInfo, change, blankLineCompletion, "", "");
                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) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) HybridInterpreter(org.strategoxt.HybridInterpreter) IStrategoTuple(org.spoofax.interpreter.terms.IStrategoTuple) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) ImploderAttachment(org.spoofax.jsglr.client.imploder.ImploderAttachment) ListImploderAttachment(org.spoofax.jsglr.client.imploder.ListImploderAttachment) IStrategoString(org.spoofax.interpreter.terms.IStrategoString) ITermFactory(org.spoofax.interpreter.terms.ITermFactory) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) StrategoAppl(org.spoofax.terms.StrategoAppl)

Example 30 with IStrategoAppl

use of org.spoofax.interpreter.terms.IStrategoAppl in project spoofax by metaborg.

the class JSGLRCompletionService method completionEmptyProgram.

public Collection<? extends ICompletion> completionEmptyProgram(Iterable<String> startSymbols, int endOffset, ILanguageImpl language, FileObject location) throws MetaborgException {
    Collection<ICompletion> completions = Lists.newLinkedList();
    final String languageName = language.belongsTo().name();
    for (ILanguageComponent component : language.components()) {
        // 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 (String startSymbol : startSymbols) {
            String placeholderName = startSymbol + "-Plhdr";
            IStrategoAppl placeholder = termFactory.makeAppl(termFactory.makeConstructor(placeholderName, 0));
            IStrategoTuple input = termFactory.makeTuple(termFactory.makeString(startSymbol), placeholder);
            final IStrategoTerm proposalsPlaceholder = strategoCommon.invoke(runtime, input, "get-proposals-empty-program-" + languageName);
            if (proposalsPlaceholder == null) {
                logger.error("Getting proposals for {} failed", placeholder);
                continue;
            }
            for (IStrategoTerm proposalTerm : proposalsPlaceholder) {
                if (!(proposalTerm instanceof IStrategoTuple)) {
                    logger.error("Unexpected proposal term {}, skipping", proposalTerm);
                    continue;
                }
                final IStrategoTuple tuple = (IStrategoTuple) proposalTerm;
                if (tuple.getSubtermCount() != 2 || !(tuple.getSubterm(0) instanceof IStrategoString) || !(tuple.getSubterm(1) 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(1));
                completions.add(new Completion(name, startSymbol, text, additionalInfo, 0, endOffset, CompletionKind.expansion));
            }
        }
    }
    return completions;
}
Also used : ICompletion(org.metaborg.core.completion.ICompletion) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) ICompletion(org.metaborg.core.completion.ICompletion) Completion(org.metaborg.core.completion.Completion) 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) ILanguageComponent(org.metaborg.core.language.ILanguageComponent) ITermFactory(org.spoofax.interpreter.terms.ITermFactory)

Aggregations

IStrategoAppl (org.spoofax.interpreter.terms.IStrategoAppl)42 IStrategoTerm (org.spoofax.interpreter.terms.IStrategoTerm)26 IStrategoString (org.spoofax.interpreter.terms.IStrategoString)21 ICompletion (org.metaborg.core.completion.ICompletion)13 Nullable (javax.annotation.Nullable)12 IStrategoList (org.spoofax.interpreter.terms.IStrategoList)9 ITermFactory (org.spoofax.interpreter.terms.ITermFactory)8 ListImploderAttachment (org.spoofax.jsglr.client.imploder.ListImploderAttachment)8 Completion (org.metaborg.core.completion.Completion)7 ITokens (org.spoofax.jsglr.client.imploder.ITokens)7 ImploderAttachment (org.spoofax.jsglr.client.imploder.ImploderAttachment)7 StrategoTerm (org.spoofax.terms.StrategoTerm)7 HybridInterpreter (org.strategoxt.HybridInterpreter)7 FileObject (org.apache.commons.vfs2.FileObject)6 MetaborgException (org.metaborg.core.MetaborgException)6 IStrategoTuple (org.spoofax.interpreter.terms.IStrategoTuple)6 CompletionKind (org.metaborg.core.completion.CompletionKind)5 StrategoAppl (org.spoofax.terms.StrategoAppl)5 IToken (org.spoofax.jsglr.client.imploder.IToken)4 ISourceRegion (org.metaborg.core.source.ISourceRegion)3