001package org.clafer.frontend; 002 003import java.util.ArrayList; 004import java.util.Collections; 005import java.util.List; 006import java.util.Set; 007 008/** 009 * Splits a model in the full Clafer language into tokens, as the compiler's 010 * lexer does ({@code clafer.cf}, generated by BNFC and Alex). 011 * <p> 012 * The rules are the compiler's, and so is the longest match: 013 * <ul> 014 * <li>a name starts with a letter, and goes on with letters, digits, 015 * {@code _} and {@code '}; a reserved word, e.g., {@code some} or {@code X}, 016 * is a {@link TokenKind#KEYWORD}. A letter is an ASCII letter or a Latin-1 017 * letter, {@code À} to {@code ÿ} without {@code ×} and {@code ÷};</li> 018 * <li>a number is an integer, a real with digits on both sides of the point, 019 * or a double, a real with an exponent ({@code 1.5e-3});</li> 020 * <li>a string has the escapes {@code \" \\ \n \t}, and may span lines;</li> 021 * <li>comments ({@code //} to the end of the line, {@code /* *}{@code /}) 022 * and escapes ({@code [alloy| |]}, {@code [choco| |]}) are set aside, with 023 * their spans.</li> 024 * </ul> 025 * The compiler's character classes are those of Latin-1, so a character after 026 * {@code U+00FF} is an error anywhere, in a string or a comment too. 027 * A column counts characters, and a tab moves to the next column after a 028 * multiple of 8, as in the compiler's messages. 029 * <p> 030 * The lexer does not stop at an error, as the compiler's does: an unexpected 031 * character is reported and skipped, and an unterminated string or comment is 032 * reported and ends the input. 033 */ 034public final class ClaferLexer { 035 036 /** 037 * The reserved words of {@code clafer.cf}. 038 */ 039 static final Set<String> Keywords = Set.of( 040 "F", "G", "U", "W", "X", 041 "abstract", "after", "all", "always", "and", "assert", "before", "between", "disj", "each", 042 "else", "enum", "eventually", "final", "finally", "finalref", "finaltarget", "follow", 043 "globally", "historically", "if", "in", "initial", "initially", "let", "lonce", "lone", 044 "max", "maximize", "min", "minimize", "must", "mux", "never", "next", "no", "not", "once", 045 "one", "opt", "or", "precede", "previous", "product", "since", "some", "sometime", "sum", 046 "then", "together", "triggered", "until", "weakuntil", "xor"); 047 048 /** 049 * The symbols of {@code clafer.cf}, longest first so that the longest 050 * match wins. 051 */ 052 private static final String[] Symbols = { 053 "-->>", "]->>", 054 "<=>", "->>", "-->", "]->", 055 "<<", ">>", "->", ":=", "..", "||", "&&", "=>", "<=", ">=", "!=", "<:", ":>", "++", "--", "**", "-[", 056 "=", "[", "]", "{", "}", "`", ":", "?", "+", "*", "|", "!", "<", ">", "-", "/", "%", "#", ",", 057 "&", ".", ";", "\\", "(", ")" 058 }; 059 060 /** 061 * The tokens of a model. 062 * 063 * @param tokens the tokens for the parser, ending with 064 * {@link TokenKind#EOF} 065 * @param others the comments and escapes, in order 066 * @param diagnostics the errors, in order 067 */ 068 public record Result(List<Token> tokens, List<Token> others, List<Diagnostic> diagnostics) { 069 } 070 071 private final String source; 072 private int pos = 0; 073 private int line = 1; 074 private int column = 1; 075 private final List<Token> tokens = new ArrayList<>(); 076 private final List<Token> others = new ArrayList<>(); 077 private final List<Diagnostic> diagnostics = new ArrayList<>(); 078 079 private ClaferLexer(String source) { 080 this.source = source; 081 } 082 083 /** 084 * Splits a model into tokens. 085 * 086 * @param source the text of the model 087 * @return the tokens, the comments and escapes, and the errors 088 */ 089 public static Result lex(String source) { 090 ClaferLexer lexer = new ClaferLexer(source); 091 lexer.run(); 092 return new Result( 093 Collections.unmodifiableList(lexer.tokens), 094 Collections.unmodifiableList(lexer.others), 095 Collections.unmodifiableList(lexer.diagnostics)); 096 } 097 098 private void run() { 099 while (pos < source.length()) { 100 char c = source.charAt(pos); 101 if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\u000B') { 102 advance(); 103 } else if (source.startsWith("//", pos)) { 104 lineComment(); 105 } else if (source.startsWith("/*", pos)) { 106 blockComment(); 107 } else if (source.startsWith("[alloy|", pos) || source.startsWith("[choco|", pos)) { 108 escape(); 109 } else if (isLetter(c)) { 110 word(); 111 } else if (isDigit(c)) { 112 number(); 113 } else if (c == '"') { 114 string(); 115 } else { 116 symbol(); 117 } 118 } 119 tokens.add(new Token(TokenKind.EOF, "", SourceSpan.at(line, column))); 120 } 121 122 static boolean isLetter(char c) { 123 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') 124 || (c >= '\u00C0' && c <= '\u00FF' && c != '\u00D7' && c != '\u00F7'); 125 } 126 127 /** 128 * Moves past a character of a string, comment or escape, which must be 129 * a Latin-1 character; reports the first that is not in each token. 130 */ 131 private boolean advanceLatin1(boolean reported) { 132 if (!reported && peek(0) > '\u00FF') { 133 diagnostics.add(new Diagnostic(SourceSpan.at(line, column), 134 "Unexpected character " + describe(peek(0)) + ": only Latin-1 characters are allowed")); 135 reported = true; 136 } 137 advance(); 138 return reported; 139 } 140 141 private static boolean isDigit(char c) { 142 return c >= '0' && c <= '9'; 143 } 144 145 private char peek(int offset) { 146 int i = pos + offset; 147 return i < source.length() ? source.charAt(i) : '\0'; 148 } 149 150 /** 151 * Moves past one character, as Alex does: a tab to the column after the 152 * next multiple of 8, a line feed to the next line, anything else, a 153 * carriage return included, one column. 154 */ 155 private void advance() { 156 char c = source.charAt(pos++); 157 if (c == '\n') { 158 line++; 159 column = 1; 160 } else if (c == '\t') { 161 column = ((column + 7) / 8) * 8 + 1; 162 } else { 163 column++; 164 } 165 } 166 167 private void advance(int n) { 168 for (int i = 0; i < n; i++) { 169 advance(); 170 } 171 } 172 173 private Token emit(List<Token> into, TokenKind kind, int startPos, int startLine, int startColumn) { 174 Token token = new Token(kind, source.substring(startPos, pos), new SourceSpan(startLine, startColumn, line, column)); 175 into.add(token); 176 return token; 177 } 178 179 private void lineComment() { 180 int startPos = pos, startLine = line, startColumn = column; 181 boolean reported = false; 182 while (pos < source.length() && source.charAt(pos) != '\n') { 183 reported = advanceLatin1(reported); 184 } 185 emit(others, TokenKind.COMMENT, startPos, startLine, startColumn); 186 } 187 188 private void blockComment() { 189 int startPos = pos, startLine = line, startColumn = column; 190 advance(2); 191 boolean reported = false; 192 while (pos < source.length() && !source.startsWith("*/", pos)) { 193 reported = advanceLatin1(reported); 194 } 195 if (pos < source.length()) { 196 advance(2); 197 emit(others, TokenKind.COMMENT, startPos, startLine, startColumn); 198 } else { 199 unterminated("comment", startPos, startLine, startColumn); 200 } 201 } 202 203 /** 204 * {@code [alloy| ... |]}: up to the first {@code |]}. 205 */ 206 private void escape() { 207 int startPos = pos, startLine = line, startColumn = column; 208 advance(7); 209 boolean reported = false; 210 while (pos < source.length() && !source.startsWith("|]", pos)) { 211 reported = advanceLatin1(reported); 212 } 213 if (pos < source.length()) { 214 advance(2); 215 emit(others, TokenKind.ESCAPE, startPos, startLine, startColumn); 216 } else { 217 unterminated("escape", startPos, startLine, startColumn); 218 } 219 } 220 221 private void unterminated(String what, int startPos, int startLine, int startColumn) { 222 diagnostics.add(new Diagnostic(new SourceSpan(startLine, startColumn, line, column), "Unterminated " + what)); 223 } 224 225 private void word() { 226 int startPos = pos, startLine = line, startColumn = column; 227 while (pos < source.length() && (isLetter(peek(0)) || isDigit(peek(0)) || peek(0) == '_' || peek(0) == '\'')) { 228 advance(); 229 } 230 String text = source.substring(startPos, pos); 231 emit(tokens, Keywords.contains(text) ? TokenKind.KEYWORD : TokenKind.WORD, startPos, startLine, startColumn); 232 } 233 234 /** 235 * An integer, a real if a point and a digit follow the digits, so that 236 * {@code 1..2} is a range of integers, and a double if an exponent follows 237 * the real. 238 */ 239 private void number() { 240 int startPos = pos, startLine = line, startColumn = column; 241 digits(); 242 TokenKind kind = TokenKind.INT; 243 if (peek(0) == '.' && isDigit(peek(1))) { 244 kind = TokenKind.DECIMAL; 245 advance(); 246 digits(); 247 int sign = peek(1) == '-' ? 1 : 0; 248 if (peek(0) == 'e' && isDigit(peek(1 + sign))) { 249 kind = TokenKind.DOUBLE; 250 advance(1 + sign); 251 digits(); 252 } 253 } 254 emit(tokens, kind, startPos, startLine, startColumn); 255 } 256 257 private void digits() { 258 while (pos < source.length() && isDigit(peek(0))) { 259 advance(); 260 } 261 } 262 263 /** 264 * A string, which may span lines. An unknown escape is reported, and the 265 * string goes on after it. 266 */ 267 private void string() { 268 int startPos = pos, startLine = line, startColumn = column; 269 advance(); 270 boolean reported = false; 271 while (pos < source.length()) { 272 char c = peek(0); 273 if (c == '"') { 274 advance(); 275 emit(tokens, TokenKind.STRING, startPos, startLine, startColumn); 276 return; 277 } 278 if (c == '\\') { 279 int escapeLine = line, escapeColumn = column; 280 advance(); 281 if (pos < source.length() && "\"\\nt".indexOf(peek(0)) < 0) { 282 diagnostics.add(new Diagnostic(SourceSpan.at(escapeLine, escapeColumn), 283 "Unknown escape in a string; use \\\", \\\\, \\n or \\t")); 284 } 285 if (pos < source.length()) { 286 advance(); 287 } 288 } else { 289 reported = advanceLatin1(reported); 290 } 291 } 292 unterminated("string", startPos, startLine, startColumn); 293 } 294 295 private void symbol() { 296 int startPos = pos, startLine = line, startColumn = column; 297 for (String symbol : Symbols) { 298 if (source.startsWith(symbol, pos)) { 299 advance(symbol.length()); 300 emit(tokens, TokenKind.SYMBOL, startPos, startLine, startColumn); 301 return; 302 } 303 } 304 char c = peek(0); 305 advance(); 306 diagnostics.add(new Diagnostic(SourceSpan.at(startLine, startColumn), "Unexpected character " + describe(c))); 307 } 308 309 private static String describe(char c) { 310 return c >= ' ' && c <= '~' ? "'" + c + "'" : String.format("U+%04X", (int) c); 311 } 312}