forked from skulpt/skulpt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.js
More file actions
350 lines (322 loc) · 13.1 KB
/
Copy pathfunction.js
File metadata and controls
350 lines (322 loc) · 13.1 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
* @constructor
* Sk.builtin.func
*
* @description
* This function converts a Javascript function into a Python object that is callable. Or just
* think of it as a Python function rather than a Javascript function now. This is an important
* distinction in skulpt because once you have Python function you cannot just call it.
* You must now use Sk.misceval.callsim to call the Python function.
*
* @param {Function} code the javascript implementation of this function
* @param {Object=} globals the globals where this function was defined.
* Can be undefined (which will be stored as null) for builtins. (is
* that ok?)
* @param {Object=} closure dict of free variables
* @param {Object=} closure2 another dict of free variables that will be
* merged into 'closure'. there's 2 to simplify generated code (one is $free,
* the other is $cell)
*
* closure is the cell variables from the parent scope that we need to close
* over. closure2 is the free variables in the parent scope that we also might
* need to access.
*
* NOTE: co_varnames and co_name are defined by compiled code only, so we have
* to access them via dict-style lookup for closure.
*
*/
Sk.builtin.func = Sk.abstr.buildNativeClass("function", {
constructor: function func(code, globals, closure, closure2) {
Sk.asserts.assert(this instanceof Sk.builtin.func, "builtin func should be called as a class with `new`");
this.func_code = code;
this.func_globals = globals || null;
// use python str to preserve identity from compilation
this.$name = code.co_name || new Sk.builtin.str(code.name || "<native JS>");
this.$d = Sk.builtin.dict ? new Sk.builtin.dict() : undefined;
this.$doc = code.co_docstring || Sk.builtin.none.none$;
this.$module = (Sk.globals && Sk.globals["__name__"]) || Sk.builtin.none.none$;
this.$qualname = code.co_qualname || this.$name;
if (closure2 !== undefined) {
// todo; confirm that modification here can't cause problems
for (let k in closure2) {
closure[k] = closure2[k];
}
}
this.func_closure = closure;
this.func_annotations = null;
this.$memoiseFlags();
this.memoised = code.co_fastcall || null;
if (code.co_fastcall) {
this.tp$call = code.bind(this);
} else {
this.tp$call = Sk.builtin.func.prototype.$funcCall.bind(this); // keep func the same shape
}
},
slots: {
tp$getattr: Sk.generic.getAttr,
tp$descr_get(obj, objtype) {
if (obj === null) {
return this;
}
return new Sk.builtin.method(this, obj);
},
$r() {
return new Sk.builtin.str("<function " + this.$qualname + ">");
},
tp$call(args, kws) {
// we'll only be here from calling __call__ since we assigned tp$call in the constructor
return this.tp$call(args, kws);
},
},
getsets: {
__name__: {
$get() {
return this.$name;
},
$set(value) {
if (!Sk.builtin.checkString(value)) {
throw new Sk.builtin.TypeError("__name__ must be set to a string object");
}
this.$name = value;
},
},
__qualname__: {
$get() {
return new Sk.builtin.str(this.$qualname);
},
$set(value) {
if (!Sk.builtin.checkString(value)) {
throw new Sk.builtin.TypeError("__qualname__ must be set to a string object");
}
this.$qualname = value;
},
},
__dict__: Sk.generic.getSetDict,
__annotations__: {
$get() {
if (this.func_annotations === null) {
this.func_annotations = new Sk.builtin.dict([]);
} else if (Array.isArray(this.func_annotations)) {
this.func_annotations = Sk.abstr.keywordArrayToPyDict(this.func_annotations);
}
return this.func_annotations;
},
$set(v) {
if (v === undefined || Sk.builtin.checkNone(v)) {
this.func_annotations = new Sk.builtin.dict([]);
} else if (v instanceof Sk.builtin.dict) {
this.func_annotations = v;
} else {
throw new Sk.builtin.TypeError("__annotations__ must be set to a dict object");
}
}
},
__defaults__: {
$get() {
return this.$defaults == null ? Sk.builtin.none.none$ : new Sk.builtin.tuple(this.$defaults);
},
$set(v) {
if (v === undefined || Sk.builtin.checkNone(v)) {
this.$defaults = null;
} else if (!(v instanceof Sk.builtin.tuple)) {
throw new Sk.builtin.TypeError("__defaults__ must be set to a tuple object");
} else {
this.$defaults = v.valueOf();
}
}
},
__doc__: {
$get() {
return this.$doc;
},
$set(v) {
// The value the user is setting __doc__ to can be any Python
// object. If we receive 'undefined' then the user is deleting
// __doc__, which is allowed and results in __doc__ being None.
this.$doc = v || Sk.builtin.none.none$;
},
},
__module__: {
$get() {
return this.$module;
},
$set(v) {
this.$module = v || Sk.builtin.none.none$;
}
}
},
proto: {
$memoiseFlags() {
this.co_varnames = this.func_code.co_varnames;
this.co_argcount = this.func_code.co_argcount;
if (this.co_argcount === undefined && this.co_varnames) {
this.co_argcount = this.co_argcount = this.co_varnames.length;
}
this.co_kwonlyargcount = this.func_code.co_kwonlyargcount || 0;
this.co_varargs = this.func_code.co_varargs;
this.co_kwargs = this.func_code.co_kwargs;
this.$defaults = this.func_code.$defaults;
this.$kwdefs = this.func_code.$kwdefs || [];
},
$resolveArgs,
$funcCall(posargs, kw) {
// Property reads from func_code are slooow, but
// the existing external API allows setup first, so as a
// hack we delay this initialisation.
// TODO change the external API to require all the co_vars
// to be supplied at construction time!
if (!this.memoised) {
this.$memoiseFlags();
this.memoised = true;
}
// Fast path for JS-native functions (which should be implemented
// in a separate tp$call, really)
if (
this.co_argcount === undefined &&
this.co_varnames === undefined &&
!this.co_kwargs &&
!this.func_closure
) {
// It's a JS function with no type info, don't hang around
// resolving anything.
if (kw && kw.length !== 0) {
throw new Sk.builtin.TypeError(this.$name + "() takes no keyword arguments");
}
return this.func_code.apply(this.func_globals, posargs);
}
// end js fast path
let args = this.$resolveArgs(posargs, kw);
if (this.func_closure) {
args.push(this.func_closure);
}
// note: functions expect 'this' to be globals to avoid having to
// slice/unshift onto the main args
return this.func_code.apply(this.func_globals, args);
},
},
});
function $resolveArgs(posargs, kw) {
// The rest of this function is a logical Javascript port of
// _PyEval_EvalCodeWithName, and follows its logic,
// plus fast-paths imported from _PyFunction_FastCall* as marked
let co_argcount = this.co_argcount;
if (co_argcount === undefined) {
co_argcount = this.co_varnames ? this.co_varnames.length : posargs.length;
}
let varnames = this.co_varnames || [];
let co_kwonlyargcount = this.co_kwonlyargcount || 0;
let totalArgs = co_argcount + co_kwonlyargcount;
// Fast path from _PyFunction_FastCallDict
if (co_kwonlyargcount === 0 && !this.co_kwargs && (!kw || kw.length === 0) && !this.co_varargs) {
if (posargs.length == co_argcount) {
return posargs;
} else if (posargs.length === 0 && this.$defaults && this.$defaults.length === co_argcount) {
for (let i = 0; i != this.$defaults.length; i++) {
posargs[i] = this.$defaults[i];
}
return posargs;
}
}
// end fast path from _PyFunction_FastCallDict
let kwargs;
/* Create a NOT-a-dictionary for keyword parameters (**kwags) */
if (this.co_kwargs) {
kwargs = [];
}
/* Copy positional arguments into arguments to our JS function*/
let nposargs = posargs.length;
let args = (posargs.length <= co_argcount) ? posargs : posargs.slice(0, co_argcount);
/* Pack other positional arguments into the *args argument */
if (this.co_varargs) {
let vararg = (posargs.length > args.length) ? posargs.slice(args.length) : [];
args[totalArgs] = new Sk.builtin.tuple(vararg);
} else if (nposargs > co_argcount) {
const plural_expected = co_argcount == 1 ? "argument" : "arguments";
const plural_given = nposargs == 1 ? "was" : "were";
throw new Sk.builtin.TypeError(`${this.$name}() takes ${co_argcount} positional ${plural_expected} but ${nposargs} ${plural_given} given`);
}
/* Handle keyword arguments */
if (kw) {
if (this.func_code["no_kw"]) {
throw new Sk.builtin.TypeError(this.$name + "() takes no keyword arguments");
}
for (let i = 0; i < kw.length; i += 2) {
let name = kw[i]; // JS string
let value = kw[i+1]; // Python value
let idx = varnames.indexOf(name);
if (idx >= 0) {
if (args[idx] !== undefined) {
throw new Sk.builtin.TypeError(this.$name + "() got multiple values for argument '" + name + "'");
}
args[idx] = value;
} else if (kwargs) {
kwargs.push(new Sk.builtin.str(name), value);
} else {
throw new Sk.builtin.TypeError(this.$name + "() got an unexpected keyword argument '" + name + "'");
}
}
}
/* "Check the number of positional arguments" (which only checks for too many)
has been handled before keywords */
/* Add missing positional arguments (copy default values from defs)
(also checks for missing args where no defaults) */
{
let defaults = this.$defaults || [];
let i = 0, missing = [], missingUnnamed = false;
// Positional args for which we *don't* have a default
let defaultStart = co_argcount - defaults.length;
for (; i < defaultStart; i++) {
if (args[i] === undefined) {
missing.push(varnames[i]);
if (varnames[i] === undefined) {
missingUnnamed = true;
}
}
}
if (missing.length != 0 && (this.co_argcount || this.co_varnames)) {
throw new Sk.builtin.TypeError(
this.$name +
"() missing " +
missing.length +
" required argument" +
(missing.length == 1 ? "" : "s") +
(missingUnnamed ? "" : ": " + missing.map((x) => "'" + x + "'").join(", "))
);
}
for (; i < co_argcount; i++) {
if (args[i] === undefined) {
args[i] = defaults[i - defaultStart];
}
}
}
/* Add missing keyword arguments (copy default values from kwdefs) */
if (co_kwonlyargcount > 0) {
let missing = [];
let kwdefs = this.$kwdefs;
for (let i = co_argcount; i < totalArgs; i++) {
if (args[i] === undefined) {
if (kwdefs[i-co_argcount] !== undefined) {
args[i] = kwdefs[i-co_argcount];
} else {
missing.push(varnames[i]);
}
}
}
if (missing.length !== 0) {
throw new Sk.builtin.TypeError(this.$name + "() missing " + missing.length + " required keyword argument" + (missing.length==1?"":"s") + ": " + missing.join(", "));
}
}
if (this.func_closure) {
// todo; OK to modify?
if (varnames) {
// Make sure all default arguments are in args before adding closure
for (let i = args.length; i < varnames.length; i++) {
args.push(undefined);
}
}
}
if (kwargs) {
args.unshift(kwargs);
}
return args;
};