001package org.clafer.frontend;
002
003import java.util.ArrayList;
004import java.util.Collections;
005import java.util.List;
006import java.util.Map;
007import java.util.Optional;
008import java.util.Set;
009import org.clafer.frontend.Syntax.*;
010
011/**
012 * Parses a model in the full Clafer language into its {@link Syntax} tree, as
013 * the compiler parses it ({@code clafer.cf}, generated by BNFC and Happy, and
014 * {@code Language.Clafer.parse}).
015 * <p>
016 * It is a recursive descent over the grammar, one method per level of
017 * expression, which takes the choices that Happy takes:
018 * <ul>
019 * <li>an expression goes on as long as it can, so that in {@code [a -b]} the
020 * {@code -} is a subtraction, and {@code a not} must go on with {@code in};
021 * a list of expressions has no separator;</li>
022 * <li>a quantifier starts a declaration, {@code some x; y : X | e}, when
023 * {@code disj}, or a name and {@code ;} or {@code :}, follow it;</li>
024 * <li>a cardinality is taken whenever one can start, e.g., the {@code 2..3}
025 * of {@code a 2..3 b} is the card of {@code a};</li>
026 * <li>a clafer must start on a new line, after its previous sibling
027 * clafer.</li>
028 * </ul>
029 * The layout is resolved first ({@link Layout}), so the parser reads blocks
030 * as braces, and lines of siblings with a separator between them.
031 * <p>
032 * The parser does not stop at an error: it reports it, skips to the next line
033 * at the same or a lower indentation, and goes on, so that a model with
034 * errors on several lines reports all of them, and the tree has the rest.
035 */
036public final class ClaferParser {
037
038    /**
039     * The tree of a model and its errors.
040     *
041     * @param model the tree; where there are errors, what was read around
042     * them
043     * @param comments the comments and escapes, in order
044     * @param diagnostics the errors of the lexer, the layout and the parser,
045     * in order
046     */
047    public record Result(Model model, List<Token> comments, List<Diagnostic> diagnostics) {
048    }
049
050    private static final class ParseError extends RuntimeException {
051
052        private static final long serialVersionUID = 1L;
053        private final transient Diagnostic diagnostic;
054
055        ParseError(Diagnostic diagnostic) {
056            super(diagnostic.toString(), null, false, false);
057            this.diagnostic = diagnostic;
058        }
059    }
060
061    private static final Map<String, BinaryOp> Comparisons = Map.of(
062            "<", BinaryOp.Lt, ">", BinaryOp.Gt, "=", BinaryOp.Eq, "<=", BinaryOp.Lte, ">=", BinaryOp.Gte,
063            "!=", BinaryOp.Neq, "in", BinaryOp.In);
064    private static final Map<String, UnaryOp> TemporalPrefix = Map.of(
065            "F", UnaryOp.LtlF, "eventually", UnaryOp.Eventually, "G", UnaryOp.LtlG, "globally", UnaryOp.Globally,
066            "X", UnaryOp.LtlX, "next", UnaryOp.Next, "previous", UnaryOp.Previous, "once", UnaryOp.Once,
067            "historically", UnaryOp.Historically);
068    private static final Map<String, Quant> Quants = Map.of(
069            "no", Quant.No, "not", Quant.Not, "lone", Quant.Lone, "one", Quant.One, "some", Quant.Some);
070    private static final Map<String, PatternKind> PrefixPatterns = Map.of(
071            "never", PatternKind.Never, "sometime", PatternKind.Sometime, "lonce", PatternKind.LessOrOnce,
072            "always", PatternKind.Always);
073    private static final Map<String, TempModifierKind> Modifiers = Map.of(
074            "initial", TempModifierKind.Initial, "final", TempModifierKind.Final,
075            "finalref", TempModifierKind.FinalRef, "finaltarget", TempModifierKind.FinalTarget);
076    private static final Set<String> GroupKeywords = Set.of("xor", "or", "mux", "opt");
077    /**
078     * The words that start an expression.
079     */
080    private static final Set<String> ExpStartWords = Set.of(
081            "all", "if", "let", "never", "sometime", "lonce", "always", "initially", "finally",
082            "F", "eventually", "G", "globally", "X", "next", "previous", "once", "historically",
083            "max", "min", "sum", "product", "no", "not", "lone", "one", "some");
084
085    private final List<Token> tokens;
086    private int pos = 0;
087    private final List<Diagnostic> diagnostics = new ArrayList<>();
088
089    private ClaferParser(List<Token> tokens) {
090        this.tokens = tokens;
091    }
092
093    /**
094     * Parses a model.
095     *
096     * @param source the text of the model
097     * @return its tree, comments and errors
098     */
099    public static Result parse(String source) {
100        ClaferLexer.Result lexed = ClaferLexer.lex(source);
101        Layout.Result laid = Layout.resolve(lexed);
102        ClaferParser parser = new ClaferParser(laid.tokens());
103        parser.diagnostics.addAll(lexed.diagnostics());
104        parser.diagnostics.addAll(laid.diagnostics());
105        Model model = parser.model();
106        sameLineClafers(model.declarations().stream()
107                .filter(d -> d instanceof Element).map(d -> (Element) d).toList(), parser.diagnostics);
108        List<Diagnostic> sorted = new ArrayList<>(parser.diagnostics);
109        sorted.sort((a, b) -> a.span().line() != b.span().line()
110                ? Integer.compare(a.span().line(), b.span().line())
111                : Integer.compare(a.span().column(), b.span().column()));
112        return new Result(model, lexed.others(), Collections.unmodifiableList(sorted));
113    }
114
115    // ------------------------------------------------------------------
116    // Tokens
117    // ------------------------------------------------------------------
118    private Token peek() {
119        return tokens.get(pos);
120    }
121
122    private Token peek(int offset) {
123        return tokens.get(Math.min(pos + offset, tokens.size() - 1));
124    }
125
126    private Token take() {
127        Token t = tokens.get(pos);
128        if (t.kind() != TokenKind.EOF) {
129            pos++;
130        }
131        return t;
132    }
133
134    /**
135     * @return whether the token is the symbol or reserved word
136     */
137    private static boolean is(Token t, String text) {
138        return (t.kind() == TokenKind.SYMBOL || t.kind() == TokenKind.KEYWORD) && t.text().equals(text);
139    }
140
141    private boolean at(String text) {
142        return is(peek(), text);
143    }
144
145    private boolean accept(String text) {
146        if (at(text)) {
147            pos++;
148            return true;
149        }
150        return false;
151    }
152
153    private Token expect(String text) {
154        if (!at(text)) {
155            throw error(peek(), "Expected '" + text + "' but found " + show(peek()));
156        }
157        return take();
158    }
159
160    private static boolean isOpen(Token t) {
161        return t.kind() == TokenKind.INDENT || is(t, "{");
162    }
163
164    private static boolean isClose(Token t) {
165        return t.kind() == TokenKind.DEDENT || is(t, "}");
166    }
167
168    /**
169     * @return the last token read that is in the source, not one the layout
170     * inserted
171     */
172    private Token last() {
173        for (int i = pos - 1; i > 0; i--) {
174            TokenKind kind = tokens.get(i).kind();
175            if (kind != TokenKind.INDENT && kind != TokenKind.DEDENT && kind != TokenKind.SEPARATOR) {
176                return tokens.get(i);
177            }
178        }
179        return tokens.get(0);
180    }
181
182    private SourceSpan from(Token start) {
183        Token end = last();
184        if (pos == 0 || end.span().line() < start.span().line()
185                || (end.span().line() == start.span().line() && end.span().endColumn() < start.span().column())) {
186            return SourceSpan.at(start.span().line(), start.span().column());
187        }
188        return new SourceSpan(start.span().line(), start.span().column(), end.span().endLine(), end.span().endColumn());
189    }
190
191    // a prefix operator's expression ends with its operand, as the compiler's spans do: the parentheses
192    // around the operand, e.g., of !(F error), are not in its span
193    private static SourceSpan prefix(Token op, Node operand) {
194        return new SourceSpan(op.span().line(), op.span().column(), operand.span().endLine(),
195                operand.span().endColumn());
196    }
197
198    private static SourceSpan join(Node a, Node b) {
199        return new SourceSpan(a.span().line(), a.span().column(), b.span().endLine(), b.span().endColumn());
200    }
201
202    /**
203     * An error at a token; at the end of the model, after the last token, an
204     * inserted one included, as the compiler puts it.
205     */
206    private ParseError error(Token at, String message) {
207        if (at.kind() == TokenKind.EOF && tokens.size() > 1) {
208            Token lastToken = tokens.get(tokens.size() - 2);
209            return new ParseError(new Diagnostic(SourceSpan.at(lastToken.span().line(),
210                    lastToken.span().column() + lastToken.text().length()), message));
211        }
212        return new ParseError(new Diagnostic(SourceSpan.at(at.span().line(), at.span().column()), message));
213    }
214
215    private static String show(Token t) {
216        return switch (t.kind()) {
217            case EOF -> "the end of the model";
218            case INDENT -> "an indented line";
219            case DEDENT -> "the end of an indented block";
220            case SEPARATOR -> "a new line";
221            case KEYWORD -> "the reserved word '" + t.text() + "'";
222            default -> "'" + t.text() + "'";
223        };
224    }
225
226    private Ident ident(String what) {
227        Token t = peek();
228        if (t.kind() != TokenKind.WORD) {
229            throw error(t, "Expected " + what + " but found " + show(t));
230        }
231        pos++;
232        return new Ident(t.span(), t.text());
233    }
234
235    // ------------------------------------------------------------------
236    // Declarations and elements
237    // ------------------------------------------------------------------
238    private Model model() {
239        Token start = peek();
240        List<Declaration> declarations = new ArrayList<>();
241        while (peek().kind() != TokenKind.EOF) {
242            if (peek().kind() == TokenKind.SEPARATOR) {
243                pos++;
244                continue;
245            }
246            int before = pos;
247            try {
248                if (at("enum")) {
249                    declarations.add(enumDecl());
250                } else if (startsElement(peek())) {
251                    declarations.add(element());
252                } else {
253                    throw error(peek(), "Expected a clafer, a constraint, an objective, an assertion or an enumeration"
254                            + " but found " + show(peek()));
255                }
256            } catch (ParseError e) {
257                recover(e, before);
258            }
259        }
260        SourceSpan span = declarations.isEmpty() ? SourceSpan.at(start.span().line(), start.span().column())
261                : join(declarations.get(0), declarations.get(declarations.size() - 1));
262        return new Model(span, declarations);
263    }
264
265    /**
266     * Reports an error and skips to the next line at the same or a lower
267     * indentation: to the next separator, or to the end of the block, outside
268     * the blocks opened since the error.
269     */
270    private void recover(ParseError e, int before) {
271        diagnostics.add(e.diagnostic);
272        if (pos == before && peek().kind() != TokenKind.EOF) {
273            Token t = take();
274            if (isOpen(t)) {
275                skipBlock();
276            }
277        }
278        int depth = 0;
279        while (peek().kind() != TokenKind.EOF) {
280            Token t = peek();
281            if (depth == 0 && (t.kind() == TokenKind.SEPARATOR || isClose(t))) {
282                return;
283            }
284            if (isOpen(t)) {
285                depth++;
286            } else if (isClose(t)) {
287                depth--;
288            }
289            pos++;
290        }
291    }
292
293    private void skipBlock() {
294        int depth = 1;
295        while (depth > 0 && peek().kind() != TokenKind.EOF) {
296            Token t = take();
297            if (isOpen(t)) {
298                depth++;
299            } else if (isClose(t)) {
300                depth--;
301            }
302        }
303    }
304
305    private EnumDecl enumDecl() {
306        Token start = expect("enum");
307        Ident name = ident("the name of the enumeration");
308        expect("=");
309        List<Ident> literals = new ArrayList<>();
310        literals.add(ident("a literal"));
311        while (accept("|")) {
312            literals.add(ident("a literal"));
313        }
314        return new EnumDecl(from(start), name, literals);
315    }
316
317    private static boolean startsElement(Token t) {
318        return switch (t.kind()) {
319            case WORD -> true;
320            case INT -> true;
321            case KEYWORD -> Set.of("abstract", "initial", "final", "finalref", "finaltarget", "xor", "or", "mux", "opt",
322                    "assert").contains(t.text());
323            case SYMBOL -> Set.of("`", "[", "<<").contains(t.text());
324            default -> false;
325        };
326    }
327
328    private Element element() {
329        Token t = peek();
330        if (is(t, "[")) {
331            return constraint();
332        }
333        if (is(t, "assert")) {
334            pos++;
335            expect("[");
336            List<Exp> exps = expList("]");
337            expect("]");
338            return new Assertion(from(t), exps);
339        }
340        if (is(t, "<<")) {
341            return goal();
342        }
343        if (is(t, "`")) {
344            pos++;
345            Name name = name();
346            Optional<Card> card = card();
347            Optional<Elements> elements = elements();
348            return new ClaferUse(from(t), name, card, elements);
349        }
350        return clafer();
351    }
352
353    private Constraint constraint() {
354        Token start = expect("[");
355        List<Exp> exps = expList("]");
356        expect("]");
357        return new Constraint(from(start), exps);
358    }
359
360    private Goal goal() {
361        Token start = expect("<<");
362        Token k = peek();
363        GoalKind kind;
364        if (is(k, "min")) {
365            kind = GoalKind.MinDeprecated;
366        } else if (is(k, "max")) {
367            kind = GoalKind.MaxDeprecated;
368        } else if (is(k, "minimize")) {
369            kind = GoalKind.Minimize;
370        } else if (is(k, "maximize")) {
371            kind = GoalKind.Maximize;
372        } else {
373            throw error(k, "Expected 'minimize' or 'maximize' after '<<' but found " + show(k));
374        }
375        pos++;
376        List<Exp> exps = expList(">>");
377        expect(">>");
378        return new Goal(from(start), kind, exps);
379    }
380
381    private Clafer clafer() {
382        Token start = peek();
383        boolean isAbstract = accept("abstract");
384        List<TempModifier> modifiers = new ArrayList<>();
385        while (peek().kind() == TokenKind.KEYWORD && Modifiers.containsKey(peek().text())) {
386            Token m = take();
387            modifiers.add(new TempModifier(m.span(), Modifiers.get(m.text())));
388        }
389        Optional<GCard> groupCard = Optional.empty();
390        if (peek().kind() == TokenKind.KEYWORD && GroupKeywords.contains(peek().text())) {
391            Token g = take();
392            groupCard = Optional.of(new GroupKeyword(g.span(), g.text()));
393        } else if (peek().kind() == TokenKind.INT) {
394            groupCard = Optional.of(ncard());
395        }
396        Ident name = ident("the name of a clafer");
397        Optional<Super> superClafer = Optional.empty();
398        if (at(":")) {
399            Token s = take();
400            superClafer = Optional.of(new Super(from(s), exp26()));
401        }
402        Optional<Reference> reference = Optional.empty();
403        if (at("->") || at("->>")) {
404            Token r = take();
405            Exp target = exp23();
406            reference = Optional.of(new Reference(from(r), r.text().equals("->>"), target));
407        }
408        Optional<Card> card = card();
409        Optional<Init> init = Optional.empty();
410        if (at("=") || at(":=")) {
411            Token i = take();
412            InitHow how = InitHow.Constant;
413            if (i.text().equals(":=")) {
414                how = accept("each") ? InitHow.Each : accept("together") ? InitHow.Together : InitHow.Default;
415            }
416            Exp value = exp();
417            init = Optional.of(new Init(from(i), how, value));
418        }
419        Optional<ClaferTransition> transition = Optional.empty();
420        if (startsArrow()) {
421            Token t = peek();
422            TransArrow arrow = arrow();
423            Exp to = exp();
424            transition = Optional.of(new ClaferTransition(from(t), arrow, to));
425        }
426        Optional<Elements> elements = elements();
427        return new Clafer(from(start), isAbstract, modifiers, groupCard, name, superClafer, reference, card, init,
428                transition, elements);
429    }
430
431    private NCard ncard() {
432        Token low = take();
433        expect("..");
434        Token high = peek();
435        if (is(high, "*")) {
436            pos++;
437            return new NCard(from(low), low.text(), Optional.empty());
438        }
439        if (high.kind() != TokenKind.INT) {
440            throw error(high, "Expected a number or '*' after '..' but found " + show(high));
441        }
442        pos++;
443        return new NCard(from(low), low.text(), Optional.of(high.text()));
444    }
445
446    private Optional<Card> card() {
447        Token t = peek();
448        if (is(t, "?") || is(t, "+") || is(t, "*")) {
449            pos++;
450            return Optional.of(new CardSymbol(t.span(), t.text()));
451        }
452        if (t.kind() == TokenKind.INT) {
453            if (is(peek(1), "..")) {
454                return Optional.of(ncard());
455            }
456            pos++;
457            return Optional.of(new CardNum(t.span(), t.text()));
458        }
459        return Optional.empty();
460    }
461
462    private Optional<Elements> elements() {
463        if (!isOpen(peek())) {
464            return Optional.empty();
465        }
466        Token start = take();
467        List<Element> elements = new ArrayList<>();
468        while (!isClose(peek())) {
469            if (peek().kind() == TokenKind.EOF) {
470                throw error(peek(), "Expected '}' but found " + show(peek()));
471            }
472            if (peek().kind() == TokenKind.SEPARATOR) {
473                pos++;
474                continue;
475            }
476            int before = pos;
477            try {
478                if (!startsElement(peek())) {
479                    throw error(peek(), "Expected a clafer, a constraint, an objective or an assertion but found "
480                            + show(peek()));
481                }
482                elements.add(element());
483            } catch (ParseError e) {
484                recover(e, before);
485            }
486        }
487        take();
488        sameLineClafers(elements, diagnostics);
489        return Optional.of(new Elements(from(start), elements));
490    }
491
492    /**
493     * Elements have no separator, so {@code b : B A 3} would be two sibling
494     * clafers, {@code b : B} and {@code A 3}: a clafer must start on a new
495     * line after its previous sibling clafer, as the compiler requires.
496     */
497    private static void sameLineClafers(List<Element> elements, List<Diagnostic> diagnostics) {
498        Element previous = null;
499        for (Element e : elements) {
500            String name = switch (e) {
501                case Clafer c -> c.name().text();
502                case ClaferUse u -> "`" + String.join("\\", u.name().path().stream().map(Ident::text).toList());
503                default -> null;
504            };
505            if (name == null) {
506                continue;
507            }
508            if (previous != null && previous.span().line() == e.span().line()) {
509                diagnostics.add(new Diagnostic(SourceSpan.at(e.span().line(), e.span().column()),
510                        "clafer " + name + " must start on a new line"));
511            }
512            previous = e;
513        }
514    }
515
516    private Name name() {
517        Token start = peek();
518        List<Ident> path = new ArrayList<>();
519        path.add(ident("a name"));
520        while (accept("\\")) {
521            path.add(ident("a name"));
522        }
523        return new Name(from(start), path);
524    }
525
526    // ------------------------------------------------------------------
527    // Expressions
528    // ------------------------------------------------------------------
529    private static boolean startsExp(Token t) {
530        return switch (t.kind()) {
531            case WORD, INT, DECIMAL, DOUBLE, STRING -> true;
532            case KEYWORD -> ExpStartWords.contains(t.text());
533            case SYMBOL -> Set.of("(", "!", "-", "#").contains(t.text());
534            default -> false;
535        };
536    }
537
538    /**
539     * Expressions up to the closing symbol, with no separator between them.
540     */
541    private List<Exp> expList(String close) {
542        List<Exp> exps = new ArrayList<>();
543        while (!at(close)) {
544            if (!startsExp(peek())) {
545                throw error(peek(), "Expected an expression or '" + close + "' but found " + show(peek()));
546            }
547            exps.add(exp());
548        }
549        return exps;
550    }
551
552    private boolean startsArrow() {
553        return at("-->") || at("-->>") || at("-[");
554    }
555
556    private TransArrow arrow() {
557        Token start = take();
558        return switch (start.text()) {
559            case "-->" -> new TransArrow(start.span(), false, Optional.empty());
560            case "-->>" -> new TransArrow(start.span(), true, Optional.empty());
561            default -> {
562                Exp guard = exp1();
563                Token close = peek();
564                if (!is(close, "]->") && !is(close, "]->>")) {
565                    throw error(close, "Expected ']->' or ']->>' after the guard but found " + show(close));
566                }
567                pos++;
568                yield new TransArrow(from(start), close.text().equals("]->>"), Optional.of(guard));
569            }
570        };
571    }
572
573    /**
574     * {@code Exp ::= Exp1 TransArrow Exp | Exp1}.
575     */
576    private Exp exp() {
577        Exp from = exp1();
578        if (startsArrow()) {
579            TransArrow arrow = arrow();
580            Exp to = exp();
581            return new TransitionExp(join(from, to), from, arrow, to);
582        }
583        return from;
584    }
585
586    /**
587     * The quantifiers with a declaration, {@code if}, {@code let}.
588     */
589    private Exp exp1() {
590        Token t = peek();
591        boolean all = is(t, "all");
592        if (all || (t.kind() == TokenKind.KEYWORD && Quants.containsKey(t.text()) && startsDecl(peek(1), peek(2)))) {
593            pos++;
594            boolean disj = accept("disj");
595            Decl decl = decl();
596            expect("|");
597            Exp body = exp1();
598            return new Quantified(from(t), all ? Quant.All : Quants.get(t.text()), disj, decl, body);
599        }
600        if (is(t, "if")) {
601            pos++;
602            Exp condition = exp1();
603            expect("then");
604            Exp then = exp1();
605            expect("else");
606            Exp otherwise = exp1();
607            return new IfThenElse(from(t), condition, then, otherwise);
608        }
609        if (is(t, "let")) {
610            pos++;
611            Ident local = ident("the name of a local variable");
612            expect("=");
613            Exp value = exp16();
614            expect("in");
615            Exp body = exp1();
616            return new Let(from(t), local, value, body);
617        }
618        return exp2();
619    }
620
621    /**
622     * A declaration follows a quantifier when {@code disj}, or a name and
623     * {@code ;} or {@code :}, follow it: one token more than Happy looks at,
624     * since Happy decides on the name.
625     */
626    private static boolean startsDecl(Token next, Token afterNext) {
627        return is(next, "disj") || (next.kind() == TokenKind.WORD && (is(afterNext, ":") || is(afterNext, ";")));
628    }
629
630    private Decl decl() {
631        Token start = peek();
632        List<Ident> locals = new ArrayList<>();
633        locals.add(ident("the name of a local variable"));
634        while (accept(";")) {
635            locals.add(ident("the name of a local variable"));
636        }
637        expect(":");
638        Exp set = exp21();
639        return new Decl(from(start), locals, set);
640    }
641
642    /**
643     * The behavioral patterns and the anchors.
644     */
645    private Exp exp2() {
646        Token t = peek();
647        if (t.kind() == TokenKind.KEYWORD && PrefixPatterns.containsKey(t.text())) {
648            pos++;
649            Exp e = exp3();
650            Optional<PatternScope> scope = patternScope();
651            return new Pattern(from(t), PrefixPatterns.get(t.text()), List.of(e), scope);
652        }
653        if (is(t, "initially") || is(t, "finally")) {
654            pos++;
655            Exp e = exp3();
656            return new Anchor(from(t), t.text().equals("initially"), e);
657        }
658        Exp left = exp3();
659        if (at("must")) {
660            pos++;
661            Token k = peek();
662            PatternKind kind;
663            if (is(k, "precede")) {
664                kind = PatternKind.Precede;
665            } else if (is(k, "follow")) {
666                kind = PatternKind.Follow;
667            } else {
668                throw error(k, "Expected 'precede' or 'follow' after 'must' but found " + show(k));
669            }
670            pos++;
671            Exp right = exp3();
672            Optional<PatternScope> scope = patternScope();
673            return new Pattern(from(left), kind, List.of(left, right), scope);
674        }
675        return left;
676    }
677
678    private SourceSpan from(Node start) {
679        return new SourceSpan(start.span().line(), start.span().column(), last().span().endLine(),
680                last().span().endColumn());
681    }
682
683    private Optional<PatternScope> patternScope() {
684        Token t = peek();
685        if (is(t, "before")) {
686            pos++;
687            return Optional.of(new PatternScope(from(t), ScopeKind.Before, List.of(exp11())));
688        }
689        if (is(t, "between")) {
690            pos++;
691            Exp a = exp11();
692            expect("and");
693            Exp b = exp11();
694            return Optional.of(new PatternScope(from(t), ScopeKind.BetweenAnd, List.of(a, b)));
695        }
696        if (is(t, "after")) {
697            pos++;
698            Exp a = exp11();
699            if (accept("until")) {
700                Exp b = exp11();
701                return Optional.of(new PatternScope(from(t), ScopeKind.AfterUntil, List.of(a, b)));
702            }
703            return Optional.of(new PatternScope(from(t), ScopeKind.After, List.of(a)));
704        }
705        return Optional.empty();
706    }
707
708    private Exp exp3() {
709        Exp left = exp4();
710        while (at("<=>")) {
711            pos++;
712            Exp right = exp4();
713            left = new Binary(join(left, right), BinaryOp.Iff, left, right);
714        }
715        return left;
716    }
717
718    private Exp exp4() {
719        Exp left = exp5();
720        while (at("=>")) {
721            pos++;
722            Exp right = exp5();
723            left = new Binary(join(left, right), BinaryOp.Implies, left, right);
724        }
725        return left;
726    }
727
728    private Exp exp5() {
729        Exp left = exp6();
730        while (at("||")) {
731            pos++;
732            Exp right = exp6();
733            left = new Binary(join(left, right), BinaryOp.Or, left, right);
734        }
735        return left;
736    }
737
738    private Exp exp6() {
739        Exp left = exp7();
740        while (at("xor")) {
741            pos++;
742            Exp right = exp7();
743            left = new Binary(join(left, right), BinaryOp.Xor, left, right);
744        }
745        return left;
746    }
747
748    private Exp exp7() {
749        Exp left = exp8();
750        while (at("&&")) {
751            pos++;
752            Exp right = exp8();
753            left = new Binary(join(left, right), BinaryOp.And, left, right);
754        }
755        return left;
756    }
757
758    private Exp exp8() {
759        Exp left = exp9();
760        while (true) {
761            BinaryOp op = at("U") ? BinaryOp.LtlU : at("until") ? BinaryOp.Until : at("since") ? BinaryOp.Since
762                    : at("triggered") ? BinaryOp.Triggered : null;
763            if (op == null) {
764                return left;
765            }
766            pos++;
767            Exp right = exp9();
768            left = new Binary(join(left, right), op, left, right);
769        }
770    }
771
772    private Exp exp9() {
773        Exp left = exp10();
774        while (at("W") || at("weakuntil")) {
775            BinaryOp op = at("W") ? BinaryOp.LtlW : BinaryOp.WeakUntil;
776            pos++;
777            Exp right = exp10();
778            left = new Binary(join(left, right), op, left, right);
779        }
780        return left;
781    }
782
783    private Exp exp10() {
784        Token t = peek();
785        if (t.kind() == TokenKind.KEYWORD && TemporalPrefix.containsKey(t.text())) {
786            pos++;
787            Exp e = exp10();
788            return new Unary(prefix(t, e), TemporalPrefix.get(t.text()), e);
789        }
790        return exp11();
791    }
792
793    private Exp exp11() {
794        Token t = peek();
795        if (is(t, "!")) {
796            pos++;
797            Exp e = exp11();
798            return new Unary(prefix(t, e), UnaryOp.Neg, e);
799        }
800        return exp15();
801    }
802
803    private Exp exp15() {
804        Exp left = exp16();
805        while (true) {
806            Token t = peek();
807            BinaryOp op;
808            if (is(t, "not")) {
809                // a not ... is a not in: Happy shifts the not
810                pos++;
811                expect("in");
812                op = BinaryOp.NotIn;
813            } else if ((t.kind() == TokenKind.SYMBOL || t.kind() == TokenKind.KEYWORD)
814                    && Comparisons.containsKey(t.text())) {
815                pos++;
816                op = Comparisons.get(t.text());
817            } else {
818                return left;
819            }
820            Exp right = exp16();
821            left = new Binary(join(left, right), op, left, right);
822        }
823    }
824
825    private Exp exp16() {
826        Token t = peek();
827        if (t.kind() == TokenKind.KEYWORD && Quants.containsKey(t.text())) {
828            pos++;
829            Exp e = exp20();
830            return new QuantExp(from(t), Quants.get(t.text()), e);
831        }
832        return exp17();
833    }
834
835    private Exp exp17() {
836        Exp left = exp18();
837        while (at("+") || at("-")) {
838            BinaryOp op = at("+") ? BinaryOp.Add : BinaryOp.Sub;
839            pos++;
840            Exp right = exp18();
841            left = new Binary(join(left, right), op, left, right);
842        }
843        return left;
844    }
845
846    private Exp exp18() {
847        Exp left = exp19();
848        while (at("*") || at("/") || at("%")) {
849            BinaryOp op = at("*") ? BinaryOp.Mul : at("/") ? BinaryOp.Div : BinaryOp.Rem;
850            pos++;
851            Exp right = exp19();
852            left = new Binary(join(left, right), op, left, right);
853        }
854        return left;
855    }
856
857    private Exp exp19() {
858        Token t = peek();
859        if (is(t, "max") || is(t, "min")) {
860            pos++;
861            Exp e = exp20();
862            return new Unary(prefix(t, e), t.text().equals("max") ? UnaryOp.GMax : UnaryOp.GMin, e);
863        }
864        return exp20();
865    }
866
867    private Exp exp20() {
868        Token t = peek();
869        UnaryOp op = is(t, "sum") ? UnaryOp.Sum : is(t, "product") ? UnaryOp.Product : is(t, "#") ? UnaryOp.Card
870                : is(t, "-") ? UnaryOp.Minus : null;
871        if (op != null) {
872            pos++;
873            Exp e = exp21();
874            return new Unary(prefix(t, e), op, e);
875        }
876        return exp21();
877    }
878
879    private Exp exp21() {
880        Exp left = exp22();
881        while (at("<:")) {
882            pos++;
883            Exp right = exp22();
884            left = new Binary(join(left, right), BinaryOp.Domain, left, right);
885        }
886        return left;
887    }
888
889    private Exp exp22() {
890        Exp left = exp23();
891        while (at(":>")) {
892            pos++;
893            Exp right = exp23();
894            left = new Binary(join(left, right), BinaryOp.Range, left, right);
895        }
896        return left;
897    }
898
899    private Exp exp23() {
900        Exp left = exp24();
901        while (at("++") || at(",")) {
902            BinaryOp op = at("++") ? BinaryOp.Union : BinaryOp.UnionCom;
903            pos++;
904            Exp right = exp24();
905            left = new Binary(join(left, right), op, left, right);
906        }
907        return left;
908    }
909
910    private Exp exp24() {
911        Exp left = exp25();
912        while (at("--")) {
913            pos++;
914            Exp right = exp25();
915            left = new Binary(join(left, right), BinaryOp.Difference, left, right);
916        }
917        return left;
918    }
919
920    private Exp exp25() {
921        Exp left = exp26();
922        while (at("**")) {
923            pos++;
924            Exp right = exp26();
925            left = new Binary(join(left, right), BinaryOp.Intersection, left, right);
926        }
927        return left;
928    }
929
930    private Exp exp26() {
931        Exp left = exp27();
932        while (at(".") || at("&")) {
933            BinaryOp op = at(".") ? BinaryOp.Join : BinaryOp.IntersectionDeprecated;
934            pos++;
935            Exp right = exp27();
936            left = new Binary(join(left, right), op, left, right);
937        }
938        return left;
939    }
940
941    private Exp exp27() {
942        Token t = peek();
943        switch (t.kind()) {
944            case WORD -> {
945                Name name = name();
946                return new ClaferId(name.span(), name);
947            }
948            case INT -> {
949                pos++;
950                return new Literal(t.span(), LiteralKind.Int, t.text());
951            }
952            case DOUBLE -> {
953                pos++;
954                return new Literal(t.span(), LiteralKind.Double, t.text());
955            }
956            case DECIMAL -> {
957                pos++;
958                return new Literal(t.span(), LiteralKind.Real, t.text());
959            }
960            case STRING -> {
961                pos++;
962                return new Literal(t.span(), LiteralKind.Str, t.text());
963            }
964            default -> {
965                if (is(t, "(")) {
966                    pos++;
967                    Exp e = exp();
968                    expect(")");
969                    return e;
970                }
971                throw error(t, "Expected an expression but found " + show(t));
972            }
973        }
974    }
975}