Search in sources :

Example 1 with TermFormatter

use of mb.nabl2.util.TermFormatter in project spoofax-pie by metaborg.

the class MessageUtils method formatMessage.

public static Tuple2<Iterable<String>, ITerm> formatMessage(final IMessage message, final IConstraint constraint, final IUniDisunifier unifier, IStatixProjectConfig config) {
    final TermFormatter formatter = Solver.shallowTermFormatter(unifier, config.messageTermDepth(config.messageTermDepth(IStatixProjectConfig.DEFAULT_MESSAGE_TERM_DEPTH)));
    final int maxTraceLength = config.messageTraceLength(config.messageTraceLength(IStatixProjectConfig.DEFAULT_MESSAGE_TRACE_LENGTH));
    ITerm originTerm = message.origin().flatMap(t -> getOriginTerm(t, unifier)).orElse(null);
    final Deque<String> trace = new LinkedList<>();
    IConstraint current = constraint;
    int traceCount = 0;
    while (current != null) {
        if (originTerm == null) {
            originTerm = findOriginArgument(current, unifier).orElse(null);
        }
        if (maxTraceLength < 0 || ++traceCount <= maxTraceLength) {
            trace.addLast(current.toString(formatter));
        }
        current = current.cause().orElse(null);
    }
    if (maxTraceLength > 0 && traceCount > maxTraceLength) {
        trace.addLast("... trace truncated ...");
    }
    // add constraint message
    trace.addFirst(message.toString(formatter, () -> constraint.toString(formatter), completeness -> {
        final ISubstitution.Transient subst = PersistentSubstitution.Transient.of();
        completeness.vars().forEach(var -> {
            ITerm sub = unifier.findRecursive(var);
            if (!sub.equals(var)) {
                subst.put(var, sub);
            }
        });
        return completeness.apply(subst.freeze()).entrySet().stream().flatMap(e -> {
            String scope = e.getKey().toString();
            return e.getValue().elementSet().stream().map(edge -> scope + "-" + edge.toString());
        }).collect(Collectors.joining(", "));
    }));
    // use empty origin if none was found
    if (originTerm == null) {
        originTerm = B.newTuple();
    }
    return Tuple2.of(trace, originTerm);
}
Also used : PersistentSubstitution(mb.nabl2.terms.substitution.PersistentSubstitution) B(mb.nabl2.terms.build.TermBuild.B) Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm) Tuple2(org.metaborg.util.tuple.Tuple2) Collection(java.util.Collection) ISubstitution(mb.nabl2.terms.substitution.ISubstitution) TermFormatter(mb.nabl2.util.TermFormatter) IMessage(mb.statix.constraints.messages.IMessage) Solver(mb.statix.solver.persistent.Solver) Streams(com.google.common.collect.Streams) Deque(java.util.Deque) IUniDisunifier(mb.nabl2.terms.unification.ud.IUniDisunifier) Collectors(java.util.stream.Collectors) TermOrigin(mb.nabl2.terms.stratego.TermOrigin) IStatixProjectConfig(mb.statix.spoofax.IStatixProjectConfig) Stream(java.util.stream.Stream) ImmutableList(com.google.common.collect.ImmutableList) IConstraint(mb.statix.solver.IConstraint) Optional(java.util.Optional) LinkedList(java.util.LinkedList) Constraints(mb.statix.constraints.Constraints) TermIndex(mb.nabl2.terms.stratego.TermIndex) TermFormatter(mb.nabl2.util.TermFormatter) ITerm(mb.nabl2.terms.ITerm) IConstraint(mb.statix.solver.IConstraint) IConstraint(mb.statix.solver.IConstraint) LinkedList(java.util.LinkedList)

Example 2 with TermFormatter

use of mb.nabl2.util.TermFormatter in project spoofax-pie by metaborg.

the class MessageUtils method formatMessage.

public static Message formatMessage(final IMessage message, final IConstraint constraint, final IUniDisunifier unifier, boolean includeTraces) {
    final TermFormatter formatter = Solver.shallowTermFormatter(unifier, Solver.TERM_FORMAT_DEPTH);
    int maxTraceCount = includeTraces ? MAX_TRACE : 0;
    @Nullable ITerm originTerm = message.origin().flatMap(t -> getOriginTerm(t, unifier)).orElse(null);
    final Deque<String> trace = new ArrayDeque<>();
    @Nullable IConstraint current = constraint;
    int traceCount = 0;
    while (current != null) {
        if (originTerm == null) {
            originTerm = findOriginArgument(current, unifier).orElse(null);
        }
        if (traceCount++ < maxTraceCount) {
            trace.addLast(current.toString(formatter));
        }
        current = current.cause().orElse(null);
    }
    if (includeTraces && traceCount >= maxTraceCount) {
        trace.addLast("... trace truncated ...");
    }
    // use empty origin if none was found
    if (originTerm == null) {
        originTerm = TermBuild.B.newTuple();
    }
    // add constraint message
    // When there is no message, and trace is empty, add failing constraint as message
    String messageString = message.toString(formatter, () -> "", Object::toString);
    if (!messageString.matches("^\\s*$")) {
        trace.addFirst(messageString);
    } else if (trace.isEmpty()) {
        trace.add(constraint.toString(formatter));
    }
    final String messageText = trace.stream().filter(s -> !s.isEmpty()).map(MessageUtils::cleanupString).collect(Collectors.joining("<br>\n&gt;&nbsp;"));
    return new Message(messageText, kindToSeverity(message.kind()), getRegion(originTerm));
}
Also used : Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm) IStrategoAppl(org.spoofax.interpreter.terms.IStrategoAppl) Solver(mb.statix.solver.persistent.Solver) Deque(java.util.Deque) IUniDisunifier(mb.nabl2.terms.unification.ud.IUniDisunifier) TermTracer(mb.jsglr.common.TermTracer) MessageKind(mb.statix.constraints.messages.MessageKind) Region(mb.common.region.Region) ParentAttachment(org.spoofax.terms.attachments.ParentAttachment) Message(mb.common.message.Message) Nullable(org.checkerframework.checker.nullness.qual.Nullable) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) ISimpleTerm(org.spoofax.interpreter.terms.ISimpleTerm) ITermAttachment(org.spoofax.terms.attachments.ITermAttachment) ResourceKeyAttachment(mb.jsglr.common.ResourceKeyAttachment) TermFormatter(mb.nabl2.util.TermFormatter) IMessage(mb.statix.constraints.messages.IMessage) Streams(com.google.common.collect.Streams) ResourceKey(mb.resource.ResourceKey) Collectors(java.util.stream.Collectors) TermOrigin(mb.nabl2.terms.stratego.TermOrigin) AStrategoAnnotations(mb.nabl2.terms.stratego.AStrategoAnnotations) ImploderAttachment(org.spoofax.jsglr.client.imploder.ImploderAttachment) Stream(java.util.stream.Stream) TermBuild(mb.nabl2.terms.build.TermBuild) IConstraint(mb.statix.solver.IConstraint) Optional(java.util.Optional) ArrayDeque(java.util.ArrayDeque) Constraints(mb.statix.constraints.Constraints) Severity(mb.common.message.Severity) TermIndex(mb.nabl2.terms.stratego.TermIndex) TermFormatter(mb.nabl2.util.TermFormatter) Message(mb.common.message.Message) IMessage(mb.statix.constraints.messages.IMessage) ITerm(mb.nabl2.terms.ITerm) IConstraint(mb.statix.solver.IConstraint) IConstraint(mb.statix.solver.IConstraint) Nullable(org.checkerframework.checker.nullness.qual.Nullable) ArrayDeque(java.util.ArrayDeque)

Example 3 with TermFormatter

use of mb.nabl2.util.TermFormatter in project nabl by metaborg.

the class StatixGenerate method run.

public void run(String file) throws MetaborgException, InterruptedException {
    final FileObject resource = STX.S.resolve(file);
    TermFormatter tf = ITerm::toString;
    try {
        final ILanguageImpl lang = STX.cli.loadLanguage(STX.project.location());
        final IContext context = STX.S.contextService.get(resource, STX.project, lang);
        tf = StatixGenerator.pretty(STX.S, context, "pp-generated");
    } catch (MetaborgException e) {
    // ignore
    }
    final TermFormatter _tf = tf;
    final Function1<SearchState, String> pretty = (s) -> _tf.format(project(VAR, s));
    final DescriptiveStatistics hitStats = new DescriptiveStatistics();
    final DescriptiveStatistics missStats = new DescriptiveStatistics();
    final StreamProgressPrinter progress = new StreamProgressPrinter(System.err, 80, out -> {
        long hits = hitStats.getN();
        long all = hits + missStats.getN();
        out.println(" " + hits + "/" + all + " " + summary(hitStats));
    });
    final SearchLogger<SearchState, SearchState> searchLog = new SearchLogger<SearchState, SearchState>() {

        @Override
        public void init(long seed, SearchStrategy<SearchState, SearchState> strategy, Iterable<IConstraint> constraints) {
            log.info("seed {}", seed);
            log.info("strategy {}", strategy);
            log.info("constraints {}", constraints);
        }

        @Override
        public void success(SearchNode<SearchState> n) {
            progress.step('+');
            addSize(n.output(), hitStats);
            logSuccess(log, Level.Debug, n, pretty);
        }

        @Override
        public void failure(SearchNodes<?> nodes) {
            progress.step('.');
            SearchNode<?> parentNode = nodes.parent();
            if (parentNode != null && parentNode.output() instanceof SearchState) {
                addSize((SearchState) parentNode.output(), missStats);
            }
            logFailure(log, Level.Debug, nodes, pretty);
        }

        private void addSize(SearchState s, DescriptiveStatistics stats) {
            s.state().unifier().size(project(VAR, s)).ifFinite(size -> {
                stats.addValue(size.doubleValue());
            });
        }
    };
    final StatixGenerator statixGen = new StatixGenerator(STX.S, STX.context, resource);
    // Paret.addFragments(statixGen.spec());
    final Spec spec = statixGen.spec();
    final RandomTermGenerator rtg = new RandomTermGenerator(spec, statixGen.constraint(), new Paret(spec).search(), searchLog);
    final Stream<SearchState> resultStream = rtg.apply().nodes().map(sn -> {
        searchLog.success(sn);
        return sn.output();
    });
    log.info("Generating random terms.");
    final List<SearchState> results = Lists.newArrayList(resultStream.limit(COUNT).iterator());
    progress.done();
    results.forEach(s -> {
        System.out.println(pretty.apply(s));
    });
    log.info("Generated {} random terms.", results.size());
    logStatsInfo("hits", hitStats);
    logStatsInfo("misses", missStats);
}
Also used : Spec(mb.statix.spec.Spec) Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm) RandomTermGenerator(mb.statix.generator.RandomTermGenerator) SearchStrategy(mb.statix.generator.SearchStrategy) MetaborgException(org.metaborg.core.MetaborgException) Lists(com.google.common.collect.Lists) SearchLogger(mb.statix.generator.SearchLogger) ITermVar(mb.nabl2.terms.ITermVar) ILogger(org.metaborg.util.log.ILogger) B(mb.nabl2.terms.build.TermBuild.B) Level(org.metaborg.util.log.Level) SearchNode(mb.statix.generator.nodes.SearchNode) TermFormatter(mb.nabl2.util.TermFormatter) SearchNodes(mb.statix.generator.nodes.SearchNodes) FileObject(org.apache.commons.vfs2.FileObject) SearchElement(mb.statix.generator.nodes.SearchElement) List(java.util.List) Stream(java.util.stream.Stream) ILanguageImpl(org.metaborg.core.language.ILanguageImpl) IConstraint(mb.statix.solver.IConstraint) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) IContext(org.metaborg.core.context.IContext) SearchState(mb.statix.generator.SearchState) LoggerUtils(org.metaborg.util.log.LoggerUtils) StatixGenerator(org.metaborg.spoofax.core.shell.StatixGenerator) StreamProgressPrinter(mb.statix.generator.util.StreamProgressPrinter) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) SearchLogger(mb.statix.generator.SearchLogger) TermFormatter(mb.nabl2.util.TermFormatter) IContext(org.metaborg.core.context.IContext) SearchStrategy(mb.statix.generator.SearchStrategy) RandomTermGenerator(mb.statix.generator.RandomTermGenerator) MetaborgException(org.metaborg.core.MetaborgException) SearchNodes(mb.statix.generator.nodes.SearchNodes) FileObject(org.apache.commons.vfs2.FileObject) SearchNode(mb.statix.generator.nodes.SearchNode) StreamProgressPrinter(mb.statix.generator.util.StreamProgressPrinter) ILanguageImpl(org.metaborg.core.language.ILanguageImpl) SearchState(mb.statix.generator.SearchState) Spec(mb.statix.spec.Spec) StatixGenerator(org.metaborg.spoofax.core.shell.StatixGenerator)

Example 4 with TermFormatter

use of mb.nabl2.util.TermFormatter in project spoofax by metaborg.

the class StatixGenerator method pretty.

public static TermFormatter pretty(Spoofax S, IContext context, String strategy) {
    final ILanguageImpl lang = context.language();
    final TermFormatter pp;
    if (!Iterables.isEmpty(lang.components())) {
        final ILanguageComponent lc = Iterables.getOnlyElement(lang.components());
        final ITermFactory tf;
        final HybridInterpreter runtime;
        try {
            tf = S.termFactory;
            runtime = S.strategoRuntimeService.runtime(lc, context);
        } catch (MetaborgException e) {
            throw new MetaborgRuntimeException(e);
        }
        final StrategoTerms strategoTerms = new StrategoTerms(tf);
        pp = (t) -> {
            final IStrategoTerm st = strategoTerms.toStratego(explicate(t));
            try {
                final IStrategoTerm r = S.strategoCommon.invoke(runtime, st, strategy);
                return r != null ? TermUtils.toJavaString(r) : t.toString();
            } catch (MetaborgException e) {
                return t.toString();
            }
        };
    } else {
        pp = ITerm::toString;
    }
    return pp;
}
Also used : MetaborgRuntimeException(org.metaborg.core.MetaborgRuntimeException) TermFormatter(mb.nabl2.util.TermFormatter) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) ILanguageImpl(org.metaborg.core.language.ILanguageImpl) MetaborgException(org.metaborg.core.MetaborgException) StrategoTerms(mb.nabl2.terms.stratego.StrategoTerms) HybridInterpreter(org.strategoxt.HybridInterpreter) ITerm(mb.nabl2.terms.ITerm) ILanguageComponent(org.metaborg.core.language.ILanguageComponent) ITermFactory(org.spoofax.interpreter.terms.ITermFactory)

Example 5 with TermFormatter

use of mb.nabl2.util.TermFormatter in project nabl by metaborg.

the class StatixPrimitive method formatMessage.

public static Tuple2<Iterable<String>, ITerm> formatMessage(final IMessage message, final IConstraint constraint, final IUniDisunifier unifier, IStatixProjectConfig config) {
    final TermFormatter formatter = Solver.shallowTermFormatter(unifier, config.messageTermDepth(config.messageTermDepth(IStatixProjectConfig.DEFAULT_MESSAGE_TERM_DEPTH)));
    final int maxTraceLength = config.messageTraceLength(config.messageTraceLength(IStatixProjectConfig.DEFAULT_MESSAGE_TRACE_LENGTH));
    ITerm originTerm = message.origin().flatMap(t -> getOriginTerm(t, unifier)).orElse(null);
    final Deque<String> trace = Lists.newLinkedList();
    IConstraint current = constraint;
    int traceCount = 0;
    while (current != null) {
        if (originTerm == null) {
            originTerm = findOriginArgument(current, unifier).orElse(null);
        }
        if (maxTraceLength < 0 || ++traceCount <= maxTraceLength) {
            trace.addLast(current.toString(formatter));
        }
        current = current.cause().orElse(null);
    }
    if (maxTraceLength > 0 && traceCount > maxTraceLength) {
        trace.addLast("... trace truncated ...");
    }
    // add constraint message
    trace.addFirst(message.toString(formatter, () -> constraint.toString(formatter), completeness -> {
        final ISubstitution.Transient subst = PersistentSubstitution.Transient.of();
        completeness.vars().forEach(var -> {
            ITerm sub = unifier.findRecursive(var);
            if (!sub.equals(var)) {
                subst.put(var, sub);
            }
        });
        return completeness.apply(subst.freeze()).entrySet().stream().flatMap(e -> {
            String scope = e.getKey().toString();
            return e.getValue().elementSet().stream().map(edge -> scope + "-" + edge.toString());
        }).collect(Collectors.joining(", "));
    }));
    // use empty origin if none was found
    if (originTerm == null) {
        originTerm = B.newTuple();
    }
    return Tuple2.of(trace, originTerm);
}
Also used : Arrays(java.util.Arrays) IDebugContext(mb.statix.solver.log.IDebugContext) Spec(mb.statix.spec.Spec) Function1(org.metaborg.util.functions.Function1) Rule(mb.statix.spec.Rule) ListMultimap(com.google.common.collect.ListMultimap) ITerm(mb.nabl2.terms.ITerm) IProgress(org.metaborg.util.task.IProgress) ITermFactory(org.spoofax.interpreter.terms.ITermFactory) Solver(mb.statix.solver.persistent.Solver) Deque(java.util.Deque) IUniDisunifier(mb.nabl2.terms.unification.ud.IUniDisunifier) NullDebugContext(mb.statix.solver.log.NullDebugContext) Lists(com.google.common.collect.Lists) ICancel(org.metaborg.util.task.ICancel) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) NullCancel(org.metaborg.util.task.NullCancel) AbstractPrimitive(org.spoofax.interpreter.library.AbstractPrimitive) Nullable(javax.annotation.Nullable) ILogger(org.metaborg.util.log.ILogger) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) PersistentSubstitution(mb.nabl2.terms.substitution.PersistentSubstitution) SolverResult(mb.statix.solver.persistent.SolverResult) B(mb.nabl2.terms.build.TermBuild.B) Level(org.metaborg.util.log.Level) NullProgress(org.metaborg.util.task.NullProgress) StrategoTerms(mb.nabl2.terms.stratego.StrategoTerms) Tuple2(org.metaborg.util.tuple.Tuple2) M(mb.nabl2.terms.matching.TermMatch.M) Collection(java.util.Collection) ISubstitution(mb.nabl2.terms.substitution.ISubstitution) TermFormatter(mb.nabl2.util.TermFormatter) IMessage(mb.statix.constraints.messages.IMessage) Streams(com.google.common.collect.Streams) Collectors(java.util.stream.Collectors) TermOrigin(mb.nabl2.terms.stratego.TermOrigin) IContext(org.spoofax.interpreter.core.IContext) List(java.util.List) LoggerDebugContext(mb.statix.solver.log.LoggerDebugContext) Stream(java.util.stream.Stream) Strategy(org.spoofax.interpreter.stratego.Strategy) InterpreterException(org.spoofax.interpreter.core.InterpreterException) IConstraint(mb.statix.solver.IConstraint) Optional(java.util.Optional) LoggerUtils(org.metaborg.util.log.LoggerUtils) Constraints(mb.statix.constraints.Constraints) TermIndex(mb.nabl2.terms.stratego.TermIndex) TermFormatter(mb.nabl2.util.TermFormatter) ITerm(mb.nabl2.terms.ITerm) IConstraint(mb.statix.solver.IConstraint) IConstraint(mb.statix.solver.IConstraint)

Aggregations

ITerm (mb.nabl2.terms.ITerm)5 TermFormatter (mb.nabl2.util.TermFormatter)5 Stream (java.util.stream.Stream)4 IConstraint (mb.statix.solver.IConstraint)4 Function1 (org.metaborg.util.functions.Function1)4 Streams (com.google.common.collect.Streams)3 Deque (java.util.Deque)3 Optional (java.util.Optional)3 Collectors (java.util.stream.Collectors)3 B (mb.nabl2.terms.build.TermBuild.B)3 TermIndex (mb.nabl2.terms.stratego.TermIndex)3 TermOrigin (mb.nabl2.terms.stratego.TermOrigin)3 IUniDisunifier (mb.nabl2.terms.unification.ud.IUniDisunifier)3 Constraints (mb.statix.constraints.Constraints)3 IMessage (mb.statix.constraints.messages.IMessage)3 Solver (mb.statix.solver.persistent.Solver)3 ImmutableList (com.google.common.collect.ImmutableList)2 Lists (com.google.common.collect.Lists)2 Collection (java.util.Collection)2 List (java.util.List)2