001package org.clafer.frontend;
002
003import java.util.List;
004import java.util.Optional;
005
006/**
007 * The syntax tree of a model in the full Clafer language, as written: the
008 * tree of the compiler's {@code clafer.cf} ({@code AbsClafer}), with a span
009 * for each node. {@link ClaferParser} builds it, and {@link SyntaxPrinter}
010 * prints it as the compiler's {@code printTree} does.
011 * <p>
012 * The sugar stays as written, e.g., a card {@code ?} or the implicit
013 * {@code this} of a name; the later passes read it from the tree. Where the
014 * parser recovered from an error, the tree has what it read around it.
015 * <p>
016 * The records are immutable; their lists are unmodifiable copies.
017 */
018public final class Syntax {
019
020    private Syntax() {
021    }
022
023    /**
024     * A node of the tree.
025     */
026    public sealed interface Node permits Model, Declaration, Ident, Name, TempModifier, GCard, Card, Super,
027            Reference, Init, ClaferTransition, Elements, TransArrow, PatternScope, Decl, Exp {
028
029        /**
030         * @return where the node is in the source
031         */
032        SourceSpan span();
033    }
034
035    /**
036     * A name as written, e.g., a clafer's name or a local variable.
037     *
038     * @param span where it is
039     * @param text the name
040     */
041    public record Ident(SourceSpan span, String text) implements Node {
042    }
043
044    /**
045     * A model: its declarations in the order they were written.
046     *
047     * @param span the whole source
048     * @param declarations the enumerations and the top-level elements
049     */
050    public record Model(SourceSpan span, List<Declaration> declarations) implements Node {
051
052        public Model {
053            declarations = List.copyOf(declarations);
054        }
055    }
056
057    /**
058     * A declaration at the top level.
059     */
060    public sealed interface Declaration extends Node permits EnumDecl, Element {
061    }
062
063    /**
064     * An enumeration, {@code enum E = a | b}.
065     *
066     * @param span where it is
067     * @param name the name of the enumeration
068     * @param literals its literals
069     */
070    public record EnumDecl(SourceSpan span, Ident name, List<Ident> literals) implements Declaration {
071
072        public EnumDecl {
073            literals = List.copyOf(literals);
074        }
075    }
076
077    /**
078     * An element: a clafer, a use of a clafer, a constraint, an objective
079     * or an assertion.
080     */
081    public sealed interface Element extends Declaration permits Clafer, ClaferUse, Constraint, Goal, Assertion {
082    }
083
084    /**
085     * A clafer, e.g., {@code abstract xor A : B -> int ? = 3 { ... }}.
086     *
087     * @param span where it is
088     * @param isAbstract whether it is written {@code abstract}
089     * @param modifiers its temporal modifiers
090     * @param groupCard its group cardinality, if written
091     * @param name its name
092     * @param superClafer its super clafer, if written
093     * @param reference its reference, if written
094     * @param card its cardinality, if written
095     * @param init its initializer, if written
096     * @param transition its transition, if written
097     * @param elements its elements, if written, in braces or indented
098     */
099    public record Clafer(SourceSpan span, boolean isAbstract, List<TempModifier> modifiers, Optional<GCard> groupCard,
100            Ident name, Optional<Super> superClafer, Optional<Reference> reference, Optional<Card> card,
101            Optional<Init> init, Optional<ClaferTransition> transition, Optional<Elements> elements)
102            implements Element {
103
104        public Clafer {
105            modifiers = List.copyOf(modifiers);
106        }
107    }
108
109    /**
110     * A use of a clafer, {@code `A ? { ... }}.
111     *
112     * @param span where it is
113     * @param name the clafer
114     * @param card its cardinality, if written
115     * @param elements its elements, if written
116     */
117    public record ClaferUse(SourceSpan span, Name name, Optional<Card> card, Optional<Elements> elements)
118            implements Element {
119    }
120
121    /**
122     * A constraint, {@code [ e1 e2 ]}: the conjunction of its expressions.
123     *
124     * @param span where it is
125     * @param exps its expressions
126     */
127    public record Constraint(SourceSpan span, List<Exp> exps) implements Element {
128
129        public Constraint {
130            exps = List.copyOf(exps);
131        }
132    }
133
134    /**
135     * An assertion, {@code assert [ e ]}.
136     *
137     * @param span where it is
138     * @param exps its expressions
139     */
140    public record Assertion(SourceSpan span, List<Exp> exps) implements Element {
141
142        public Assertion {
143            exps = List.copyOf(exps);
144        }
145    }
146
147    /**
148     * An objective, {@code << minimize e >>}.
149     *
150     * @param span where it is
151     * @param kind how it is written
152     * @param exps its expressions
153     */
154    public record Goal(SourceSpan span, GoalKind kind, List<Exp> exps) implements Element {
155
156        public Goal {
157            exps = List.copyOf(exps);
158        }
159    }
160
161    /**
162     * How an objective is written.
163     */
164    public enum GoalKind {
165        MinDeprecated("min"), MaxDeprecated("max"), Minimize("minimize"), Maximize("maximize");
166
167        private final String syntax;
168
169        GoalKind(String syntax) {
170            this.syntax = syntax;
171        }
172
173        /**
174         * @return the keyword after {@code <<}
175         */
176        public String syntax() {
177            return syntax;
178        }
179    }
180
181    /**
182     * A path of names, {@code a\b}.
183     *
184     * @param span where it is
185     * @param path the names
186     */
187    public record Name(SourceSpan span, List<Ident> path) implements Node {
188
189        public Name {
190            path = List.copyOf(path);
191        }
192    }
193
194    /**
195     * A temporal modifier of a clafer.
196     *
197     * @param span where it is
198     * @param kind which one
199     */
200    public record TempModifier(SourceSpan span, TempModifierKind kind) implements Node {
201    }
202
203    /**
204     * The temporal modifiers.
205     */
206    public enum TempModifierKind {
207        Initial("initial"), Final("final"), FinalRef("finalref"), FinalTarget("finaltarget");
208
209        private final String syntax;
210
211        TempModifierKind(String syntax) {
212            this.syntax = syntax;
213        }
214
215        /**
216         * @return the keyword
217         */
218        public String syntax() {
219            return syntax;
220        }
221    }
222
223    /**
224     * A group cardinality: a keyword or an interval.
225     */
226    public sealed interface GCard extends Node permits GroupKeyword, NCard {
227    }
228
229    /**
230     * A group cardinality written as a keyword: {@code xor}, {@code or},
231     * {@code mux} or {@code opt}.
232     *
233     * @param span where it is
234     * @param keyword the keyword
235     */
236    public record GroupKeyword(SourceSpan span, String keyword) implements GCard {
237    }
238
239    /**
240     * A cardinality: {@code ?}, {@code +}, {@code *}, a number or an
241     * interval.
242     */
243    public sealed interface Card extends Node permits CardSymbol, CardNum, NCard {
244    }
245
246    /**
247     * A cardinality written as {@code ?}, {@code +} or {@code *}.
248     *
249     * @param span where it is
250     * @param symbol the symbol
251     */
252    public record CardSymbol(SourceSpan span, String symbol) implements Card {
253    }
254
255    /**
256     * A cardinality written as a number, {@code 2}.
257     *
258     * @param span where it is
259     * @param number the number as written
260     */
261    public record CardNum(SourceSpan span, String number) implements Card {
262    }
263
264    /**
265     * An interval, {@code 2..3} or {@code 2..*}, of a cardinality or of a
266     * group cardinality.
267     *
268     * @param span where it is
269     * @param low the lower bound as written
270     * @param high the upper bound as written, empty for {@code *}
271     */
272    public record NCard(SourceSpan span, String low, Optional<String> high) implements Card, GCard {
273    }
274
275    /**
276     * The super clafer, {@code : e}.
277     *
278     * @param span where it is
279     * @param exp the super clafer
280     */
281    public record Super(SourceSpan span, Exp exp) implements Node {
282    }
283
284    /**
285     * A reference, {@code -> e} to a set or {@code ->> e} to a bag.
286     *
287     * @param span where it is
288     * @param bag whether it is to a bag
289     * @param exp the target
290     */
291    public record Reference(SourceSpan span, boolean bag, Exp exp) implements Node {
292    }
293
294    /**
295     * An initializer, {@code = e} or {@code := e}.
296     *
297     * @param span where it is
298     * @param how how it is written
299     * @param exp the value
300     */
301    public record Init(SourceSpan span, InitHow how, Exp exp) implements Node {
302    }
303
304    /**
305     * How an initializer is written.
306     */
307    public enum InitHow {
308        Constant("="), Default(":="), Each(":= each"), Together(":= together");
309
310        private final String syntax;
311
312        InitHow(String syntax) {
313            this.syntax = syntax;
314        }
315
316        /**
317         * @return the symbol, with its clock if written
318         */
319        public String syntax() {
320            return syntax;
321        }
322    }
323
324    /**
325     * The transition of a clafer, {@code --> e}.
326     *
327     * @param span where it is
328     * @param arrow the arrow
329     * @param exp the expression after it
330     */
331    public record ClaferTransition(SourceSpan span, TransArrow arrow, Exp exp) implements Node {
332    }
333
334    /**
335     * The elements of a clafer, in braces or indented.
336     *
337     * @param span where they are
338     * @param elements the elements
339     */
340    public record Elements(SourceSpan span, List<Element> elements) implements Node {
341
342        public Elements {
343            elements = List.copyOf(elements);
344        }
345    }
346
347    /**
348     * A transition arrow: {@code -->}, {@code -->>} (synchronous), or with a
349     * guard, {@code -[ g ]->} and {@code -[ g ]->>}.
350     *
351     * @param span where it is
352     * @param sync whether it is synchronous
353     * @param guard the guard, if written
354     */
355    public record TransArrow(SourceSpan span, boolean sync, Optional<Exp> guard) implements Node {
356    }
357
358    /**
359     * The scope of a pattern: {@code before e}, {@code after e},
360     * {@code between e and e}, {@code after e until e}.
361     *
362     * @param span where it is
363     * @param kind which one
364     * @param exps its expressions
365     */
366    public record PatternScope(SourceSpan span, ScopeKind kind, List<Exp> exps) implements Node {
367
368        public PatternScope {
369            exps = List.copyOf(exps);
370        }
371    }
372
373    /**
374     * The scopes of a pattern.
375     */
376    public enum ScopeKind {
377        Before, After, BetweenAnd, AfterUntil
378    }
379
380    /**
381     * The declaration of a quantifier, {@code x; y : e}.
382     *
383     * @param span where it is
384     * @param locals the local variables
385     * @param exp the set they range over
386     */
387    public record Decl(SourceSpan span, List<Ident> locals, Exp exp) implements Node {
388
389        public Decl {
390            locals = List.copyOf(locals);
391        }
392    }
393
394    // ------------------------------------------------------------------
395    // Expressions
396    // ------------------------------------------------------------------
397    /**
398     * An expression.
399     */
400    public sealed interface Exp extends Node permits TransitionExp, Quantified, IfThenElse, Let, Pattern, Anchor,
401            Binary, Unary, QuantExp, ClaferId, Literal {
402
403        /**
404         * @return the level of the expression in {@code clafer.cf}, from 0
405         * (a transition) to 27 (a name or a literal)
406         */
407        int level();
408    }
409
410    /**
411     * A transition, {@code e1 --> e2}.
412     *
413     * @param span where it is
414     * @param from the expression before the arrow
415     * @param arrow the arrow
416     * @param to the expression after it
417     */
418    public record TransitionExp(SourceSpan span, Exp from, TransArrow arrow, Exp to) implements Exp {
419
420        @Override
421        public int level() {
422            return 0;
423        }
424    }
425
426    /**
427     * The quantifiers.
428     */
429    public enum Quant {
430        All("all"), No("no"), Not("not"), Lone("lone"), One("one"), Some("some");
431
432        private final String syntax;
433
434        Quant(String syntax) {
435            this.syntax = syntax;
436        }
437
438        /**
439         * @return the keyword
440         */
441        public String syntax() {
442            return syntax;
443        }
444    }
445
446    /**
447     * A quantified expression with a declaration,
448     * {@code some disj x : e | body}.
449     *
450     * @param span where it is
451     * @param quant the quantifier
452     * @param disj whether it is written {@code disj}
453     * @param decl the declaration
454     * @param body the body
455     */
456    public record Quantified(SourceSpan span, Quant quant, boolean disj, Decl decl, Exp body) implements Exp {
457
458        @Override
459        public int level() {
460            return 1;
461        }
462    }
463
464    /**
465     * {@code if c then t else e}.
466     *
467     * @param span where it is
468     * @param condition the condition
469     * @param then the expression if it holds
470     * @param otherwise the expression if it does not
471     */
472    public record IfThenElse(SourceSpan span, Exp condition, Exp then, Exp otherwise) implements Exp {
473
474        @Override
475        public int level() {
476            return 1;
477        }
478    }
479
480    /**
481     * {@code let x = v in body}.
482     *
483     * @param span where it is
484     * @param local the local variable
485     * @param value its value
486     * @param body the body
487     */
488    public record Let(SourceSpan span, Ident local, Exp value, Exp body) implements Exp {
489
490        @Override
491        public int level() {
492            return 1;
493        }
494    }
495
496    /**
497     * The behavioral patterns.
498     */
499    public enum PatternKind {
500        Never, Sometime, LessOrOnce, Always, Precede, Follow
501    }
502
503    /**
504     * A behavioral pattern, e.g., {@code never e after s}, or
505     * {@code a must precede b}.
506     *
507     * @param span where it is
508     * @param kind which one
509     * @param exps the expression, or the two of precede and follow
510     * @param scope its scope, if written
511     */
512    public record Pattern(SourceSpan span, PatternKind kind, List<Exp> exps, Optional<PatternScope> scope)
513            implements Exp {
514
515        public Pattern {
516            exps = List.copyOf(exps);
517        }
518
519        @Override
520        public int level() {
521            return 2;
522        }
523    }
524
525    /**
526     * {@code initially e} or {@code finally e}.
527     *
528     * @param span where it is
529     * @param initially whether it is {@code initially}
530     * @param exp the expression
531     */
532    public record Anchor(SourceSpan span, boolean initially, Exp exp) implements Exp {
533
534        @Override
535        public int level() {
536            return 2;
537        }
538    }
539
540    /**
541     * The binary operators, with their symbols and levels. Each is left
542     * associative: its right operand is one level higher.
543     */
544    public enum BinaryOp {
545        Iff("<=>", 3), Implies("=>", 4), Or("||", 5), Xor("xor", 6), And("&&", 7),
546        LtlU("U", 8), Until("until", 8), Since("since", 8), Triggered("triggered", 8),
547        LtlW("W", 9), WeakUntil("weakuntil", 9),
548        Lt("<", 15), Gt(">", 15), Eq("=", 15), Lte("<=", 15), Gte(">=", 15), Neq("!=", 15), In("in", 15),
549        NotIn("not in", 15),
550        Add("+", 17), Sub("-", 17), Mul("*", 18), Div("/", 18), Rem("%", 18),
551        Domain("<:", 21), Range(":>", 22), Union("++", 23), UnionCom(",", 23), Difference("--", 24),
552        Intersection("**", 25), IntersectionDeprecated("&", 26), Join(".", 26);
553
554        private final String syntax;
555        private final int level;
556
557        BinaryOp(String syntax, int level) {
558            this.syntax = syntax;
559            this.level = level;
560        }
561
562        /**
563         * @return the operator as written
564         */
565        public String syntax() {
566            return syntax;
567        }
568
569        /**
570         * @return the level of {@code clafer.cf}
571         */
572        public int level() {
573            return level;
574        }
575    }
576
577    /**
578     * A binary expression.
579     *
580     * @param span where it is
581     * @param op the operator
582     * @param left the left operand
583     * @param right the right operand
584     */
585    public record Binary(SourceSpan span, BinaryOp op, Exp left, Exp right) implements Exp {
586
587        @Override
588        public int level() {
589            return op.level();
590        }
591    }
592
593    /**
594     * The prefix operators, with their symbols, levels and the levels of
595     * their operands.
596     */
597    public enum UnaryOp {
598        LtlF("F", 10, 10), Eventually("eventually", 10, 10), LtlG("G", 10, 10), Globally("globally", 10, 10),
599        LtlX("X", 10, 10), Next("next", 10, 10), Previous("previous", 10, 10), Once("once", 10, 10),
600        Historically("historically", 10, 10),
601        Neg("!", 11, 11),
602        GMax("max", 19, 20), GMin("min", 19, 20),
603        Sum("sum", 20, 21), Product("product", 20, 21), Card("#", 20, 21), Minus("-", 20, 21);
604
605        private final String syntax;
606        private final int level;
607        private final int operandLevel;
608
609        UnaryOp(String syntax, int level, int operandLevel) {
610            this.syntax = syntax;
611            this.level = level;
612            this.operandLevel = operandLevel;
613        }
614
615        /**
616         * @return the operator as written
617         */
618        public String syntax() {
619            return syntax;
620        }
621
622        /**
623         * @return the level of {@code clafer.cf}
624         */
625        public int level() {
626            return level;
627        }
628
629        /**
630         * @return the level of the operand
631         */
632        public int operandLevel() {
633            return operandLevel;
634        }
635    }
636
637    /**
638     * A prefix expression.
639     *
640     * @param span where it is
641     * @param op the operator
642     * @param exp the operand
643     */
644    public record Unary(SourceSpan span, UnaryOp op, Exp exp) implements Exp {
645
646        @Override
647        public int level() {
648            return op.level();
649        }
650    }
651
652    /**
653     * A quantified expression without a declaration, {@code some e}.
654     *
655     * @param span where it is
656     * @param quant the quantifier, not {@link Quant#All}
657     * @param exp the expression
658     */
659    public record QuantExp(SourceSpan span, Quant quant, Exp exp) implements Exp {
660
661        @Override
662        public int level() {
663            return 16;
664        }
665    }
666
667    /**
668     * A name in an expression.
669     *
670     * @param span where it is
671     * @param name the name
672     */
673    public record ClaferId(SourceSpan span, Name name) implements Exp {
674
675        @Override
676        public int level() {
677            return 27;
678        }
679    }
680
681    /**
682     * The kinds of literals.
683     */
684    public enum LiteralKind {
685        Int, Double, Real, Str
686    }
687
688    /**
689     * A literal: an integer, a double, a real or a string, as written.
690     *
691     * @param span where it is
692     * @param kind its kind
693     * @param text the literal as written, a string with its quotes and
694     * escapes
695     */
696    public record Literal(SourceSpan span, LiteralKind kind, String text) implements Exp {
697
698        @Override
699        public int level() {
700            return 27;
701        }
702    }
703}