001package org.clafer.frontend;
002
003import java.util.ArrayList;
004import java.util.Collections;
005import java.util.HashMap;
006import java.util.List;
007import java.util.Map;
008import java.util.Optional;
009import java.util.OptionalInt;
010import java.util.Set;
011import org.clafer.frontend.Ir.*;
012
013/**
014 * Reads the rich or the core explicit language, as the Clafer compiler prints
015 * them ({@code clafer -m clafer}, and {@code --core}), and the explicit form
016 * that chocosolver's {@code AstPrinter} prints, into the {@link Ir explicit
017 * IR}. {@link ExplicitPrinter} prints the tree back as it was read.
018 * <p>
019 * The parser does not resolve names, so it reads the model in one pass; what
020 * reads the tree resolves them. It reads the options of the first line and
021 * the provenance comments, {@code // construct, file:line:column}, at the end
022 * of the line of a clafer's opening brace or of a constraint. Other comments
023 * are not in the tree.
024 * <p>
025 * The explicit languages have no sugar and no defaults: every card and group
026 * card is written, every name is a UID, nesting is in braces, and every
027 * operand that is not an atom or a navigation is parenthesized, so the
028 * expressions have no precedence. Errors are diagnostics: the parser goes on
029 * with the next declaration or constraint.
030 */
031public final class ExplicitParser {
032
033    /**
034     * A parsed model.
035     *
036     * @param model the tree, with what could be read
037     * @param diagnostics the errors of the lexer and the parser, by position;
038     * empty if the model was read completely
039     */
040    public record Result(Model model, List<Diagnostic> diagnostics) {
041    }
042
043    /**
044     * An error at a token, unwinding to the declaration or expression that
045     * contains it.
046     */
047    private static final class ParseError extends RuntimeException {
048
049        private final Diagnostic diagnostic;
050
051        ParseError(SourceSpan span, String message) {
052            super(message, null, false, false);
053            this.diagnostic = new Diagnostic(span, message);
054        }
055    }
056
057    private static final Map<String, Quantifier> Quantifiers = Map.of(
058            "all", Quantifier.ALL, "some", Quantifier.SOME, "no", Quantifier.NO,
059            "lone", Quantifier.LONE, "one", Quantifier.ONE);
060    private static final Map<String, ModifierKind> Modifiers = Map.of(
061            "initial", ModifierKind.INITIAL, "final", ModifierKind.FINAL,
062            "finalref", ModifierKind.FINALREF, "finaltarget", ModifierKind.FINALTARGET);
063    private static final Map<String, BinaryOp> BinaryOps = new HashMap<>();
064    private static final Map<String, TemporalOp> UnaryTemporal = new HashMap<>();
065    private static final Map<String, TemporalOp> BinaryTemporal = new HashMap<>();
066    private static final Map<String, PatternKind> UnaryPatterns = Map.of(
067            "never", PatternKind.NEVER, "sometime", PatternKind.SOMETIME,
068            "lonce", PatternKind.LONCE, "always", PatternKind.ALWAYS);
069    private static final Set<String> Calls = Set.of(
070            "concat", "prefix", "suffix", "upcast", "downcast", "connected", "dref", "parent");
071
072    static {
073        for (BinaryOp op : BinaryOp.values()) {
074            BinaryOps.put(op.syntax(), op);
075        }
076        for (TemporalOp op : TemporalOp.values()) {
077            (op.arity() == 1 ? UnaryTemporal : BinaryTemporal).put(op.keyword(), op);
078        }
079    }
080
081    private final List<Token> tokens;
082    private final Map<Integer, Token> lineComments = new HashMap<>();
083    private final List<Diagnostic> diagnostics = new ArrayList<>();
084    private int pos = 0;
085
086    private ExplicitParser(List<Token> tokens, List<Token> comments) {
087        this.tokens = tokens;
088        for (Token comment : comments) {
089            if (comment.text().startsWith("//") && !comment.text().startsWith("//#")) {
090                lineComments.put(comment.span().line(), comment);
091            }
092        }
093    }
094
095    /**
096     * Parses an explicit model.
097     *
098     * @param source the text
099     * @return the tree and the errors
100     */
101    public static Result parse(String source) {
102        Lexer.Result lexed = Lexer.lex(source);
103        List<Token> parseable = lexed.tokens().stream().filter(t -> t.kind() != TokenKind.ERROR).toList();
104        ExplicitParser parser = new ExplicitParser(parseable, lexed.comments());
105        parser.diagnostics.addAll(lexed.diagnostics());
106        Options options = parser.readOptions(lexed.comments());
107        Model model = parser.readModel(options);
108        // a model that declares itself the core (--core) has no rich construct, as in the compiler
109        parser.diagnostics.addAll(Core.richInCore(model));
110        List<Diagnostic> diagnostics = new ArrayList<>(parser.diagnostics);
111        diagnostics.sort((a, b) -> a.span().line() != b.span().line()
112                ? Integer.compare(a.span().line(), b.span().line())
113                : Integer.compare(a.span().column(), b.span().column()));
114        return new Result(model, Collections.unmodifiableList(diagnostics));
115    }
116
117    // ------------------------------------------------------------------
118    // Options and provenance
119    // ------------------------------------------------------------------
120    /**
121     * The options of the first line, {@code //# OPTIONS --explicit --core --tl=N}.
122     */
123    private Options readOptions(List<Token> comments) {
124        Token first = comments.isEmpty() ? null : comments.get(0);
125        if (first == null || first.span().line() != 1 || !first.text().startsWith("//# OPTIONS")) {
126            return Options.Rich;
127        }
128        boolean core = false;
129        OptionalInt traceLength = OptionalInt.empty();
130        for (String option : first.text().substring("//# OPTIONS".length()).trim().split("\\s+")) {
131            if (option.equals("--explicit") || option.isEmpty()) {
132                continue;
133            }
134            if (option.equals("--core")) {
135                core = true;
136            } else if (option.matches("--tl=[0-9]+")) {
137                traceLength = OptionalInt.of(Integer.parseInt(option.substring("--tl=".length())));
138            } else {
139                diagnostics.add(new Diagnostic(first.span(), "Unknown option of an explicit model: " + option));
140            }
141        }
142        return new Options(core, traceLength);
143    }
144
145    /**
146     * The provenance comment at the end of the line of a token, if any.
147     */
148    private Optional<Origin> originAfter(Token token) {
149        Token comment = lineComments.get(token.span().endLine());
150        if (comment == null || comment.span().column() < token.span().endColumn()) {
151            return Optional.empty();
152        }
153        return Optional.of(origin(comment.text().substring(2).trim()));
154    }
155
156    /**
157     * {@code construct, file:line:column}, or the construct alone.
158     */
159    static Origin origin(String text) {
160        int comma = text.lastIndexOf(", ");
161        if (comma >= 0) {
162            String[] parts = text.substring(comma + 2).split(":");
163            if (parts.length >= 3 && parts[parts.length - 1].matches("[0-9]+") && parts[parts.length - 2].matches("[0-9]+")) {
164                String file = String.join(":", java.util.Arrays.copyOf(parts, parts.length - 2));
165                return new Origin(text.substring(0, comma), Optional.of(new Position(file,
166                        Integer.parseInt(parts[parts.length - 2]), Integer.parseInt(parts[parts.length - 1]))));
167            }
168        }
169        return new Origin(text, Optional.empty());
170    }
171
172    // ------------------------------------------------------------------
173    // Tokens
174    // ------------------------------------------------------------------
175    private Token peek() {
176        return tokens.get(pos);
177    }
178
179    private Token peek(int offset) {
180        return tokens.get(Math.min(pos + offset, tokens.size() - 1));
181    }
182
183    private Token next() {
184        Token t = tokens.get(pos);
185        if (t.kind() != TokenKind.EOF) {
186            pos++;
187        }
188        return t;
189    }
190
191    private Token previous() {
192        return tokens.get(Math.max(0, pos - 1));
193    }
194
195    private boolean atSymbol(String symbol) {
196        return peek().isSymbol(symbol);
197    }
198
199    private boolean atWord(String word) {
200        return peek().isWord(word);
201    }
202
203    private ParseError error(Token at, String message) {
204        return new ParseError(at.span(), message);
205    }
206
207    private static String show(Token t) {
208        return t.kind() == TokenKind.EOF ? "the end" : "'" + t.text() + "'";
209    }
210
211    private Token expectSymbol(String symbol) {
212        if (!atSymbol(symbol)) {
213            throw error(peek(), "Expected '" + symbol + "' but found " + show(peek()));
214        }
215        return next();
216    }
217
218    private Name expectName(String what) {
219        if (peek().kind() != TokenKind.WORD) {
220            throw error(peek(), "Expected " + what + " but found " + show(peek()));
221        }
222        Token t = next();
223        return new Name(t.span(), t.text());
224    }
225
226    private int expectInt() {
227        boolean negative = false;
228        if (atSymbol("-") && peek(1).kind() == TokenKind.INT) {
229            next();
230            negative = true;
231        }
232        Token t = peek();
233        if (t.kind() != TokenKind.INT) {
234            throw error(t, "Expected a number but found " + show(t));
235        }
236        next();
237        try {
238            int value = Integer.parseInt(t.text());
239            return negative ? -value : value;
240        } catch (NumberFormatException e) {
241            throw error(t, "The number " + t.text() + " is too large");
242        }
243    }
244
245    private Card expectCard() {
246        Token start = peek();
247        int low = expectInt();
248        expectSymbol("..");
249        if (atSymbol("*")) {
250            next();
251            return new Card(spanFrom(start, previous()), low, Card.Unbounded);
252        }
253        int high = expectInt();
254        if (low > high) {
255            throw error(start, "The card " + low + ".." + high + " is empty");
256        }
257        return new Card(spanFrom(start, previous()), low, high);
258    }
259
260    private static SourceSpan spanFrom(Token start, Token end) {
261        return spanFrom(start.span(), end.span());
262    }
263
264    private static SourceSpan spanFrom(SourceSpan start, SourceSpan end) {
265        if (end.endLine() < start.line() || (end.endLine() == start.line() && end.endColumn() < start.column())) {
266            return start;
267        }
268        return new SourceSpan(start.line(), start.column(), end.endLine(), end.endColumn());
269    }
270
271    // ------------------------------------------------------------------
272    // Declarations
273    // ------------------------------------------------------------------
274    private Model readModel(Options options) {
275        List<Element> elements = new ArrayList<>();
276        List<Objective> objectives = new ArrayList<>();
277        List<Assertion> assertions = new ArrayList<>();
278        Token first = peek();
279        while (peek().kind() != TokenKind.EOF) {
280            int start = pos;
281            try {
282                Token t = peek();
283                if (t.isSymbol("<<")) {
284                    objectives.add(readObjective());
285                } else if (t.isWord("assert")) {
286                    Token at = next();
287                    Token open = peek();
288                    Exp exp = readBracketed();
289                    Token close = previous();
290                    assertions.add(new Assertion(spanFrom(at, close), exp, originAfter(close)));
291                    if (open == close) {
292                        throw error(open, "Empty assertion");
293                    }
294                } else if (t.isWord("root") && peek(1).isSymbol("{")) {
295                    elements.add(readRoot());
296                } else if (t.isWord("enum") && peek(1).kind() == TokenKind.WORD && peek(2).isSymbol("=")) {
297                    elements.add(readEnum());
298                } else {
299                    elements.add(readElement(true));
300                }
301            } catch (ParseError e) {
302                diagnostics.add(e.diagnostic);
303                recover(start);
304            }
305        }
306        return new Model(spanFrom(first, peek()), options, elements, objectives, assertions);
307    }
308
309    /**
310     * Skips to the start of the next top-level declaration: a token that can
311     * start one at the beginning of a line, outside braces.
312     */
313    private void recover(int start) {
314        if (pos == start) {
315            next();
316        }
317        int depth = 0;
318        while (peek().kind() != TokenKind.EOF) {
319            Token t = peek();
320            if (depth == 0 && t.span().column() == 1 && startsTopLevel(t)) {
321                return;
322            }
323            if (t.isSymbol("{")) {
324                depth++;
325            } else if (t.isSymbol("}")) {
326                depth = Math.max(0, depth - 1);
327            }
328            next();
329        }
330    }
331
332    private static boolean startsTopLevel(Token t) {
333        return t.kind() == TokenKind.INT || t.isSymbol("[") || t.isSymbol("<<")
334                || (t.kind() == TokenKind.WORD && (Set.of("abstract", "root", "assert", "enum").contains(t.text())
335                || Modifiers.containsKey(t.text())));
336    }
337
338    private Objective readObjective() {
339        Token start = expectSymbol("<<");
340        boolean maximize;
341        if (atWord("max") || atWord("min")) {
342            maximize = next().text().equals("max");
343        } else {
344            throw error(peek(), "Expected 'max' or 'min' but found " + show(peek()));
345        }
346        int exprStart = pos;
347        while (!atSymbol(">>") && peek().kind() != TokenKind.EOF) {
348            next();
349        }
350        int exprEnd = pos;
351        Token end = expectSymbol(">>");
352        if (exprEnd == exprStart) {
353            throw error(end, "Empty objective");
354        }
355        return new Objective(spanFrom(start, end), maximize, parseRange(exprStart, exprEnd));
356    }
357
358    private RootBlock readRoot() {
359        Token start = next();
360        expectSymbol("{");
361        List<Constraint> constraints = new ArrayList<>();
362        while (atSymbol("[")) {
363            constraints.add(readConstraint());
364        }
365        Token end = expectSymbol("}");
366        return new RootBlock(spanFrom(start, end), constraints);
367    }
368
369    /**
370     * {@code enum E = a | b}
371     */
372    private EnumDecl readEnum() {
373        Token start = next();
374        Name name = expectName("the name of the enumeration");
375        expectSymbol("=");
376        List<Name> literals = new ArrayList<>();
377        literals.add(expectName("a literal"));
378        while (atSymbol("|")) {
379            next();
380            literals.add(expectName("a literal"));
381        }
382        return new EnumDecl(spanFrom(start, previous()), name, literals);
383    }
384
385    private Element readElement(boolean topLevel) {
386        if (atSymbol("[")) {
387            return readConstraint();
388        }
389        if (atSymbol("(")) {
390            throw error(peek(), "Soft constraints are not supported");
391        }
392        return readClafer(topLevel);
393    }
394
395    private Constraint readConstraint() {
396        Token open = peek();
397        Exp exp = readBracketed();
398        Token close = previous();
399        return new Constraint(spanFrom(open, close), exp, originAfter(close));
400    }
401
402    /**
403     * {@code [ exp ]}
404     */
405    private Exp readBracketed() {
406        Token open = expectSymbol("[");
407        int start = pos;
408        int depth = 1;
409        while (peek().kind() != TokenKind.EOF) {
410            if (atSymbol("[")) {
411                depth++;
412            } else if (atSymbol("]") && --depth == 0) {
413                break;
414            }
415            next();
416        }
417        int end = pos;
418        expectSymbol("]");
419        if (end == start) {
420            throw error(open, "Empty constraint");
421        }
422        return parseRange(start, end);
423    }
424
425    /**
426     * {@code [abstract] [modifiers] gcard name [: super] [-> | ->> target] card [initializer] { elements }}
427     */
428    private ClaferDecl readClafer(boolean topLevel) {
429        Token start = peek();
430        boolean isAbstract = false;
431        if (atWord("abstract")) {
432            next();
433            isAbstract = true;
434        }
435        List<Modifier> modifiers = new ArrayList<>();
436        while (peek().kind() == TokenKind.WORD && Modifiers.containsKey(peek().text())) {
437            Token m = next();
438            modifiers.add(new Modifier(m.span(), Modifiers.get(m.text())));
439        }
440        if (peek().kind() != TokenKind.INT && !atSymbol("-")) {
441            throw error(peek(), "Expected a clafer, a constraint, an objective or an assertion but found " + show(peek()));
442        }
443        Card groupCard = expectCard();
444        Name name = expectName("the name of a clafer");
445        Optional<Name> superName = Optional.empty();
446        if (atSymbol(":")) {
447            next();
448            superName = Optional.of(expectName("the name of the super clafer"));
449        }
450        Optional<RefDecl> ref = Optional.empty();
451        if (atSymbol("->") || atSymbol("->>")) {
452            Token arrow = next();
453            Name target = expectName("the target of the reference");
454            ref = Optional.of(new RefDecl(spanFrom(arrow.span(), target.span()), arrow.text().equals("->"), target));
455        }
456        Card card = expectCard();
457        // The written bound of a top-level abstract clafer counts all its
458        // instances, a rich construct; the core has it as a constraint.
459        Optional<AbstractMultiplicity> abstractMultiplicity = Optional.empty();
460        if (isAbstract && topLevel && !card.isAny()) {
461            abstractMultiplicity = Optional.of(new AbstractMultiplicity(card.span(), card));
462            card = new Card(card.span(), 0, Card.Unbounded);
463        }
464        Optional<Initializer> initializer = Optional.empty();
465        if (atSymbol("=") || atSymbol(":=")) {
466            int initStart = pos;
467            try {
468                initializer = Optional.of(readInitializer());
469            } catch (ParseError e) {
470                // Go on with the clafer without its initializer, so that it is
471                // declared and its name is found.
472                diagnostics.add(e.diagnostic);
473                pos = initStart + 1;
474                pos = endOfValue();
475            }
476        }
477        Token open = expectSymbol("{");
478        Optional<Origin> origin = originAfter(open);
479        List<Element> elements = new ArrayList<>();
480        while (!atSymbol("}")) {
481            if (peek().kind() == TokenKind.EOF) {
482                throw error(peek(), "Expected '}' to close " + name.text());
483            }
484            int elementStart = pos;
485            try {
486                elements.add(readElement(false));
487            } catch (ParseError e) {
488                // Go on with the next element of the same clafer.
489                diagnostics.add(e.diagnostic);
490                skipElement(elementStart);
491            }
492        }
493        Token close = expectSymbol("}");
494        if (elements.isEmpty() && origin.isEmpty()) {
495            origin = originAfter(close);
496        }
497        return new ClaferDecl(spanFrom(start, close), isAbstract, modifiers, groupCard, name, superName, ref, card,
498                abstractMultiplicity, initializer, elements, origin);
499    }
500
501    /**
502     * {@code = value}, {@code := each value} or {@code := together value},
503     * up to the clafer's opening brace.
504     */
505    private Initializer readInitializer() {
506        Token op = next();
507        InitKind kind = InitKind.FIXED;
508        if (op.text().equals(":=")) {
509            if (atWord("each")) {
510                kind = InitKind.EACH;
511            } else if (atWord("together")) {
512                kind = InitKind.TOGETHER;
513            } else {
514                throw error(peek(), "Expected 'each' or 'together' after ':=' but found " + show(peek()));
515            }
516            next();
517        }
518        int valueStart = pos;
519        int valueEnd = endOfValue();
520        if (valueEnd == valueStart) {
521            throw error(peek(), "Expected the value of the initializer but found " + show(peek()));
522        }
523        Exp value = parseRange(valueStart, valueEnd);
524        pos = valueEnd;
525        return new Initializer(spanFrom(op.span(), value.span()), kind, value);
526    }
527
528    /**
529     * The end of the value of an initializer: the clafer's opening brace,
530     * outside parentheses.
531     */
532    private int endOfValue() {
533        int depth = 0;
534        for (int i = pos; i < tokens.size(); i++) {
535            Token t = tokens.get(i);
536            if (t.kind() == TokenKind.EOF) {
537                return i;
538            }
539            if (t.isSymbol("(") || t.isSymbol("[") || t.isSymbol("-[")) {
540                depth++;
541            } else if (t.isSymbol(")") || t.isSymbol("]") || t.isSymbol("]->") || t.isSymbol("]->>")) {
542                depth--;
543            } else if (t.isSymbol("{") && depth == 0) {
544                return i;
545            }
546        }
547        return tokens.size() - 1;
548    }
549
550    /**
551     * Skips the rest of a broken element of a clafer: to its end at the same
552     * depth, or to the clafer's closing brace.
553     */
554    private void skipElement(int start) {
555        if (pos == start) {
556            next();
557        }
558        int depth = 0;
559        while (peek().kind() != TokenKind.EOF) {
560            if (atSymbol("{")) {
561                depth++;
562            } else if (atSymbol("}")) {
563                if (depth == 0) {
564                    return;
565                }
566                depth--;
567                if (depth == 0) {
568                    next();
569                    return;
570                }
571            } else if (depth == 0 && (atSymbol("[") || atWord("abstract"))) {
572                return;
573            }
574            next();
575        }
576    }
577
578    // ------------------------------------------------------------------
579    // Expressions
580    // ------------------------------------------------------------------
581    /**
582     * Parses the tokens [start, end) as one expression.
583     */
584    private Exp parseRange(int start, int end) {
585        int saved = pos;
586        pos = start;
587        try {
588            Exp exp = parseExpr(end);
589            if (pos != end) {
590                Token t = tokens.get(pos);
591                throw error(t, "Unexpected " + show(t) + ": the explicit form needs parentheses around an operand that is not a name, a number or a navigation");
592            }
593            return exp;
594        } finally {
595            pos = saved;
596        }
597    }
598
599    private Token at(int end) {
600        return pos < end ? tokens.get(pos) : new Token(TokenKind.EOF, "", tokens.get(Math.max(0, end - 1)).span());
601    }
602
603    private Token take(int end) {
604        Token t = at(end);
605        if (pos >= end) {
606            throw error(t, "The expression ends too early");
607        }
608        pos++;
609        return t;
610    }
611
612    private void expect(int end, String symbol) {
613        Token t = at(end);
614        if (!t.isSymbol(symbol)) {
615            throw error(t, "Expected '" + symbol + "' but found " + (pos >= end ? "the end of the expression" : show(t)));
616        }
617        pos++;
618    }
619
620    private void expectWord(int end, String word) {
621        Token t = at(end);
622        if (!t.isWord(word)) {
623            throw error(t, "Expected '" + word + "' but found " + (pos >= end ? "the end of the expression" : show(t)));
624        }
625        pos++;
626    }
627
628    private SourceSpan from(Token start) {
629        return spanFrom(start, previous());
630    }
631
632    /**
633     * Whether the token after the current one starts an operand, so that a
634     * keyword here is an operator, e.g., {@code F (x)}, and not a clafer of
635     * that name, e.g., {@code F = x} or {@code F.x}.
636     */
637    private boolean operandFollows(int end) {
638        if (pos + 1 >= end) {
639            return false;
640        }
641        Token t = tokens.get(pos + 1);
642        return switch (t.kind()) {
643            case WORD -> !BinaryOps.containsKey(t.text()) && !BinaryTemporal.containsKey(t.text())
644                    && !Set.of("not", "must", "then", "else", "before", "after", "between", "and", "until").contains(t.text());
645            case INT, DECIMAL, DOUBLE, STRING -> true;
646            case SYMBOL -> Set.of("(", "!", "#", "~", "^", "{").contains(t.text())
647                    || (t.text().equals("-") && pos + 2 < end);
648            default -> false;
649        };
650    }
651
652    /**
653     * expr := quantified | if | pattern | temporal | anchor | unary
654     * | operand [must ... | transition | (op operand)*]
655     */
656    private Exp parseExpr(int end) {
657        Token t = at(end);
658        if (t.kind() == TokenKind.WORD) {
659            if (Quantifiers.containsKey(t.text()) && operandFollows(end)) {
660                return parseQuantified(end);
661            }
662            if (t.isWord("if")) {
663                pos++;
664                Exp condition = parseOperand(end);
665                expectWord(end, "then");
666                Exp then = parseOperand(end);
667                expectWord(end, "else");
668                Exp otherwise = parseOperand(end);
669                return new IfThenElse(from(t), condition, then, otherwise);
670            }
671            if (UnaryPatterns.containsKey(t.text()) && operandFollows(end)) {
672                pos++;
673                List<Exp> args = new ArrayList<>();
674                args.add(parseOperand(end));
675                return parseScope(t, UnaryPatterns.get(t.text()), args, end);
676            }
677            if (UnaryTemporal.containsKey(t.text()) && operandFollows(end)) {
678                pos++;
679                Exp arg = parseOperand(end);
680                return new Temporal(from(t), UnaryTemporal.get(t.text()), List.of(arg));
681            }
682            if ((t.isWord("initially") || t.isWord("finally")) && operandFollows(end)) {
683                pos++;
684                Exp body = parseOperand(end);
685                return new Anchor(from(t), t.isWord("initially"), body);
686            }
687        }
688        Exp unary = parseUnary(end);
689        if (unary != null) {
690            return unary;
691        }
692        Exp first = parseOperand(end);
693        Token next = at(end);
694        if (pos < end && next.isWord("must")) {
695            pos++;
696            Token kind = take(end);
697            PatternKind pattern = kind.isWord("precede") ? PatternKind.PRECEDE
698                    : kind.isWord("follow") ? PatternKind.FOLLOW : null;
699            if (pattern == null) {
700                throw error(kind, "Expected 'precede' or 'follow' but found " + show(kind));
701            }
702            List<Exp> args = new ArrayList<>();
703            args.add(first);
704            args.add(parseOperand(end));
705            return parseScope(t, pattern, args, end);
706        }
707        if (pos < end && (next.isSymbol("-->") || next.isSymbol("-->>") || next.isSymbol("-["))) {
708            return parseTransition(t, first, end);
709        }
710        return parseOperators(t, first, end);
711    }
712
713    /**
714     * The scope of a pattern, after its own formulas.
715     */
716    private Exp parseScope(Token start, PatternKind kind, List<Exp> args, int end) {
717        PatternScope scope = PatternScope.GLOBALLY;
718        Token t = at(end);
719        if (pos < end && t.isWord("before")) {
720            pos++;
721            scope = PatternScope.BEFORE;
722            args.add(parseOperand(end));
723        } else if (pos < end && t.isWord("after")) {
724            pos++;
725            args.add(parseOperand(end));
726            scope = PatternScope.AFTER;
727            if (pos < end && at(end).isWord("until")) {
728                pos++;
729                args.add(parseOperand(end));
730                scope = PatternScope.AFTER_UNTIL;
731            }
732        } else if (pos < end && t.isWord("between")) {
733            pos++;
734            args.add(parseOperand(end));
735            expectWord(end, "and");
736            args.add(parseOperand(end));
737            scope = PatternScope.BETWEEN;
738        }
739        return new Pattern(from(start), kind, scope, args);
740    }
741
742    /**
743     * {@code from --> to}, {@code from -[guard]-> to}, and the synchronous
744     * {@code -->>} and {@code -[guard]->>}; the target may be a chain.
745     */
746    private Exp parseTransition(Token start, Exp from, int end) {
747        Token arrow = take(end);
748        Optional<Exp> guard = Optional.empty();
749        boolean sync;
750        if (arrow.isSymbol("-[")) {
751            guard = Optional.of(parseOperand(end));
752            Token close = take(end);
753            if (!close.isSymbol("]->") && !close.isSymbol("]->>")) {
754                throw error(close, "Expected ']->' or ']->>' but found " + show(close));
755            }
756            sync = close.isSymbol("]->>");
757        } else {
758            sync = arrow.isSymbol("-->>");
759        }
760        Token targetStart = at(end);
761        Exp to = parseOperand(end);
762        Token next = at(end);
763        if (pos < end && (next.isSymbol("-->") || next.isSymbol("-->>") || next.isSymbol("-["))) {
764            to = parseTransition(targetStart, to, end);
765        }
766        return new Transition(from(start), sync, from, guard, to);
767    }
768
769    /**
770     * A prefix operator applied to an operand, or null if there is none here.
771     * A minus before a number is part of the number.
772     */
773    private Exp parseUnary(int end) {
774        Token t = at(end);
775        if (pos >= end) {
776            return null;
777        }
778        UnaryOp op = null;
779        if (t.kind() == TokenKind.SYMBOL) {
780            op = switch (t.text()) {
781                case "!" -> UnaryOp.NOT;
782                case "-" -> {
783                    Token number = pos + 1 < end ? tokens.get(pos + 1) : null;
784                    yield number != null && (number.kind() == TokenKind.INT || number.kind() == TokenKind.DECIMAL
785                            || number.kind() == TokenKind.DOUBLE) ? null : UnaryOp.MINUS;
786                }
787                case "#" -> UnaryOp.CARD;
788                case "~" -> UnaryOp.INVERSE;
789                case "^" -> UnaryOp.CLOSURE;
790                case "*" -> UnaryOp.REFLEXIVE_CLOSURE;
791                default -> null;
792            };
793        } else if (t.kind() == TokenKind.WORD && operandFollows(end)) {
794            op = switch (t.text()) {
795                case "sum" -> UnaryOp.SUM;
796                case "product" -> UnaryOp.PRODUCT;
797                case "max" -> UnaryOp.MAX;
798                case "min" -> UnaryOp.MIN;
799                case "length" -> UnaryOp.LENGTH;
800                default -> null;
801            };
802        }
803        if (op == null) {
804            return null;
805        }
806        pos++;
807        Exp arg = parseOperand(end);
808        if (op == UnaryOp.SUM || op == UnaryOp.PRODUCT) {
809            // The dref that sum and product take from each instance is
810            // printed, but not in the tree.
811            if (!(arg instanceof Dref dref)) {
812                throw error(t, t.text() + " takes the dref of each instance: write " + t.text() + " x.dref");
813            }
814            arg = dref.left();
815        }
816        return new Unary(from(t), op, arg);
817    }
818
819    /**
820     * A chain of one binary operator. The explicit form has no precedence:
821     * different operators need parentheses.
822     */
823    private Exp parseOperators(Token start, Exp first, int end) {
824        String symbol = operator(end);
825        if (symbol == null) {
826            return first;
827        }
828        Token op = at(end);
829        List<Exp> operands = new ArrayList<>();
830        operands.add(first);
831        while (true) {
832            pos += symbol.equals("not in") ? 2 : 1;
833            operands.add(parseOperand(end));
834            String nextSymbol = operator(end);
835            if (nextSymbol == null) {
836                break;
837            }
838            if (!nextSymbol.equals(symbol)) {
839                throw error(at(end), "Parenthesize: '" + symbol + "' and '" + nextSymbol + "' without parentheses");
840            }
841        }
842        if (BinaryTemporal.containsKey(symbol)) {
843            if (operands.size() > 2) {
844                throw error(op, "Parenthesize: '" + symbol + "' takes two operands");
845            }
846            return new Temporal(from(start), BinaryTemporal.get(symbol), operands);
847        }
848        return new Binary(from(start), BinaryOps.get(symbol), operands);
849    }
850
851    /**
852     * The binary operator at the current token, or null.
853     */
854    private String operator(int end) {
855        if (pos >= end) {
856            return null;
857        }
858        Token t = at(end);
859        if (t.isWord("not") && pos + 1 < end && tokens.get(pos + 1).isWord("in")) {
860            return "not in";
861        }
862        if (t.kind() == TokenKind.WORD && (t.text().equals("in") || t.text().equals("xor")
863                || BinaryTemporal.containsKey(t.text()))) {
864            return t.text();
865        }
866        if (t.kind() == TokenKind.SYMBOL && BinaryOps.containsKey(t.text())) {
867            return t.text();
868        }
869        return null;
870    }
871
872    /**
873     * operand := primary ("." step)*
874     */
875    private Exp parseOperand(int end) {
876        Token start = at(end);
877        Exp exp = parsePrimary(end);
878        while (pos < end && at(end).isSymbol(".")) {
879            pos++;
880            Token step = at(end);
881            boolean call = pos + 1 < end && tokens.get(pos + 1).isSymbol("(");
882            if (step.isWord("dref") && !call) {
883                pos++;
884                exp = new Dref(from(start), exp);
885            } else if (step.isWord("parent") && !call) {
886                pos++;
887                exp = new ParentOf(from(start), exp);
888            } else if (step.kind() == TokenKind.WORD && !isCall(end)) {
889                pos++;
890                exp = new Join(from(start), exp, new NameExp(step.span(), step.text()));
891            } else {
892                Exp right = parsePrimary(end);
893                exp = new Join(from(start), exp, right);
894            }
895        }
896        return exp;
897    }
898
899    private boolean isCall(int end) {
900        Token t = at(end);
901        return t.kind() == TokenKind.WORD && pos + 1 < end && tokens.get(pos + 1).isSymbol("(")
902                && Calls.contains(t.text());
903    }
904
905    private Exp parsePrimary(int end) {
906        Token t = at(end);
907        if (pos >= end) {
908            throw error(t, "The expression ends too early");
909        }
910        switch (t.kind()) {
911            case INT, DECIMAL, DOUBLE -> {
912                pos++;
913                return number(t, t, false);
914            }
915            case STRING -> {
916                pos++;
917                return new StringLit(t.span(), t.text());
918            }
919            case SYMBOL -> {
920                switch (t.text()) {
921                    case "(" -> {
922                        pos++;
923                        Exp inner = parseExpr(end);
924                        expect(end, ")");
925                        return inner;
926                    }
927                    case "-" -> {
928                        pos++;
929                        Token number = take(end);
930                        return number(t, number, true);
931                    }
932                    case "{" -> {
933                        return parseConstantSet(end);
934                    }
935                    default -> throw error(t, "Unexpected " + show(t));
936                }
937            }
938            case WORD -> {
939                if (t.isWord("this")) {
940                    pos++;
941                    return new This(t.span());
942                }
943                if (t.isWord("noclafer")) {
944                    pos++;
945                    return new NoClafer(t.span());
946                }
947                if (isCall(end)) {
948                    return parseCall(end);
949                }
950                pos++;
951                return new NameExp(t.span(), t.text());
952            }
953            default -> throw error(t, "Unexpected " + show(t));
954        }
955    }
956
957    private Exp number(Token start, Token t, boolean negative) {
958        SourceSpan span = spanFrom(start, t);
959        return switch (t.kind()) {
960            case DECIMAL -> new DecimalLit(span, (negative ? "-" : "") + t.text());
961            case DOUBLE -> new DoubleLit(span, (negative ? "-" : "") + t.text());
962            case INT -> {
963                try {
964                    long value = Long.parseLong(t.text());
965                    yield new IntLit(span, negative ? -value : value);
966                } catch (NumberFormatException e) {
967                    throw error(t, "The number " + t.text() + " is too large");
968                }
969            }
970            default -> throw error(t, "Expected a number after '-' but found " + show(t));
971        };
972    }
973
974    /**
975     * {@code {[1, 2], [3, 4]} :: type}: a constant set, one row per column of
976     * the type.
977     */
978    private Exp parseConstantSet(int end) {
979        Token open = take(end);
980        List<List<Integer>> rows = new ArrayList<>();
981        do {
982            expect(end, "[");
983            List<Integer> row = new ArrayList<>();
984            if (!at(end).isSymbol("]")) {
985                do {
986                    boolean negative = false;
987                    if (at(end).isSymbol("-")) {
988                        pos++;
989                        negative = true;
990                    }
991                    Token n = take(end);
992                    if (n.kind() != TokenKind.INT) {
993                        throw error(n, "Expected a number but found " + show(n));
994                    }
995                    row.add(negative ? -Integer.parseInt(n.text()) : Integer.parseInt(n.text()));
996                } while (at(end).isSymbol(",") && take(end) != null);
997            }
998            expect(end, "]");
999            rows.add(row);
1000        } while (at(end).isSymbol(",") && take(end) != null);
1001        expect(end, "}");
1002        expect(end, "::");
1003        List<Name> type = parseType(end);
1004        return new ConstantSet(from(open), rows, type);
1005    }
1006
1007    /**
1008     * type := name ("*" name)*
1009     */
1010    private List<Name> parseType(int end) {
1011        List<Name> types = new ArrayList<>();
1012        types.add(typeName(take(end)));
1013        while (pos < end && at(end).isSymbol("*")) {
1014            pos++;
1015            types.add(typeName(take(end)));
1016        }
1017        return types;
1018    }
1019
1020    private Name typeName(Token t) {
1021        if (t.kind() != TokenKind.WORD) {
1022            throw error(t, "Expected the name of a clafer but found " + show(t));
1023        }
1024        return new Name(t.span(), t.text());
1025    }
1026
1027    private Exp parseCall(int end) {
1028        Token name = take(end);
1029        expect(end, "(");
1030        Exp result;
1031        switch (name.text()) {
1032            case "dref", "parent" -> {
1033                Name clafer = typeName(take(end));
1034                expect(end, ")");
1035                return new RelationOf(from(name), name.text().equals("dref"), clafer);
1036            }
1037            case "upcast", "downcast" -> {
1038                Exp base = parseExpr(end);
1039                expect(end, ",");
1040                List<Name> type = parseType(end);
1041                expect(end, ")");
1042                return new Cast(from(name), name.text().equals("upcast"), base, type);
1043            }
1044            case "connected" -> {
1045                Exp nodes = parseExpr(end);
1046                expect(end, ",");
1047                Exp relation = parseExpr(end);
1048                expect(end, ",");
1049                Token directed = take(end);
1050                if (!directed.isWord("directed") && !directed.isWord("undirected")) {
1051                    throw error(directed, "Expected 'directed' or 'undirected' but found " + show(directed));
1052                }
1053                expect(end, ")");
1054                return new Connected(from(name), nodes, relation, directed.isWord("directed"));
1055            }
1056            default -> {
1057                Exp first = parseExpr(end);
1058                expect(end, ",");
1059                Exp second = parseExpr(end);
1060                expect(end, ")");
1061                result = new Call(from(name), name.text(), List.of(first, second));
1062            }
1063        }
1064        return result;
1065    }
1066
1067    /**
1068     * {@code q [disj] x; y : e, z : f | body}, or {@code q e}
1069     */
1070    private Exp parseQuantified(int end) {
1071        Token q = take(end);
1072        Quantifier quantifier = Quantifiers.get(q.text());
1073        // some e, without variables
1074        boolean declares = at(end).isWord("disj") || (at(end).kind() == TokenKind.WORD && pos + 1 < end
1075                && (tokens.get(pos + 1).isSymbol(":") || tokens.get(pos + 1).isSymbol(";")));
1076        if (!declares) {
1077            Exp set = parseOperand(end);
1078            return new QuantifiedSet(from(q), quantifier, set);
1079        }
1080        List<Decl> decls = new ArrayList<>();
1081        do {
1082            Token declStart = at(end);
1083            boolean disjoint = false;
1084            if (at(end).isWord("disj")) {
1085                pos++;
1086                disjoint = true;
1087            }
1088            List<Name> names = new ArrayList<>();
1089            do {
1090                Token name = take(end);
1091                if (name.kind() != TokenKind.WORD) {
1092                    throw error(name, "Expected the name of a variable but found " + show(name));
1093                }
1094                names.add(new Name(name.span(), name.text()));
1095            } while (at(end).isSymbol(";") && take(end) != null);
1096            expect(end, ":");
1097            Exp set = parseExpr(end);
1098            decls.add(new Decl(from(declStart), disjoint, names, set));
1099        } while (at(end).isSymbol(",") && take(end) != null);
1100        expect(end, "|");
1101        Exp body = parseExpr(end);
1102        return new Quantified(from(q), quantifier, decls, body);
1103    }
1104}