Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/tools/web_repl.js
1396 views
1
/* vim:fileencoding=utf-8
2
*
3
* Copyright (C) 2016 Kovid Goyal <kovid at kovidgoyal.net>
4
*
5
* Distributed under terms of the BSD license
6
*/
7
"use strict"; /*jshint node:true */
8
var vm = require("vm");
9
var embedded_compiler = require("tools/embedded_compiler.js");
10
11
module.exports = function (compiler, baselib) {
12
var ctx = vm.createContext();
13
var LINE_CONTINUATION_CHARS = ":\\";
14
var find_completions = null;
15
var streaming_compiler = embedded_compiler(
16
compiler,
17
baselib,
18
function (js) {
19
return vm.runInContext(js, ctx);
20
},
21
"__repl__"
22
);
23
24
return {
25
in_block_mode: false,
26
27
replace_print: (write_line_func) => {
28
ctx.print = function () {
29
var parts = [];
30
for (var i = 0; i < arguments.length; i++)
31
parts.push(ctx.ρσ_str(arguments[i]));
32
write_line_func(parts.join(" "));
33
};
34
},
35
36
is_input_complete: (source) => {
37
if (!source || !source.trim()) return false;
38
var lines = source.split("\n");
39
var last_line = lines[lines.length - 1].trimRight();
40
if (this.in_block_mode) {
41
// In a block only exit after two blank lines
42
if (lines.length < 2) return false;
43
var second_last_line = lines[lines.length - 2].trimRight();
44
var block_ended = !!(!last_line && !second_last_line);
45
if (!block_ended) return false;
46
this.in_block_mode = false;
47
return true;
48
}
49
50
if (
51
last_line &&
52
LINE_CONTINUATION_CHARS.indexOf(
53
last_line.substr(last_line.length - 1)
54
) > -1
55
) {
56
this.in_block_mode = true;
57
return false;
58
}
59
try {
60
compiler.parse(source, { filename: "<repl>", basedir: "__stdlib__" });
61
} catch (e) {
62
if (e.is_eof && e.line === lines.length && e.col > 0) {
63
return false;
64
}
65
this.in_block_mode = false;
66
return true;
67
}
68
this.in_block_mode = false;
69
return true;
70
},
71
72
compile: (code, opts) => {
73
opts = opts || {};
74
opts.keep_docstrings = true;
75
opts.filename = "<input>";
76
return streaming_compiler.compile(code, opts);
77
},
78
79
runjs: (code) => {
80
var ans = vm.runInContext(code, ctx);
81
if (ans !== undefined || ans === null) {
82
ctx.ρσ_repl_val = ans;
83
var q = vm.runInContext("ρσ_repr(ρσ_repl_val)", ctx);
84
ans = q === "undefined" ? ans.toString() : q;
85
}
86
return ans;
87
},
88
89
init_completions: (completelib) => {
90
find_completions = completelib(compiler);
91
},
92
93
find_completions: (line) => {
94
return find_completions(line, ctx);
95
},
96
};
97
};
98
99