-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython2js.py
More file actions
51 lines (43 loc) · 1.41 KB
/
python2js.py
File metadata and controls
51 lines (43 loc) · 1.41 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
__author__ = 'long'
import sys
import os
from antlr4 import *
from antlr4.InputStream import InputStream
from Python3Lexer import Python3Lexer
from Python3Parser import Python3Parser
from JSEmitter import JSEmitter
from filter import spaceFilter
if __name__ == '__main__':
file_name = 'result'
lexer_name = 'lexer.py'
# 由于词法分析对空行处理有bug, 故先预处理, 将空行消除
if len(sys.argv) > 1:
file_name = sys.argv[1].split('.')[0]
spaceFilter(sys.argv[1], lexer_name)
else:
with open('lexer_tmp.py', 'w') as fi:
fi.write(sys.stdin.read())
spaceFilter('lexer_tmp.py', lexer_name)
os.remove('lexer_tmp.py')
input_stream = FileStream(lexer_name, encoding='utf-8')
os.remove(lexer_name)
lexer = Python3Lexer(input_stream)
token_stream = CommonTokenStream(lexer)
parser = Python3Parser(token_stream)
tree = parser.parse()
lisp_tree_str = tree.toStringTree(recog=parser)
# listener
print("Start Walking...")
listener = JSEmitter()
walker = ParseTreeWalker()
walker.walk(listener, tree)
listener.clearAll()
walker.walk(listener, tree)
if len(listener.errorLog) > 0:
for e in listener.errorLog:
print(e)
else:
with open('tmp.js', 'w') as fi:
fi.write(listener.getJS(tree))
spaceFilter('tmp.js', file_name+'.js')
os.remove('tmp.js')