Search in sources :

Example 1 with IConstraint

use of mb.statix.solver.IConstraint in project spoofax-pie by metaborg.

the class ExpandQueryStrategy method applyDataWF.

/**
 * Applies the dataWF to the specified datum.
 *
 * applyDataWF :: DataWF * Data -> Unifier?
 *
 * @param dataWF       the data WF predicate
 * @param d            the datum
 * @param state        the current state
 * @param unifier      the unifier of the context
 * @param completeness the completeness of the context
 * @param spec         the Statix specification
 * @return either a {@link SolverResult} with the result of applying the {@code dataWF} to the given datum;
 * otherwise, nothing if the {@code dataWF} could not be applied
 */
private static Optional<SolverResult> applyDataWF(Rule dataWF, ITerm d, IState.Immutable state, IUniDisunifier.Immutable unifier, ICompleteness.Immutable completeness, Spec spec) {
    // Apply the 'dataWF' to the specified 'd'
    final ApplyResult applyResult;
    if ((applyResult = RuleUtil.apply(unifier, dataWF, Collections.singletonList(d), null, ApplyMode.RELAXED, ApplyMode.Safety.SAFE).orElse(null)) == null) {
        return Optional.empty();
    }
    final IState.Immutable applyState = state;
    final IConstraint applyConstraint = applyResult.body();
    // Update completeness for new state and constraint
    final ICompleteness.Transient _completeness = completeness.melt();
    _completeness.add(applyConstraint, spec, applyState.unifier());
    final IConstraint constraint = applyResult.body();
    // TODO: Reutrn a PreSolveResult or find another way to merge the SolverResult and PreSolveResult
    // final Optional<Solver.PreSolveResult> solverResult = trySolveFast(constraint, state, _completeness, spec);
    // if (!solverResult.isPresent()) return Optional.empty();
    // final Solver.PreSolveResult result = solverResult.get();
    // final IState.Immutable newState = result.state;
    final Optional<SolverResult> solverResult = trySolveSlow(constraint, state, _completeness, spec);
    if (!solverResult.isPresent())
        return Optional.empty();
    final SolverResult result = solverResult.get();
    final IState.Immutable newState = result.state();
    // NOTE: This part is almost a duplicate of ResolveDataWF::wf and should be kept in sync
    // NOTE: The retain operation is important because it may change
    // representatives, which can be local to newUnifier.
    final IUniDisunifier.Immutable newUnifier = newState.unifier().retainAll(state.vars()).unifier();
    // Check that all (remaining) disequalities are implied (i.e., not unifiable) in the original unifier
    // @formatter:off
    final List<ITermVar> disunifiedVars = newUnifier.disequalities().stream().filter(diseq -> diseq.toTuple().apply(unifier::disunify).map(r -> r.result().isPresent()).orElse(true)).flatMap(diseq -> diseq.domainSet().stream()).collect(Collectors.toList());
    // @formatter:on
    if (!disunifiedVars.isEmpty())
        return Optional.empty();
    // Applying dataWF succeeded.
    return Optional.of(result);
}
Also used : ResolveDataWF(mb.statix.generator.strategy.ResolveDataWF) StatixTerms(mb.statix.spoofax.StatixTerms) Spec(mb.statix.spec.Spec) FastNameResolution(mb.scopegraph.oopsla20.reference.FastNameResolution) ITerm(mb.nabl2.terms.ITerm) Seq(mb.tego.sequences.Seq) Solver(mb.statix.solver.persistent.Solver) Collections2(com.google.common.collect.Collections2) SolverContext(mb.statix.codecompletion.SolverContext) ApplyResult(mb.statix.spec.ApplyResult) RegExpLabelWF(mb.scopegraph.oopsla20.reference.RegExpLabelWF) Delay(mb.statix.solver.Delay) RigidException(mb.nabl2.terms.unification.RigidException) ApplyMode(mb.statix.spec.ApplyMode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ITermVar(mb.nabl2.terms.ITermVar) SelectedConstraintSolverState(mb.statix.codecompletion.SelectedConstraintSolverState) DataWF(mb.statix.generator.scopegraph.DataWF) IState(mb.statix.solver.IState) B(mb.nabl2.terms.build.TermBuild.B) ImmutableSet(com.google.common.collect.ImmutableSet) NamedStrategy2(mb.tego.strategies.NamedStrategy2) Env(mb.scopegraph.oopsla20.reference.Env) Collection(java.util.Collection) Range(com.google.common.collect.Range) Set(io.usethesource.capsule.Set) Predicate2(org.metaborg.util.functions.Predicate2) PreSolvedConstraint(mb.statix.spec.PreSolvedConstraint) NameResolution(mb.statix.generator.scopegraph.NameResolution) Collectors(java.util.stream.Collectors) Iterables2(org.metaborg.util.iterators.Iterables2) StreamUtils(mb.tego.utils.StreamUtils) ResolutionException(mb.scopegraph.oopsla20.reference.ResolutionException) List(java.util.List) IUnifier(mb.nabl2.terms.unification.u.IUnifier) Stream(java.util.stream.Stream) Optionals(org.metaborg.util.optionals.Optionals) CAstId(mb.statix.constraints.CAstId) IConstraint(mb.statix.solver.IConstraint) ConstraintQueries(mb.statix.solver.persistent.query.ConstraintQueries) IListTerm(mb.nabl2.terms.IListTerm) Optional(java.util.Optional) RelationLabelOrder(mb.scopegraph.oopsla20.reference.RelationLabelOrder) IsComplete(mb.statix.solver.completeness.IsComplete) Match(mb.statix.generator.scopegraph.Match) CInequal(mb.statix.constraints.CInequal) IntStream(java.util.stream.IntStream) Completeness(mb.statix.solver.completeness.Completeness) ListTerms(mb.nabl2.terms.ListTerms) Rule(mb.statix.spec.Rule) LabelOrder(mb.scopegraph.oopsla20.reference.LabelOrder) EdgeOrData(mb.scopegraph.oopsla20.reference.EdgeOrData) RuleUtil(mb.statix.spec.RuleUtil) HashMap(java.util.HashMap) SolverState(mb.statix.codecompletion.SolverState) Deque(java.util.Deque) IUniDisunifier(mb.nabl2.terms.unification.ud.IUniDisunifier) NullDebugContext(mb.statix.solver.log.NullDebugContext) ArrayList(java.util.ArrayList) IncompleteException(mb.scopegraph.oopsla20.reference.IncompleteException) HashSet(java.util.HashSet) Map(io.usethesource.capsule.Map) CEqual(mb.statix.constraints.CEqual) ImmutableList(com.google.common.collect.ImmutableList) Scope(mb.statix.scopegraph.Scope) NullCancel(org.metaborg.util.task.NullCancel) OccursException(mb.nabl2.terms.unification.OccursException) LinkedList(java.util.LinkedList) Nullable(org.checkerframework.checker.nullness.qual.Nullable) ICompleteness(mb.statix.solver.completeness.ICompleteness) SolverResult(mb.statix.solver.persistent.SolverResult) DataLeq(mb.scopegraph.oopsla20.reference.DataLeq) NullProgress(org.metaborg.util.task.NullProgress) Iterator(java.util.Iterator) LabelWF(mb.scopegraph.oopsla20.reference.LabelWF) M(mb.nabl2.terms.matching.TermMatch.M) ResolutionPath(mb.scopegraph.oopsla20.terms.newPath.ResolutionPath) CResolveQuery(mb.statix.constraints.CResolveQuery) AbstractMap(java.util.AbstractMap) TegoEngine(mb.tego.strategies.runtime.TegoEngine) TermBuild(mb.nabl2.terms.build.TermBuild) Collections(java.util.Collections) ITermVar(mb.nabl2.terms.ITermVar) SolverResult(mb.statix.solver.persistent.SolverResult) IConstraint(mb.statix.solver.IConstraint) ApplyResult(mb.statix.spec.ApplyResult) IState(mb.statix.solver.IState) ICompleteness(mb.statix.solver.completeness.ICompleteness) IUniDisunifier(mb.nabl2.terms.unification.ud.IUniDisunifier)

Example 2 with IConstraint

use of mb.statix.solver.IConstraint in project spoofax-pie by metaborg.

the class ExpandQueryStrategy method updateSolverStateOld.

/**
 * Creates a new solver state for the given matches.
 *
 * @param spec       the spec
 * @param query      the query
 * @param state      the input state
 * @param optMatches the accepted optional matches
 * @param optRejects the rejected optional matches
 * @param reqMatches the required matches
 * @param reqRejects the required rejects
 * @return the new solver state
 */
private static SolverState updateSolverStateOld(Spec spec, CResolveQuery query, SolverState state, Collection<Match<Scope, ITerm, ITerm, CEqual>> optMatches, Collection<Match<Scope, ITerm, ITerm, CEqual>> optRejects, Collection<Match<Scope, ITerm, ITerm, CEqual>> reqMatches, Collection<Match<Scope, ITerm, ITerm, CEqual>> reqRejects) {
    // Build a new environment with all the matches and rejects.
    final mb.statix.generator.scopegraph.Env.Builder<Scope, ITerm, ITerm, CEqual> subEnvBuilder = mb.statix.generator.scopegraph.Env.builder();
    optMatches.forEach(subEnvBuilder::match);
    reqMatches.forEach(subEnvBuilder::match);
    optRejects.forEach(subEnvBuilder::reject);
    reqRejects.forEach(subEnvBuilder::reject);
    final mb.statix.generator.scopegraph.Env<Scope, ITerm, ITerm, CEqual> subEnv = subEnvBuilder.build();
    // Build the list of constraints to add
    final ImmutableList.Builder<IConstraint> addConstraints = ImmutableList.builder();
    // The explicated match path must match the query result term
    final List<ITerm> pathTerms = subEnv.matches.stream().map(m -> StatixTerms.pathToTerm(m.path, spec.dataLabels())).collect(ImmutableList.toImmutableList());
    addConstraints.add(new CEqual(B.newList(pathTerms), query.resultTerm(), query));
    subEnv.matches.stream().flatMap(m -> Optionals.stream(m.condition)).forEach(addConstraints::add);
    subEnv.rejects.stream().flatMap(m -> Optionals.stream(m.condition)).forEach(condition -> addConstraints.add(new CInequal(ImmutableSet.of(), condition.term1(), condition.term2(), condition.cause().orElse(null), condition.message().orElse(null))));
    // Build the list of constraints to remove
    final Iterable<IConstraint> remConstraints = Iterables2.singleton(query);
    // Update the given state with the added and removed constraints
    return state.withUpdatedConstraints(addConstraints.build(), remConstraints).withMeta(state.getMeta().withExpandedQueriesIncremented());
}
Also used : ResolveDataWF(mb.statix.generator.strategy.ResolveDataWF) StatixTerms(mb.statix.spoofax.StatixTerms) Spec(mb.statix.spec.Spec) FastNameResolution(mb.scopegraph.oopsla20.reference.FastNameResolution) ITerm(mb.nabl2.terms.ITerm) Seq(mb.tego.sequences.Seq) Solver(mb.statix.solver.persistent.Solver) Collections2(com.google.common.collect.Collections2) SolverContext(mb.statix.codecompletion.SolverContext) ApplyResult(mb.statix.spec.ApplyResult) RegExpLabelWF(mb.scopegraph.oopsla20.reference.RegExpLabelWF) Delay(mb.statix.solver.Delay) RigidException(mb.nabl2.terms.unification.RigidException) ApplyMode(mb.statix.spec.ApplyMode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ITermVar(mb.nabl2.terms.ITermVar) SelectedConstraintSolverState(mb.statix.codecompletion.SelectedConstraintSolverState) DataWF(mb.statix.generator.scopegraph.DataWF) IState(mb.statix.solver.IState) B(mb.nabl2.terms.build.TermBuild.B) ImmutableSet(com.google.common.collect.ImmutableSet) NamedStrategy2(mb.tego.strategies.NamedStrategy2) Env(mb.scopegraph.oopsla20.reference.Env) Collection(java.util.Collection) Range(com.google.common.collect.Range) Set(io.usethesource.capsule.Set) Predicate2(org.metaborg.util.functions.Predicate2) PreSolvedConstraint(mb.statix.spec.PreSolvedConstraint) NameResolution(mb.statix.generator.scopegraph.NameResolution) Collectors(java.util.stream.Collectors) Iterables2(org.metaborg.util.iterators.Iterables2) StreamUtils(mb.tego.utils.StreamUtils) ResolutionException(mb.scopegraph.oopsla20.reference.ResolutionException) List(java.util.List) IUnifier(mb.nabl2.terms.unification.u.IUnifier) Stream(java.util.stream.Stream) Optionals(org.metaborg.util.optionals.Optionals) CAstId(mb.statix.constraints.CAstId) IConstraint(mb.statix.solver.IConstraint) ConstraintQueries(mb.statix.solver.persistent.query.ConstraintQueries) IListTerm(mb.nabl2.terms.IListTerm) Optional(java.util.Optional) RelationLabelOrder(mb.scopegraph.oopsla20.reference.RelationLabelOrder) IsComplete(mb.statix.solver.completeness.IsComplete) Match(mb.statix.generator.scopegraph.Match) CInequal(mb.statix.constraints.CInequal) IntStream(java.util.stream.IntStream) Completeness(mb.statix.solver.completeness.Completeness) ListTerms(mb.nabl2.terms.ListTerms) Rule(mb.statix.spec.Rule) LabelOrder(mb.scopegraph.oopsla20.reference.LabelOrder) EdgeOrData(mb.scopegraph.oopsla20.reference.EdgeOrData) RuleUtil(mb.statix.spec.RuleUtil) HashMap(java.util.HashMap) SolverState(mb.statix.codecompletion.SolverState) Deque(java.util.Deque) IUniDisunifier(mb.nabl2.terms.unification.ud.IUniDisunifier) NullDebugContext(mb.statix.solver.log.NullDebugContext) ArrayList(java.util.ArrayList) IncompleteException(mb.scopegraph.oopsla20.reference.IncompleteException) HashSet(java.util.HashSet) Map(io.usethesource.capsule.Map) CEqual(mb.statix.constraints.CEqual) ImmutableList(com.google.common.collect.ImmutableList) Scope(mb.statix.scopegraph.Scope) NullCancel(org.metaborg.util.task.NullCancel) OccursException(mb.nabl2.terms.unification.OccursException) LinkedList(java.util.LinkedList) Nullable(org.checkerframework.checker.nullness.qual.Nullable) ICompleteness(mb.statix.solver.completeness.ICompleteness) SolverResult(mb.statix.solver.persistent.SolverResult) DataLeq(mb.scopegraph.oopsla20.reference.DataLeq) NullProgress(org.metaborg.util.task.NullProgress) Iterator(java.util.Iterator) LabelWF(mb.scopegraph.oopsla20.reference.LabelWF) M(mb.nabl2.terms.matching.TermMatch.M) ResolutionPath(mb.scopegraph.oopsla20.terms.newPath.ResolutionPath) CResolveQuery(mb.statix.constraints.CResolveQuery) AbstractMap(java.util.AbstractMap) TegoEngine(mb.tego.strategies.runtime.TegoEngine) TermBuild(mb.nabl2.terms.build.TermBuild) Collections(java.util.Collections) CInequal(mb.statix.constraints.CInequal) ImmutableList(com.google.common.collect.ImmutableList) CEqual(mb.statix.constraints.CEqual) IConstraint(mb.statix.solver.IConstraint) Env(mb.scopegraph.oopsla20.reference.Env) Scope(mb.statix.scopegraph.Scope) ITerm(mb.nabl2.terms.ITerm)

Example 3 with IConstraint

use of mb.statix.solver.IConstraint in project spoofax-pie by metaborg.

the class MessageUtils method addMessage.

// //////////////////////////////////////////////
// Helper methods for creating error messages //
// //////////////////////////////////////////////
public static void addMessage(final IMessage message, final IConstraint constraint, final IUniDisunifier unifier, IStatixProjectConfig config, final Collection<ITerm> errors, final Collection<ITerm> warnings, final Collection<ITerm> notes) {
    Tuple2<Iterable<String>, ITerm> message_origin = formatMessage(message, constraint, unifier, config);
    final String messageText = Streams.stream(message_origin._1()).filter(s -> !s.isEmpty()).map(s -> cleanupString(s)).collect(Collectors.joining("<br>\n&gt;&nbsp;", "", "<br>\n"));
    final ITerm messageTerm = B.newTuple(message_origin._2(), B.newString(messageText));
    switch(message.kind()) {
        case ERROR:
            errors.add(messageTerm);
            break;
        case WARNING:
            warnings.add(messageTerm);
            break;
        case NOTE:
            notes.add(messageTerm);
            break;
        case IGNORE:
            break;
    }
}
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) ITerm(mb.nabl2.terms.ITerm)

Example 4 with IConstraint

use of mb.statix.solver.IConstraint 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 5 with IConstraint

use of mb.statix.solver.IConstraint in project spoofax-pie by metaborg.

the class SmlPartialSolveProject method exec.

@Override
public Result<SolverResult, MultiLangAnalysisException> exec(ExecContext context, Input input) {
    return context.require(instantiateGlobalScope.createTask(input.logLevel)).mapErr(MultiLangAnalysisException::wrapIfNeeded).flatMap(globalResult -> {
        Set<ITerm> scopeArgs = Collections.singleton(globalResult.globalScope());
        return languageMetadataManager.get().getLanguageMetadataResult(input.languageId).flatMap(lmd -> {
            String qualifiedFileConstraintName = String.format("%s:%s", input.languageId.getId(), lmd.projectConstraint());
            IConstraint projectConstraint = new CUser(qualifiedFileConstraintName, scopeArgs);
            IDebugContext debug = SolverUtils.createDebugContext(input.logLevel);
            return context.require(buildSpec.createSupplier(new SmlBuildSpec.Input(input.languageId))).mapErr(MultiLangAnalysisException::wrapIfNeeded).flatMap(spec -> {
                try {
                    IState.Immutable initialState = State.of().add(globalResult.result().state()).withResource(input.languageId.getId());
                    SolverResult res = SolverUtils.partialSolve(spec, initialState, projectConstraint, debug, new NullCancel(), new NullProgress());
                    return Result.ofOk(res);
                } catch (InterruptedException e) {
                    return Result.ofErr(new MultiLangAnalysisException(e));
                }
            });
        });
    });
}
Also used : NullCancel(org.metaborg.util.task.NullCancel) SolverResult(mb.statix.solver.persistent.SolverResult) IConstraint(mb.statix.solver.IConstraint) IDebugContext(mb.statix.solver.log.IDebugContext) IState(mb.statix.solver.IState) CUser(mb.statix.constraints.CUser) MultiLangAnalysisException(mb.statix.multilang.MultiLangAnalysisException) ITerm(mb.nabl2.terms.ITerm) NullProgress(org.metaborg.util.task.NullProgress)

Aggregations

IConstraint (mb.statix.solver.IConstraint)88 ITerm (mb.nabl2.terms.ITerm)38 ITermVar (mb.nabl2.terms.ITermVar)38 ICompleteness (mb.statix.solver.completeness.ICompleteness)35 ISubstitution (mb.nabl2.terms.substitution.ISubstitution)33 IUniDisunifier (mb.nabl2.terms.unification.ud.IUniDisunifier)32 Set (io.usethesource.capsule.Set)27 List (java.util.List)24 B (mb.nabl2.terms.build.TermBuild.B)23 ImmutableList (com.google.common.collect.ImmutableList)22 Optional (java.util.Optional)22 SolverResult (mb.statix.solver.persistent.SolverResult)22 Collectors (java.util.stream.Collectors)21 IState (mb.statix.solver.IState)21 Spec (mb.statix.spec.Spec)20 CEqual (mb.statix.constraints.CEqual)17 Tuple2 (org.metaborg.util.tuple.Tuple2)17 Nullable (javax.annotation.Nullable)16 Delay (mb.statix.solver.Delay)16 M (mb.nabl2.terms.matching.TermMatch.M)15