Search in sources :

Example 1 with Iterables2

use of org.metaborg.util.iterators.Iterables2 in project spoofax by metaborg.

the class ConstraintSingleFileAnalyzer method analyzeAll.

@Override
protected ISpoofaxAnalyzeResults analyzeAll(Map<String, ISpoofaxParseUnit> changed, Set<String> removed, ISingleFileScopeGraphContext context, HybridInterpreter runtime, String strategy, IProgress progress, ICancel cancel) throws AnalysisException {
    final NaBL2DebugConfig debugConfig = context.config().debug();
    for (String input : removed) {
        context.removeUnit(input);
    }
    final int n = changed.size();
    progress.setWorkRemaining(n + 1);
    if (debugConfig.analysis() || debugConfig.files()) {
        logger.info("Analyzing {} files in {}.", n, context.location());
    }
    final Collection<ISpoofaxAnalyzeUnit> results = Lists.newArrayList();
    try {
        for (Map.Entry<String, ISpoofaxParseUnit> input : changed.entrySet()) {
            final String source = input.getKey();
            final ISpoofaxParseUnit parseUnit = input.getValue();
            final ITerm ast = strategoTerms.fromStratego(parseUnit.ast());
            if (debugConfig.files()) {
                logger.info("Analyzing {}.", source);
            }
            final ISingleFileScopeGraphUnit unit = context.unit(source);
            unit.clear();
            try {
                // initial
                InitialResult initialResult;
                final Optional<ITerm> customInitial;
                {
                    if (debugConfig.collection()) {
                        logger.info("Collecting initial constraints of {}.", source);
                    }
                    ITerm initialResultTerm = doAction(strategy, Actions.analyzeInitial(source, ast), context, runtime).orElseThrow(() -> new AnalysisException(context, "No initial result."));
                    initialResult = InitialResult.matcher().match(initialResultTerm).orElseThrow(() -> new MetaborgException("Invalid initial results."));
                    customInitial = doCustomAction(strategy, Actions.customInitial(source, ast), context, runtime);
                    initialResult = initialResult.withCustomResult(customInitial);
                    if (debugConfig.collection()) {
                        logger.info("Collected {} initial constraints of {}.", initialResult.getConstraints().size(), source);
                    }
                }
                // unit
                UnitResult unitResult;
                final Optional<ITerm> customUnit;
                {
                    if (debugConfig.collection()) {
                        logger.info("Collecting constraints of {}.", source);
                    }
                    final ITerm unitResultTerm = doAction(strategy, Actions.analyzeUnit(source, ast, initialResult.getArgs()), context, runtime).orElseThrow(() -> new AnalysisException(context, "No unit result."));
                    unitResult = UnitResult.matcher().match(unitResultTerm).orElseThrow(() -> new MetaborgException("Invalid unit results."));
                    final ITerm desugaredAST = unitResult.getAST();
                    customUnit = doCustomAction(strategy, Actions.customUnit(source, desugaredAST, customInitial.orElse(B.EMPTY_TUPLE)), context, runtime);
                    unitResult = unitResult.withCustomResult(customUnit);
                    unit.setUnitResult(unitResult);
                    if (debugConfig.collection()) {
                        logger.info("Collected {} constraints of {}.", unitResult.getConstraints().size(), source);
                    }
                }
                // solve
                ISolution solution;
                {
                    Set<IConstraint> constraints = Sets.union(initialResult.getConstraints(), unitResult.getConstraints());
                    if (debugConfig.resolution()) {
                        logger.info("Solving {} constraints of {}.", constraints.size(), source);
                    }
                    Function1<String, String> fresh = base -> context.unit(source).fresh().fresh(base);
                    final IProgress subprogress = progress.subProgress(1);
                    final SingleFileSolver solver = new SingleFileSolver(context.config().debug(), callExternal(runtime));
                    GraphSolution preSolution = solver.solveGraph(ImmutableBaseSolution.of(initialResult.getConfig(), constraints, PersistentUnifier.Immutable.of()), fresh, cancel, subprogress);
                    preSolution = solver.reportUnsolvedGraphConstraints(preSolution);
                    solution = solver.solve(preSolution, fresh, cancel, subprogress);
                    solution = solver.reportUnsolvedConstraints(solution);
                    if (!solution.flowSpecSolution().controlFlowGraph().isEmpty()) {
                        logger.debug("CFG is not empty: calling FlowSpec dataflow solver");
                        solution = new FixedPoint().entryPoint(solution, getFlowSpecTransferFunctions(context.language()));
                    }
                    unit.setSolution(solution);
                    if (debugConfig.resolution()) {
                        logger.info("Solved constraints of {}.", source);
                    }
                }
                // final
                FinalResult finalResult;
                final Optional<ITerm> customFinal;
                {
                    if (debugConfig.files()) {
                        logger.info("Finalizing analysis of {}.", source);
                    }
                    ITerm finalResultTerm = doAction(strategy, Actions.analyzeFinal(source), context, runtime).orElseThrow(() -> new AnalysisException(context, "No final result."));
                    finalResult = FinalResult.matcher().match(finalResultTerm).orElseThrow(() -> new MetaborgException("Invalid final results."));
                    customFinal = doCustomAction(strategy, Actions.customFinal(source, customInitial.orElse(B.EMPTY_TUPLE), customUnit.map(cu -> Collections.singletonList(cu)).orElse(Collections.emptyList())), context, runtime);
                    finalResult = finalResult.withCustomResult(customFinal);
                    unit.setFinalResult(finalResult);
                    if (debugConfig.files()) {
                        logger.info("Finalized analysis of {}.", source);
                    }
                }
                final IStrategoTerm analyzedAST = strategoTerms.toStratego(unitResult.getAST());
                Optional<CustomSolution> customSolution = customFinal.flatMap(CustomSolution.matcher()::match);
                customSolution.ifPresent(cs -> unit.setCustomSolution(cs));
                // errors
                final boolean success;
                {
                    if (debugConfig.files()) {
                        logger.info("Processing messages of {}.", source);
                    }
                    Messages.Transient messageBuilder = Messages.Transient.of();
                    messageBuilder.addAll(Messages.unsolvedErrors(solution.constraints()));
                    messageBuilder.addAll(solution.messages().getAll());
                    customSolution.map(CustomSolution::getMessages).map(IMessages::getAll).ifPresent(messageBuilder::addAll);
                    IMessages messages = messageBuilder.freeze();
                    success = messages.getErrors().isEmpty();
                    Iterable<IMessage> fileMessages = Iterables.concat(analysisCommon.ambiguityMessages(parseUnit.source(), parseUnit.ast()), messages(messages.getAll(), solution.unifier(), context, context.location()));
                    // result
                    results.add(unitService.analyzeUnit(parseUnit, new AnalyzeContrib(true, success, true, analyzedAST, fileMessages, -1), context));
                    if (debugConfig.analysis() || debugConfig.files()) {
                        logger.info("Analyzed {}: {} errors, {} warnings, {} notes.", source, messages.getErrors().size(), messages.getWarnings().size(), messages.getNotes().size());
                    }
                }
            } catch (MetaborgException | SolverException e) {
                logger.warn("Analysis of " + source + " failed.", e);
                Iterable<IMessage> messages = Iterables2.singleton(MessageFactory.newAnalysisErrorAtTop(parseUnit.source(), "File analysis failed.", e));
                results.add(unitService.analyzeUnit(parseUnit, new AnalyzeContrib(false, false, true, parseUnit.ast(), messages, -1), context));
            }
        }
    } catch (InterruptedException e) {
        logger.debug("Analysis was interrupted.");
    }
    if (debugConfig.analysis()) {
        logger.info("Analyzed {} files.", n);
    }
    return new SpoofaxAnalyzeResults(results, Collections.emptyList(), context);
}
Also used : UnitResult(mb.nabl2.spoofax.analysis.UnitResult) ITerm(mb.nabl2.terms.ITerm) ISpoofaxAnalyzeUnit(org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit) IProgress(org.metaborg.util.task.IProgress) Inject(com.google.inject.Inject) IConstraint(mb.nabl2.constraints.IConstraint) MetaborgException(org.metaborg.core.MetaborgException) ICancel(org.metaborg.util.task.ICancel) Map(java.util.Map) SolverException(mb.nabl2.solver.SolverException) ISolution(mb.nabl2.solver.ISolution) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) B(mb.nabl2.terms.build.TermBuild.B) GraphSolution(mb.nabl2.solver.solvers.BaseSolver.GraphSolution) ISpoofaxAnalyzer(org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzer) ISpoofaxParseUnit(org.metaborg.spoofax.core.unit.ISpoofaxParseUnit) Collection(java.util.Collection) ISpoofaxTracingService(org.metaborg.spoofax.core.tracing.ISpoofaxTracingService) Set(java.util.Set) Sets(com.google.common.collect.Sets) Iterables2(org.metaborg.util.iterators.Iterables2) FinalResult(mb.nabl2.spoofax.analysis.FinalResult) Optional(java.util.Optional) LoggerUtils(org.metaborg.util.log.LoggerUtils) ImmutableBaseSolution(mb.nabl2.solver.solvers.ImmutableBaseSolution) ITermFactoryService(org.metaborg.spoofax.core.terms.ITermFactoryService) Iterables(com.google.common.collect.Iterables) Function1(org.metaborg.util.functions.Function1) AnalysisCommon(org.metaborg.spoofax.core.analysis.AnalysisCommon) ISpoofaxAnalyzeResults(org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults) ISingleFileScopeGraphContext(org.metaborg.spoofax.core.context.scopegraph.ISingleFileScopeGraphContext) Actions(mb.nabl2.spoofax.analysis.Actions) Lists(com.google.common.collect.Lists) ISpoofaxUnitService(org.metaborg.spoofax.core.unit.ISpoofaxUnitService) HybridInterpreter(org.strategoxt.HybridInterpreter) SingleFileSolver(mb.nabl2.solver.solvers.SingleFileSolver) PersistentUnifier(mb.nabl2.terms.unification.PersistentUnifier) ILogger(org.metaborg.util.log.ILogger) Messages(mb.nabl2.solver.messages.Messages) ISingleFileScopeGraphUnit(org.metaborg.spoofax.core.context.scopegraph.ISingleFileScopeGraphUnit) CustomSolution(mb.nabl2.spoofax.analysis.CustomSolution) IMessage(org.metaborg.core.messages.IMessage) NaBL2DebugConfig(mb.nabl2.config.NaBL2DebugConfig) AnalyzeContrib(org.metaborg.spoofax.core.unit.AnalyzeContrib) IMessages(mb.nabl2.solver.messages.IMessages) SpoofaxAnalyzeResults(org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults) FixedPoint(mb.flowspec.runtime.solver.FixedPoint) IResourceService(org.metaborg.core.resource.IResourceService) IStrategoCommon(org.metaborg.spoofax.core.stratego.IStrategoCommon) InitialResult(mb.nabl2.spoofax.analysis.InitialResult) Collections(java.util.Collections) AnalysisException(org.metaborg.core.analysis.AnalysisException) IStrategoRuntimeService(org.metaborg.spoofax.core.stratego.IStrategoRuntimeService) MessageFactory(org.metaborg.core.messages.MessageFactory) ISpoofaxAnalyzeResults(org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults) SpoofaxAnalyzeResults(org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults) ISingleFileScopeGraphUnit(org.metaborg.spoofax.core.context.scopegraph.ISingleFileScopeGraphUnit) Set(java.util.Set) IStrategoTerm(org.spoofax.interpreter.terms.IStrategoTerm) MetaborgException(org.metaborg.core.MetaborgException) UnitResult(mb.nabl2.spoofax.analysis.UnitResult) AnalyzeContrib(org.metaborg.spoofax.core.unit.AnalyzeContrib) SingleFileSolver(mb.nabl2.solver.solvers.SingleFileSolver) FixedPoint(mb.flowspec.runtime.solver.FixedPoint) GraphSolution(mb.nabl2.solver.solvers.BaseSolver.GraphSolution) InitialResult(mb.nabl2.spoofax.analysis.InitialResult) ISpoofaxAnalyzeUnit(org.metaborg.spoofax.core.unit.ISpoofaxAnalyzeUnit) ISpoofaxParseUnit(org.metaborg.spoofax.core.unit.ISpoofaxParseUnit) IProgress(org.metaborg.util.task.IProgress) FinalResult(mb.nabl2.spoofax.analysis.FinalResult) IMessages(mb.nabl2.solver.messages.IMessages) Function1(org.metaborg.util.functions.Function1) ISolution(mb.nabl2.solver.ISolution) IConstraint(mb.nabl2.constraints.IConstraint) FixedPoint(mb.flowspec.runtime.solver.FixedPoint) CustomSolution(mb.nabl2.spoofax.analysis.CustomSolution) NaBL2DebugConfig(mb.nabl2.config.NaBL2DebugConfig) AnalysisException(org.metaborg.core.analysis.AnalysisException) ITerm(mb.nabl2.terms.ITerm) SolverException(mb.nabl2.solver.SolverException) Map(java.util.Map)

Example 2 with Iterables2

use of org.metaborg.util.iterators.Iterables2 in project nabl by metaborg.

the class SetComponent method makeMessages.

private Iterable<IMessageInfo> makeMessages(IMessageInfo template, Collection<IElement<ITerm>> elements) {
    boolean nameOrigin = M.appl0(NAME_OP).match(template.getOriginTerm(), unifier()).isPresent();
    if (nameOrigin && !elements.isEmpty()) {
        return elements.stream().<IMessageInfo>map(e -> {
            Function1<ITerm, ITerm> f = T.sometd(t -> M.appl0(NAME_OP, a -> e.getValue()).match(t, unifier()));
            return ImmutableMessageInfo.of(template.getKind(), template.getContent().apply(f), e.getPosition());
        }).collect(Collectors.toList());
    } else {
        ITerm es = B.newList(elements.stream().map(e -> e.getValue()).collect(Collectors.toList()));
        Function1<ITerm, ITerm> f = T.sometd(t -> M.appl0(NAME_OP, a -> es).match(t, unifier()));
        return Iterables2.singleton(ImmutableMessageInfo.of(template.getKind(), template.getContent().apply(f), template.getOriginTerm()));
    }
}
Also used : ISetConstraint(mb.nabl2.constraints.sets.ISetConstraint) Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm) ImmutableCEqual(mb.nabl2.constraints.equality.ImmutableCEqual) Multimap(com.google.common.collect.Multimap) SolveResult(mb.nabl2.solver.ISolver.SolveResult) SolverCore(mb.nabl2.solver.SolverCore) CEvalSet(mb.nabl2.constraints.sets.CEvalSet) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) SetEvaluator(mb.nabl2.sets.SetEvaluator) T(mb.nabl2.terms.matching.Transform.T) Unit(org.metaborg.util.unit.Unit) B(mb.nabl2.terms.build.TermBuild.B) ImmutableMessageInfo(mb.nabl2.constraints.messages.ImmutableMessageInfo) ASolver(mb.nabl2.solver.ASolver) M(mb.nabl2.terms.matching.TermMatch.M) Collection(java.util.Collection) Set(java.util.Set) CDistinct(mb.nabl2.constraints.sets.CDistinct) Collectors(java.util.stream.Collectors) IMessageInfo(mb.nabl2.constraints.messages.IMessageInfo) MessageContent(mb.nabl2.constraints.messages.MessageContent) CSubsetEq(mb.nabl2.constraints.sets.CSubsetEq) Iterables2(org.metaborg.util.iterators.Iterables2) List(java.util.List) Optional(java.util.Optional) IMatcher(mb.nabl2.terms.matching.TermMatch.IMatcher) IElement(mb.nabl2.sets.IElement) Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm)

Example 3 with Iterables2

use of org.metaborg.util.iterators.Iterables2 in project nabl by metaborg.

the class BaseMultiFileSolver method solveIntra.

public ISolution solveIntra(GraphSolution initial, Collection<ITermVar> intfVars, @Nullable Collection<Scope> intfScopes, Function1<String, String> fresh, ICancel cancel, IProgress progress) throws SolverException, InterruptedException {
    final SolverConfig config = initial.config();
    // shared
    final Ref<IUnifier.Immutable> unifier = new Ref<>(initial.unifier());
    // constraint set properties
    final ActiveVars activeVars = new ActiveVars(unifier);
    intfVars.stream().forEach(activeVars::add);
    // guards -- intfScopes == null indicates we do not know the interface scopes, and resolution should be delayed.
    final Predicate2<Scope, Label> isEdgeClosed = (s, l) -> intfScopes != null && !intfScopes.contains(s);
    // more shared
    final IEsopScopeGraph.Transient<Scope, Label, Occurrence, ITerm> scopeGraph = initial.scopeGraph().melt();
    final IEsopNameResolution<Scope, Label, Occurrence> nameResolution = EsopNameResolution.of(config.getResolutionParams(), scopeGraph, isEdgeClosed);
    // solver components
    final SolverCore core = new SolverCore(config, unifier, fresh, callExternal);
    final BaseComponent baseSolver = new BaseComponent(core);
    final EqualityComponent equalitySolver = new EqualityComponent(core, unifier);
    final NameResolutionComponent nameResolutionSolver = new NameResolutionComponent(core, scopeGraph, nameResolution, Properties.Transient.of());
    final NameSetsComponent nameSetSolver = new NameSetsComponent(core, scopeGraph, nameResolution);
    final PolymorphismComponent polySolver = new PolymorphismComponent(core, Predicate1.never(), Predicate1.never(), nameResolutionSolver::getProperty);
    final RelationComponent relationSolver = new RelationComponent(core, Predicate1.never(), config.getFunctions(), VariantRelations.transientOf(config.getRelations()));
    final SetComponent setSolver = new SetComponent(core, nameSetSolver.nameSets());
    final SymbolicComponent symSolver = new SymbolicComponent(core, SymbolicConstraints.of());
    final ControlFlowComponent cfgSolver = new ControlFlowComponent(core, ImmutableFlowSpecSolution.of());
    final ISolver component = c -> c.matchOrThrow(IConstraint.CheckedCases.<Optional<SolveResult>, InterruptedException>builder().onBase(baseSolver::solve).onEquality(equalitySolver::solve).onNameResolution(nameResolutionSolver::solve).onPoly(polySolver::solve).onRelation(relationSolver::solve).onSet(setSolver::solve).onSym(symSolver::solve).onControlflow(cfgSolver::solve).otherwise(ISolver.deny("Not allowed in this phase")));
    final FixedPointSolver solver = new FixedPointSolver(cancel, progress, component, Iterables2.from(activeVars));
    solver.step().subscribe(r -> {
        if (!r.unifierDiff().isEmpty()) {
            try {
                nameResolutionSolver.update();
            } catch (InterruptedException ex) {
            // ignore here
            }
        }
    });
    try {
        nameResolutionSolver.update();
        final SolveResult solveResult = solver.solve(initial.constraints());
        NameResolutionResult nameResolutionResult = nameResolutionSolver.finish();
        IUnifier.Immutable unifierResult = equalitySolver.finish();
        Map<String, IVariantRelation.Immutable<ITerm>> relationResult = relationSolver.finish();
        ISymbolicConstraints symbolicConstraints = symSolver.finish();
        IFlowSpecSolution<CFGNode> fsSolution = cfgSolver.finish();
        return ImmutableSolution.of(config, initial.astProperties(), nameResolutionResult.scopeGraph(), nameResolutionResult.declProperties(), relationResult, unifierResult, symbolicConstraints, fsSolution, solveResult.messages(), solveResult.constraints()).withNameResolutionCache(nameResolutionResult.resolutionCache());
    } catch (RuntimeException ex) {
        throw new SolverException("Internal solver error.", ex);
    }
}
Also used : VariantRelations(mb.nabl2.relations.variants.VariantRelations) ControlFlowComponent(mb.nabl2.solver.components.ControlFlowComponent) IUnifier(mb.nabl2.terms.unification.IUnifier) Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm) IProgress(org.metaborg.util.task.IProgress) ImmutableSolution(mb.nabl2.solver.ImmutableSolution) Ref(org.metaborg.util.Ref) IConstraint(mb.nabl2.constraints.IConstraint) SetComponent(mb.nabl2.solver.components.SetComponent) Occurrence(mb.nabl2.scopegraph.terms.Occurrence) IEsopNameResolution(mb.nabl2.scopegraph.esop.IEsopNameResolution) NameResolutionResult(mb.nabl2.solver.components.NameResolutionComponent.NameResolutionResult) SolveResult(mb.nabl2.solver.ISolver.SolveResult) SolverCore(mb.nabl2.solver.SolverCore) IVariantRelation(mb.nabl2.relations.variants.IVariantRelation) RelationComponent(mb.nabl2.solver.components.RelationComponent) CFGNode(mb.nabl2.controlflow.terms.CFGNode) ICancel(org.metaborg.util.task.ICancel) Label(mb.nabl2.scopegraph.terms.Label) IFlowSpecSolution(mb.nabl2.controlflow.terms.IFlowSpecSolution) Map(java.util.Map) SymbolicComponent(mb.nabl2.solver.components.SymbolicComponent) ITermVar(mb.nabl2.terms.ITermVar) Properties(mb.nabl2.util.collections.Properties) SolverException(mb.nabl2.solver.SolverException) ISolution(mb.nabl2.solver.ISolution) ISymbolicConstraints(mb.nabl2.symbolic.ISymbolicConstraints) Nullable(javax.annotation.Nullable) EqualityComponent(mb.nabl2.solver.components.EqualityComponent) ActiveVars(mb.nabl2.solver.properties.ActiveVars) NameResolutionComponent(mb.nabl2.solver.components.NameResolutionComponent) BaseComponent(mb.nabl2.solver.components.BaseComponent) Collection(java.util.Collection) ImmutableFlowSpecSolution(mb.nabl2.controlflow.terms.ImmutableFlowSpecSolution) IEsopScopeGraph(mb.nabl2.scopegraph.esop.IEsopScopeGraph) SymbolicConstraints(mb.nabl2.symbolic.SymbolicConstraints) EsopNameResolution(mb.nabl2.scopegraph.esop.lazy.EsopNameResolution) Predicate2(org.metaborg.util.functions.Predicate2) Scope(mb.nabl2.scopegraph.terms.Scope) Predicate1(org.metaborg.util.functions.Predicate1) NaBL2DebugConfig(mb.nabl2.config.NaBL2DebugConfig) Iterables2(org.metaborg.util.iterators.Iterables2) PolymorphismComponent(mb.nabl2.solver.components.PolymorphismComponent) NameSetsComponent(mb.nabl2.solver.components.NameSetsComponent) ISolver(mb.nabl2.solver.ISolver) Optional(java.util.Optional) SolverConfig(mb.nabl2.solver.SolverConfig) SetComponent(mb.nabl2.solver.components.SetComponent) BaseComponent(mb.nabl2.solver.components.BaseComponent) IUnifier(mb.nabl2.terms.unification.IUnifier) SymbolicComponent(mb.nabl2.solver.components.SymbolicComponent) RelationComponent(mb.nabl2.solver.components.RelationComponent) Label(mb.nabl2.scopegraph.terms.Label) IEsopScopeGraph(mb.nabl2.scopegraph.esop.IEsopScopeGraph) ControlFlowComponent(mb.nabl2.solver.components.ControlFlowComponent) NameResolutionComponent(mb.nabl2.solver.components.NameResolutionComponent) ActiveVars(mb.nabl2.solver.properties.ActiveVars) ISymbolicConstraints(mb.nabl2.symbolic.ISymbolicConstraints) Occurrence(mb.nabl2.scopegraph.terms.Occurrence) SolverConfig(mb.nabl2.solver.SolverConfig) ISolver(mb.nabl2.solver.ISolver) Optional(java.util.Optional) CFGNode(mb.nabl2.controlflow.terms.CFGNode) NameSetsComponent(mb.nabl2.solver.components.NameSetsComponent) SolverCore(mb.nabl2.solver.SolverCore) PolymorphismComponent(mb.nabl2.solver.components.PolymorphismComponent) Ref(org.metaborg.util.Ref) SolveResult(mb.nabl2.solver.ISolver.SolveResult) Scope(mb.nabl2.scopegraph.terms.Scope) ITerm(mb.nabl2.terms.ITerm) EqualityComponent(mb.nabl2.solver.components.EqualityComponent) NameResolutionResult(mb.nabl2.solver.components.NameResolutionComponent.NameResolutionResult) SolverException(mb.nabl2.solver.SolverException)

Example 4 with Iterables2

use of org.metaborg.util.iterators.Iterables2 in project nabl by metaborg.

the class BaseSolver method solveGraph.

public GraphSolution solveGraph(BaseSolution initial, Function1<String, String> fresh, ICancel cancel, IProgress progress) throws SolverException, InterruptedException {
    // shared
    final Ref<IUnifier.Immutable> unifier = new Ref<>(initial.unifier());
    final IEsopScopeGraph.Transient<Scope, Label, Occurrence, ITerm> scopeGraph = EsopScopeGraph.Transient.of();
    // solver components
    final SolverCore core = new SolverCore(initial.config(), unifier, fresh, callExternal);
    final AstComponent astSolver = new AstComponent(core, Properties.Transient.of());
    final BaseComponent baseSolver = new BaseComponent(core);
    final EqualityComponent equalitySolver = new EqualityComponent(core, unifier);
    final ScopeGraphComponent scopeGraphSolver = new ScopeGraphComponent(core, scopeGraph);
    try {
        ISolver component = c -> c.matchOrThrow(IConstraint.CheckedCases.<Optional<SolveResult>, InterruptedException>builder().onAst(astSolver::solve).onBase(baseSolver::solve).onEquality(equalitySolver::solve).onScopeGraph(scopeGraphSolver::solve).otherwise(cc -> Optional.empty()));
        final FixedPointSolver solver = new FixedPointSolver(cancel, progress, component, Iterables2.empty());
        final SolveResult solveResult = solver.solve(initial.constraints());
        return ImmutableGraphSolution.of(initial.config(), astSolver.finish(), scopeGraphSolver.finish(), equalitySolver.finish(), solveResult.messages(), solveResult.constraints());
    } catch (RuntimeException ex) {
        throw new SolverException("Internal solver error.", ex);
    }
}
Also used : IUnifier(mb.nabl2.terms.unification.IUnifier) Function1(org.metaborg.util.functions.Function1) ITerm(mb.nabl2.terms.ITerm) IProgress(org.metaborg.util.task.IProgress) ImmutableSolution(mb.nabl2.solver.ImmutableSolution) Ref(org.metaborg.util.Ref) IConstraint(mb.nabl2.constraints.IConstraint) ScopeGraphComponent(mb.nabl2.solver.components.ScopeGraphComponent) Occurrence(mb.nabl2.scopegraph.terms.Occurrence) IProperties(mb.nabl2.util.collections.IProperties) SolveResult(mb.nabl2.solver.ISolver.SolveResult) SolverCore(mb.nabl2.solver.SolverCore) ICancel(org.metaborg.util.task.ICancel) Value(org.immutables.value.Value) Label(mb.nabl2.scopegraph.terms.Label) Properties(mb.nabl2.util.collections.Properties) IAstConstraint(mb.nabl2.constraints.ast.IAstConstraint) SolverException(mb.nabl2.solver.SolverException) ISolution(mb.nabl2.solver.ISolution) EqualityComponent(mb.nabl2.solver.components.EqualityComponent) EsopScopeGraph(mb.nabl2.scopegraph.esop.reference.EsopScopeGraph) ImmutableSet(com.google.common.collect.ImmutableSet) TermIndex(mb.nabl2.stratego.TermIndex) BaseComponent(mb.nabl2.solver.components.BaseComponent) IScopeGraphConstraint(mb.nabl2.constraints.scopegraph.IScopeGraphConstraint) IEsopScopeGraph(mb.nabl2.scopegraph.esop.IEsopScopeGraph) Set(java.util.Set) Messages(mb.nabl2.solver.messages.Messages) Scope(mb.nabl2.scopegraph.terms.Scope) Sets(com.google.common.collect.Sets) NaBL2DebugConfig(mb.nabl2.config.NaBL2DebugConfig) AstComponent(mb.nabl2.solver.components.AstComponent) Iterables2(org.metaborg.util.iterators.Iterables2) IMessages(mb.nabl2.solver.messages.IMessages) ISolver(mb.nabl2.solver.ISolver) Serial(org.immutables.serial.Serial) SeedResult(mb.nabl2.solver.ISolver.SeedResult) Optional(java.util.Optional) SolverConfig(mb.nabl2.solver.SolverConfig) Collections(java.util.Collections) ScopeGraphComponent(mb.nabl2.solver.components.ScopeGraphComponent) BaseComponent(mb.nabl2.solver.components.BaseComponent) AstComponent(mb.nabl2.solver.components.AstComponent) ISolver(mb.nabl2.solver.ISolver) Optional(java.util.Optional) Label(mb.nabl2.scopegraph.terms.Label) SolverCore(mb.nabl2.solver.SolverCore) IEsopScopeGraph(mb.nabl2.scopegraph.esop.IEsopScopeGraph) Ref(org.metaborg.util.Ref) SolveResult(mb.nabl2.solver.ISolver.SolveResult) Scope(mb.nabl2.scopegraph.terms.Scope) ITerm(mb.nabl2.terms.ITerm) EqualityComponent(mb.nabl2.solver.components.EqualityComponent) SolverException(mb.nabl2.solver.SolverException) Occurrence(mb.nabl2.scopegraph.terms.Occurrence)

Example 5 with Iterables2

use of org.metaborg.util.iterators.Iterables2 in project nabl by metaborg.

the class SemiIncrementalMultiFileSolver method solveInter.

public ISolution solveInter(ISolution initial, Iterable<? extends ISolution> unitSolutions, IMessageInfo message, Function1<String, String> fresh, ICancel cancel, IProgress progress) throws SolverException, InterruptedException {
    final SolverConfig config = initial.config();
    // shared
    final Ref<IUnifier.Immutable> unifier = new Ref<>(initial.unifier());
    final IEsopScopeGraph.Transient<Scope, Label, Occurrence, ITerm> scopeGraph = initial.scopeGraph().melt();
    final IEsopNameResolution<Scope, Label, Occurrence> nameResolution = EsopNameResolution.of(config.getResolutionParams(), scopeGraph, (s, l) -> true);
    // constraint set properties
    final ActiveVars activeVars = new ActiveVars(unifier);
    final ActiveDeclTypes activeDeclTypes = new ActiveDeclTypes(unifier);
    final HasRelationBuildConstraints hasRelationBuildConstraints = new HasRelationBuildConstraints();
    // guards
    final Predicate1<String> isRelationComplete = r -> !hasRelationBuildConstraints.contains(r);
    // solver components
    final SolverCore core = new SolverCore(config, unifier, fresh, callExternal);
    final AstComponent astSolver = new AstComponent(core, initial.astProperties().melt());
    final BaseComponent baseSolver = new BaseComponent(core);
    final EqualityComponent equalitySolver = new EqualityComponent(core, unifier);
    final NameResolutionComponent nameResolutionSolver = new NameResolutionComponent(core, scopeGraph, nameResolution, initial.declProperties().melt());
    final NameSetsComponent nameSetSolver = new NameSetsComponent(core, scopeGraph, nameResolution);
    final RelationComponent relationSolver = new RelationComponent(core, isRelationComplete, config.getFunctions(), VariantRelations.melt(initial.relations()));
    final SetComponent setSolver = new SetComponent(core, nameSetSolver.nameSets());
    final SymbolicComponent symSolver = new SymbolicComponent(core, initial.symbolic());
    final ControlFlowComponent cfgSolver = new ControlFlowComponent(core, ImmutableFlowSpecSolution.of());
    final PolySafe polySafe = new PolySafe(activeVars, activeDeclTypes, nameResolutionSolver);
    final PolymorphismComponent polySolver = new PolymorphismComponent(core, polySafe::isGenSafe, polySafe::isInstSafe, nameResolutionSolver::getProperty);
    final ISolver component = c -> c.matchOrThrow(IConstraint.CheckedCases.<Optional<SolveResult>, InterruptedException>builder().onBase(baseSolver::solve).onEquality(equalitySolver::solve).onNameResolution(nameResolutionSolver::solve).onPoly(polySolver::solve).onRelation(relationSolver::solve).onSet(setSolver::solve).onSym(symSolver::solve).onControlflow(cfgSolver::solve).otherwise(ISolver.deny("Not allowed in this phase")));
    final FixedPointSolver solver = new FixedPointSolver(cancel, progress, component, Iterables2.from(activeVars, hasRelationBuildConstraints));
    solver.step().subscribe(r -> {
        if (!r.unifierDiff().isEmpty()) {
            try {
                nameResolutionSolver.update();
            } catch (InterruptedException ex) {
            // ignore here
            }
        }
    });
    try {
        // seed unit solutions
        final java.util.Set<IConstraint> constraints = Sets.newHashSet(initial.constraints());
        final IMessages.Transient messages = initial.messages().melt();
        for (ISolution unitSolution : unitSolutions) {
            seed(astSolver.seed(unitSolution.astProperties(), message), messages, constraints);
            seed(equalitySolver.seed(unitSolution.unifier(), message), messages, constraints);
            final NameResolutionResult nameResult = ImmutableNameResolutionResult.of(unitSolution.scopeGraph(), unitSolution.declProperties()).withResolutionCache(unitSolution.nameResolutionCache());
            seed(nameResolutionSolver.seed(nameResult, message), messages, constraints);
            seed(relationSolver.seed(unitSolution.relations(), message), messages, constraints);
            seed(symSolver.seed(unitSolution.symbolic(), message), messages, constraints);
            seed(cfgSolver.seed(unitSolution.flowSpecSolution(), message), messages, constraints);
            constraints.addAll(unitSolution.constraints());
            messages.addAll(unitSolution.messages());
        }
        // solve constraints
        nameResolutionSolver.update();
        SolveResult solveResult = solver.solve(constraints);
        messages.addAll(solveResult.messages());
        // build result
        IProperties.Immutable<TermIndex, ITerm, ITerm> astResult = astSolver.finish();
        NameResolutionResult nameResolutionResult = nameResolutionSolver.finish();
        IUnifier.Immutable unifierResult = equalitySolver.finish();
        Map<String, IVariantRelation.Immutable<ITerm>> relationResult = relationSolver.finish();
        ISymbolicConstraints symbolicConstraints = symSolver.finish();
        IFlowSpecSolution<CFGNode> fsSolution = cfgSolver.finish();
        return ImmutableSolution.of(config, astResult, nameResolutionResult.scopeGraph(), nameResolutionResult.declProperties(), relationResult, unifierResult, symbolicConstraints, fsSolution, messages.freeze(), solveResult.constraints()).withNameResolutionCache(nameResolutionResult.resolutionCache());
    } catch (RuntimeException ex) {
        throw new SolverException("Internal solver error.", ex);
    }
}
Also used : ControlFlowComponent(mb.nabl2.solver.components.ControlFlowComponent) IUnifier(mb.nabl2.terms.unification.IUnifier) ITerm(mb.nabl2.terms.ITerm) IProgress(org.metaborg.util.task.IProgress) Ref(org.metaborg.util.Ref) IConstraint(mb.nabl2.constraints.IConstraint) IProperties(mb.nabl2.util.collections.IProperties) SolverCore(mb.nabl2.solver.SolverCore) ICancel(org.metaborg.util.task.ICancel) IFlowSpecSolution(mb.nabl2.controlflow.terms.IFlowSpecSolution) Map(java.util.Map) SymbolicComponent(mb.nabl2.solver.components.SymbolicComponent) SolverException(mb.nabl2.solver.SolverException) ISolution(mb.nabl2.solver.ISolution) EqualityComponent(mb.nabl2.solver.components.EqualityComponent) ImmutableFlowSpecSolution(mb.nabl2.controlflow.terms.ImmutableFlowSpecSolution) IEsopScopeGraph(mb.nabl2.scopegraph.esop.IEsopScopeGraph) Predicate1(org.metaborg.util.functions.Predicate1) IMessageInfo(mb.nabl2.constraints.messages.IMessageInfo) Sets(com.google.common.collect.Sets) ImmutableNameResolutionResult(mb.nabl2.solver.components.ImmutableNameResolutionResult) AstComponent(mb.nabl2.solver.components.AstComponent) Iterables2(org.metaborg.util.iterators.Iterables2) NameSetsComponent(mb.nabl2.solver.components.NameSetsComponent) ISolver(mb.nabl2.solver.ISolver) Optional(java.util.Optional) VariantRelations(mb.nabl2.relations.variants.VariantRelations) Function1(org.metaborg.util.functions.Function1) ImmutableSolution(mb.nabl2.solver.ImmutableSolution) SetComponent(mb.nabl2.solver.components.SetComponent) Occurrence(mb.nabl2.scopegraph.terms.Occurrence) IEsopNameResolution(mb.nabl2.scopegraph.esop.IEsopNameResolution) NameResolutionResult(mb.nabl2.solver.components.NameResolutionComponent.NameResolutionResult) SolveResult(mb.nabl2.solver.ISolver.SolveResult) IVariantRelation(mb.nabl2.relations.variants.IVariantRelation) RelationComponent(mb.nabl2.solver.components.RelationComponent) CFGNode(mb.nabl2.controlflow.terms.CFGNode) Label(mb.nabl2.scopegraph.terms.Label) ActiveDeclTypes(mb.nabl2.solver.properties.ActiveDeclTypes) ISymbolicConstraints(mb.nabl2.symbolic.ISymbolicConstraints) ActiveVars(mb.nabl2.solver.properties.ActiveVars) NameResolutionComponent(mb.nabl2.solver.components.NameResolutionComponent) TermIndex(mb.nabl2.stratego.TermIndex) BaseComponent(mb.nabl2.solver.components.BaseComponent) EsopNameResolution(mb.nabl2.scopegraph.esop.lazy.EsopNameResolution) Scope(mb.nabl2.scopegraph.terms.Scope) NaBL2DebugConfig(mb.nabl2.config.NaBL2DebugConfig) PolymorphismComponent(mb.nabl2.solver.components.PolymorphismComponent) IMessages(mb.nabl2.solver.messages.IMessages) HasRelationBuildConstraints(mb.nabl2.solver.properties.HasRelationBuildConstraints) PolySafe(mb.nabl2.solver.properties.PolySafe) SolverConfig(mb.nabl2.solver.SolverConfig) SymbolicComponent(mb.nabl2.solver.components.SymbolicComponent) Label(mb.nabl2.scopegraph.terms.Label) IProperties(mb.nabl2.util.collections.IProperties) IEsopScopeGraph(mb.nabl2.scopegraph.esop.IEsopScopeGraph) ControlFlowComponent(mb.nabl2.solver.components.ControlFlowComponent) Occurrence(mb.nabl2.scopegraph.terms.Occurrence) SolverConfig(mb.nabl2.solver.SolverConfig) ActiveDeclTypes(mb.nabl2.solver.properties.ActiveDeclTypes) AstComponent(mb.nabl2.solver.components.AstComponent) ISolver(mb.nabl2.solver.ISolver) Optional(java.util.Optional) CFGNode(mb.nabl2.controlflow.terms.CFGNode) SolverCore(mb.nabl2.solver.SolverCore) IConstraint(mb.nabl2.constraints.IConstraint) ISolution(mb.nabl2.solver.ISolution) TermIndex(mb.nabl2.stratego.TermIndex) SolveResult(mb.nabl2.solver.ISolver.SolveResult) SetComponent(mb.nabl2.solver.components.SetComponent) BaseComponent(mb.nabl2.solver.components.BaseComponent) IUnifier(mb.nabl2.terms.unification.IUnifier) RelationComponent(mb.nabl2.solver.components.RelationComponent) NameResolutionComponent(mb.nabl2.solver.components.NameResolutionComponent) ActiveVars(mb.nabl2.solver.properties.ActiveVars) PolySafe(mb.nabl2.solver.properties.PolySafe) ISymbolicConstraints(mb.nabl2.symbolic.ISymbolicConstraints) NameSetsComponent(mb.nabl2.solver.components.NameSetsComponent) IMessages(mb.nabl2.solver.messages.IMessages) PolymorphismComponent(mb.nabl2.solver.components.PolymorphismComponent) Ref(org.metaborg.util.Ref) Scope(mb.nabl2.scopegraph.terms.Scope) HasRelationBuildConstraints(mb.nabl2.solver.properties.HasRelationBuildConstraints) ITerm(mb.nabl2.terms.ITerm) EqualityComponent(mb.nabl2.solver.components.EqualityComponent) ImmutableNameResolutionResult(mb.nabl2.solver.components.ImmutableNameResolutionResult) NameResolutionResult(mb.nabl2.solver.components.NameResolutionComponent.NameResolutionResult) SolverException(mb.nabl2.solver.SolverException)

Aggregations

Optional (java.util.Optional)6 ITerm (mb.nabl2.terms.ITerm)6 NaBL2DebugConfig (mb.nabl2.config.NaBL2DebugConfig)5 IConstraint (mb.nabl2.constraints.IConstraint)5 ISolution (mb.nabl2.solver.ISolution)5 SolveResult (mb.nabl2.solver.ISolver.SolveResult)5 SolverCore (mb.nabl2.solver.SolverCore)5 SolverException (mb.nabl2.solver.SolverException)5 Function1 (org.metaborg.util.functions.Function1)5 Iterables2 (org.metaborg.util.iterators.Iterables2)5 Map (java.util.Map)4 IEsopScopeGraph (mb.nabl2.scopegraph.esop.IEsopScopeGraph)4 Label (mb.nabl2.scopegraph.terms.Label)4 Occurrence (mb.nabl2.scopegraph.terms.Occurrence)4 Scope (mb.nabl2.scopegraph.terms.Scope)4 ISolver (mb.nabl2.solver.ISolver)4 ImmutableSolution (mb.nabl2.solver.ImmutableSolution)4 SolverConfig (mb.nabl2.solver.SolverConfig)4 BaseComponent (mb.nabl2.solver.components.BaseComponent)4 EqualityComponent (mb.nabl2.solver.components.EqualityComponent)4