-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathExecutable.java
More file actions
377 lines (308 loc) · 11.1 KB
/
Copy pathExecutable.java
File metadata and controls
377 lines (308 loc) · 11.1 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package loop;
import loop.ast.ClassDecl;
import loop.ast.Node;
import loop.ast.script.FunctionDecl;
import loop.ast.script.RequireDecl;
import loop.ast.script.Unit;
import loop.lisp.SexprParser;
import loop.runtime.Scope;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Reprents an executable loop program (or script). An executable is produced
* from loop source code by pushing it through the following phases that represent
* "compilation".
*
* The output of each phase is used as input to the next phase.
*
* <ol>
* <li>Tokenizer (Tokenizing) - converts the text of the program to well-understood tokens (sometimes called lexing)</li>
* <li>Tokenizer (Normalizing) - inserts additional tokens as appropriate to convert context-sensitive
* grammatical constructs to relatively regular constructs</li>
* <li>Parser - processes the stream of tokens to create productions in the form of an AST</li>
* <li>Reducer - strips the AST of redundant or crufty nodes to make a compact AST</li>
* <li>Verifier - Analyzes the compact AST for scope, symbol and import errors and reports them</li>
* <li>AsmCodeEmitter - Translates the compact AST into JVM bytecode (loadable Classes)</li>
* <li>LoopClassLoader - Loads the raw bytecode into a special classloader during execution</li>
* </ol>
*
* @author [email protected] (Dhanji R. Prasanna)
*/
public class Executable {
private static final Pattern INDENT_REGEX = Pattern.compile("^(\\s+)");
private static final int MAX_BACKTRACK_LINES = 5;
private volatile String source; // Raw source code, discarded after compile.
private final List<String> lines; // Loop source code lines (for error tracing).
private Scope scope;
private List<AnnotatedError> staticErrors;
private Class<?> compiled;
private boolean runMain;
private final String file;
private final boolean isLisp;
public Executable(Reader source) {
this(source, null, false);
}
public Executable(Reader source, String file) {
this(source, file, false);
}
public Executable(Reader source, String file, boolean isLisp) {
this.file = file;
this.isLisp = isLisp;
List<String> lines = new ArrayList<String>();
StringBuilder builder;
try {
BufferedReader br = new BufferedReader(source);
builder = new StringBuilder();
while (br.ready()) {
String line = br.readLine();
if (line == null)
break;
builder.append(line);
builder.append('\n');
lines.add(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
this.source = builder.toString();
this.lines = lines;
}
private Unit parse(String input) {
Parser parser = isLisp
? new SexprParser(new Tokenizer(input).tokenize())
: new LexprParser(new Tokenizer(input).tokenize());
Unit unit = null;
try {
unit = parser.script(file);
unit.reduceAll();
this.scope = unit;
} catch (RuntimeException e) {
// Ignored.
System.out.println("Parse errors exist.");
if (!(e instanceof LoopCompileException))
e.printStackTrace();
}
if (!parser.getErrors().isEmpty())
this.staticErrors = parser.getErrors();
return unit;
}
public boolean verify(Unit unit) {
return null == (this.staticErrors = new Verifier(unit).verify());
}
public String printStaticErrorsIfNecessary() {
if (staticErrors != null)
return printErrors(getStaticErrors());
return "";
}
public void printErrorsTo(PrintStream out, List<AnnotatedError> errors) {
for (int i = 0, errorsSize = errors.size(); i < errorsSize; i++) {
AnnotatedError error = errors.get(i);
out.println((i + 1) + ") " + error.getMessage());
out.println();
// Unwrap to previous line if column is 0, or line is empty.
int errorLineNumber = error.line(), column = error.column();
if (errorLineNumber >= lines.size())
errorLineNumber = lines.size() - 1;
if (error.column() == 0 || lines.get(errorLineNumber).trim().isEmpty()) {
errorLineNumber = Math.max(0, errorLineNumber - 1);
column = lines.get(errorLineNumber).length();
}
String thisLine = lines.get(errorLineNumber);
// Detect the nearest indent-drop above the error, but only if there is an indent.
int indent, startLine = errorLineNumber;
Matcher matcher = INDENT_REGEX.matcher(thisLine);
if (matcher.find()) {
indent = matcher.group(1).length();
// Find an indent-drop before this line.
ListIterator<String> lineIterator = lines.listIterator(errorLineNumber);
int backtrackCount = 0;
while (backtrackCount <= MAX_BACKTRACK_LINES && lineIterator.hasPrevious()) {
String previous = lineIterator.previous();
Matcher previousMatcher = INDENT_REGEX.matcher(previous);
if (!previousMatcher.find() || previousMatcher.group(1).length() < indent) {
startLine = Math.max(0, errorLineNumber - backtrackCount - 1);
break;
}
backtrackCount++;
}
// If we weren't able to find an indent drop within MAX_BACKTRACK_LINES,
// just show MAX_BACKTRACK_LINES of context.
if (startLine == errorLineNumber) {
startLine -= backtrackCount;
}
} // otherwise this is an unindented line anyway.
// Print from startLine to error line.
for (int lineNumber = startLine; lineNumber <= errorLineNumber; lineNumber++) {
String line = lines.get(lineNumber);
int lineNumberLabel = lineNumber + 1;
// if there is a change in line number label width, we need to change the indent
// so that everything lines up properly.
int leader = 2;
if (Math.floor(Math.log10(lineNumberLabel)) > Math.floor(Math.log10(lineNumber)))
leader--;
out.println(whitespace(leader) + lineNumberLabel + ": " + line);
}
// Caret line (^)
int spaces = column + Integer.toString(errorLineNumber).length() + 1;
out.println(" " + whitespace(spaces) + "^\n");
}
}
public String printErrors(List<AnnotatedError> errors) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
printErrorsTo(new PrintStream(buffer), errors);
String errorText = buffer.toString();
System.out.print(errorText);
return errorText;
}
public String file() {
return file;
}
public boolean runMain() {
return runMain;
}
public boolean hasErrors() {
return staticErrors != null;
}
private void requireJavaImports(Set<RequireDecl> imports) {
for (RequireDecl requireDecl : imports) {
if (requireDecl.javaLiteral != null)
try {
Class.forName(requireDecl.javaLiteral);
} catch (ClassNotFoundException e) {
if (staticErrors == null)
staticErrors = new ArrayList<AnnotatedError>();
staticErrors.add(new StaticError("Unable to find Java type for import: "
+ requireDecl.javaLiteral, requireDecl.sourceLine, requireDecl.sourceColumn));
}
}
}
public Object main(String[] commandLine) {
FunctionDecl main = scope.resolveFunction("main", false);
if (main != null) {
int args = main.arguments().children().size();
if(commandLine == null)
commandLine = new String[] {};
try {
if (args == 0)
return compiled.getDeclaredMethod("main").invoke(null);
else
return compiled.getDeclaredMethod("main", Object.class).invoke(null, Arrays.asList(commandLine));
} catch (NoSuchMethodException e) {
System.out.println("Incorrect main method declaration in: " + file);
} catch (InvocationTargetException e) {
// Unwrap Java stack trace using our special wrapper exception.
Throwable cause = e.getCause();
StackTraceSanitizer.clean(cause);
if (cause instanceof VerifyError)
throw (Error) cause;
// Rethrow cleaned up exception.
if (cause instanceof RuntimeException)
throw (RuntimeException) cause;
throw new RuntimeException(cause);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
// Attempt to force class initialization.
try {
Class.forName(compiled.getName(), true, LoopClassLoader.CLASS_LOADER);
} catch (ClassNotFoundException e) {
throw new Error("Not supposed to happen. A previously loaded class disappeared.", e);
}
}
return null;
}
public void compile() {
Unit unit = parse(source);
if (hasErrors())
return;
// Recursively loads and compiles all dependency modules.
List<AnnotatedError> depErrors = unit.loadDeps(file);
if (depErrors != null) {
this.staticErrors = depErrors;
return;
}
// Run the verifier just before we emit code.
if (!verify(unit))
return;
AsmCodeEmitter codeEmitter = new AsmCodeEmitter(unit);
this.scope = unit;
this.compiled = codeEmitter.write(unit);
requireJavaImports(unit.imports());
this.source = null;
}
public void compileExpression(Unit scope) {
this.scope = scope;
if (!verify(scope))
return;
AsmCodeEmitter codeEmitter = new AsmCodeEmitter(scope);
this.compiled = codeEmitter.write(scope);
this.source = null;
requireJavaImports(scope.requires());
}
public void compileClassOrFunction(Unit scope) {
this.scope = scope;
List<Token> tokens = new Tokenizer(source).tokenize();
Parser parser = isLisp
? new SexprParser(tokens)
: new LexprParser(tokens);
FunctionDecl functionDecl = parser.functionDecl();
ClassDecl classDecl = null;
Node node;
if (null == functionDecl) {
classDecl = parser.classDecl();
node = classDecl;
} else
node = functionDecl;
if (hasErrors())
return;
if (node == null) {
this.staticErrors = Arrays.<AnnotatedError>asList(
new StaticError("malformed function definition",
tokens.get(tokens.size() - 1)));
return;
}
new Reducer(node).reduce();
if (!verify(scope))
return;
// We don't need to actually compile this code, yet.
this.source = null;
requireJavaImports(scope.requires());
if (functionDecl != null)
scope.declare(functionDecl);
else
scope.declare(classDecl);
}
private static String whitespace(int amount) {
StringBuilder builder = new StringBuilder(amount);
for (int i = 0; i < amount; i++) {
builder.append(' ');
}
return builder.toString();
}
public Class<?> getCompiled() {
return compiled;
}
public void runMain(boolean runMain) {
if (runMain)
this.runMain = runMain;
}
@SuppressWarnings("unchecked")
public List<AnnotatedError> getStaticErrors() {
return (List) staticErrors;
}
public Scope getScope() {
return scope;
}
}