001package org.clafer.frontend; 002 003import java.util.ArrayList; 004import java.util.Collections; 005import java.util.List; 006 007/** 008 * Splits the explicit form of a Clafer model, as {@link org.clafer.ast.AstPrinter} 009 * prints it, into tokens. 010 * <p> 011 * Whitespace and line breaks only separate tokens: nesting is in braces, and 012 * indentation carries no meaning. Comments ({@code // ...} to the end of the 013 * line and {@code /* ... *}{@code /}) are set aside with their spans, for 014 * tools that show or keep them. 015 * <p> 016 * Lines and columns start at 1. A column counts UTF-16 code units, as the 017 * Language Server Protocol does by default, so a tab is one column. A span 018 * ends after its last character. 019 * <p> 020 * The lexer does not stop at an error: an unexpected character or an 021 * unterminated string becomes an {@link TokenKind#ERROR} token with a 022 * diagnostic, and lexing goes on after it. 023 */ 024public final class Lexer { 025 026 /** 027 * The operators and punctuation, longest first so that the longest match 028 * wins, e.g., {@code ->>} over {@code ->}. 029 */ 030 private static final String[] Symbols = { 031 "-->>", "]->>", 032 "<=>", "->>", "-->", "]->", 033 "<<", ">>", "->", "-[", ":=", "..", "::", "<=", ">=", "!=", "&&", "||", "=>", 034 "++", "--", "**", "<:", ":>", "*.", "/.", 035 ".", ":", "[", "]", "(", ")", "{", "}", ",", ";", "|", 036 "<", ">", "=", "!", "#", "+", "-", "*", "/", "%", "~", "^" 037 }; 038 039 /** 040 * The tokens of a source text. 041 * 042 * @param tokens the tokens for the parser, ending with 043 * {@link TokenKind#EOF} 044 * @param comments the comments, in order 045 * @param diagnostics the errors, in order 046 */ 047 public record Result(List<Token> tokens, List<Token> comments, List<Diagnostic> diagnostics) { 048 } 049 050 private final String source; 051 private int pos = 0; 052 private int line = 1; 053 private int column = 1; 054 private final List<Token> tokens = new ArrayList<>(); 055 private final List<Token> comments = new ArrayList<>(); 056 private final List<Diagnostic> diagnostics = new ArrayList<>(); 057 058 private Lexer(String source) { 059 this.source = source; 060 } 061 062 /** 063 * Splits a source text into tokens. 064 * 065 * @param source the source text 066 * @return the tokens, the comments and the errors 067 */ 068 public static Result lex(String source) { 069 Lexer lexer = new Lexer(source); 070 lexer.run(); 071 return new Result( 072 Collections.unmodifiableList(lexer.tokens), 073 Collections.unmodifiableList(lexer.comments), 074 Collections.unmodifiableList(lexer.diagnostics)); 075 } 076 077 private void run() { 078 while (pos < source.length()) { 079 char c = source.charAt(pos); 080 if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f') { 081 advance(); 082 } else if (source.startsWith("//", pos)) { 083 lineComment(); 084 } else if (source.startsWith("/*", pos)) { 085 blockComment(); 086 } else if (isWordStart(c)) { 087 word(); 088 } else if (isDigit(c)) { 089 number(); 090 } else if (c == '"') { 091 string(); 092 } else { 093 symbol(); 094 } 095 } 096 tokens.add(new Token(TokenKind.EOF, "", new SourceSpan(line, column, line, column))); 097 } 098 099 private static boolean isWordStart(char c) { 100 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; 101 } 102 103 private static boolean isWordPart(char c) { 104 return isWordStart(c) || isDigit(c) || c == '\''; 105 } 106 107 private static boolean isDigit(char c) { 108 return c >= '0' && c <= '9'; 109 } 110 111 private char peek(int offset) { 112 int i = pos + offset; 113 return i < source.length() ? source.charAt(i) : '\0'; 114 } 115 116 /** 117 * Moves past one character, counting a line break (LF, CRLF or CR) once. 118 */ 119 private void advance() { 120 char c = source.charAt(pos++); 121 if (c == '\n' || (c == '\r' && peek(0) != '\n')) { 122 line++; 123 column = 1; 124 } else if (c != '\r') { 125 column++; 126 } 127 } 128 129 private Token emit(List<Token> into, TokenKind kind, int startPos, int startLine, int startColumn) { 130 Token token = new Token(kind, source.substring(startPos, pos), 131 new SourceSpan(startLine, startColumn, line, column)); 132 into.add(token); 133 return token; 134 } 135 136 private void lineComment() { 137 int startPos = pos, startLine = line, startColumn = column; 138 while (pos < source.length() && source.charAt(pos) != '\n' && source.charAt(pos) != '\r') { 139 advance(); 140 } 141 emit(comments, TokenKind.COMMENT, startPos, startLine, startColumn); 142 } 143 144 private void blockComment() { 145 int startPos = pos, startLine = line, startColumn = column; 146 advance(); 147 advance(); 148 while (pos < source.length() && !source.startsWith("*/", pos)) { 149 advance(); 150 } 151 if (pos < source.length()) { 152 advance(); 153 advance(); 154 emit(comments, TokenKind.COMMENT, startPos, startLine, startColumn); 155 } else { 156 Token error = emit(tokens, TokenKind.ERROR, startPos, startLine, startColumn); 157 diagnostics.add(new Diagnostic(error.span(), "Unterminated comment")); 158 } 159 } 160 161 private void word() { 162 int startPos = pos, startLine = line, startColumn = column; 163 while (pos < source.length() && isWordPart(source.charAt(pos))) { 164 advance(); 165 } 166 emit(tokens, TokenKind.WORD, startPos, startLine, startColumn); 167 } 168 169 /** 170 * An integer, or a decimal if a point and a digit follow the digits, so 171 * that {@code 1..2} is a range of integers. 172 */ 173 private void number() { 174 int startPos = pos, startLine = line, startColumn = column; 175 while (pos < source.length() && isDigit(source.charAt(pos))) { 176 advance(); 177 } 178 TokenKind kind = TokenKind.INT; 179 if (peek(0) == '.' && isDigit(peek(1))) { 180 kind = TokenKind.DECIMAL; 181 advance(); 182 while (pos < source.length() && isDigit(source.charAt(pos))) { 183 advance(); 184 } 185 // a double, with its exponent, e.g., 1.2e2 or 1.0e-2 186 int sign = peek(1) == '-' ? 1 : 0; 187 if (peek(0) == 'e' && isDigit(peek(1 + sign))) { 188 kind = TokenKind.DOUBLE; 189 for (int i = 0; i <= sign; i++) { 190 advance(); 191 } 192 while (pos < source.length() && isDigit(source.charAt(pos))) { 193 advance(); 194 } 195 } 196 } 197 emit(tokens, kind, startPos, startLine, startColumn); 198 } 199 200 /** 201 * A string on one line. The escapes are checked here, and 202 * {@link #unescape} decodes them. 203 */ 204 private void string() { 205 int startPos = pos, startLine = line, startColumn = column; 206 advance(); 207 while (pos < source.length()) { 208 char c = source.charAt(pos); 209 if (c == '"') { 210 advance(); 211 emit(tokens, TokenKind.STRING, startPos, startLine, startColumn); 212 return; 213 } 214 if (c == '\n' || c == '\r') { 215 break; 216 } 217 if (c == '\\') { 218 int escapeLine = line, escapeColumn = column; 219 advance(); 220 int length = escapeLength(peek(0), pos); 221 if (length == 0) { 222 // Report the backslash and the character after it, unless 223 // that ends the string or the line, and go on. 224 char next = peek(0); 225 if (pos < source.length() && next != '"' && next != '\n' && next != '\r') { 226 advance(); 227 } 228 diagnostics.add(new Diagnostic(new SourceSpan(escapeLine, escapeColumn, line, column), 229 "Unknown escape in a string; use \\\", \\\\, \\n, \\t or \\uXXXX")); 230 } 231 for (int i = 0; i < length; i++) { 232 advance(); 233 } 234 } else { 235 advance(); 236 } 237 } 238 Token error = emit(tokens, TokenKind.ERROR, startPos, startLine, startColumn); 239 diagnostics.add(new Diagnostic(error.span(), "Unterminated string")); 240 } 241 242 /** 243 * @return how many characters after the backslash the escape takes, or 0 244 * if it is not one 245 */ 246 private int escapeLength(char c, int at) { 247 switch (c) { 248 case '"', '\\', 'n', 't' -> { 249 return 1; 250 } 251 case 'u' -> { 252 for (int i = 1; i <= 4; i++) { 253 int j = at + i; 254 if (j >= source.length() || Character.digit(source.charAt(j), 16) < 0) { 255 return 0; 256 } 257 } 258 return 5; 259 } 260 default -> { 261 return 0; 262 } 263 } 264 } 265 266 private void symbol() { 267 int startPos = pos, startLine = line, startColumn = column; 268 for (String symbol : Symbols) { 269 if (source.startsWith(symbol, pos)) { 270 for (int i = 0; i < symbol.length(); i++) { 271 advance(); 272 } 273 emit(tokens, TokenKind.SYMBOL, startPos, startLine, startColumn); 274 return; 275 } 276 } 277 advance(); 278 Token error = emit(tokens, TokenKind.ERROR, startPos, startLine, startColumn); 279 diagnostics.add(new Diagnostic(error.span(), "Unexpected character " + describe(error.text().charAt(0)))); 280 } 281 282 private static String describe(char c) { 283 return c >= ' ' && c <= '~' ? "'" + c + "'" : String.format("U+%04X", (int) c); 284 } 285 286 /** 287 * Decodes a string token: drops the quotes and replaces the escapes. 288 * 289 * @param token the text of a {@link TokenKind#STRING} token 290 * @return the string it denotes 291 */ 292 public static String unescape(String token) { 293 StringBuilder out = new StringBuilder(); 294 for (int i = 1; i < token.length() - 1; i++) { 295 char c = token.charAt(i); 296 if (c != '\\') { 297 out.append(c); 298 continue; 299 } 300 char e = token.charAt(++i); 301 switch (e) { 302 case 'n' -> out.append('\n'); 303 case 't' -> out.append('\t'); 304 case 'u' -> { 305 out.append((char) Integer.parseInt(token.substring(i + 1, i + 5), 16)); 306 i += 4; 307 } 308 default -> out.append(e); 309 } 310 } 311 return out.toString(); 312 } 313}