001package org.clafer.frontend;
002
003import java.util.List;
004import java.util.Optional;
005import java.util.OptionalInt;
006
007/**
008 * The explicit IR: one tree for the rich and the core explicit language of
009 * Clafer, as the Clafer compiler prints them ({@code clafer -m clafer}, with
010 * {@code --core} for the core). The core is a strict subset of the rich
011 * language, so a core model is a rich model without rich nodes. Whether a node
012 * is rich is a property of its type ({@link Node#isRich()}), never of a field
013 * value: every rich part of a declaration is a node of its own, e.g., a
014 * {@link Modifier} or an {@link Initializer} of a {@link ClaferDecl}, which is
015 * core. {@link Core#richNodes} lists the rich nodes of a tree.
016 * <p>
017 * The tree is the text: names are not resolved, and every declaration and
018 * constraint stays where it was written, so that {@link ExplicitPrinter}
019 * prints it back as it was read. Resolving the names is the job of what reads
020 * the tree, e.g., chocosolver's {@code ToAst}.
021 * <p>
022 * The records are immutable; their lists are unmodifiable copies.
023 */
024public final class Ir {
025
026    private Ir() {
027    }
028
029    /**
030     * A node of the tree.
031     */
032    public sealed interface Node permits Model, Element, Exp, Name, Card, RefDecl, Modifier, Initializer,
033            AbstractMultiplicity, Objective, Assertion, Decl {
034
035        /**
036         * @return where the node is in the source
037         */
038        SourceSpan span();
039
040        /**
041         * @return whether nodes of this type are outside the core, a constant
042         * of the type
043         */
044        default boolean isRich() {
045            return false;
046        }
047    }
048
049    // ------------------------------------------------------------------
050    // The model
051    // ------------------------------------------------------------------
052    /**
053     * The options of the first line, {@code //# OPTIONS --explicit}, as the
054     * compiler writes them.
055     *
056     * @param core whether the model is an explicit core model,
057     * {@code --core}
058     * @param traceLength the trace length of a temporal model,
059     * {@code --tl=N}
060     */
061    public record Options(boolean core, OptionalInt traceLength) {
062
063        /**
064         * The options of a static rich explicit model.
065         */
066        public static final Options Rich = new Options(false, OptionalInt.empty());
067    }
068
069    /**
070     * A model: its declarations and constraints in the order they were
071     * written, then its objectives and assertions, which the compiler prints
072     * at the end.
073     *
074     * @param span the whole source
075     * @param options the options of the first line
076     * @param elements the top-level clafers, enumerations and constraints
077     * @param objectives the objectives
078     * @param assertions the assertions, quantified at the top level
079     */
080    public record Model(SourceSpan span, Options options, List<Element> elements, List<Objective> objectives,
081            List<Assertion> assertions) implements Node {
082
083        public Model {
084            elements = List.copyOf(elements);
085            objectives = List.copyOf(objectives);
086            assertions = List.copyOf(assertions);
087        }
088    }
089
090    /**
091     * Where a clafer or constraint of the core comes from, as
092     * {@code --record-provenance} writes it: the rich construct that a
093     * lowering made it from, and the position of that construct, e.g.,
094     * {@code // final, model.cfr:56:5}. Not a node: it is read from a
095     * comment, and no backend needs it.
096     *
097     * @param construct the rich construct, e.g., {@code final} or
098     * {@code never between}
099     * @param position its position, if the compiler knew one
100     */
101    public record Origin(String construct, Optional<Position> position) {
102    }
103
104    /**
105     * A position in a source file, as in the compiler's messages.
106     *
107     * @param file the file name
108     * @param line the line
109     * @param column the column
110     */
111    public record Position(String file, int line, int column) {
112
113        @Override
114        public String toString() {
115            return file + ":" + line + ":" + column;
116        }
117    }
118
119    /**
120     * A name as written: of a clafer, a variable, or a type.
121     *
122     * @param span where it is
123     * @param text the name
124     */
125    public record Name(SourceSpan span, String text) implements Node {
126    }
127
128    /**
129     * A cardinality, {@code low..high}, or {@code low..*}.
130     *
131     * @param span where it is
132     * @param low the lower bound
133     * @param high the upper bound, or {@link #Unbounded}
134     */
135    public record Card(SourceSpan span, int low, int high) implements Node {
136
137        /**
138         * The upper bound {@code *}.
139         */
140        public static final int Unbounded = -1;
141
142        public boolean isUnbounded() {
143            return high == Unbounded;
144        }
145
146        /**
147         * @return whether this is {@code 0..*}
148         */
149        public boolean isAny() {
150            return low == 0 && high == Unbounded;
151        }
152
153        @Override
154        public String toString() {
155            return low + ".." + (high == Unbounded ? "*" : Integer.toString(high));
156        }
157    }
158
159    // ------------------------------------------------------------------
160    // Elements
161    // ------------------------------------------------------------------
162    /**
163     * A declaration or constraint of a model or of a clafer.
164     */
165    public sealed interface Element extends Node permits ClaferDecl, Constraint, EnumDecl, RootBlock {
166    }
167
168    /**
169     * A clafer:
170     * {@code [abstract] [modifiers] gcard name [: super] [-> | ->> target] card [initializer] { elements }}.
171     * The core parts are its fields; the rich ones are nodes of their own.
172     *
173     * @param span from its first token to its closing brace
174     * @param isAbstract whether it is abstract
175     * @param modifiers its temporal modifiers, rich
176     * @param groupCard its group card, as written
177     * @param name its name, the compiler's UID
178     * @param superName its super clafer
179     * @param ref its own reference
180     * @param card its multiplicity as the core has it: {@code 0..*} for a
181     * top-level abstract clafer, whose written bound is its
182     * {@code abstractMultiplicity}
183     * @param abstractMultiplicity the written bound of a top-level abstract
184     * clafer, {@code abstract Tools 3..6}, rich
185     * @param initializer its initializer, rich
186     * @param elements its constraints and subclafers, in the order written
187     * @param origin the rich construct it was lowered from
188     */
189    public record ClaferDecl(SourceSpan span, boolean isAbstract, List<Modifier> modifiers, Card groupCard,
190            Name name, Optional<Name> superName, Optional<RefDecl> ref, Card card,
191            Optional<AbstractMultiplicity> abstractMultiplicity, Optional<Initializer> initializer,
192            List<Element> elements, Optional<Origin> origin) implements Element {
193
194        public ClaferDecl {
195            modifiers = List.copyOf(modifiers);
196            elements = List.copyOf(elements);
197        }
198    }
199
200    /**
201     * A reference: {@code -> target}, a set, or {@code ->> target}, a bag.
202     *
203     * @param span from the arrow to the target
204     * @param isSet whether the reference is {@code ->}, whose targets are
205     * distinct
206     * @param target the target: a clafer, or {@code int}, {@code string},
207     * {@code real}, {@code double}, {@code decimal}
208     */
209    public record RefDecl(SourceSpan span, boolean isSet, Name target) implements Node {
210    }
211
212    /**
213     * A temporal modifier of a clafer, rich.
214     *
215     * @param span where it is
216     * @param kind which one
217     */
218    public record Modifier(SourceSpan span, ModifierKind kind) implements Node {
219
220        @Override
221        public boolean isRich() {
222            return true;
223        }
224    }
225
226    /**
227     * The temporal modifiers, by their keywords.
228     */
229    public enum ModifierKind {
230        INITIAL("initial"), FINAL("final"), FINALREF("finalref"), FINALTARGET("finaltarget");
231
232        private final String keyword;
233
234        ModifierKind(String keyword) {
235            this.keyword = keyword;
236        }
237
238        public String keyword() {
239            return keyword;
240        }
241    }
242
243    /**
244     * An initializer, rich: {@code = value}, or {@code := each value} or
245     * {@code := together value}, with its clock written out
246     * (kbak/clafer-semantics#194).
247     *
248     * @param span from the operator to the end of the value
249     * @param kind the operator and clock
250     * @param value the value
251     */
252    public record Initializer(SourceSpan span, InitKind kind, Exp value) implements Node {
253
254        @Override
255        public boolean isRich() {
256            return true;
257        }
258    }
259
260    /**
261     * The initializers, by their syntax.
262     */
263    public enum InitKind {
264        /**
265         * {@code =}: the value in every state.
266         */
267        FIXED("="),
268        /**
269         * {@code := each}: the value when each instance is born.
270         */
271        EACH(":= each"),
272        /**
273         * {@code := together}: the value of the set when the parent is born.
274         */
275        TOGETHER(":= together");
276
277        private final String syntax;
278
279        InitKind(String syntax) {
280            this.syntax = syntax;
281        }
282
283        public String syntax() {
284            return syntax;
285        }
286    }
287
288    /**
289     * The written bound of a top-level abstract clafer, which counts all its
290     * instances, rich: {@code abstract Tools 3..6}. A nested abstract
291     * multiplicity is core, the clafer's {@code card}.
292     *
293     * @param span where the bound is
294     * @param card the bound
295     */
296    public record AbstractMultiplicity(SourceSpan span, Card card) implements Node {
297
298        @Override
299        public boolean isRich() {
300            return true;
301        }
302    }
303
304    /**
305     * A constraint, {@code [ exp ]}.
306     *
307     * @param span from the bracket to the bracket
308     * @param exp the formula
309     * @param origin the rich construct it was lowered from
310     */
311    public record Constraint(SourceSpan span, Exp exp, Optional<Origin> origin) implements Element {
312    }
313
314    /**
315     * An enumeration, rich: {@code enum E = a | b}, at the top level.
316     *
317     * @param span the declaration
318     * @param name the enumeration
319     * @param literals its literals, in order
320     */
321    public record EnumDecl(SourceSpan span, Name name, List<Name> literals) implements Element {
322
323        public EnumDecl {
324            literals = List.copyOf(literals);
325        }
326
327        @Override
328        public boolean isRich() {
329            return true;
330        }
331    }
332
333    /**
334     * Constraints directly under the root, {@code root { [ exp ] }}, as
335     * chocosolver's {@code AstPrinter} prints a model of its Java API that
336     * has them; Clafer has none.
337     *
338     * @param span the block
339     * @param constraints the constraints
340     */
341    public record RootBlock(SourceSpan span, List<Constraint> constraints) implements Element {
342
343        public RootBlock {
344            constraints = List.copyOf(constraints);
345        }
346    }
347
348    /**
349     * An objective, {@code << max exp >>} or {@code << min exp >>}.
350     *
351     * @param span the objective
352     * @param maximize whether it maximizes
353     * @param exp what it optimizes
354     */
355    public record Objective(SourceSpan span, boolean maximize, Exp exp) implements Node {
356    }
357
358    /**
359     * An assertion, {@code assert [ exp ]}.
360     *
361     * @param span the assertion
362     * @param exp the formula
363     * @param origin the rich construct it was lowered from
364     */
365    public record Assertion(SourceSpan span, Exp exp, Optional<Origin> origin) implements Node {
366    }
367
368    // ------------------------------------------------------------------
369    // Expressions
370    // ------------------------------------------------------------------
371    /**
372     * An expression. The explicit languages parenthesize every operand that is
373     * not an atom or a navigation, so the tree has no precedence to keep.
374     */
375    public sealed interface Exp extends Node permits This, NameExp, IntLit, DecimalLit, DoubleLit, StringLit,
376            NoClafer, Join, Dref, ParentOf, Unary, Binary, IfThenElse, Quantified, QuantifiedSet, Call, RelationOf, Cast,
377            Connected, ConstantSet, Temporal, Anchor, Pattern, Transition {
378    }
379
380    /**
381     * {@code this}.
382     */
383    public record This(SourceSpan span) implements Exp {
384    }
385
386    /**
387     * A name in an expression: a clafer, all its instances or, on the right
388     * of a navigation, its relation, or a variable.
389     *
390     * @param span where it is
391     * @param name the name
392     */
393    public record NameExp(SourceSpan span, String name) implements Exp {
394    }
395
396    /**
397     * An integer, {@code -3} with its sign.
398     */
399    public record IntLit(SourceSpan span, long value) implements Exp {
400    }
401
402    /**
403     * A decimal as written, e.g., {@code 19.99} or {@code -0.5}.
404     */
405    public record DecimalLit(SourceSpan span, String text) implements Exp {
406    }
407
408    /**
409     * A double as written, with its exponent, e.g., {@code 1.2e2}.
410     */
411    public record DoubleLit(SourceSpan span, String text) implements Exp {
412    }
413
414    /**
415     * A string literal as written, with its quotes and escapes.
416     */
417    public record StringLit(SourceSpan span, String text) implements Exp {
418    }
419
420    /**
421     * {@code noclafer}, the empty set.
422     */
423    public record NoClafer(SourceSpan span) implements Exp {
424    }
425
426    /**
427     * A navigation, {@code left.right}: the right is a name (a child
428     * relation), or in chocosolver's printing a relation or a parenthesized
429     * set.
430     */
431    public record Join(SourceSpan span, Exp left, Exp right) implements Exp {
432    }
433
434    /**
435     * {@code left.dref}.
436     */
437    public record Dref(SourceSpan span, Exp left) implements Exp {
438    }
439
440    /**
441     * {@code left.parent}.
442     */
443    public record ParentOf(SourceSpan span, Exp left) implements Exp {
444    }
445
446    /**
447     * A prefix operator.
448     */
449    public record Unary(SourceSpan span, UnaryOp op, Exp arg) implements Exp {
450    }
451
452    /**
453     * The prefix operators. {@code sum} and {@code product} are printed with
454     * the {@code .dref} they take from each instance, which is not in the
455     * tree: {@code sum x.dref} is {@code Unary(SUM, x)}.
456     */
457    public enum UnaryOp {
458        NOT("!"), MINUS("-"), CARD("#"), SUM("sum "), PRODUCT("product "), MAX("max "), MIN("min "),
459        LENGTH("length "), INVERSE("~"), CLOSURE("^"), REFLEXIVE_CLOSURE("*");
460
461        private final String syntax;
462
463        UnaryOp(String syntax) {
464            this.syntax = syntax;
465        }
466
467        /**
468         * @return the operator as printed before its operand, with its space
469         */
470        public String syntax() {
471            return syntax;
472        }
473    }
474
475    /**
476     * A chain of one binary operator: {@code a op b op c}. The compiler
477     * prints two operands; chocosolver's printer chains the associative
478     * ones.
479     */
480    public record Binary(SourceSpan span, BinaryOp op, List<Exp> operands) implements Exp {
481
482        public Binary {
483            operands = List.copyOf(operands);
484        }
485    }
486
487    /**
488     * The binary operators, by their syntax.
489     */
490    public enum BinaryOp {
491        ADD("+"), SUB("-"), MUL("*"), DIV("/"), DECIMAL_MUL("*."), DECIMAL_DIV("/."), MOD("%"),
492        AND("&&"), OR("||"), IMPLIES("=>"), IFF("<=>"), XOR("xor"),
493        LT("<"), LE("<="), GT(">"), GE(">="), EQ("="), NE("!="), IN("in"), NOT_IN("not in"),
494        UNION("++"), DIFF("--"), INTER("**"), DOMAIN("<:"), RANGE(":>");
495
496        private final String syntax;
497
498        BinaryOp(String syntax) {
499            this.syntax = syntax;
500        }
501
502        public String syntax() {
503            return syntax;
504        }
505    }
506
507    /**
508     * {@code if c then a else b}, a formula or a set.
509     */
510    public record IfThenElse(SourceSpan span, Exp condition, Exp then, Exp otherwise) implements Exp {
511    }
512
513    /**
514     * {@code q decls | body}.
515     */
516    public record Quantified(SourceSpan span, Quantifier quantifier, List<Decl> decls, Exp body) implements Exp {
517
518        public Quantified {
519            decls = List.copyOf(decls);
520        }
521    }
522
523    /**
524     * The quantifiers.
525     */
526    public enum Quantifier {
527        ALL("all"), SOME("some"), NO("no"), LONE("lone"), ONE("one");
528
529        private final String keyword;
530
531        Quantifier(String keyword) {
532            this.keyword = keyword;
533        }
534
535        public String keyword() {
536            return keyword;
537        }
538    }
539
540    /**
541     * The declarations of a quantifier, {@code [disj] x; y : set}.
542     */
543    public record Decl(SourceSpan span, boolean disjoint, List<Name> locals, Exp set) implements Node {
544
545        public Decl {
546            locals = List.copyOf(locals);
547        }
548    }
549
550    /**
551     * A quantifier over a set, without variables: {@code some x}, {@code no x},
552     * {@code lone x}, {@code one x}, {@code all x}. It is a formula on the set
553     * as a whole, e.g., {@code some x} holds if x has an element, which needs
554     * no count.
555     */
556    public record QuantifiedSet(SourceSpan span, Quantifier quantifier, Exp set) implements Exp {
557    }
558
559    /**
560     * A function of strings, {@code concat(a, b)}, {@code prefix(a, b)} or
561     * {@code suffix(a, b)}.
562     */
563    public record Call(SourceSpan span, String function, List<Exp> args) implements Exp {
564
565        public Call {
566            args = List.copyOf(args);
567        }
568    }
569
570    /**
571     * {@code dref(c)} or {@code parent(c)}, a relation of a clafer, as
572     * chocosolver's printer writes it.
573     */
574    public record RelationOf(SourceSpan span, boolean isDref, Name clafer) implements Exp {
575    }
576
577    /**
578     * {@code upcast(e, T)} or {@code downcast(e, T)}, as chocosolver's
579     * printer writes the casts of its analysis.
580     */
581    public record Cast(SourceSpan span, boolean up, Exp base, List<Name> type) implements Exp {
582
583        public Cast {
584            type = List.copyOf(type);
585        }
586    }
587
588    /**
589     * {@code connected(nodes, relation, directed)}.
590     */
591    public record Connected(SourceSpan span, Exp nodes, Exp relation, boolean directed) implements Exp {
592    }
593
594    /**
595     * {@code {[1, 2], [3, 4]} :: T * U}, a constant set of chocosolver's
596     * printer: one row per column of the type.
597     */
598    public record ConstantSet(SourceSpan span, List<List<Integer>> rows, List<Name> type) implements Exp {
599
600        public ConstantSet {
601            rows = rows.stream().map(List::copyOf).toList();
602            type = List.copyOf(type);
603        }
604    }
605
606    /**
607     * A temporal operator of the core: {@code X}, {@code F}, {@code G},
608     * {@code previous}, {@code once}, {@code historically} on one formula,
609     * {@code U}, {@code W}, {@code since}, {@code triggered} between two.
610     */
611    public record Temporal(SourceSpan span, TemporalOp op, List<Exp> args) implements Exp {
612
613        public Temporal {
614            args = List.copyOf(args);
615        }
616    }
617
618    /**
619     * The temporal operators of the core.
620     */
621    public enum TemporalOp {
622        X("X", 1), F("F", 1), G("G", 1), PREVIOUS("previous", 1), ONCE("once", 1), HISTORICALLY("historically", 1),
623        U("U", 2), W("W", 2), SINCE("since", 2), TRIGGERED("triggered", 2);
624
625        private final String keyword;
626        private final int arity;
627
628        TemporalOp(String keyword, int arity) {
629            this.keyword = keyword;
630            this.arity = arity;
631        }
632
633        public String keyword() {
634            return keyword;
635        }
636
637        public int arity() {
638            return arity;
639        }
640    }
641
642    /**
643     * An anchor, rich: {@code initially p}, at the birth of the context, or
644     * {@code finally p}, at its death.
645     */
646    public record Anchor(SourceSpan span, boolean initially, Exp body) implements Exp {
647
648        @Override
649        public boolean isRich() {
650            return true;
651        }
652    }
653
654    /**
655     * A behavioral pattern of Dwyer et al.'s catalogue, rich, e.g.,
656     * {@code never p between q and r} or {@code s must precede p}.
657     *
658     * @param span the pattern
659     * @param kind the pattern
660     * @param scope where it holds
661     * @param args the formulas of the pattern ({@code p}, or {@code s} and
662     * {@code p}), then those of the scope
663     */
664    public record Pattern(SourceSpan span, PatternKind kind, PatternScope scope, List<Exp> args) implements Exp {
665
666        public Pattern {
667            args = List.copyOf(args);
668        }
669
670        @Override
671        public boolean isRich() {
672            return true;
673        }
674    }
675
676    /**
677     * The patterns.
678     */
679    public enum PatternKind {
680        NEVER("never", 1), SOMETIME("sometime", 1), LONCE("lonce", 1), ALWAYS("always", 1),
681        PRECEDE("precede", 2), FOLLOW("follow", 2);
682
683        private final String keyword;
684        private final int arity;
685
686        PatternKind(String keyword, int arity) {
687            this.keyword = keyword;
688            this.arity = arity;
689        }
690
691        public String keyword() {
692            return keyword;
693        }
694
695        /**
696         * @return the number of formulas of the pattern itself
697         */
698        public int arity() {
699            return arity;
700        }
701    }
702
703    /**
704     * The scopes of a pattern.
705     */
706    public enum PatternScope {
707        GLOBALLY(0), BEFORE(1), AFTER(1), BETWEEN(2), AFTER_UNTIL(2);
708
709        private final int arity;
710
711        PatternScope(int arity) {
712            this.arity = arity;
713        }
714
715        /**
716         * @return the number of formulas of the scope
717         */
718        public int arity() {
719            return arity;
720        }
721    }
722
723    /**
724     * A transition, rich: {@code a --> b}, {@code a -[g]-> b},
725     * {@code a -->> b} or {@code a -[g]->> b}, whose target may be a chain
726     * of transitions.
727     */
728    public record Transition(SourceSpan span, boolean sync, Exp from, Optional<Exp> guard, Exp to) implements Exp {
729
730        @Override
731        public boolean isRich() {
732            return true;
733        }
734    }
735}