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