Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/tools/embedded_compiler.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
9
var has_prop = Object.prototype.hasOwnProperty.call.bind(
10
Object.prototype.hasOwnProperty
11
);
12
13
module.exports = function (compiler, baselib, runjs, name) {
14
var LINE_CONTINUATION_CHARS = ":\\";
15
runjs = runjs || eval;
16
runjs(print_ast(compiler.parse(""), true));
17
runjs('var __name__ = "' + (name || "__embedded__") + '";');
18
19
function print_ast(
20
ast,
21
keep_baselib,
22
keep_docstrings,
23
private_scope,
24
write_name
25
) {
26
var output_options = {
27
omit_baselib: !keep_baselib,
28
write_name: !!write_name,
29
private_scope: !!private_scope,
30
beautify: true,
31
keep_docstrings: keep_docstrings,
32
};
33
if (keep_baselib) output_options.baselib_plain = baselib;
34
var output = new compiler.OutputStream(output_options);
35
ast.print(output);
36
return output.get();
37
}
38
39
return {
40
toplevel: null,
41
42
compile: (code, opts) => {
43
opts = opts || {};
44
var classes = this.toplevel ? this.toplevel.classes : undefined;
45
var scoped_flags = this.toplevel ? this.toplevel.scoped_flags : undefined;
46
this.toplevel = compiler.parse(code, {
47
filename: opts.filename || "<embedded>",
48
basedir: "__stdlib__",
49
classes: classes,
50
scoped_flags: scoped_flags,
51
discard_asserts: opts.discard_asserts,
52
});
53
var ans = print_ast(
54
this.toplevel,
55
opts.keep_baselib,
56
opts.keep_docstrings,
57
opts.private_scope,
58
opts.write_name
59
);
60
if (classes) {
61
var class_exports = {};
62
var self = this;
63
this.toplevel.exports.forEach(function (name) {
64
class_exports[name] = true;
65
});
66
Object.getOwnPropertyNames(classes).forEach(function (name) {
67
if (
68
!has_prop(class_exports, name) &&
69
!has_prop(self.toplevel.classes, name)
70
)
71
self.toplevel.classes[name] = classes[name];
72
});
73
}
74
scoped_flags = this.toplevel.scoped_flags;
75
76
return ans;
77
},
78
};
79
};
80
81