-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava.py
More file actions
executable file
·469 lines (389 loc) · 13.6 KB
/
java.py
File metadata and controls
executable file
·469 lines (389 loc) · 13.6 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import random
import re
import subprocess
import sys
from time import perf_counter
pygments_available = True
try:
import pygments
from pygments.lexers import JavaLexer
from pygments.formatters import TerminalFormatter
except ImportError:
pygments_available = False
config = {
'verbosity': 0,
'pretty': False,
'setup': [],
'classpath': [],
'raw': False,
'java_args': [],
'bytecode': False,
'mvn': [],
'javac_args': ['-nowarn', '-encoding', 'utf-8'],
'timings': False,
'debug': False,
'pretty_imports': [
'java.util.Arrays',
'java.util.Map',
'java.util.Spliterator',
'java.util.stream.Collector',
'java.util.stream.Collectors',
'java.util.stream.DoubleStream',
'java.util.stream.IntStream',
'java.util.stream.LongStream',
'java.util.stream.Stream',
'java.util.stream.StreamSupport',
],
'imports': [
'java.io.*',
'java.lang.reflect.*',
'java.math.*',
'java.nio.*',
'java.nio.charset.*',
'java.nio.file.*',
'java.security.*',
'java.time.*',
'java.time.chrono.*',
'java.time.format.*',
'java.time.temporal.*',
'java.time.zone.*',
'java.util.*',
'java.util.concurrent.*',
'java.util.concurrent.atomic.*',
'java.util.concurrent.locks.*',
'java.util.function.*',
'java.util.regex.*',
'java.util.stream.*',
'javax.crypto.*',
'javax.crypto.spec.*',
],
}
OUT = os.path.join('/tmp' if os.name != 'nt' else os.getenv('temp'),
'java.py')
CLASS = 'Paul%s' % int(random.random() * 100)
SOURCE = '%s.java' % CLASS
COMPILED = '%s.class' % CLASS
TEMPLATE = """
%s;
%s;
public class %s {
private %s() {}
public static void main(String[] args) throws Exception {
%s;
%s
}
private static void p(Object obj) {
System.out.println(obj);
}
private static void p(String format, Object... params) {
System.out.println(String.format(format, params));
}
}
"""
OUTPUT_CODE_TEMPLATE = """
Object ಠ_ಠ = %s;
String ᴥ = "null";
if(ಠ_ಠ != null) {
if((ᴥ = ಠ_ಠ.getClass().getCanonicalName()) == null) {
ᴥ = ಠ_ಠ.getClass().getName();
}
if(ᴥ.startsWith("java.lang.")) {
ᴥ = ᴥ.substring("java.lang.".length());
}
}
Stream<? extends Object> ϟ = null;
if(ಠ_ಠ instanceof Object[]) {
ϟ = Arrays.stream((Object[]) ಠ_ಠ);
} else if(ಠ_ಠ instanceof int[]) {
ϟ = Arrays.stream((int[]) ಠ_ಠ).mapToObj(Integer::valueOf);
} else if(ಠ_ಠ instanceof long[]) {
ϟ = Arrays.stream((long[]) ಠ_ಠ).mapToObj(Long::valueOf);
} else if(ಠ_ಠ instanceof double[]) {
ϟ = Arrays.stream((double[]) ಠ_ಠ).mapToObj(Double::valueOf);
} else if(ಠ_ಠ instanceof Map<?, ?>) {
ϟ = ((Map<?, ?>) ಠ_ಠ).entrySet().stream()
.map(ツ -> String.format("%%s: %%s", ツ.getKey(), ツ.getValue()));
} else if(ಠ_ಠ instanceof Stream<?>) {
ϟ = (Stream<?>) ಠ_ಠ;
} else if(ಠ_ಠ instanceof IntStream) {
ϟ = ((IntStream) ಠ_ಠ).boxed();
} else if(ಠ_ಠ instanceof LongStream) {
ϟ = ((LongStream) ಠ_ಠ).boxed();
} else if(ಠ_ಠ instanceof DoubleStream) {
ϟ = ((DoubleStream) ಠ_ಠ).boxed();
} else if(ಠ_ಠ instanceof Iterable<?>) {
ϟ = StreamSupport.stream(((Iterable<?>) ಠ_ಠ).spliterator(), false);
} else if(ಠ_ಠ instanceof Spliterator<?>) {
ϟ = StreamSupport.stream((Spliterator<?>) ಠ_ಠ, false);
}
if(ϟ == null) {
System.out.printf("(%%s) %%s", ᴥ, ಠ_ಠ);
} else {
String separator;
if (%s) {
separator = ",\\n";
} else {
separator = ", ";
}
boolean[] first = { true };
System.out.printf("(%%s) [", ᴥ);
ϟ
.map(ツ -> {
if(ツ == null) {
return "null";
}
if(ツ instanceof Character) {
return "'" + ツ + "'";
}
if(ツ instanceof Number) {
return ツ.toString();
}
return "\\"" + ツ + '"';
})
.forEach(ツ -> {
if (first[0]) {
first[0] = false;
} else {
System.out.print(separator);
}
System.out.print(ツ);
});
System.out.print("]");
}
"""
def help():
print('Usage is ./java.py [options] <code>')
print()
print('Options')
print(' -b, -bytecode Prints the bytecode instead of executing the program (implies -r)')
print(' -d, -debug Prints the code compiled and executed (requires pygments installed)')
print(' -h, -help Prints this help message.')
print(' -ci -clear-imports Clear the list of imports (also clear the default imports) (not that if you ')
print(' don\'t use raw mode, the imports for the formatting code are still included)')
print(' -p, -pretty Pretty output(in case of program result convertible to stream, each item will be')
print(' printed on a new line).')
print(' -r, -raw Prevents adding some code to display the result of the last operation')
print(' and replaces strip calls applied to each line of the program output with rstrip.')
print(' -t, -timing Prints timing information about compilation and execution')
print(' -v, -verbose Prints the commands used to compile and execute the script (provide this argument')
print(' twice if you want non-simplified commands).')
print()
print('Options with value')
print(' -c, -arg Parameters to add to the java invocation')
print(' -cp, -classpath Adds a jar to the classpath.')
print(' -i -import Add the value to the list of imports')
print(' -mvn, -maven Adds maven dependencies of a project to the runtime classpath')
print(' -s, -setup Setup code to put before the class declaration (i.e. imports or class definitions).')
sys.exit()
def parse_args(args):
code = []
if len(args) == 1:
help()
arg_it = iter(args)
next(arg_it) # skip command
for x in arg_it:
if x == '-s' or x == '-setup':
setup = next(arg_it)
config['setup'] += setup.strip(';').split(';')
elif x == '-p' or x == '-pretty':
config['pretty'] = True
elif x == '-v' or x == '-verbose':
config['verbosity'] += 1
elif x == '-vv':
config['verbosity'] += 2
elif x == '-r' or x == '-raw':
config['raw'] = True
elif x == '-cp' or x == '-classpath':
config['classpath'].append(next(arg_it))
elif x == '-h' or x == '-help' or x == '--help':
help()
elif x == '-c' or x == '-arg':
config['java_args'].append(next(arg_it))
elif x == '-b' or x == '-bytecode':
config['bytecode'] = True
config['raw'] = True
elif x == '-mvn' or x == '-maven':
config['mvn'].append(next(arg_it))
elif x == '-t' or x == '-timing':
config['timings'] = True
elif x == '-d' or x == '-debug':
config['debug'] = True
elif x == '-ci' or x == '-clear-imports':
config['imports'] = []
elif x == '-i' or x == '-import':
config['imports'].append(next(arg_it))
else:
code.append(x)
if not code and not config['raw']:
help()
return code, config
def deduplicate(list):
seen = set()
out = []
for x in list:
if not x in seen:
seen.add(x)
out.append(x)
return out
def log(command):
if not config['verbosity']:
return
if config['verbosity'] == 3:
print(command)
return
if config['verbosity'] == 1:
try:
command = command.split(' ')
except AttributeError:
pass
parts = []
for part in command:
if len(part) > 50:
part = part[:20] + '[...]' + part[-20:]
parts.append(part)
command = ' '.join(parts)
if not isinstance(command, str):
command = ' '.join(command)
print('%% %s' % command)
def generate_code(code, clazz, template, out_template=''):
# Splitting on ; is really horrible and breaks in many cases but
# it's a fair trade compared to the complexity of writing a parser
code = code.strip().strip(';').split(';')
last_instr = code[-1].strip()
output = ''
imports = []
if not config['raw']:
imports = config['pretty_imports']
output = out_template % (code[-1],
('true' if config['pretty'] else 'false'))
del code[-1]
imports += config['imports']
return template % (
'\n'.join('import %s;' % i for i in imports),
';'.join(config['setup']),
clazz,
clazz,
';'.join(code), output)
def display_code(code):
if not pygments_available:
print('Warning: pygments not found')
return
print(pygments.highlight(code, JavaLexer(), TerminalFormatter()))
def write_to_file(file, content):
dirname = os.path.dirname(file)
if not os.path.exists(dirname):
os.mkdir(dirname)
with open(file, 'w', encoding='utf-8') as f:
f.write(content)
def which(name):
for path in os.getenv('PATH').split(os.pathsep):
file = os.path.join(path, name)
if os.path.isfile(file) and os.access(file, os.X_OK):
return file
def dirname(name, count):
for i in range(count):
name = os.path.dirname(name)
return name
def find_java_home():
java_home = os.getenv('JAVA_HOME')
if java_home:
return java_home
java_home = which('javac')
if java_home:
return dirname(java_home, 2)
def read_stdin():
return sys.stdin.readlines()
def exec(cmd, shell=True):
log(cmd)
return subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, universal_newlines=True,
shell=shell, bufsize=1)
def find_maven_classpath(mvn):
if not mvn:
return []
cp = []
for folder in mvn:
proc = exec(['mvn', 'dependency:build-classpath', '-f', folder], False)
for line in proc.stdout:
if line.startswith('[ERROR]') or line.startswith('[FATAL]'):
print(line)
break
if not line.startswith('['):
cp += line.strip().split(':')
return cp
def compile(file, folder, java_home, javac_args, classpath):
exe = '%s/bin/javac' % java_home
args = list(javac_args)
if classpath:
args.append('-cp')
args.append(':'.join(classpath))
args.append('-d')
args.append(folder)
args.append(file)
start = perf_counter()
p = exec([exe] + args, False)
for line in p.stdout:
print('| %s' % line.rstrip())
if p.wait() != 0:
print('Compilation failed')
cleanup(False)
sys.exit(-1)
return False
if config['timings']:
print('Program compiled in %f seconds' % (perf_counter() - start))
return True
def run(clazz, bytecode, raw, java_home, java_args, classpath):
exe = '%s/bin/java' % java_home
cp = ':'.join(classpath + [OUT])
args = java_args + ['-cp', cp]
if bytecode:
exe = '%s/bin/javap' % java_home
args += ['-constants', '-package', '-c']
if config['verbosity'] > 0:
args.append('-v')
args.append(clazz)
start = perf_counter()
execution = exec([exe] + args, False)
if bytecode:
# skip preamble
for i in range(4 if config['verbosity'] > 0 else 1):
execution.stdout.readline()
for line in execution.stdout:
if raw:
line = line.rstrip()
else:
line = line.strip()
print('>> %s' % line)
execution.wait()
if config['timings']:
print('Program executed in %f seconds' % (perf_counter() - start))
def cleanup(compiled=True):
os.remove('%s/%s' % (OUT, SOURCE))
if compiled:
os.remove('%s/%s' % (OUT, COMPILED))
if __name__ == '__main__':
code_args, config = parse_args(sys.argv)
if len(code_args) == 1 and code_args[0] == '-':
code_args = read_stdin()
java_home = find_java_home()
if not java_home:
print('| Java home not found, aborting...')
sys.exit(1)
code = generate_code(' '.join(code_args), CLASS,
TEMPLATE, OUTPUT_CODE_TEMPLATE)
if config['verbosity'] > 2:
print(code)
source = '%s/%s' % (OUT, SOURCE)
if config['debug']:
display_code(code)
write_to_file(source, code)
config['classpath'] += find_maven_classpath(config['mvn'])
compiled = compile(source, OUT, java_home, config['javac_args'],
config['classpath'])
if compiled:
run(CLASS, config['bytecode'], config['raw'], java_home,
config['java_args'], config['classpath'])
cleanup(source)