Search in sources :

Example 6 with A4Reporter

use of edu.mit.csail.sdg.alloy4.A4Reporter in project org.alloytools.alloy by AlloyTools.

the class TranslateAlloyToKodkod method execute_commandFromBook.

/**
 * Based on the specified "options", execute one command and return the
 * resulting A4Solution object.
 * <p>
 * Note: it will first test whether the model fits one of the model from the
 * "Software Abstractions" book; if so, it will use the exact instance that was
 * in the book.
 *
 * @param rep - if nonnull, we'll send compilation diagnostic messages to it
 * @param sigs - the list of sigs; this list must be complete
 * @param cmd - the Command to execute
 * @param opt - the set of options guiding the execution of the command
 * @return null if the user chose "save to FILE" as the SAT solver, and nonnull
 *         if the solver finishes the entire solving and is either satisfiable
 *         or unsatisfiable.
 *         <p>
 *         If the return value X is satisfiable, you can call X.next() to get
 *         the next satisfying solution X2; and you can call X2.next() to get
 *         the next satisfying solution X3... until you get an unsatisfying
 *         solution.
 */
public static A4Solution execute_commandFromBook(A4Reporter rep, Iterable<Sig> sigs, Command cmd, A4Options opt) throws Err {
    if (rep == null)
        rep = A4Reporter.NOP;
    TranslateAlloyToKodkod tr = null;
    try {
        if (cmd.parent != null || !cmd.getGrowableSigs().isEmpty())
            return execute_greedyCommand(rep, sigs, cmd, opt);
        tr = new TranslateAlloyToKodkod(rep, opt, sigs, cmd);
        tr.makeFacts(cmd.formula);
        return tr.frame.solve(rep, cmd, new Simplifier(), true);
    } catch (UnsatisfiedLinkError ex) {
        throw new ErrorFatal("The required JNI library cannot be found: " + ex.toString().trim(), ex);
    } catch (CapacityExceededException ex) {
        throw rethrow(ex);
    } catch (HigherOrderDeclException ex) {
        Pos p = tr != null ? tr.frame.kv2typepos(ex.decl().variable()).b : Pos.UNKNOWN;
        throw new ErrorType(p, "Analysis cannot be performed since it requires higher-order quantification that could not be skolemized.");
    } catch (Throwable ex) {
        if (ex instanceof Err)
            throw (Err) ex;
        else
            throw new ErrorFatal("Unknown exception occurred: " + ex, ex);
    }
}
Also used : CapacityExceededException(kodkod.engine.CapacityExceededException) ErrorFatal(edu.mit.csail.sdg.alloy4.ErrorFatal) ErrorType(edu.mit.csail.sdg.alloy4.ErrorType) Err(edu.mit.csail.sdg.alloy4.Err) Pos(edu.mit.csail.sdg.alloy4.Pos) HigherOrderDeclException(kodkod.engine.fol2sat.HigherOrderDeclException)

Example 7 with A4Reporter

use of edu.mit.csail.sdg.alloy4.A4Reporter in project org.alloytools.alloy by AlloyTools.

the class CompUtil method parseEverything_fromFile.

/**
 * Read everything from "file" and parse it; if it mentions submodules, open
 * them and parse them too.
 *
 * @param rep - if nonnull, we will report compilation progress messages to it
 * @param loaded - a cache of files that have been pre-fetched (can be null if
 *            there were no prefetching)
 * @param filename - the main module we are parsing
 * @param initialResolutionMode - use 1 for the historical behavior, and 2 for
 *            Alloy 4.2's new "universal implicit this" name resolution behavior
 * @return the root CompModule which contains pointers to all submodules
 * @throws Err if an error occurred
 *             <p>
 *             And if loaded!=null, it will contain all the files needed for
 *             this parse, and furthermore, other entries will be deleted.
 */
public static CompModule parseEverything_fromFile(A4Reporter rep, Map<String, String> loaded, String filename, int initialResolutionMode) throws Err {
    try {
        filename = Util.canon(filename);
        Set<String> thispath = new LinkedHashSet<String>();
        if (loaded == null)
            loaded = new LinkedHashMap<String, String>();
        Map<String, String> fc = new LinkedHashMap<String, String>(loaded);
        loaded.clear();
        List<Object> seenDollar = new ArrayList<Object>();
        CompModule root = parseRecursively(seenDollar, loaded, fc, new Pos(filename, 1, 1), filename, null, "", thispath, initialResolutionMode);
        // if no sigs are defined by the user, add one
        if (root.getAllReachableUserDefinedSigs().isEmpty()) {
            root.addGhostSig();
        }
        root.seenDollar = seenDollar.size() > 0;
        return CompModule.resolveAll(rep == null ? A4Reporter.NOP : rep, root);
    } catch (FileNotFoundException ex) {
        throw new ErrorSyntax("File cannot be found.\n" + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new ErrorFatal("IOException occurred: " + ex.getMessage(), ex);
    } catch (Throwable ex) {
        if (ex instanceof Err)
            throw (Err) ex;
        else
            throw new ErrorFatal("Unknown exception occurred: " + ex, ex);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Err(edu.mit.csail.sdg.alloy4.Err) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ErrorSyntax(edu.mit.csail.sdg.alloy4.ErrorSyntax) ErrorFatal(edu.mit.csail.sdg.alloy4.ErrorFatal) Pos(edu.mit.csail.sdg.alloy4.Pos)

Example 8 with A4Reporter

use of edu.mit.csail.sdg.alloy4.A4Reporter in project org.alloytools.alloy by AlloyTools.

the class EvaluatorExample method main.

public static void main(String[] args) throws Exception {
    A4Reporter rep = new A4Reporter();
    File tmpAls = CompUtil.flushModelToFile(model, null);
    {
        Module world = CompUtil.parseEverything_fromString(rep, model);
        A4Options opt = new A4Options();
        opt.originalFilename = tmpAls.getAbsolutePath();
        opt.solver = A4Options.SatSolver.SAT4J;
        Command cmd = world.getAllCommands().get(0);
        A4Solution sol = TranslateAlloyToKodkod.execute_commandFromBook(rep, world.getAllReachableSigs(), cmd, opt);
        assert sol.satisfiable();
        sol.writeXML(outputfilename);
        // eval with existing A4Solution
        Expr e = CompUtil.parseOneExpression_fromString(world, "univ");
        System.out.println(sol.eval(e));
        e = CompUtil.parseOneExpression_fromString(world, "Point");
        System.out.println(sol.eval(e));
    }
    // reload everything from files
    {
        XMLNode xmlNode = new XMLNode(new File(outputfilename));
        String alloySourceFilename = xmlNode.iterator().next().getAttribute("filename");
        Module ansWorld = CompUtil.parseEverything_fromFile(rep, null, alloySourceFilename);
        A4Solution ans = A4SolutionReader.read(ansWorld.getAllReachableSigs(), xmlNode);
        Expr e = CompUtil.parseOneExpression_fromString(ansWorld, "univ");
        System.out.println(ans.eval(e));
        e = CompUtil.parseOneExpression_fromString(ansWorld, "Point");
        System.out.println(ans.eval(e));
    }
}
Also used : Expr(edu.mit.csail.sdg.ast.Expr) XMLNode(edu.mit.csail.sdg.alloy4.XMLNode) Command(edu.mit.csail.sdg.ast.Command) A4Reporter(edu.mit.csail.sdg.alloy4.A4Reporter) A4Options(edu.mit.csail.sdg.translator.A4Options) Module(edu.mit.csail.sdg.ast.Module) File(java.io.File) A4Solution(edu.mit.csail.sdg.translator.A4Solution)

Example 9 with A4Reporter

use of edu.mit.csail.sdg.alloy4.A4Reporter in project org.alloytools.alloy by AlloyTools.

the class ExampleUsingTheCompiler method main.

/*
     * Execute every command in every file. This method parses every file, then
     * execute every command. If there are syntax or type errors, it may throw a
     * ErrorSyntax or ErrorType or ErrorAPI or ErrorFatal exception. You should
     * catch them and display them, and they may contain filename/line/column
     * information.
     */
public static void main(String[] args) throws Err {
    // The visualizer (We will initialize it to nonnull when we visualize an
    // Alloy solution)
    VizGUI viz = null;
    // Alloy4 sends diagnostic messages and progress reports to the
    // A4Reporter.
    // By default, the A4Reporter ignores all these events (but you can
    // extend the A4Reporter to display the event for the user)
    A4Reporter rep = new A4Reporter() {

        // For example, here we choose to display each "warning" by printing
        // it to System.out
        @Override
        public void warning(ErrorWarning msg) {
            System.out.print("Relevance Warning:\n" + (msg.toString().trim()) + "\n\n");
            System.out.flush();
        }
    };
    for (String filename : args) {
        // Parse+typecheck the model
        System.out.println("=========== Parsing+Typechecking " + filename + " =============");
        Module world = CompUtil.parseEverything_fromFile(rep, null, filename);
        // Choose some default options for how you want to execute the
        // commands
        A4Options options = new A4Options();
        options.solver = A4Options.SatSolver.SAT4J;
        for (Command command : world.getAllCommands()) {
            // Execute the command
            System.out.println("============ Command " + command + ": ============");
            A4Solution ans = TranslateAlloyToKodkod.execute_command(rep, world.getAllReachableSigs(), command, options);
            // Print the outcome
            System.out.println(ans);
            // If satisfiable...
            if (ans.satisfiable()) {
                // You can query "ans" to find out the values of each set or
                // type.
                // This can be useful for debugging.
                // 
                // You can also write the outcome to an XML file
                ans.writeXML("alloy_example_output.xml");
                // You can then visualize the XML file by calling this:
                if (viz == null) {
                    viz = new VizGUI(false, "alloy_example_output.xml", null);
                } else {
                    viz.loadXML("alloy_example_output.xml", true);
                }
            }
        }
    }
}
Also used : VizGUI(edu.mit.csail.sdg.alloy4viz.VizGUI) Command(edu.mit.csail.sdg.ast.Command) A4Reporter(edu.mit.csail.sdg.alloy4.A4Reporter) A4Options(edu.mit.csail.sdg.translator.A4Options) ErrorWarning(edu.mit.csail.sdg.alloy4.ErrorWarning) Module(edu.mit.csail.sdg.ast.Module) A4Solution(edu.mit.csail.sdg.translator.A4Solution)

Example 10 with A4Reporter

use of edu.mit.csail.sdg.alloy4.A4Reporter in project org.alloytools.alloy by AlloyTools.

the class CompModule method resolveFuncDecls.

/**
 * Each FunAST will now point to a bodyless Func object.
 */
private JoinableList<Err> resolveFuncDecls(A4Reporter rep, JoinableList<Err> errors, List<ErrorWarning> warns) throws Err {
    for (ArrayList<Func> list : funcs.values()) {
        for (int listi = 0; listi < list.size(); listi++) {
            Func f = list.get(listi);
            String fullname = (path.length() == 0 ? "this/" : (path + "/")) + f.label;
            // Each PARAMETER can refer to earlier parameter in the same
            // function, and any SIG or FIELD visible from here.
            // Each RETURNTYPE can refer to the parameters of the same
            // function, and any SIG or FIELD visible from here.
            Context cx = new Context(this, warns);
            cx.rootfunparam = true;
            TempList<Decl> tmpdecls = new TempList<Decl>();
            boolean err = false;
            for (Decl d : f.decls) {
                TempList<ExprVar> tmpvars = new TempList<ExprVar>();
                Expr val = cx.check(d.expr).resolve_as_set(warns);
                if (!val.errors.isEmpty()) {
                    err = true;
                    errors = errors.make(val.errors);
                }
                for (ExprHasName n : d.names) {
                    ExprVar v = ExprVar.make(n.span(), n.label, val.type());
                    cx.put(n.label, v);
                    tmpvars.add(v);
                    rep.typecheck((f.isPred ? "pred " : "fun ") + fullname + ", Param " + n.label + ": " + v.type() + "\n");
                }
                tmpdecls.add(new Decl(d.isPrivate, d.disjoint, d.disjoint2, tmpvars.makeConst(), val));
            }
            Expr ret = null;
            if (!f.isPred) {
                ret = cx.check(f.returnDecl).resolve_as_set(warns);
                if (!ret.errors.isEmpty()) {
                    err = true;
                    errors = errors.make(ret.errors);
                }
            }
            if (err)
                continue;
            try {
                f = new Func(f.pos, f.isPrivate, fullname, tmpdecls.makeConst(), ret, f.getBody());
                list.set(listi, f);
                rep.typecheck("" + f + ", RETURN: " + f.returnDecl.type() + "\n");
            } catch (Err ex) {
                errors = errors.make(ex);
            }
        }
    }
    return errors;
}
Also used : ExprVar(edu.mit.csail.sdg.ast.ExprVar) Err(edu.mit.csail.sdg.alloy4.Err) Func(edu.mit.csail.sdg.ast.Func) Decl(edu.mit.csail.sdg.ast.Decl) TempList(edu.mit.csail.sdg.alloy4.ConstList.TempList) Expr(edu.mit.csail.sdg.ast.Expr) ExprHasName(edu.mit.csail.sdg.ast.ExprHasName)

Aggregations

Err (edu.mit.csail.sdg.alloy4.Err)9 A4Reporter (edu.mit.csail.sdg.alloy4.A4Reporter)6 ErrorFatal (edu.mit.csail.sdg.alloy4.ErrorFatal)6 Pos (edu.mit.csail.sdg.alloy4.Pos)5 Command (edu.mit.csail.sdg.ast.Command)5 ErrorSyntax (edu.mit.csail.sdg.alloy4.ErrorSyntax)4 Expr (edu.mit.csail.sdg.ast.Expr)4 Sig (edu.mit.csail.sdg.ast.Sig)4 A4Options (edu.mit.csail.sdg.translator.A4Options)4 A4Solution (edu.mit.csail.sdg.translator.A4Solution)4 ArrayList (java.util.ArrayList)4 ErrorType (edu.mit.csail.sdg.alloy4.ErrorType)3 ErrorWarning (edu.mit.csail.sdg.alloy4.ErrorWarning)3 Decl (edu.mit.csail.sdg.ast.Decl)3 ExprHasName (edu.mit.csail.sdg.ast.ExprHasName)3 Module (edu.mit.csail.sdg.ast.Module)3 LinkedHashSet (java.util.LinkedHashSet)3 CapacityExceededException (kodkod.engine.CapacityExceededException)3 ErrorAPI (edu.mit.csail.sdg.alloy4.ErrorAPI)2 Func (edu.mit.csail.sdg.ast.Func)2