-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathrusthon.py
executable file
·1952 lines (1690 loc) · 60.8 KB
/
rusthon.py
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '0.9.9'
import os, sys, subprocess, hashlib, time
import tempfile
import webbrowser
## if installed as a symbolic link, this ensures things can still be bootstrapped from the `src` subfolder
RUSTHON_LIB_ROOT = os.path.dirname(unicode(os.path.realpath(__file__), sys.getfilesystemencoding()))
GO_EXE = None
if os.path.isfile('/usr/bin/go'):
GO_EXE = '/usr/bin/go'
elif os.path.isfile('/usr/local/go/bin/go'):
GO_EXE = '/usr/local/go/bin/go'
elif os.path.isfile(os.path.expanduser('~/go/bin/go')):
GO_EXE = os.path.expanduser('~/go/bin/go')
nodewebkit_runnable = False
nodewebkit = os.path.expanduser('~/nwjs-v0.12.2-linux-x64/nw')
if os.path.isfile( nodewebkit ): nodewebkit_runnable = True
else:
nodewebkit = os.path.expanduser('~/nwjs-v0.12.3-linux-x64/nw')
if os.path.isfile( nodewebkit ): nodewebkit_runnable = True
if sys.platform=='darwin':
nodewebkit = os.path.expanduser('~/nwjs-v0.12.3-osx-x64/nwjs.app/Contents/MacOS/nwjs')
if os.path.isfile( nodewebkit ):
nodewebkit_runnable = True
## special case for linux, just for debugging, look for google-chrome,
## if found then use it to launch tests, with the --disable-gpu-sandbox
## otherwise webgl may fail on some graphics cards, this is dangerous
## and can lockup the desktop, this was an issue on Fedora21 with intel graphics,
## but is no longer an issue in Fedora22. Enable this at your own risk.
CHROME_EXE = None
#if os.path.isfile('/opt/google/chrome-unstable/google-chrome-unstable'):
# CHROME_EXE = '/opt/google/chrome-unstable/google-chrome-unstable'
#elif os.path.isfile('/opt/google/chrome-beta/google-chrome-beta'):
# CHROME_EXE = '/opt/google/chrome-beta/google-chrome-beta'
#elif os.path.isfile('/opt/google/chrome/google-chrome'):
# CHROME_EXE = '/opt/google/chrome/google-chrome'
## on fedora nodejs command is `node`, but on others it can be `nodejs`
nodejs_exe = 'node'
if os.path.isfile('/usr/sbin/ax25-node'):
if os.path.isfile('/usr/sbin/node'):
if os.path.realpath('/usr/sbin/node') == '/usr/sbin/ax25-node':
nodejs_exe = 'nodejs'
JS_WEBWORKER_HEADER = u'''
var __$UID$__ = 1;
var __construct__ = function(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
};
var __instances__ = {};
var __bin__ = null;
self.onmessage = function (evt) {
var id;
if (__bin__) {
var bmsg;
if (__bin__.type=="Float32Array") {
bmsg = new Float32Array(evt.data);
} else if (__bin__.type=="Float64Array") {
bmsg = new Float64Array(evt.data);
} // TODO other types
if (__bin__.send_binary) {
id = __bin__.send_binary;
var ob = __instances__[id];
var re = ob.send(bmsg);
if (re !== undefined) {
if (ob.send.returns=="Float32Array") {
self.postMessage({'id':id, 'bin':ob.send.returns});
self.postMessage(re.buffer, [re.buffer]);
} else {
self.postMessage({'id':id, 'message':re, 'proto':ob.send.returns});
}
}
}
__bin__ = null;
return;
}
var msg = evt.data;
if (msg.send_binary) {
// should assert here that __bin__ is null
__bin__ = msg;
return;
}
if (msg['spawn']) {
id = msg.spawn;
self.postMessage({debug:"SPAWN:"+id});
if (__instances__[id] !== undefined) {
self.postMessage({debug:"SPAWN ERROR - existing id:"+id});
}
//self.postMessage({debug:"SPAWN-CLASS:"+msg['new']});
//self.postMessage({debug:"SPAWN-ARGS:"+msg['args']});
__instances__[id] = __construct__(eval(msg['new']), msg.args );
__instances__[id].__uid__ = id;
}
if (msg['send']) {
id = msg.send;
//self.postMessage({debug:"SEND:"+id});
var ob = __instances__[id];
var re = ob.send(msg.message);
if (re !== undefined) {
//self.postMessage({debug:"SEND-BACK:"+re});
self.postMessage({'id':id, 'message':re, 'proto':ob.send.returns});
} else {
//self.postMessage({debug:"SEND-BACK-NONE:"});
}
}
if (msg['call']) {
self.postMessage({
'CALL' : 1,
'message': self[ msg.call ].apply(null,msg.args),
'proto' : self[ msg.call ].returns
});
}
if (msg['callmeth']) {
id = msg.id;
//self.postMessage({debug:"CALLM:"+id});
var ob = __instances__[id];
if (typeof(ob) == "undefined") {
self.postMessage({debug:"invalid spawn instance id:"+id});
self.postMessage({debug:"instances:"+Object.keys(__instances__).length});
} else {
self.postMessage({
'CALLMETH': 1,
'message' : ob[msg.callmeth].apply(ob,msg.args),
'proto' : ob[msg.callmeth].returns
});
}
}
if (msg['get']) {
id = msg.id;
//self.postMessage({debug:"GET:"+id});
var ob = __instances__[id];
self.postMessage({'GET':1, 'message':ob[msg.get]});
}
}
'''
OPENSHIFT_PY = [
u'''#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
#
# IMPORTANT: Put any additional includes below this line. If placed above this
# line, it's possible required libraries won't be in your searchable path
#
from base64 import b64decode
INDEX_HTML = b64decode("%s")
''', ## header
u'''
def application(environ, start_response):
ctype = 'text/plain'
if environ['PATH_INFO'] == '/health':
response_body = "1"
elif environ['PATH_INFO'] == '/env':
response_body = ['%s: %s' % (key, value)
for key, value in sorted(environ.items())]
response_body = '\\n'.join(response_body)
else:
ctype = 'text/html'
response_body = INDEX_HTML
status = '200 OK'
response_headers = [('Content-Type', ctype), ('Content-Length', str(len(response_body)))]
#
start_response(status, response_headers)
return [response_body]
#
# Below for testing only
#
if __name__ == '__main__':
from wsgiref.simple_server import make_server
httpd = make_server('localhost', 8051, application)
# Wait for a single request, serve it and quit.
httpd.handle_request()
''']
def compile_js( script, module_path, main_name='main', directjs=False, directloops=False ):
'''
directjs = False ## compatible with pythonjs-minimal.js
directloops = False ## allows for looping over strings, arrays, hmtlElements, etc. if true outputs cleaner code.
'''
fastjs = True ## this is now the default, and complete python mode is deprecated
result = {}
pyjs = python_to_pythonjs(
script,
module_path=module_path,
fast_javascript = fastjs,
pure_javascript = directjs
)
if isinstance(pyjs, dict): ## split apart by webworkers
workers = []
mainjs = None
for jsfile in pyjs:
js = translate_to_javascript(
pyjs[jsfile],
webworker=jsfile == 'worker.js',
requirejs=False,
insert_runtime=False,
fast_javascript = fastjs,
fast_loops = directloops,
runtime_checks = '--release' not in sys.argv
)
result[ jsfile ] = js
if jsfile == 'worker.js':
workers.append(js)
else:
mainjs = jsfile
src = [ 'var __workersrc__ = [' ]
a = JS_WEBWORKER_HEADER.encode('utf-8') + workers[0]
for line in a.strip().splitlines():
src.append( '"%s\\n",' % line.replace('"', '\\"'))
src.append(']')
src.append(result[mainjs])
result[mainjs] = '\n'.join(src)
else:
code = translate_to_javascript(
pyjs,
as_module='--ES6-module' in sys.argv,
requirejs=False,
insert_runtime=False,
fast_javascript = fastjs,
fast_loops = directloops,
runtime_checks = '--release' not in sys.argv
)
if isinstance(code, dict):
result.update( code )
else:
result['main'] = code
if main_name != 'main':
#assert main_name.endswith('.js') ## allow tag names
result[main_name] = result.pop('main')
return result
def compile_java( javafiles ):
assert 'JAVA_HOME' in os.environ
tmpdir = tempfile.gettempdir()
cmd = ['javac']
cmd.extend( javafiles )
print(' '.join(cmd))
subprocess.check_call(cmd, cwd=tmpdir)
classfiles = [jfile.replace('.java', '.class') for jfile in javafiles]
cmd = ['jar', 'cvf', 'mybuild.jar']
cmd.extend( classfiles )
print(' '.join(cmd))
subprocess.check_call(cmd, cwd=tmpdir)
jarfile = os.path.join(tmpdir,'mybuild.jar')
assert os.path.isfile(jarfile)
return {'class-files':classfiles, 'jar':jarfile}
def compile_giws_bindings( xml ):
tmpdir = tempfile.gettempdir()
tmpfile = os.path.join(tmpdir, 'rusthon_giws.xml')
open(tmpfile, 'wb').write(xml)
cmd = [
'giws',
'--description-file='+tmpfile,
'--output-dir='+tmpdir,
#'--per-package',
'--disable-return-size-array',
#'--throws-exception-on-error', # requires GiwsException.hxx and GiwsException.cpp
]
#subprocess.check_call(cmd)
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
proc.wait()
if proc.returncode:
raise RuntimeError(proc.stderr.read())
else:
headers = []
impls = []
for line in proc.stdout.read().splitlines():
if line.endswith(' generated ...'): ## TODO something better
name = line.split()[0]
if name.endswith('.hxx'):
headers.append( name )
elif name.endswith('.cpp'):
impls.append( name )
code = []
for header in headers:
data = open(os.path.join(tmpdir,header), 'rb').read()
code.append( data )
for impl in impls:
data = open(os.path.join(tmpdir,impl), 'rb').read()
lines = ['/* %s */' %impl]
includes = [] ## ignore these
for line in data.splitlines():
if line.startswith('#include'):
includes.append(line)
else:
lines.append(line)
code.append( '\n'.join(lines) )
return '\n'.join(code)
def java_to_rusthon( input ):
j2pybin = 'j2py'
if os.path.isfile(os.path.expanduser('~/java2python/bin/j2py')):
j2pybin = os.path.expanduser('~/java2python/bin/j2py')
print('======== %s : translate to rusthon' %j2pybin)
j2py = subprocess.Popen([j2pybin, '--rusthon'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout,stderr = j2py.communicate( input )
if stderr: raise RuntimeError(stderr)
if j2py.returncode: raise RuntimeError('j2py error!')
print(stdout)
print('---------------------------------')
rcode = typedpython.transform_source(stdout.replace(' ', '\t'))
print(rcode)
print('---------------------------------')
return rcode
def new_module():
return {
'markdown': '',
'coffee' : [],
'python' : [],
'rusthon' : [],
'rust' : [],
'elm' : [],
'c' : [],
'c++' : [],
'c#' : [],
'go' : [],
'html' : [],
'verilog' : [],
'bash' : [],
'java' : [],
'nim' : [],
'xml' : [],
'json' : [],
'bazel' : [],
'gyp' : [],
'rapydscript':[],
'javascript':[],
}
def import_md( url, modules=None, index_offset=0, force_tagname=None ):
assert modules is not None
doc = []
code = []
code_links = []
code_idirs = []
code_defines = []
lang = False
in_code = False
index = 0
prevline = None
tag = force_tagname or None
fences = 0
base_path, markdown_name = os.path.split(url)
#data = open(url, 'rb').read().decode('utf-8')
import codecs
data = codecs.open(url, 'r', 'utf-8').read()
for line in data.splitlines():
if line.startswith('* @link:'):
code_links.append( os.path.expanduser(line.split(':')[-1]) )
elif line.startswith('* @include:'):
code_idirs.append( os.path.expanduser(line.split(':')[-1]) )
elif line.startswith('* @define:'):
code_defines.extend( line.split(':')[-1].strip().split() )
# Start or end of a code block.
elif line.strip().startswith('```'):
fences += 1
# End of a code block.
if in_code:
if lang:
if lang=='python' and 'from rusthon import *' in code:
rusthonpy = []
for rln in open(__file__, 'rb').read().splitlines():
if rln == 'if __name__ == "__main__":':
break
else:
rusthonpy.append(rln)
rusthonpy = '\n'.join(rusthonpy)
utfheader = u'# -*- coding: utf-8 -*-\n'
code.insert(0, utfheader + BOOTSTRAPED + '\n' + rusthonpy.decode('utf-8'))
code.pop(code.index('from rusthon import *'))
p, n = os.path.split(url)
mod = {
'path':p,
'markdown':url,
'code':'\n'.join(code),
'index':index+index_offset,
'tag':tag,
'links':code_links,
'include-dirs':code_idirs,
'defines':code_defines,
}
if tag and '.' in tag:
ext = tag.split('.')[-1].lower()
#if ext in 'xml html js css py c cs h cpp hpp rust go java json'.split():
mod['name'] = tag
modules[ lang ].append( mod )
in_code = False
code = []
code_links = []
code_idirs = []
index += 1
# Start of a code block.
else:
in_code = True
if prevline and prevline.strip().startswith('@'):
tag = prevline.strip()[1:]
else:
tag = None
lang = line.strip().split('```')[-1]
# The middle of a code block.
elif in_code:
code.append(line)
else:
## import submarkdown file ##
if line.startswith('* ') and '@import' in line and line.count('[')==1 and line.count(']')==1 and line.count('(')==1 and line.count(')')==1:
submarkdown = line.split('(')[-1].split(')')[0].strip()
subpath = os.path.join(base_path, submarkdown)
if not os.path.isfile(subpath):
raise RuntimeError('error: can not find markdown file: '+subpath)
#print 'importing submarkdown'
#print subpath
index += import_md( subpath, modules, index_offset=index )
doc.append(line)
prevline = line
modules['markdown'] += '\n'.join(doc)
if fences % 2:
raise SyntaxError('invalid markdown - unclosed tripple back quote fence in: %s' %url)
return index
def hack_nim_stdlib(code):
'''
already talked to the nim guys in irc, they dont know why these dl functions need to be stripped
'''
out = []
for line in code.splitlines():
if 'dlclose(' in line or 'dlopen(' in line or 'dlsym(' in line:
pass
else:
out.append( line )
return '\n'.join(out)
def is_restricted_bash( line ):
if '&&' in line:
return False
if "`" in line:
return False
if '"' in line:
return False
okcmds = [
'./configure',
'make', 'cmake',
'scons', 'bazel',
'cd', 'mkdir', 'cp', #'pwd', 'ls',
'npm', 'grunt', 'gyp', 'nw-gyp',
'apt-get', 'yum',
'pip', 'docker', 'rhc',
]
cmd = line.split()[0]
if cmd == 'sudo': cmd = line.split()[1]
if cmd in okcmds:
return True
else:
return False
GITCACHE = os.path.expanduser('~/rusthon_cache')
def build( modules, module_path, datadirs=None ):
if '--debug-build' in sys.argv:
raise RuntimeError(modules)
output = {'executeables':[], 'rust':[], 'c':[], 'c++':[], 'c#':[], 'go':[], 'javascript':[], 'java':[], 'xml':[], 'json':[], 'python':[], 'html':[], 'verilog':[], 'nim':[], 'lua':[], 'dart':[], 'datadirs':datadirs, 'datafiles':{}}
python_main = {'name':'main.py', 'script':[]}
go_main = {'name':'main.go', 'source':[]}
tagged = {}
link = []
giws = [] ## xml jni generator so c++ can call into java, blocks tagged with @gwis are compiled and linked with the final exe.
java2rusthon = []
nim_wrappers = []
libdl = False ## provides: dlopen, dlclose, for dynamic libs. Nim needs this
cached_json = {}
gyp_builds = {}
if modules['bash']:
for mod in modules['bash']:
if 'tag' in mod and mod['tag']:
tag = mod['tag']
if tag.startswith('http://') or tag.startswith('https://'):
if not tag.endswith('.git'):
raise SyntaxError('only git repos links are allowed: '+tag)
if not os.path.isdir(GITCACHE):
print 'making new rusthon cache folder: ' + GITCACHE
os.mkdir(GITCACHE)
gitname = tag.split('/')[-1][:-4]
projectdir = os.path.join(GITCACHE, gitname)
rebuild = True
if gitname not in os.listdir(GITCACHE):
cmd = ['git', 'clone', tag]
subprocess.check_call(cmd, cwd=GITCACHE)
elif '--git-sync' in sys.argv:
cmd = ['git', 'pull']
subprocess.check_call(cmd, cwd=projectdir)
else:
rebuild = False
if rebuild or '--force-rebuild-deps' in sys.argv:
print 'rebuilding git repo: ' + tag
## TODO restrict the bash syntax allowed here,
## or build it in a sandbox or docker container.
for line in mod['code'].splitlines():
if not line.strip(): continue
if not is_restricted_bash(line):
raise SyntaxError('bash build script syntax is restricted:\n'+line)
else:
print '>>'+line
subprocess.check_call( line.split(), cwd=projectdir )
else:
output['datafiles'][tag] = mod['code']
if modules['gyp']:
for mod in modules['gyp']:
if 'tag' in mod and mod['tag']:
if not mod['tag'] != 'binding.gyp':
raise RuntimeError('nw-gyp requires the gyp file is named `binding.gyp`')
output['datafiles']['binding.gyp'] = mod['code']
gypcfg = json.loads( mod['code'].replace("'", '"') )
#if len(gypcfg['targets']) > 1:
# continue
for gtarget in gypcfg['targets']:
for gsrc in gtarget['sources']:
gyp_builds[ gsrc ] = {
'gyp':mod['code'],
'src': None
}
if modules['javascript']:
for mod in modules['javascript']:
if 'tag' in mod and mod['tag']:
tagged[ mod['tag'] ] = mod['code']
if '.' in mod['tag']:
output['datafiles'][mod['tag']] = mod['code']
if modules['json']:
for mod in modules['json']:
cached_json[ mod['name'] ] = mod['code']
output['json'].append(mod)
if modules['c#']:
for mod in modules['c#']:
output['c#'].append(mod)
if modules['elm']:
for mod in modules['elm']:
tmpelm = tempfile.gettempdir() + '/MyApp.elm'
tmpjs = tempfile.gettempdir() + '/elm-output.js'
open(tmpelm, 'wb').write(mod['code'])
subprocess.check_call(['elm-make', tmpelm, '--output', tmpjs])
elmdata = open(tmpjs,'rb').read()
output['datafiles'][mod['tag']] = elmdata
tagged[ mod['tag'] ] = elmdata
if modules['coffee']:
for mod in modules['coffee']:
tmpcoff = tempfile.gettempdir() + '/temp.coffee'
tmpjs = tempfile.gettempdir() + '/coffee-output.js'
open(tmpcoff, 'wb').write(mod['code'])
subprocess.check_call(['coffee', '--compile', '--bare', '--output', tmpjs, tmpcoff])
coffdata = open(tmpjs+'/temp.js','rb').read()
output['datafiles'][mod['tag']] = coffdata
tagged[ mod['tag'] ] = coffdata
if modules['rapydscript']:
for mod in modules['rapydscript']:
tmprapyd = tempfile.gettempdir() + '/temp.rapyd'
tmpjs = tempfile.gettempdir() + '/rapyd-output.js'
open(tmprapyd, 'wb').write(mod['code'].encode('utf-8'))
subprocess.check_call(['rapydscript', tmprapyd, '--bare', '--output', tmpjs])
rapydata = open(tmpjs,'rb').read()
output['datafiles'][mod['tag']] = rapydata
tagged[ mod['tag'] ] = rapydata
if modules['nim']:
libdl = True
## if compile_nim_lib is False then use old hack to compile nim source by extracting it and forcing into a single file.
compile_nim_lib = True
nimbin = os.path.expanduser('~/Nim/bin/nim')
niminclude = os.path.expanduser('~/Nim/lib')
if os.path.isfile(nimbin):
mods_sorted_by_index = sorted(modules['nim'], key=lambda mod: mod.get('index'))
for mod in mods_sorted_by_index:
if mod['tag']: ## save standalone nim program, can be run with `rusthon.py my.md --run=myapp.nim`
output['nim'].append(mod)
else: ## use nim to translate to C and build later as staticlib
tmpfile = tempfile.gettempdir() + '/rusthon_build.nim'
nimsrc = mod['code'].replace('\t', ' ') ## nim will not accept tabs, replace with two spaces.
gen_nim_wrappers( nimsrc, nim_wrappers )
open(tmpfile, 'wb').write( nimsrc )
if compile_nim_lib:
## lets nim compile the library
#cmd = [nimbin, 'compile', '--app:staticLib', '--noMain', '--header'] ## staticlib has problems linking with dlopen,etc.
cmd = [nimbin, 'compile', '--app:lib', '--noMain', '--header']
else:
cmd = [
nimbin,
'compile',
'--header',
'--noMain',
'--noLinking',
'--compileOnly',
'--genScript', ## broken?
'--app:staticLib', ## Araq says staticlib and noMain will not work together.
'--deadCodeElim:on',
]
if 'import threadpool' in nimsrc:
cmd.append('--threads:on')
cmd.append('rusthon_build.nim')
print('-------- compile nim program -----------')
print(' '.join(cmd))
subprocess.check_call(cmd, cwd=tempfile.gettempdir())
if compile_nim_lib:
## staticlib broken in nim? missing dlopen
libname = 'rusthon_build'
link.append(libname)
#output['c'].append({'source':mod['code'], 'staticlib':libname+'.a'})
output['c'].append(
{'source':mod['code'], 'dynamiclib':libname+'.so', 'name':'lib%s.so'%libname}
)
else:
## get source from nim cache ##
nimcache = os.path.join(tempfile.gettempdir(), 'nimcache')
nim_stdlib = hack_nim_stdlib(
open(os.path.join(nimcache,'stdlib_system.c'), 'rb').read()
)
#nim_header = open(os.path.join(nimcache,'rusthon_build.h'), 'rb').read()
nim_code = hack_nim_code(
open(os.path.join(nimcache,'rusthon_build.c'), 'rb').read()
)
## gets compiled below
cfg = {
'dynamic' : True,
'link-dirs' :[nimcache, niminclude],
#'build-dirs':[nimcache], ## not working
'index' : mod['index'],
'code' : '\n'.join([nim_stdlib, nim_code])
#'code' : header
}
modules['c'].append( cfg )
else:
print('WARNING: can not find nim compiler')
if modules['java']:
mods_sorted_by_index = sorted(modules['java'], key=lambda mod: mod.get('index'))
javafiles = []
tmpdir = tempfile.gettempdir()
for mod in mods_sorted_by_index:
if mod['tag']=='java2rusthon':
rcode = java_to_rusthon( mod['code'] )
java2rusthon.append( rcode )
elif 'name' in mod:
jpath = os.path.join(tmpdir, mod['name'])
if '/' in mod['name']:
jdir,jname = os.path.split(jpath)
if not os.path.isdir(jdir):
os.makedirs(jdir)
open(jpath, 'wb').write(mod['code'])
javafiles.append( jpath )
else:
raise SyntaxError('java code must have a tag header: `java2rusthon` or a file path')
if javafiles:
output['java'].append( compile_java( javafiles ) )
if modules['xml']:
mods_sorted_by_index = sorted(modules['xml'], key=lambda mod: mod.get('index'))
for mod in mods_sorted_by_index:
if mod['tag']=='gwis':
giws.append(mod['code']) ## hand written bindings should get saved in output tar.
bindings = compile_giws_bindings(mod['code'])
modules['c++'].append( {'code':bindings, 'index': mod['index']}) ## gets compiled below
else:
output['xml'].append(mod)
js_merge = []
cpp_merge = []
cpp_links = []
cpp_idirs = []
cpp_defines = []
compile_mode = 'binary'
exename = 'rusthon-test-bin'
tagged_trans_src = {}
if modules['rusthon']:
mods_sorted_by_index = sorted(modules['rusthon'], key=lambda mod: mod.get('index'))
for mod in mods_sorted_by_index:
script = mod['code']
index = mod.get('index')
header = script.splitlines()[0]
backend = 'c++' ## default to c++ backend
if header.startswith('#backend:'):
backend = header.split(':')[-1].strip()
if ' ' in backend:
backend, compile_mode = backend.split(' ')
if '\t' in backend:
backend, compile_mode = backend.split('\t')
if backend not in 'c++ rust javascript go verilog dart lua'.split():
raise SyntaxError('invalid backend: %s' %backend)
if compile_mode and compile_mode not in 'binary staticlib dynamiclib'.split():
raise SyntaxError('invalid backend option <%s> (valid types: binary, staticlib, dynamiclib)' %backend)
if backend == 'verilog':
vcode = translate_to_verilog( script )
modules['verilog'].append( {'code':vcode, 'index': index}) ## gets compiled below
elif backend == 'c++':
if mod['tag'] and mod['tag'] and '.' not in mod['tag']:
exename = mod['tag']
## user named output for external build tools that need .h,.hpp,.cpp, files output to hardcoded paths.
if mod['tag'] and (mod['tag'].endswith('.h') or mod['tag'].endswith('.hpp') or mod['tag'].endswith('.cpp') or mod['tag'].endswith('.cc')):
pyjs = python_to_pythonjs(script, cpp=True, module_path=module_path)
use_try = True
if '--no-except' in sys.argv:
use_try = False
elif mod['tag'] in gyp_builds.keys(): ## nw-gyp builds without c++ exceptions
use_try = False
pak = translate_to_cpp(
pyjs,
cached_json_files=cached_json,
insert_runtime=mod['tag'] in gyp_builds.keys(),
use_try = use_try
)
if '--debug-c++' in sys.argv:
raise RuntimeError(pak)
## pak contains: c_header and cpp_header
output['datafiles'][ mod['tag'] ] = pak['main'] ## save to output c++ to tar
if mod['tag'] in gyp_builds.keys():
gyp_builds[ mod['tag'] ]['src'] = pak['main']
if 'user-headers' in pak:
for classtag in pak['user-headers'].keys():
classheader = pak['user-headers'][ classtag ]
headerfile = classheader['file']
if headerfile in output['datafiles']:
output['datafiles'][ headerfile ] += '\n' + '\n'.join(classheader['source'])
else:
output['datafiles'][ headerfile ] = '\n' + '\n'.join(classheader['source'])
else:
cpp_merge.append(script)
if 'links' in mod:
cpp_links.extend(mod['links'])
if 'include-dirs' in mod:
cpp_idirs.extend(mod['include-dirs'])
if 'defines' in mod:
cpp_defines.extend(mod['defines'])
elif backend == 'rust':
pyjs = python_to_pythonjs(script, rust=True, module_path=module_path)
rustcode = translate_to_rust( pyjs )
modules['rust'].append( {'code':rustcode, 'index': index}) ## gets compiled below
elif backend == 'go':
pyjs = python_to_pythonjs(script, go=True, module_path=module_path)
gocode = translate_to_go( pyjs )
#modules['go'].append( {'code':gocode}) ## gets compiled below
go_main['source'].append( gocode )
elif backend == 'javascript':
if mod['tag'] and mod['tag'].endswith('.js'): ## saves to external js file
js = compile_js( mod['code'], module_path, main_name=mod['tag'] )
mod['build'] = {'script':js[mod['tag']]}
tagged[ mod['tag'] ] = js[mod['tag']]
tagged_trans_src[ mod['tag'] ] = mod['code'] ## so user can embed original source using <!tagname>
for name in js:
output['javascript'].append( {'name':name, 'script':js[name], 'index': index} )
else:
js_merge.append(mod)
elif backend == 'lua':
pyjs = python_to_pythonjs(script, lua=True, module_path=module_path)
luacode = translate_to_lua( pyjs )
name = 'main.lua'
if mod['tag']: name = mod['tag']
if not name.endswith('.lua'): name += '.lua'
output['lua'].append( {'name':name, 'script':luacode, 'index': index} )
elif backend == 'dart':
pyjs = python_to_pythonjs(script, dart=True, module_path=module_path)
dartcode = translate_to_dart( pyjs )
name = 'main.dart'
if mod['tag']: name = mod['tag']
if not name.endswith('.dart'): name += '.dart'
output['dart'].append( {'name':name, 'script':dartcode, 'index': index} )
if js_merge:
taggroups = {}
for mod in js_merge:
tagname = mod['tag']
if tagname not in taggroups:
taggroups[tagname] = []
src = taggroups[tagname]
src.append( mod['code'] )
for tagname in taggroups.keys():
groupsrc = '\n'.join( taggroups[tagname] )
js = compile_js( groupsrc, module_path, main_name=tagname )
tagged[ tagname ] = js[ tagname ]
tagged_trans_src[ tagname ] = groupsrc
for name in js:
output['javascript'].append( {'name':name, 'script':js[name], 'index': index} )
cpyembed = []
nuitka = []
nuitka_include_path = None ## TODO option for this
nuitka_module_name = 'unnamed_nuitka_module'
if modules['python']:
mods_sorted_by_index = sorted(modules['python'], key=lambda mod: mod.get('index'))
for mod in mods_sorted_by_index:
if mod['tag']:
name = mod['tag']
if name == 'nuitka' or name.startswith('nuitka:'):
if ':' in name:
nuitka_module_name = name.split(':')[-1]
if not len(nuitka):
## __file__ is undefined when CPython is embedded
#cpyembed.append('sys.path.append(os.path.dirname(__file__))')
#cpyembed.append('print sys.argv') ## also undefined
cpyembed.append('import sys')
cpyembed.append('sys.path.append("./")')
cpyembed.append('from %s import *'%nuitka_module_name)
nuitka.append(mod['code'])
elif name == 'embed' or name == 'embed:cpython':
cpyembed.append(mod['code'])
else:
if not name.endswith('.py'):
name += '.py'
output['python'].append( {'name':name, 'script':mod['code']} )
else:
if len(output['python'])==0:
python_main['script'].append( mod['code'] )
else:
output['python'][-1]['script'] += '\n' + mod['code']
if cpp_merge:
merge = []
nuitka_funcs = []
if java2rusthon:
merge.extend(java2rusthon)
java2rusthon = None
if nim_wrappers:
## inserts generated rusthon nim wrappers into script before translation ##
nim_wrappers.insert(0,'# nim wrappers generated by rusthon #')
nim_wrappers.insert(1, 'with extern(abi="C"):')
merge.extend(nim_wrappers)
if nuitka:
#npak = nuitka_compile_integrated('\n'.join(nuitka), nuitka_funcs)
#for h in npak['files']:
# modules['c++'].append(
# {'code':h['data'], 'tag':h['name'], 'index':0}
# )
nsrc = '\n'.join(nuitka)
output['c++'].append(
{
'staticlib' : nuitka_compile( nsrc, nuitka_module_name ),
'source-name' : 'my_nuitka_module.py',
'name' : 'my_nuitka_module.so',
'source' : nsrc,
}
)
merge.extend(cpp_merge)
script = '\n'.join(merge)
pyjs = python_to_pythonjs(script, cpp=True, module_path=module_path)
pak = translate_to_cpp( pyjs, cached_json_files=cached_json ) ## pak contains: c_header and cpp_header
n = len(modules['c++']) + len(giws)
cppcode = pak['main']
#if nuitka:
# cppcode = npak['main'] + '\n' + cppcode
if cpyembed:
inlinepy = ('\n'.join(cpyembed)).replace('\n', '\\n').replace('"', '\\"')
staticstr = 'const char* __python_main_script__ = "%s";\n' %inlinepy
cppcode = staticstr + cppcode
modules['c++'].append(
{'code':cppcode, 'index':n+1, 'links':cpp_links, 'include-dirs':cpp_idirs, 'defines':cpp_defines}
) ## gets compiled below
## HTML ##
if modules['html']:
mods_sorted_by_index = sorted(modules['html'], key=lambda mod: mod.get('index'))
for mod in mods_sorted_by_index:
html = []
for line in mod['code'].splitlines():
## `~/some/path/myscript.js` special syntax to copy javascript directly into the output html, good for testing locally.
if line.strip().startswith('<script ') and line.strip().endswith('</script>') and 'src="~/' in line:
url = line.split('src="')[-1].split('"')[0]
url = os.path.expanduser( url )
if os.path.isfile(url):
html.append('<script type="text/javascript">')
html.append( open(url, 'rb').read().decode('utf-8') )
html.append('</script>')
elif 'git="' in line:
giturl = line.split('git="')[-1].split('"')[0]
print 'downloading library-> ' + giturl
cmd = ['git', 'clone', giturl]
subprocess.check_call(cmd, cwd=os.environ['HOME'])
assert os.path.isfile(url)
html.append('<script type="text/javascript">')
html.append( open(url, 'rb').read().decode('utf-8') )
html.append('</script>')
elif 'source="' in line:
srcurl = line.split('source="')[-1].split('"')[0]
print 'downloading javascript-> ' + srcurl
import urllib
srcdata = urllib.urlopen(srcurl).read()
srcpath = os.path.split(url)[0]
if not os.path.isdir(srcpath):
os.makedirs(srcpath)
open(url, 'wb').write(srcdata)
assert os.path.isfile(url)
html.append('<script type="text/javascript">')
html.append( open(url, 'rb').read().decode('utf-8') )