001package org.clafer.frontend;
002
003import java.util.ArrayDeque;
004import java.util.ArrayList;
005import java.util.Collections;
006import java.util.Deque;
007import java.util.HashMap;
008import java.util.List;
009import java.util.Map;
010
011/**
012 * Turns indentation into blocks, as the compiler's layout resolver does
013 * ({@code LayoutResolver.resolveLayout}): a line indented more than the line
014 * before opens a block ({@link TokenKind#INDENT}), a line indented less
015 * closes the blocks it leaves ({@link TokenKind#DEDENT}), and a line at the
016 * indentation of a sibling is separated from the line before
017 * ({@link TokenKind#SEPARATOR}).
018 * <p>
019 * The rules are the compiler's, quirks included, so that the parser sees the
020 * tokens that the compiler's parser sees:
021 * <ul>
022 * <li>layout is off on a line that starts inside {@code [ ]} or
023 * {@code { }};</li>
024 * <li>a line that starts with {@code {} or {@code }} has no layout;</li>
025 * <li>a line that starts with a comment or an escape is indented at the
026 * column of the first of them, even one that starts on an earlier line;</li>
027 * <li>a model whose brackets are open by more than one at its end has
028 * {@code ']' bracket missing}.</li>
029 * </ul>
030 * An inserted token has an empty span where the compiler puts it: after the
031 * token before it, past one space.
032 */
033public final class Layout {
034
035    /**
036     * The tokens with the layout made explicit.
037     *
038     * @param tokens the tokens for the parser, ending with
039     * {@link TokenKind#EOF}
040     * @param diagnostics the errors
041     */
042    public record Result(List<Token> tokens, List<Diagnostic> diagnostics) {
043    }
044
045    private Layout() {
046    }
047
048    /**
049     * Where a line starts: the column that gives its indentation, and how
050     * deep in brackets it starts.
051     */
052    private record NewLine(int column, int depth) {
053    }
054
055    /**
056     * Resolves the layout of the tokens of a model.
057     *
058     * @param lexed the tokens, comments and escapes of {@link ClaferLexer}
059     * @return the tokens with the blocks and separators of the layout
060     */
061    public static Result resolve(ClaferLexer.Result lexed) {
062        List<Token> tokens = lexed.tokens().subList(0, lexed.tokens().size() - 1);
063        Token eof = lexed.tokens().get(lexed.tokens().size() - 1);
064        List<Diagnostic> diagnostics = new ArrayList<>();
065        List<Object> marked = addNewLines(tokens, lexed.others(), diagnostics);
066        List<Token> out = new ArrayList<>();
067        Deque<Integer> levels = new ArrayDeque<>();
068        levels.push(1);
069        NewLine lastNewLine = null;
070        for (Object item : marked) {
071            if (item instanceof NewLine newLine) {
072                lastNewLine = newLine;
073                continue;
074            }
075            Token t = (Token) item;
076            if (lastNewLine != null && lastNewLine.depth() <= 0) {
077                int level = lastNewLine.column();
078                if (level > levels.peek()) {
079                    levels.push(level);
080                    out.add(inserted(TokenKind.INDENT, "{", out));
081                } else if (level == levels.peek()) {
082                    out.add(inserted(TokenKind.SEPARATOR, "", out));
083                } else {
084                    while (level < levels.peek()) {
085                        levels.pop();
086                        out.add(inserted(TokenKind.DEDENT, "}", out));
087                    }
088                    out.add(inserted(TokenKind.SEPARATOR, "", out));
089                }
090                lastNewLine = null;
091            }
092            out.add(t);
093        }
094        while (levels.size() > 1) {
095            levels.pop();
096            out.add(inserted(TokenKind.DEDENT, "}", out));
097        }
098        out.add(eof);
099        return new Result(Collections.unmodifiableList(out), Collections.unmodifiableList(diagnostics));
100    }
101
102    /**
103     * A token that the layout inserts, after the token before it past one
104     * space ({@code LayoutResolver.nextPos}).
105     */
106    private static Token inserted(TokenKind kind, String text, List<Token> out) {
107        if (out.isEmpty()) {
108            return new Token(kind, text, SourceSpan.at(1, 1));
109        }
110        Token before = out.get(out.size() - 1);
111        int column = before.span().column() + before.text().length() + 1;
112        return new Token(kind, text, SourceSpan.at(before.span().line(), column));
113    }
114
115    /**
116     * The tokens, with a {@link NewLine} before each token that starts a
117     * line, except a line that starts with {@code {} or {@code }}
118     * ({@code LayoutResolver.addNewLines}).
119     */
120    private static List<Object> addNewLines(List<Token> tokens, List<Token> others, List<Diagnostic> diagnostics) {
121        List<Object> out = new ArrayList<>();
122        if (tokens.isEmpty()) {
123            return out;
124        }
125        Map<Integer, int[]> firstOther = firstOtherOnLine(others);
126        int depth = tokens.get(0).isSymbol("[") ? 1 : 0;
127        for (int i = 0; i < tokens.size(); i++) {
128            Token t0 = tokens.get(i);
129            out.add(t0);
130            if (i + 1 == tokens.size()) {
131                if (depth != 0 && depth != 1) {
132                    diagnostics.add(new Diagnostic(SourceSpan.at(t0.span().line(), t0.span().column()),
133                            "']' bracket missing"));
134                }
135                break;
136            }
137            Token t1 = tokens.get(i + 1);
138            boolean newLine = t0.span().line() < t1.span().line();
139            if (newLine && t1.isSymbol("[")) {
140                out.add(new NewLine(layoutColumn(firstOther, t1), depth));
141                depth++;
142            } else if (newLine && t1.isSymbol("]")) {
143                out.add(new NewLine(layoutColumn(firstOther, t1), depth));
144                depth--;
145            } else if (t1.isSymbol("{") || t1.isSymbol("[")) {
146                depth++;
147            } else if (t1.isSymbol("}") || t1.isSymbol("]")) {
148                depth--;
149            } else if (newLine) {
150                out.add(new NewLine(layoutColumn(firstOther, t1), depth));
151            }
152        }
153        return out;
154    }
155
156    /**
157     * For each line, the start of the first comment or escape that ends on
158     * it.
159     */
160    private static Map<Integer, int[]> firstOtherOnLine(List<Token> others) {
161        Map<Integer, int[]> first = new HashMap<>();
162        for (Token o : others) {
163            int endLine = o.span().line() + (int) o.text().chars().filter(c -> c == '\n').count();
164            int[] start = {o.span().line(), o.span().column()};
165            first.merge(endLine, start, (a, b) -> compare(a, b) <= 0 ? a : b);
166        }
167        return first;
168    }
169
170    private static int compare(int[] a, int[] b) {
171        return a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]);
172    }
173
174    /**
175     * The column that gives the indentation of a line that starts with a
176     * token: that of the first comment or escape that ends on the line before
177     * the token, if any ({@code LayoutResolver.layoutColumn}).
178     */
179    private static int layoutColumn(Map<Integer, int[]> firstOther, Token t) {
180        int[] start = firstOther.get(t.span().line());
181        if (start != null && compare(start, new int[]{t.span().line(), t.span().column()}) < 0) {
182            return start[1];
183        }
184        return t.span().column();
185    }
186}