001package org.clafer.frontend;
002
003import java.util.List;
004import java.util.Optional;
005import java.util.stream.Collectors;
006import org.clafer.frontend.Ir.*;
007
008/**
009 * Prints the {@link Ir explicit IR} exactly as the Clafer compiler prints the
010 * rich and the core explicit model ({@code Generator/Explicit.hs}), with or
011 * without the provenance comments, so that every comparison of two models is a
012 * comparison of text. A tree that {@link ExplicitParser} read from the
013 * compiler's output prints as that output.
014 * <p>
015 * The declarations and constraints are printed where they were written, the
016 * objectives and assertions at the end. Every operand that is not an atom or a
017 * navigation is parenthesized. Literals are printed as they were written.
018 */
019public final class ExplicitPrinter {
020
021    private static final String Indent = "  ";
022
023    private ExplicitPrinter() {
024    }
025
026    /**
027     * @param model the model
028     * @return the model, with its provenance comments
029     */
030    public static String print(Model model) {
031        return print(model, true);
032    }
033
034    /**
035     * @param model the model
036     * @param withOrigins whether to print the provenance comments
037     * @return the model as text
038     */
039    public static String print(Model model, boolean withOrigins) {
040        StringBuilder out = new StringBuilder();
041        Options options = model.options();
042        out.append("//# OPTIONS --explicit");
043        if (options.core()) {
044            out.append(" --core");
045        }
046        options.traceLength().ifPresent(tl -> out.append(" --tl=").append(tl));
047        out.append('\n');
048        for (Element element : model.elements()) {
049            printElement(element, "", withOrigins, out);
050        }
051        if (!model.objectives().isEmpty() || !model.assertions().isEmpty()) {
052            out.append('\n');
053        }
054        for (Objective objective : model.objectives()) {
055            out.append("<< ").append(objective.maximize() ? "max " : "min ").append(print(objective.exp())).append(" >>\n");
056        }
057        for (Assertion assertion : model.assertions()) {
058            out.append("assert [").append(print(assertion.exp())).append(']')
059                    .append(origin(assertion.origin(), withOrigins)).append('\n');
060        }
061        return out.toString();
062    }
063
064    private static String origin(Optional<Origin> origin, boolean withOrigins) {
065        if (!withOrigins || origin.isEmpty()) {
066            return "";
067        }
068        Origin o = origin.get();
069        return " // " + o.construct() + o.position().map(p -> ", " + p).orElse("");
070    }
071
072    private static void printElement(Element element, String indent, boolean withOrigins, StringBuilder out) {
073        switch (element) {
074            case Constraint c -> out.append(indent).append('[').append(print(c.exp())).append(']')
075                    .append(origin(c.origin(), withOrigins)).append('\n');
076            case EnumDecl e -> out.append(indent).append("enum ").append(e.name().text()).append(" = ")
077                    .append(e.literals().stream().map(Name::text).collect(Collectors.joining(" | "))).append('\n');
078            case RootBlock r -> {
079                out.append(indent).append("root {\n");
080                for (Constraint c : r.constraints()) {
081                    printElement(c, indent + Indent, withOrigins, out);
082                }
083                out.append(indent).append("}\n");
084            }
085            case ClaferDecl c -> printClafer(c, indent, withOrigins, out);
086        }
087    }
088
089    private static void printClafer(ClaferDecl c, String indent, boolean withOrigins, StringBuilder out) {
090        out.append(indent);
091        if (c.isAbstract()) {
092            out.append("abstract ");
093        }
094        for (Modifier m : c.modifiers()) {
095            out.append(m.kind().keyword()).append(' ');
096        }
097        out.append(c.groupCard()).append(' ').append(c.name().text());
098        c.superName().ifPresent(s -> out.append(" : ").append(s.text()));
099        c.ref().ifPresent(r -> out.append(r.isSet() ? " -> " : " ->> ").append(r.target().text()));
100        out.append(' ').append(c.abstractMultiplicity().map(AbstractMultiplicity::card).orElse(c.card()));
101        c.initializer().ifPresent(i -> out.append(' ').append(i.kind().syntax()).append(' ').append(print(i.value())));
102        if (c.elements().isEmpty()) {
103            out.append(" {}").append(origin(c.origin(), withOrigins)).append('\n');
104            return;
105        }
106        out.append(" {").append(origin(c.origin(), withOrigins)).append('\n');
107        for (Element e : c.elements()) {
108            printElement(e, indent + Indent, withOrigins, out);
109        }
110        out.append(indent).append("}\n");
111    }
112
113    /**
114     * @param exp an expression
115     * @return the expression as text, its operands parenthesized unless they
116     * are atoms or navigations
117     */
118    public static String print(Exp exp) {
119        return switch (exp) {
120            case This e -> "this";
121            case NameExp e -> e.name();
122            case IntLit e -> Long.toString(e.value());
123            case DecimalLit e -> e.text();
124            case DoubleLit e -> e.text();
125            case StringLit e -> e.text();
126            case NoClafer e -> "noclafer";
127            case Join e -> operand(e.left()) + "." + step(e.right());
128            case Dref e -> operand(e.left()) + ".dref";
129            case ParentOf e -> operand(e.left()) + ".parent";
130            case Unary e -> switch (e.op()) {
131                // -1 is a constant, so the negation of a number is -(1)
132                case MINUS -> "-" + (isConstant(e.arg()) ? "(" + print(e.arg()) + ")" : operand(e.arg()));
133                case SUM, PRODUCT -> e.op().syntax() + operand(e.arg()) + ".dref";
134                default -> e.op().syntax() + operand(e.arg());
135            };
136            case Binary e -> e.operands().stream().map(ExplicitPrinter::operand)
137                    .collect(Collectors.joining(" " + e.op().syntax() + " "));
138            case IfThenElse e -> "if " + operand(e.condition()) + " then " + operand(e.then())
139                    + " else " + operand(e.otherwise());
140            case Quantified e -> e.quantifier().keyword() + " "
141                    + e.decls().stream().map(ExplicitPrinter::decl).collect(Collectors.joining(", "))
142                    + " | " + print(e.body());
143            case QuantifiedSet e -> e.quantifier().keyword() + " " + operand(e.set());
144            case Call e -> e.function() + "(" + e.args().stream().map(ExplicitPrinter::print)
145                    .collect(Collectors.joining(", ")) + ")";
146            case RelationOf e -> (e.isDref() ? "dref(" : "parent(") + e.clafer().text() + ")";
147            case Cast e -> (e.up() ? "upcast(" : "downcast(") + print(e.base()) + ", " + type(e.type()) + ")";
148            case Connected e -> "connected(" + print(e.nodes()) + ", " + print(e.relation())
149                    + (e.directed() ? ", directed)" : ", undirected)");
150            case ConstantSet e -> "{" + e.rows().stream().map(List::toString).collect(Collectors.joining(", "))
151                    + "} :: " + type(e.type());
152            case Temporal e -> e.op().arity() == 1
153                    ? e.op().keyword() + " " + operand(e.args().get(0))
154                    : operand(e.args().get(0)) + " " + e.op().keyword() + " " + operand(e.args().get(1));
155            case Anchor e -> (e.initially() ? "initially " : "finally ") + operand(e.body());
156            case Pattern e -> pattern(e);
157            case Transition e -> operand(e.from())
158                    + e.guard().map(g -> " -[" + operand(g) + (e.sync() ? "]->> " : "]-> "))
159                            .orElse(e.sync() ? " -->> " : " --> ")
160                    + (e.to() instanceof Transition ? print(e.to()) : operand(e.to()));
161        };
162    }
163
164    private static String pattern(Pattern p) {
165        List<Exp> args = p.args();
166        int own = p.kind().arity();
167        String pattern = own == 2
168                ? operand(args.get(0)) + " must " + p.kind().keyword() + " " + operand(args.get(1))
169                : p.kind().keyword() + " " + operand(args.get(0));
170        List<Exp> scope = args.subList(own, args.size());
171        return pattern + switch (p.scope()) {
172            case GLOBALLY -> "";
173            case BEFORE -> " before " + operand(scope.get(0));
174            case AFTER -> " after " + operand(scope.get(0));
175            case BETWEEN -> " between " + operand(scope.get(0)) + " and " + operand(scope.get(1));
176            case AFTER_UNTIL -> " after " + operand(scope.get(0)) + " until " + operand(scope.get(1));
177        };
178    }
179
180    private static String decl(Decl decl) {
181        return (decl.disjoint() ? "disj " : "")
182                + decl.locals().stream().map(Name::text).collect(Collectors.joining("; "))
183                + " : " + print(decl.set());
184    }
185
186    private static String type(List<Name> type) {
187        return type.stream().map(Name::text).collect(Collectors.joining(" * "));
188    }
189
190    private static boolean isConstant(Exp exp) {
191        return exp instanceof IntLit || exp instanceof DecimalLit || exp instanceof NoClafer
192                || exp instanceof ConstantSet;
193    }
194
195    /**
196     * Atoms: names, literals and calls, which need no parentheses anywhere.
197     */
198    private static boolean isAtom(Exp exp) {
199        return switch (exp) {
200            case This e -> true;
201            case NameExp e -> true;
202            case IntLit e -> true;
203            case DecimalLit e -> true;
204            case DoubleLit e -> true;
205            case StringLit e -> true;
206            case NoClafer e -> true;
207            case Call e -> true;
208            case RelationOf e -> true;
209            case Cast e -> true;
210            case Connected e -> true;
211            case ConstantSet e -> true;
212            default -> false;
213        };
214    }
215
216    private static boolean isNavigation(Exp exp) {
217        return exp instanceof Join || exp instanceof Dref || exp instanceof ParentOf;
218    }
219
220    /**
221     * An operand of an operator: navigation binds tighter than any operator.
222     */
223    private static String operand(Exp exp) {
224        return isAtom(exp) || isNavigation(exp) ? print(exp) : "(" + print(exp) + ")";
225    }
226
227    /**
228     * The right of a navigation, parenthesized unless it is an atom.
229     */
230    private static String step(Exp exp) {
231        return isAtom(exp) ? print(exp) : "(" + print(exp) + ")";
232    }
233}