Skip to content

Commit 06304cc

Browse files
Merge pull request #79 from Distributive-Network/wes/pmjs-use-inspect
pmjs + util.inspect
2 parents 2db4d63 + 5a6afd0 commit 06304cc

File tree

3 files changed

+45
-56
lines changed

3 files changed

+45
-56
lines changed

pmjs

Lines changed: 4 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ cmds.python = function pythonCmd(...args) {
4545
4646
const retval = python.eval(cmd);
4747
pythonCmd.serial = (pythonCmd.serial || 0) + 1;
48-
python.print('$' + pythonCmd.serial, '=', formatResult(retval));
48+
python.print('$' + pythonCmd.serial, '=', util.inspect(retval));
4949
globalThis['$' + pythonCmd.serial] = retval;
5050
};
5151
@@ -77,52 +77,6 @@ globalThis.replCmd = function replCmd(cmdLine)
7777
return cmds[cmdName].apply(null, argv);
7878
}
7979
80-
/** Return String(val) surrounded by appropriate ANSI escape codes to change the console text colour. */
81-
function colour(colourCode, val)
82-
{
83-
const esc=String.fromCharCode(27);
84-
return `${esc}[${colourCode}m${val}${esc}[0m`
85-
}
86-
87-
/**
88-
* Format result more intelligently than toString. Inspired by Node.js util.inspect, but far less
89-
* capable.
90-
*/
91-
globalThis.formatResult = function formatResult(result)
92-
{
93-
switch (typeof result)
94-
{
95-
case 'undefined':
96-
return colour(90, result);
97-
case 'function':
98-
return colour(36, result);
99-
case 'string':
100-
return colour(32, `'${result}'`);
101-
case 'boolean':
102-
case 'number':
103-
return colour(33, result);
104-
case 'object':
105-
if (result instanceof Date)
106-
return colour(35, result.toISOString());
107-
if (result instanceof Error)
108-
{
109-
const error = result;
110-
const LF = String.fromCharCode(10);
111-
const stackEls = error.stack
112-
.split(LF)
113-
.filter(a => a.length > 0)
114-
.map(a => ` ${a}`);
115-
return (`${error.name}: ${error.message}` + LF
116-
+ stackEls[0] + LF
117-
+ colour(90, stackEls.slice(1).join(LF))
118-
);
119-
}
120-
return JSON.stringify(result);
121-
default:
122-
return colour(31, `<unknown type ${typeof result}>${result}`);
123-
}
124-
}
125-
12680
/**
12781
* Evaluate a complete statement, built by the Python readline loop.
12882
*/
@@ -132,11 +86,11 @@ globalThis.replEval = function replEval(statement)
13286
try
13387
{
13488
const result = indirectEval(`${statement}`);
135-
return formatResult(result);
89+
return util.inspect(result);
13690
}
13791
catch(error)
13892
{
139-
return formatResult(error);
93+
return util.inspect(error);
14094
}
14195
}
14296
""");
@@ -348,6 +302,7 @@ def main():
348302
globalInitModule.patchGlobalRequire()
349303
pm.runProgramModule(args[0], args, requirePath)
350304
elif (enterRepl or forceRepl):
305+
globalInitModule.initReplLibs()
351306
repl()
352307

353308
if __name__ == "__main__":

pmjs-lib/global-init.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,12 @@ exports.makeArgvBuilder = function pmjsRequire$$makeArgvBuilder()
4040
* side effects in terms of local module id resolution, so this patch happens only right before we want
4141
* to fire up the program module.
4242
*/
43-
exports.patchGlobalRequire = function pmjsRequire$$patchGlobalRequire()
43+
exports.patchGlobalRequire = function pmjs$$patchGlobalRequire()
4444
{
4545
globalThis.require = require;
4646
}
47+
48+
exports.initReplLibs = function pmjs$$initReplLibs()
49+
{
50+
globalThis.util = require('util');
51+
}

python/pythonmonkey/builtin_modules/util.js

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,13 @@ const inspectDefaultOptions = Object.seal({
115115
const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
116116
const regExpToString = RegExp.prototype.toString;
117117
const dateToISOString = Date.prototype.toISOString;
118-
const errorToString = Error.prototype.toString;
118+
119+
/** Return String(val) surrounded by appropriate ANSI escape codes to change the console text colour. */
120+
function colour(colourCode, val)
121+
{
122+
const esc=String.fromCharCode(27);
123+
return `${esc}[${colourCode}m${val}${esc}[0m`
124+
}
119125

120126
var CIRCULAR_ERROR_MESSAGE;
121127

@@ -357,7 +363,8 @@ inspect.styles = Object.assign(Object.create(null), {
357363
'symbol': 'green',
358364
'date': 'magenta',
359365
// "name": intentionally not styling
360-
'regexp': 'red'
366+
'regexp': 'red',
367+
'error2': 'grey',
361368
});
362369

363370
function stylizeWithColor(str, styleType) {
@@ -524,8 +531,8 @@ function formatValue(ctx, value, recurseTimes, ln) {
524531
} else if (isError(value)) {
525532
// Make error with message first say the error
526533
if (keyLength === 0)
527-
return formatError(value);
528-
base = ` ${formatError(value)}`;
534+
return formatError(ctx, value);
535+
base = ` ${formatError(ctx, value)}`;
529536
} else if (isAnyArrayBuffer(value)) {
530537
// Fast path for ArrayBuffer and SharedArrayBuffer.
531538
// Can't do the same for DataView because it has a non-primitive
@@ -620,8 +627,30 @@ function formatPrimitive(fn, value) {
620627
return fn(value.toString(), 'symbol');
621628
}
622629

623-
function formatError(value) {
624-
return `[${errorToString.call(value)}]`;
630+
/**
631+
* Format an instance of Error. Error is the only type which is typically displayed using two different
632+
* colours -- the stack gets darker at the bottom where it's less relevant.
633+
*
634+
* @param ctx {object} inspect context - lets us know if we're using colors or not
635+
* @param error {object} instance of Error to inspect
636+
*/
637+
function formatError(ctx, error)
638+
{
639+
function style(str)
640+
{
641+
if (!ctx.stylize)
642+
return str;
643+
return ctx.stylize(str, 'error2');
644+
}
645+
646+
const stackEls = error.stack
647+
.split('\n')
648+
.filter(a => a.length > 0)
649+
.map(a => ` ${a}`);
650+
return (`${error.name}: ${error.message}\n`
651+
+ stackEls[0] + '\n'
652+
+ style(stackEls.slice(1).join('\n'))
653+
);
625654
}
626655

627656
function formatObject(ctx, value, recurseTimes, keys) {

0 commit comments

Comments
 (0)