-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathTokenizer.java
More file actions
342 lines (277 loc) · 9.61 KB
/
Copy pathTokenizer.java
File metadata and controls
342 lines (277 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package loop;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Stack;
/**
* @author Dhanji R. Prasanna
*/
public class Tokenizer {
private final String input;
public Tokenizer(String input) {
try {
// Clean input of leading whitespace on empty lines.
StringBuilder cleaned = new StringBuilder();
@SuppressWarnings("unchecked")
List<String> lines = Util.toLines(new StringReader(input));
for (int i = 0, linesSize = lines.size(); i < linesSize; i++) {
String line = lines.get(i);
if (!line.trim().isEmpty())
cleaned.append(line);
// Append newlines for all but the last line, because we don't want to introduce an
// unnecessary newline at the eof.
if (i < linesSize - 1)
cleaned.append('\n');
}
// Unless it explicitly has one.
if (input.endsWith("\n") || input.endsWith("\r"))
cleaned.append('\n');
this.input = cleaned.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static final int NON = 0; // MUST be zero
private static final int SINGLE_TOKEN = 1;
private static final int SEQUENCE_TOKEN = 2;
private static final int[] DELIMITERS = new int[256];
private static final boolean[] STRING_TERMINATORS = new boolean[256];
static {
DELIMITERS['-'] = SEQUENCE_TOKEN;
DELIMITERS['='] = SEQUENCE_TOKEN;
DELIMITERS['+'] = SEQUENCE_TOKEN;
DELIMITERS['/'] = SEQUENCE_TOKEN;
DELIMITERS['*'] = SEQUENCE_TOKEN;
DELIMITERS['>'] = SEQUENCE_TOKEN;
DELIMITERS['<'] = SEQUENCE_TOKEN;
// SINGLE token delimiters are one char in length in any context
DELIMITERS['\n'] = SINGLE_TOKEN;
DELIMITERS['.'] = SINGLE_TOKEN;
DELIMITERS[','] = SINGLE_TOKEN;
DELIMITERS[':'] = SINGLE_TOKEN;
DELIMITERS['('] = SINGLE_TOKEN;
DELIMITERS[')'] = SINGLE_TOKEN;
DELIMITERS['['] = SINGLE_TOKEN;
DELIMITERS[']'] = SINGLE_TOKEN;
DELIMITERS['{'] = SINGLE_TOKEN;
DELIMITERS['}'] = SINGLE_TOKEN;
STRING_TERMINATORS['"'] = true;
STRING_TERMINATORS['\''] = true;
STRING_TERMINATORS['`'] = true;
}
public List<Token> tokenize() {
List<Token> tokens = new ArrayList<Token>();
char[] input = this.input.toCharArray();
int line = 0, column = 0;
int i = 0, start = 0;
boolean inWhitespace = false, inDelimiter = false, inComment = false, leading = true;
char inStringSequence = 0;
for (; i < input.length; i++) {
char c = input[i];
column++;
if (c == '\n') {
line++;
column = 0;
}
// strings and sequences
if (STRING_TERMINATORS[c] && !inComment) {
if (inStringSequence > 0) {
// end of the current string sequence. bake.
if (inStringSequence == c) {
// +1 to include the terminating token.
bakeToken(tokens, input, i + 1, start, line, column);
start = i + 1;
inStringSequence = 0; // reset to normal language
leading = false;
continue;
}
// it's a string terminator but it's ok, it's part of the string, ignore...
} else {
// Also bake if there is any leading tokenage.
if (i > start) {
bakeToken(tokens, input, i, start, line, column);
start = i;
}
inStringSequence = c; // start string
}
}
// skip everything if we're in a string...
if (inStringSequence > 0)
continue;
if (c == '\n') {
leading = true;
}
// Comments beginning with #
if (c == '#') {
inComment = true;
}
// We run the comment until the end of the line
if (inComment) {
if (c == '\n')
inComment = false;
start = i;
continue;
}
// whitespace is ignored unless it is leading...
if (isWhitespace(c)) {
inDelimiter = false;
if (!inWhitespace) {
//bake token
bakeToken(tokens, input, i, start, line, column);
inWhitespace = true;
}
// leading whitespace is a special token...
if (leading) {
tokens.add(new Token(" ", Token.Kind.INDENT, line, column));
}
// skip whitespace
start = i + 1;
continue;
}
// any non-whitespace character encountered
inWhitespace = false;
if (c != '\n')
leading = false;
// For delimiters that are 1-char long in all contexts,
// break early.
if (isSingleTokenDelimiter(c)) {
bakeToken(tokens, input, i, start, line, column);
start = i;
// Also add the delimiter.
bakeToken(tokens, input, i + 1, start, line, column);
start = i + 1;
continue;
}
// is delimiter
if (isDelimiter(c)) {
if (!inDelimiter) {
bakeToken(tokens, input, i, start, line, column);
inDelimiter = true;
start = i;
}
continue;
}
// if coming out of a delimiter, we still need to bake
if (inDelimiter) {
bakeToken(tokens, input, i, start, line, column);
start = i;
inDelimiter = false;
}
}
// collect residual token
if (i > start && !inComment) {
// we don't want trailing whitespace
bakeToken(tokens, input, i, start, line, column);
}
return cleanTokens(tokens);
}
private List<Token> cleanTokens(List<Token> tokens) {
// Analyze token stream and remove line breaks inside groups and such.
int groups = 0;
Stack<Token.Kind> groupStack = new Stack<Token.Kind>();
for (ListIterator<Token> iterator = tokens.listIterator(); iterator.hasNext();) {
Token token = iterator.next();
if (Token.Kind.LPAREN == token.kind
|| Token.Kind.LBRACE == token.kind
|| Token.Kind.LBRACKET == token.kind) {
groupStack.push(token.kind);
groups++;
} else if (Token.Kind.RPAREN == token.kind
|| Token.Kind.RBRACE == token.kind
|| Token.Kind.RBRACKET == token.kind) {
if (!groupStack.empty() && groupStack.peek() == token.kind)
groupStack.pop();
groups--;
}
// Remove token.
if (groups > 0
&& (token.kind == Token.Kind.EOL || token.kind == Token.Kind.INDENT))
iterator.remove();
}
// Iterate again and dress function bodies with { }
groupStack = new Stack<Token.Kind>();
for (ListIterator<Token> iterator = tokens.listIterator(); iterator.hasNext();) {
Token token = iterator.next();
// Insert new function start token if necessary.
if (isThinOrFatArrow(token)) {
// Don't bother doing this if there is already an lbrace next.
if (iterator.hasNext() && iterator.next().kind != Token.Kind.LBRACE) {
iterator.previous();
iterator.add(new Token("{", Token.Kind.LBRACE, token.line, token.column));
groupStack.push(Token.Kind.LBRACE);
}
}
Token previous = null;
if (iterator.previousIndex() - 1 >= 0)
previous = tokens.get(iterator.previousIndex() - 1);
if ( (token.kind == Token.Kind.EOL
&& (previous != null
&& (isThinOrFatArrow(previous) || previous.kind == Token.Kind.EOL)))
|| ((token.kind == Token.Kind.RPAREN && groups > 0))) {
while (!groupStack.isEmpty() && groupStack.peek() == Token.Kind.LBRACE) {
// Add before cursor.
Token prev = iterator.previous();
iterator.add(new Token("}", Token.Kind.RBRACE, prev.line, prev.column));
iterator.next();
groupStack.pop();
}
}
if (Token.Kind.LPAREN == token.kind) {
groupStack.push(Token.Kind.LPAREN);
} else if (Token.Kind.RPAREN == token.kind) {
while (groupStack.peek() != Token.Kind.LPAREN) {
// Add before cursor.
Token prev = iterator.previous();
iterator.add(new Token("}", Token.Kind.RBRACE, prev.line, prev.column));
iterator.next();
groupStack.pop();
}
// Pop the matching lparen.
groupStack.pop();
}
}
// Close dangling functions
while (!groupStack.isEmpty())
if (groupStack.pop() == Token.Kind.LBRACE) {
tokens.add(new Token("}", Token.Kind.RBRACE, 0, 0));
}
return tokens;
}
private static boolean isThinOrFatArrow(Token token) {
return token.kind == Token.Kind.ARROW || (token.kind == Token.Kind.HASHROCKET);
}
private static boolean isWhitespace(char c) {
return '\n' != c && Character.isWhitespace(c);
}
static boolean isSingleTokenDelimiter(char c) {
return DELIMITERS[c] == SINGLE_TOKEN;
}
public static String detokenize(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
for (Token token : tokens) {
if (Token.Kind.INDENT == token.kind)
builder.append("~");
else
builder.append(token.value);
builder.append(' ');
}
return builder.toString().trim();
}
private static boolean isDelimiter(char c) {
return DELIMITERS[c] != NON;
}
private static void bakeToken(List<Token> tokens,
char[] input,
int i,
int start,
int line,
int column) {
if (i > start) {
String value = new String(input, start, i - start);
// remove this disgusting hack when you can fix the lexer.
tokens.add(new Token(value, Token.Kind.determine(value), line, column));
}
}
}