forked from Distributive-Network/PythonMonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpmjs
More file actions
executable file
·309 lines (273 loc) · 11.3 KB
/
pmjs
File metadata and controls
executable file
·309 lines (273 loc) · 11.3 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
#! /usr/bin/env python3
# @file pmjs - PythonMonkey REPL
# @author Wes Garland, wes@distributive.network
# @date June 2023
import sys, os, readline, signal, getopt
import pythonmonkey as pm
globalThis = pm.eval("globalThis")
if (os.getenv('PMJS_PATH')):
requirePath = list(map(os.path.abspath, os.getenv('PMJS_PATH').split(':')))
else:
requirePath = False;
globalThis = pm.eval("globalThis;")
pm.eval("""'use strict';
const cmds = {};
cmds.help = function help() {
return '.' +
`exit Exit the REPL
.help Print this help message
.load Load JS from a file into the REPL session
.save Save all evaluated commands in this REPL session to a file
.python Evaluate a Python statement, returning result as global variable $n.
Use '.python reset' to rest back to $1.
Statement starting with 'from' or 'import' are silently executed.
Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL`
};
cmds.exit = python.exit;
cmds.python = function pythonCmd(...args) {
const cmd = args.join(' ').trim();
if (cmd === 'reset')
{
pythonCmd.serial = 0;
return;
}
if (arguments[0] === 'from' || arguments[0] === 'import')
return python.exec(cmd);
const retval = python.eval(cmd);
pythonCmd.serial = (pythonCmd.serial || 0) + 1;
python.print('$' + pythonCmd.serial, '=', util.inspect(retval));
globalThis['$' + pythonCmd.serial] = retval;
};
/**
* Handle a .xyz repl command. Invokes function cmds[XXX], passing arguments that the user typed as the
* function arguments. The function arguments are space-delimited arguments; arguments surrounded by
* quotes can include spaces, similar to how bash parses arguments. Argument parsing cribbed from
* stackoverflow user Tsuneo Yoshioka, question 4031900.
*
* @param {string} cmdLine the command the user typed, without the leading .
* @returns {string} to display
*/
globalThis.replCmd = function replCmd(cmdLine)
{
const cmdName = (cmdLine.match(/^[^ ]+/) || ['help'])[0];
const args = cmdLine.slice(cmdName.length).trim();
const argv = args.match(/\\\\?.|^$/g).reduce((p, c) => {
if (c === '"')
p.quote ^= 1;
else if (!p.quote && c === ' ')
p.a.push('');
else
p.a[p.a.length-1] += c.replace(/\\\\(.)/,"$1");
return p;
}, {a: ['']}).a;
if (!cmds.hasOwnProperty(cmdName))
return `Invalid REPL keyword`;
return cmds[cmdName].apply(null, argv);
}
/**
* Evaluate a complete statement, built by the Python readline loop.
*/
globalThis.replEval = function replEval(statement)
{
const indirectEval = eval;
try
{
const result = indirectEval(`${statement}`);
return util.inspect(result);
}
catch(error)
{
return util.inspect(error);
}
}
""");
def repl():
"""
Start a REPL to evaluate JavaScript code in the extra-module environment. Multi-line statements and
readline history are supported. ^C support is sketchy. Exit the REPL with ^D or ".quit".
"""
print('Welcome to PythonMonkey v' + pm.__version__ +'.')
print('Type ".help" for more information.')
readline.parse_and_bind('set editing-mode emacs')
histfile = os.getenv('PMJS_REPL_HISTORY') or os.path.expanduser('~/.pmjs_history')
if (os.path.exists(histfile)):
try:
readline.read_history_file(histfile)
except:
pass
got_sigint = 0
statement = ''
readline_skip_chars = 0
inner_loop = False
def save_history():
nonlocal histfile
readline.write_history_file(histfile)
import atexit
atexit.register(save_history)
def quit():
"""
Quit the REPL. Repl saved by atexit handler.
"""
sys.exit(0)
def sigint_handler(signum, frame):
"""
Handle ^C by aborting the entry of the current statement and quitting when double-struck.
Sometimes this happens in the main input() function. When that happens statement is "", because
we have not yet returned from input(). Sometimes it happens in the middle of the inner loop's
input() - in that case, statement is the beginning of a multiline expression. Hitting ^C in the
middle of a multiline express cancels its input, but readline's input() doesn't return, so we
have to print the extra > prompt and fake it by later getting rid of the first readline_skip_chars
characters from the input buffer.
"""
nonlocal got_sigint
nonlocal statement
nonlocal readline_skip_chars
nonlocal inner_loop
got_sigint = got_sigint + 1
if (got_sigint > 1):
sys.stdout.write("\n")
quit()
if (inner_loop != True):
if (got_sigint == 1 and len(readline.get_line_buffer()) == readline_skip_chars):
# First ^C with nothing in the input buffer
sys.stdout.write("\n(To exit, press Ctrl+C again or Ctrl+D or type .exit)")
elif (got_sigint == 1 and readline.get_line_buffer() != ""):
# Input buffer has text - clear it
got_sigint = 0
readline_skip_chars = len(readline.get_line_buffer())
else:
if (got_sigint == 1 and statement == "" and len(readline.get_line_buffer()) == readline_skip_chars):
# statement == "" means that the inner loop has already seen ^C and is now faking the outer loop
sys.stdout.write("\n(To exit, press Ctrl+C again or Ctrl+D or type .exit)")
elif (got_sigint == 1 and statement != ""):
# ^C happened on inner loop while it was still thinking we were doing a multiline-expression; since
# we can't break the input() function, we set it up to return an outer expression and fake the outer loop
got_sigint = 0
readline_skip_chars = len(readline.get_line_buffer())
sys.stdout.write("\n> ")
statement = ""
signal.signal(signal.SIGINT, sigint_handler)
# Main Loop
#
# Read lines entered by the user and collect them in a statement. Once the statement is a candiate
# for JavaScript evaluation (determined by pm.isCompilableUnit(), send it to replEval(). Statements
# beginning with a . are interpreted as REPL commands and sent to replCmd().
#
# Beware - extremely tricky interplay between readline and the SIGINT handler. This is largely because we
# we can't clear the pending line buffer, so we have to fake it by re-displaying the prompt and subtracting
# characters. Another complicating factor is that the handler will suspend and resume readline, but there
# is no mechanism to force readline to return before the user presses enter.
#
while got_sigint < 2:
try:
inner_loop = False
if (statement == ""):
statement = input('> ')[readline_skip_chars:]
readline_skip_chars = 0
if (len(statement) == 0):
continue
if (statement[0] == '.'):
print(globalThis.replCmd(statement[1:]))
statement = ""
continue
if (pm.isCompilableUnit(statement)):
print(globalThis.replEval(statement))
statement = ""
got_sigint = 0
else:
got_sigint = 0
# This loop builds a multi-line statement, but if the user hits ^C during this build, we
# abort the statement. The tricky part here is that the input('... ') doesn't quit when
# SIGINT is received, so we have to patch things up so that the next-entered line is
# treated as the input at the top of the loop.
while (got_sigint == 0):
inner_loop = True
lineBuffer = input('... ')
more = lineBuffer[readline_skip_chars:]
readline_skip_chars = 0
if (got_sigint > 0):
statement = more
break
statement = statement + '\n' + more
if (pm.isCompilableUnit(statement)):
print(globalThis.replEval(statement))
statement = ""
break
except EOFError:
print()
quit()
def usage():
print("""Usage: pmjs [options] [ script.js ] [arguments]
Options:
- script read from stdin (default if no file name is provided, interactive mode if a tty)
-- indicate the end of node options
-e, --eval=... evaluate script
-h, --help print pnode command line options (currently set)
-i, --interactive always enter the REPL even if stdin does not appear to be a terminal
-p, --print [...] evaluate script and print result
-r, --require... module to preload (option can be repeated)
-v, --version print PythonMonkey version
Environment variables:
TZ specify the timezone configuration
PMJS_PATH ':'-separated list of directories prefixed to the module search path
PMJS_REPL_HISTORY path to the persistent REPL history file"""
)
def initGlobalThis():
"""
Initialize globalThis for for pmjs use in the extra-module context (eg -r, -e, -p). This context
needs a require function which resolve modules relative to the current working directory at pmjs
launch. The global require is to the JS function using a trick iinstead of a JS-wrapped-Python-wrapped function
"""
global requirePath
require = pm.createRequire(os.path.abspath(os.getcwd() + '/__pmjs_virtual__'), requirePath)
globalThis.require = require
globalInitModule = require(os.path.dirname(__file__) + "/pmjs-lib/global-init") # module load has side-effects
argvBuilder = globalInitModule.makeArgvBuilder()
for arg in sys.argv:
argvBuilder(arg); # list=>Array not working yet
return globalInitModule
def main():
"""
Main program entry point
"""
enterRepl = sys.stdin.isatty()
forceRepl = False
globalInitModule = initGlobalThis()
global requirePath
try:
opts, args = getopt.getopt(sys.argv[1:], "hie:p:r:v", ["help", "eval=", "print=", "require=", "version"])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o in ("-v", "--version"):
print(pm.__version__)
sys.exit()
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--interactive"):
forceRepl = True
elif o in ("-e", "--eval"):
pm.eval(a)
enterRepl = False
elif o in ("-p", "--print"):
print(pm.eval(a))
enterRepl = False
elif o in ("-r", "--require"):
globalThis.require(a)
# pm.eval('require')(a)
else:
assert False, "unhandled option"
if (len(args) > 0):
globalInitModule.patchGlobalRequire()
pm.runProgramModule(args[0], args, requirePath)
elif (enterRepl or forceRepl):
globalInitModule.initReplLibs()
repl()
if __name__ == "__main__":
main()