001package org.clafer.frontend;
002
003import java.util.List;
004import java.util.Map;
005import org.clafer.frontend.Symbols.ClaferSymbol;
006
007/**
008 * What the names of a model refer to, for the language server: the clafers,
009 * whose {@link ClaferSymbol#nameSpan()} is where each is declared, and the
010 * clafer that each written name refers to, by the span of the name.
011 * <p>
012 * The names are those of the constraints, assertions, objectives, initial
013 * values and reference targets, as the resolver resolves them, and those of
014 * the supers and the references to a clafer by name, as the symbols resolve
015 * them. In a path {@code a.b} or
016 * {@code A\b}, each name has its own span. The special names ({@code this},
017 * {@code parent}, {@code dref}, ...), the primitive types and the locals of
018 * quantifiers and {@code let} are not in it. The spans are in the lines of
019 * the model, the files of its imports first ({@link ModelFiles#position}).
020 *
021 * @param clafers the clafers of the model, enumerations and their literals
022 * included, in declaration order
023 * @param uses the clafer each written name refers to, by the name's span
024 */
025public record Names(List<ClaferSymbol> clafers, Map<SourceSpan, ClaferSymbol> uses) {
026
027    /**
028     * The names of a model that has errors before the resolver.
029     */
030    public static final Names None = new Names(List.of(), Map.of());
031
032    public Names {
033        clafers = List.copyOf(clafers);
034        uses = java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(uses));
035    }
036
037    /**
038     * @param name a word
039     * @return whether a clafer or a local can be named so: it lexes as one
040     * name, and it is neither a reserved word nor one of the words that no
041     * clafer can be named
042     */
043    public static boolean isClaferName(String name) {
044        ClaferLexer.Result lexed = ClaferLexer.lex(name);
045        return lexed.diagnostics().isEmpty() && lexed.others().isEmpty() && lexed.tokens().size() == 2
046                && lexed.tokens().get(0).kind() == TokenKind.WORD && lexed.tokens().get(0).text().equals(name)
047                && !ModelChecks.KeywordIdents.contains(name);
048    }
049
050    /**
051     * The names of a model: the uses that the resolver found, and the supers.
052     */
053    static Names of(Symbols.Result symbols, Map<SourceSpan, ClaferSymbol> resolved) {
054        Map<SourceSpan, ClaferSymbol> uses = new java.util.LinkedHashMap<>(resolved);
055        for (ClaferSymbol c : symbols.all()) {
056            if (c.superClafer().isPresent() && c.superExp().isPresent()) {
057                superPath(symbols, c.superExp().get(), uses);
058                lastName(c.superExp().get()).ifPresent(span -> uses.put(span, c.superClafer().get()));
059            }
060            // a reference to a clafer by its name, which the symbols resolve
061            c.reference().ifPresent(r -> {
062                List<Syntax.Ident> path = new java.util.ArrayList<>();
063                if (r.clafer().isPresent() && flatten(r.target(), path)
064                        && path.get(path.size() - 1).text().equals(r.clafer().get().name())) {
065                    superPath(symbols, r.target(), uses);
066                    uses.putIfAbsent(path.get(path.size() - 1).span(), r.clafer().get());
067                }
068            });
069        }
070        return new Names(symbols.all(), uses);
071    }
072
073    /**
074     * The names before the last of a path of a super or a reference,
075     * {@code A} in {@code : A.B}: a top-level clafer, then a child of the clafer before,
076     * its own or an inherited one.
077     */
078    private static void superPath(Symbols.Result symbols, Syntax.Exp e, Map<SourceSpan, ClaferSymbol> uses) {
079        List<Syntax.Ident> path = new java.util.ArrayList<>();
080        if (!flatten(e, path) || path.size() < 2) {
081            return;
082        }
083        List<ClaferSymbol> at = symbols.topLevel().stream().filter(c -> c.name().equals(path.get(0).text())).toList();
084        for (int i = 0; i < path.size() - 1 && at.size() == 1; i++) {
085            ClaferSymbol c = at.get(0);
086            uses.putIfAbsent(path.get(i).span(), c);
087            String next = path.get(i + 1).text();
088            List<ClaferSymbol> children = new java.util.ArrayList<>();
089            java.util.Set<ClaferSymbol> seen = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
090            for (ClaferSymbol h = c; h != null && seen.add(h); h = h.superClafer().orElse(null)) {
091                h.children().stream().filter(x -> x.name().equals(next)).forEach(children::add);
092            }
093            at = children;
094        }
095    }
096
097    /**
098     * The names of a path {@code A.B.C}, or false if it is not one.
099     */
100    private static boolean flatten(Syntax.Exp e, List<Syntax.Ident> out) {
101        return switch (e) {
102            case Syntax.ClaferId id -> {
103                out.add(id.name().path().get(id.name().path().size() - 1));
104                yield true;
105            }
106            case Syntax.Binary b when b.op() == Syntax.BinaryOp.Join -> flatten(b.left(), out) && flatten(b.right(), out);
107            default -> false;
108        };
109    }
110
111    /**
112     * The span of the last name of a super, {@code B} in {@code : B} or in
113     * {@code : A.B}.
114     */
115    private static java.util.Optional<SourceSpan> lastName(Syntax.Exp e) {
116        return switch (e) {
117            case Syntax.ClaferId id -> java.util.Optional.of(id.name().path().get(id.name().path().size() - 1).span());
118            case Syntax.Binary b when b.op() == Syntax.BinaryOp.Join -> lastName(b.right());
119            default -> java.util.Optional.empty();
120        };
121    }
122}