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);
}
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> "));
return new Message(messageText, kindToSeverity(message.kind()), getRegion(originTerm));
}
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);
}
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;
}
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);
}
Aggregations