001package org.clafer.frontend;
002
003import java.util.ArrayList;
004import java.util.List;
005import java.util.Optional;
006import org.clafer.frontend.Syntax.*;
007
008/**
009 * Prints a syntax tree as the compiler's {@code printTree} prints its parse
010 * tree ({@code PrintClafer}, generated by BNFC): the same words, parentheses
011 * and line breaks. Two trees print the same text when they are the same tree,
012 * up to the spans, so the text is what the parser is compared on with the
013 * compiler's.
014 * <p>
015 * The output is not meant for reading: BNFC puts a line break after each
016 * brace and semicolon, and the layout of the source is gone.
017 */
018public final class SyntaxPrinter {
019
020    private final List<String> docs = new ArrayList<>();
021
022    private SyntaxPrinter() {
023    }
024
025    /**
026     * @param model a syntax tree
027     * @return the text that {@code printTree} prints for the same tree
028     */
029    public static String print(Model model) {
030        SyntaxPrinter printer = new SyntaxPrinter();
031        for (Declaration d : model.declarations()) {
032            printer.declaration(d);
033        }
034        return render(printer.docs);
035    }
036
037    /**
038     * @param exp an expression
039     * @return the text that {@code printTree} prints for it
040     */
041    public static String print(Exp exp) {
042        SyntaxPrinter printer = new SyntaxPrinter();
043        printer.exp(0, exp);
044        return render(printer.docs);
045    }
046
047    private void doc(String s) {
048        docs.add(s);
049    }
050
051    private void declaration(Declaration d) {
052        switch (d) {
053            case EnumDecl e -> {
054                doc("enum");
055                doc(e.name().text());
056                doc("=");
057                separated(e.literals(), "|");
058            }
059            case Element e -> element(e);
060        }
061    }
062
063    private void separated(List<Ident> idents, String separator) {
064        for (int i = 0; i < idents.size(); i++) {
065            if (i > 0) {
066                doc(separator);
067            }
068            doc(idents.get(i).text());
069        }
070    }
071
072    private void element(Element e) {
073        switch (e) {
074            case Clafer c -> {
075                if (c.isAbstract()) {
076                    doc("abstract");
077                }
078                c.modifiers().forEach(m -> doc(m.kind().syntax()));
079                c.groupCard().ifPresent(g -> {
080                    switch (g) {
081                        case GroupKeyword k -> doc(k.keyword());
082                        case NCard n -> ncard(n);
083                    }
084                });
085                doc(c.name().text());
086                c.superClafer().ifPresent(s -> {
087                    doc(":");
088                    exp(26, s.exp());
089                });
090                c.reference().ifPresent(r -> {
091                    doc(r.bag() ? "->>" : "->");
092                    exp(23, r.exp());
093                });
094                card(c.card());
095                c.init().ifPresent(i -> {
096                    switch (i.how()) {
097                        case Constant -> doc("=");
098                        case Default -> doc(":=");
099                        case Each -> {
100                            doc(":=");
101                            doc("each");
102                        }
103                        case Together -> {
104                            doc(":=");
105                            doc("together");
106                        }
107                    }
108                    exp(0, i.exp());
109                });
110                c.transition().ifPresent(t -> {
111                    arrow(t.arrow());
112                    exp(0, t.exp());
113                });
114                elements(c.elements());
115            }
116            case ClaferUse u -> {
117                doc("`");
118                name(u.name());
119                card(u.card());
120                elements(u.elements());
121            }
122            case Constraint c -> {
123                doc("[");
124                exps(c.exps());
125                doc("]");
126            }
127            case Assertion a -> {
128                doc("assert");
129                doc("[");
130                exps(a.exps());
131                doc("]");
132            }
133            case Goal g -> {
134                doc("<<");
135                doc(g.kind().syntax());
136                exps(g.exps());
137                doc(">>");
138            }
139        }
140    }
141
142    private void elements(Optional<Elements> elements) {
143        elements.ifPresent(es -> {
144            doc("{");
145            es.elements().forEach(this::element);
146            doc("}");
147        });
148    }
149
150    private void card(Optional<Card> card) {
151        card.ifPresent(c -> {
152            switch (c) {
153                case CardSymbol s -> doc(s.symbol());
154                case CardNum n -> doc(n.number());
155                case NCard n -> ncard(n);
156            }
157        });
158    }
159
160    private void ncard(NCard n) {
161        doc(n.low());
162        doc("..");
163        doc(n.high().orElse("*"));
164    }
165
166    private void name(Name n) {
167        separated(n.path(), "\\");
168    }
169
170    private void exps(List<Exp> exps) {
171        exps.forEach(e -> exp(0, e));
172    }
173
174    private void arrow(TransArrow a) {
175        if (a.guard().isPresent()) {
176            doc("-[");
177            exp(1, a.guard().get());
178            doc(a.sync() ? "]->>" : "]->");
179        } else {
180            doc(a.sync() ? "-->>" : "-->");
181        }
182    }
183
184    /**
185     * {@code prt i e}: the expression, in parentheses if its level is below
186     * {@code i} ({@code prPrec}).
187     */
188    private void exp(int i, Exp e) {
189        boolean parens = e.level() < i;
190        if (parens) {
191            doc("(");
192        }
193        switch (e) {
194            case TransitionExp t -> {
195                exp(1, t.from());
196                arrow(t.arrow());
197                exp(0, t.to());
198            }
199            case Quantified q -> {
200                doc(q.quant().syntax());
201                if (q.disj()) {
202                    doc("disj");
203                }
204                separated(q.decl().locals(), ";");
205                doc(":");
206                exp(21, q.decl().exp());
207                doc("|");
208                exp(1, q.body());
209            }
210            case IfThenElse ite -> {
211                doc("if");
212                exp(1, ite.condition());
213                doc("then");
214                exp(1, ite.then());
215                doc("else");
216                exp(1, ite.otherwise());
217            }
218            case Let l -> {
219                doc("let");
220                doc(l.local().text());
221                doc("=");
222                exp(16, l.value());
223                doc("in");
224                exp(1, l.body());
225            }
226            case Pattern p -> {
227                switch (p.kind()) {
228                    case Never, Sometime, LessOrOnce, Always -> {
229                        doc(switch (p.kind()) {
230                            case Never -> "never";
231                            case Sometime -> "sometime";
232                            case LessOrOnce -> "lonce";
233                            default -> "always";
234                        });
235                        exp(3, p.exps().get(0));
236                    }
237                    case Precede, Follow -> {
238                        exp(3, p.exps().get(0));
239                        doc("must");
240                        doc(p.kind() == PatternKind.Precede ? "precede" : "follow");
241                        exp(3, p.exps().get(1));
242                    }
243                }
244                p.scope().ifPresent(s -> {
245                    switch (s.kind()) {
246                        case Before -> doc("before");
247                        case After, AfterUntil -> doc("after");
248                        case BetweenAnd -> doc("between");
249                    }
250                    exp(11, s.exps().get(0));
251                    if (s.kind() == ScopeKind.BetweenAnd || s.kind() == ScopeKind.AfterUntil) {
252                        doc(s.kind() == ScopeKind.BetweenAnd ? "and" : "until");
253                        exp(11, s.exps().get(1));
254                    }
255                });
256            }
257            case Anchor a -> {
258                doc(a.initially() ? "initially" : "finally");
259                exp(3, a.exp());
260            }
261            case Binary b -> {
262                exp(b.op().level(), b.left());
263                if (b.op() == BinaryOp.NotIn) {
264                    doc("not");
265                    doc("in");
266                } else {
267                    doc(b.op().syntax());
268                }
269                exp(b.op().level() + 1, b.right());
270            }
271            case Unary u -> {
272                doc(u.op().syntax());
273                exp(u.op().operandLevel(), u.exp());
274            }
275            case QuantExp q -> {
276                doc(q.quant().syntax());
277                exp(20, q.exp());
278            }
279            case ClaferId c -> name(c.name());
280            case Literal l -> doc(l.text());
281        }
282        if (parens) {
283            doc(")");
284        }
285    }
286
287    // ------------------------------------------------------------------
288    // BNFC's render
289    // ------------------------------------------------------------------
290    /**
291     * BNFC's {@code render}, which composes functions on the rest of the
292     * output: a line break drops the spaces that start the rest, and a word
293     * is followed by a space unless it ends the output. The words are
294     * grouped from the left, as {@code rend} matches them, then each group
295     * is applied from the right.
296     */
297    static String render(List<String> docs) {
298        record Step(int kind, String word, int indent) {
299        }
300        List<Step> steps = new ArrayList<>();
301        int i = 0;
302        int k = 0;
303        while (k < docs.size()) {
304            String t = docs.get(k);
305            String next = k + 1 < docs.size() ? docs.get(k + 1) : null;
306            switch (t) {
307                case "[", "(" -> {
308                    steps.add(new Step(0, t, i));
309                    k++;
310                }
311                case "{" -> {
312                    steps.add(new Step(1, t, i));
313                    i++;
314                    k++;
315                }
316                case "}" -> {
317                    if (";".equals(next)) {
318                        steps.add(new Step(2, t, i));
319                        k += 2;
320                    } else {
321                        steps.add(new Step(3, t, i));
322                        k++;
323                    }
324                    i--;
325                }
326                case ";" -> {
327                    steps.add(new Step(4, t, i));
328                    k++;
329                }
330                default -> {
331                    if (",".equals(next)) {
332                        steps.add(new Step(5, t, i));
333                        k += 2;
334                    } else if (")".equals(next) || "]".equals(next)) {
335                        steps.add(new Step(6, t + next, i));
336                        k += 2;
337                    } else {
338                        steps.add(new Step(7, t, i));
339                        k++;
340                    }
341                }
342            }
343        }
344        // the rest of the output, reversed, so that prepending is appending
345        StringBuilder rest = new StringBuilder();
346        for (int s = steps.size() - 1; s >= 0; s--) {
347            Step step = steps.get(s);
348            switch (step.kind()) {
349                // "[" and "(": the character
350                case 0 -> prepend(rest, step.word());
351                // "{": the brace, a line break at the next indentation
352                case 1 -> {
353                    newLine(rest, step.indent() + 1);
354                    prepend(rest, "{");
355                }
356                // "}" ";": a line break, "} ;", a line break
357                case 2 -> {
358                    newLine(rest, step.indent() - 1);
359                    prepend(rest, ";");
360                    space(rest, "}");
361                    newLine(rest, step.indent() - 1);
362                }
363                // "}": a line break, the brace, a line break
364                case 3 -> {
365                    newLine(rest, step.indent() - 1);
366                    prepend(rest, "}");
367                    newLine(rest, step.indent() - 1);
368                }
369                // ";": the semicolon, a line break
370                case 4 -> {
371                    newLine(rest, step.indent());
372                    prepend(rest, ";");
373                }
374                // t ",": t, then the comma and a space
375                case 5 -> {
376                    space(rest, ",");
377                    prepend(rest, step.word());
378                }
379                // t ")" or t "]": t and the bracket, with no space
380                case 6 -> prepend(rest, step.word());
381                default -> space(rest, step.word());
382            }
383        }
384        return rest.reverse().toString();
385    }
386
387    private static void prepend(StringBuilder reversed, String s) {
388        for (int j = s.length() - 1; j >= 0; j--) {
389            reversed.append(s.charAt(j));
390        }
391    }
392
393    /**
394     * {@code space t}: t, then a space unless the rest is empty.
395     */
396    private static void space(StringBuilder reversed, String t) {
397        if (!reversed.isEmpty()) {
398            reversed.append(' ');
399        }
400        prepend(reversed, t);
401    }
402
403    /**
404     * {@code new i}: a line break and the indentation, with the spaces that
405     * start the rest dropped.
406     */
407    private static void newLine(StringBuilder reversed, int indent) {
408        int end = reversed.length();
409        while (end > 0 && Character.isWhitespace(reversed.charAt(end - 1))) {
410            end--;
411        }
412        reversed.setLength(end);
413        reversed.append(" ".repeat(Math.max(0, 2 * indent)));
414        reversed.append('\n');
415    }
416}