File size: 26,868 Bytes
baac5bb |
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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _PyDict_dict;
import { check, deepFreeze } from "./shared_utils.js";
const MEMOIZED = { parser: null };
class ExecuteContext {
constructor(existing = {}) {
Object.assign(this, !!window.structuredClone ? structuredClone(existing) : { ...existing });
}
}
class InitialExecuteContext extends ExecuteContext {
}
const TYPE_TO_HANDLER = new Map([
["module", handleChildren],
["expression_statement", handleChildren],
["interpolation", handleInterpolation],
["block", handleChildren],
["comment", handleSwallow],
["return_statement", handleReturn],
["assignment", handleAssignment],
["named_expression", handleNamedExpression],
["identifier", handleIdentifier],
["attribute", handleAttribute],
["subscript", handleSubscript],
["call", handleCall],
["argument_list", handleArgumentsList],
["for_statement", handleForStatement],
["list_comprehension", handleListComprehension],
["comparison_operator", handleComparisonOperator],
["boolean_operator", handleBooleanOperator],
["binary_operator", handleBinaryOperator],
["not_operator", handleNotOperator],
["unary_operator", handleUnaryOperator],
["integer", handleNumber],
["float", handleNumber],
["string", handleString],
["tuple", handleList],
["list", handleList],
["dictionary", handleDictionary],
["pair", handleDictionaryPair],
["true", async (...args) => true],
["false", async (...args) => false],
]);
const DEFAULT_BUILT_INS = {
round: { fn: (n) => Math.round(Number(n)) },
ceil: { fn: (n) => Math.ceil(Number(n)) },
floor: { fn: (n) => Math.floor(Number(n)) },
len: { fn: (n) => { var _a, _b; return (_b = (_a = n === null || n === void 0 ? void 0 : n.__len__) === null || _a === void 0 ? void 0 : _a.call(n)) !== null && _b !== void 0 ? _b : n === null || n === void 0 ? void 0 : n.length; } },
int: { fn: (n) => Math.floor(Number(n)) },
float: { fn: (n) => Number(n) },
str: { fn: (n) => String(n) },
bool: { fn: (n) => !!n },
list: { fn: (tupl = []) => new PyList(tupl) },
tuple: { fn: (list = []) => new PyTuple(list) },
dict: { fn: (dict = {}) => new PyDict(dict) },
dir: { fn: (...args) => console.dir(...__unwrap__(...args)) },
print: { fn: (...args) => console.log(...__unwrap__(...args)) },
log: { fn: (...args) => console.log(...__unwrap__(...args)) },
};
export async function execute(code, ctx, additionalBuiltins) {
var _a, _b;
const builtIns = deepFreeze({ ...DEFAULT_BUILT_INS, ...(additionalBuiltins !== null && additionalBuiltins !== void 0 ? additionalBuiltins : {}) });
ctx = new InitialExecuteContext(ctx);
const root = (await parse(code)).rootNode;
const value = await handleNode(new Node(root), ctx, builtIns);
console.log("=====");
console.log(`value`, (_b = (_a = value === null || value === void 0 ? void 0 : value.__unwrap__) === null || _a === void 0 ? void 0 : _a.call(value)) !== null && _b !== void 0 ? _b : value);
console.log("context", ctx);
return value;
}
async function parse(code) {
if (!MEMOIZED.parser) {
const TreeSitter = (await import("../lib/tree-sitter.js"));
await TreeSitter.Parser.init();
const lang = await TreeSitter.Language.load("rgthree/lib/tree-sitter-python.wasm");
MEMOIZED.parser = new TreeSitter.Parser();
MEMOIZED.parser.setLanguage(lang);
}
return MEMOIZED.parser.parse(code);
}
async function handleNode(node, ctx, builtIns) {
const type = node.type;
if (ctx.hasOwnProperty("__returned__"))
return ctx["__returned__"];
const handler = TYPE_TO_HANDLER.get(type);
check(handler, "Unhandled type: " + type, node);
return handler(node, ctx, builtIns);
}
async function handleChildren(node, ctx, builtIns) {
let lastValue = null;
for (const child of node.children) {
if (!child)
continue;
lastValue = await handleNode(child, ctx, builtIns);
}
return lastValue;
}
async function handleSwallow(node, ctx, builtIns) {
}
async function handleReturn(node, ctx, builtIns) {
const value = node.children.length > 1 ? handleNode(node.child(1), ctx, builtIns) : undefined;
ctx["__returned__"] = value;
return value;
}
async function handleIdentifier(node, ctx, builtIns) {
var _a, _b;
let value = ctx[node.text];
if (value === undefined) {
value = (_b = (_a = builtIns[node.text]) === null || _a === void 0 ? void 0 : _a.fn) !== null && _b !== void 0 ? _b : undefined;
}
return maybeWrapValue(value);
}
async function handleAttribute(node, ctx, builtIns) {
const children = node.children;
check(children.length === 3, "Expected 3 children for attribute.");
check(children[1].type === ".", "Expected middle child to be '.' for attribute.");
const inst = await handleNode(children[0], ctx, builtIns);
const attr = children[2].text;
checkAttributeAccessibility(inst, attr);
let attribute = maybeWrapValue(inst[attr]);
return typeof attribute === "function" ? attribute.bind(inst) : attribute;
}
async function handleSubscript(node, ctx, builtIns) {
const children = node.children;
check(children.length === 4, "Expected 4 children for subscript.");
check(children[1].type === "[", "Expected 2nd child to be '[' for subscript.");
check(children[3].type === "]", "Expected 4thd child to be ']' for subscript.");
const inst = await handleNode(children[0], ctx, builtIns);
const attr = await handleNode(children[2], ctx, builtIns);
if (inst instanceof PyTuple && isInt(attr)) {
return maybeWrapValue(inst.__at__(attr));
}
if (inst instanceof PyDict && typeof attr === "string") {
return maybeWrapValue(inst.get(attr));
}
checkAttributeAccessibility(inst, attr);
let attribute = maybeWrapValue(inst[attr]);
return typeof attribute === "function" ? attribute.bind(inst) : attribute;
}
async function handleAssignment(node, ctx, builtIns) {
check(node.children.length === 3, "Expected 3 children for assignment: identifier/attr, =, and value.");
check(node.children[1].type === "=", "Expected middle child to be an '='.");
let right = await handleNode(node.children[2], ctx, builtIns);
const leftNode = node.children[0];
let leftObj = ctx;
let leftProp = "";
if (leftNode.type === "identifier") {
leftProp = leftNode.text;
}
else if (leftNode.type === "attribute") {
leftObj = await handleNode(leftNode.children[0], ctx, builtIns);
check(leftNode.children[2].type === "identifier", "Expected left hand assignment attribute to be an identifier.", leftNode);
leftProp = leftNode.children[2].text;
}
else if (leftNode.type === "subscript") {
leftObj = await handleNode(leftNode.children[0], ctx, builtIns);
check(leftNode.children[1].type === "[");
check(leftNode.children[3].type === "]");
leftProp = await handleNode(leftNode.children[2], ctx, builtIns);
}
else {
throw new Error(`Unhandled left-hand assignement type: ${leftNode.type}`);
}
if (leftProp == null) {
throw new Error(`No property to assign value`);
}
if (leftObj instanceof PyTuple) {
check(isInt(leftProp), "Expected an int for list assignment");
leftObj.__put__(leftProp, right);
}
else if (leftObj instanceof PyDict) {
check(typeof leftProp === "string", "Expected a string for dict assignment");
leftObj.__put__(leftProp, right);
}
else {
check(typeof leftProp === "string", "Expected a string for object assignment");
if (!(leftObj instanceof InitialExecuteContext)) {
checkAttributeAccessibility(leftObj, leftProp);
}
leftObj[leftProp] = right;
}
return right;
}
async function handleNamedExpression(node, ctx, builtIns) {
check(node.children.length === 3, "Expected three children for named expression.");
check(node.child(0).type === "identifier", "Expected identifier first in named expression.");
const varName = node.child(0).text;
ctx[varName] = await handleNode(node.child(2), ctx, builtIns);
return maybeWrapValue(ctx[varName]);
}
async function handleCall(node, ctx, builtIns) {
check(node.children.length === 2, "Expected 2 children for call, identifier and arguments.");
const fn = await handleNode(node.children[0], ctx, builtIns);
const args = await handleNode(node.children[1], ctx, builtIns);
console.log("handleCall", fn, args);
return fn(...args);
}
async function handleArgumentsList(node, ctx, builtIns) {
const args = (await handleList(node, ctx, builtIns)).__unwrap__(false);
return [...args];
}
async function handleForStatement(node, ctx, builtIns) {
const childs = node.children;
check(childs.length === 6);
check(childs[4].type === ":");
check(childs[5].type === "block");
await helperGetLoopForIn(node, ctx, builtIns, async (forCtx) => {
await handleNode(childs[5], forCtx, builtIns);
});
}
async function handleListComprehension(node, ctx, builtIns) {
const finalList = new PyList();
const newCtx = { ...ctx };
let finalEntryNode;
const loopNodes = [];
for (const child of node.children) {
if (!child || ["[", "]"].includes(child.type))
continue;
if (child.type === "identifier" || child.type === "attribute") {
if (finalEntryNode) {
throw Error("Already have a list comprehension finalEntryNode.");
}
finalEntryNode = child;
}
else if (child.type === "for_in_clause") {
loopNodes.push({ forIn: child });
}
else if (child.type === "if_clause") {
loopNodes[loopNodes.length - 1]["if"] = child;
}
}
if (!finalEntryNode) {
throw Error("No list comprehension finalEntryNode.");
}
console.log(`handleListComprehension.loopNodes`, loopNodes);
const handleLoop = async (loopNodes) => {
const loopNode = loopNodes.shift();
await helperGetLoopForIn(loopNode.forIn, newCtx, builtIns, async (forCtx) => {
if (loopNode.if) {
const ifNode = loopNode.if;
check(ifNode.children.length === 2, "Expected 2 children for if_clause.");
check(ifNode.child(0).text === "if", "Expected first child to be 'if'.");
const good = await handleNode(ifNode.child(1), forCtx, builtIns);
if (!good)
return;
}
Object.assign(newCtx, forCtx);
if (loopNodes.length) {
await handleLoop(loopNodes);
}
else {
finalList.append(await handleNode(finalEntryNode, newCtx, builtIns));
}
}, () => ({ ...newCtx }));
loopNodes.unshift(loopNode);
};
await handleLoop(loopNodes);
return finalList;
}
async function helperGetLoopForIn(node, ctx, builtIns, eachFn, provideForCtx) {
var _a;
const childs = node.children;
check(childs.length >= 3);
check(childs[0].type === "for");
check(["identifier", "pattern_list"].includes(childs[1].type), "Expected identifier for for loop.");
check(childs[2].type === "in");
let identifiers;
if (childs[1].type === "identifier") {
identifiers = [childs[1].text];
}
else {
identifiers = childs[1].children
.map((n) => {
if (n.type === ",")
return null;
check(n.type === "identifier");
return node.text;
})
.filter((n) => n != null);
}
const iterable = await handleNode(childs[3], ctx, builtIns);
check(iterable instanceof PyTuple, "Expected for loop instance to be a list/tuple.");
for (const item of iterable.__unwrap__(false)) {
const forCtx = (_a = provideForCtx === null || provideForCtx === void 0 ? void 0 : provideForCtx()) !== null && _a !== void 0 ? _a : ctx;
if (identifiers.length === 1) {
forCtx[identifiers[0]] = item;
}
else {
check(Array.isArray(item) && identifiers.length === item.length, "Expected iterable to be a list, like using dict.items()");
for (let i = 0; i < identifiers.length; i++) {
forCtx[identifiers[i]] = item[i];
}
}
await eachFn(forCtx);
}
}
async function handleNumber(node, ctx, builtIns) {
return Number(node.text);
}
async function handleString(node, ctx, builtIns) {
let str = "";
for (const child of node.children) {
if (!child || ["string_start", "string_end"].includes(child.type))
continue;
if (child.type === "string_content") {
str += child.text;
}
else if (child.type === "interpolation") {
check(child.children.length === 3, "Expected interpolation");
str += await handleNode(child, ctx, builtIns);
}
}
return str;
}
async function handleInterpolation(node, ...args) {
check(node.children.length === 3, "Expected interpolation to be three nodes length.");
check(node.children[0].type === "{" && node.children[2].type === "}", 'Expected interpolation to be wrapped in "{" and "}".');
return await handleNode(node.children[1], ...args);
}
async function handleList(node, ctx, builtIns) {
const list = [];
for (const child of node.children) {
if (!child || ["(", "[", ",", "]", ")"].includes(child.type))
continue;
list.push(await handleNode(child, ctx, builtIns));
}
if (node.type === "tuple") {
return new PyTuple(list);
}
return new PyList(list);
}
async function handleComparisonOperator(node, ctx, builtIns) {
const op = node.child(1).text;
const left = await handleNode(node.child(0), ctx, builtIns);
const right = await handleNode(node.child(2), ctx, builtIns);
if (op === "==")
return left === right;
if (op === "!=")
return left !== right;
if (op === ">")
return left > right;
if (op === ">=")
return left >= right;
if (op === "<")
return left < right;
if (op === "<=")
return left <= right;
if (op === "in")
return (right.__unwrap__ ? right.__unwrap__(false) : right).includes(left);
throw new Error(`Comparison not handled: "${op}"`);
}
async function handleBooleanOperator(node, ctx, builtIns) {
const op = node.child(1).text;
const left = await handleNode(node.child(0), ctx, builtIns);
if (!left && op === "and")
return left;
const right = await handleNode(node.child(2), ctx, builtIns);
if (op === "and")
return left && right;
if (op === "or")
return left || right;
}
async function handleBinaryOperator(node, ctx, builtIns) {
const op = node.child(1).text;
const left = await handleNode(node.child(0), ctx, builtIns);
const right = await handleNode(node.child(2), ctx, builtIns);
if (left.constructor !== right.constructor) {
throw new Error(`Can only run ${op} operator on same type.`);
}
if (op === "+")
return left.__add__ ? left.__add__(right) : left + right;
if (op === "-")
return left - right;
if (op === "/")
return left / right;
if (op === "//")
return Math.floor(left / right);
if (op === "*")
return left * right;
if (op === "%")
return left % right;
if (op === "&")
return left & right;
if (op === "|")
return left | right;
if (op === "^")
return left ^ right;
if (op === "<<")
return left << right;
if (op === ">>")
return left >> right;
throw new Error(`Comparison not handled: "${op}"`);
}
async function handleNotOperator(node, ctx, builtIns) {
check(node.children.length === 2, "Expected 2 children for not operator.");
check(node.child(0).text === "not", "Expected first child to be 'not'.");
const value = await handleNode(node.child(1), ctx, builtIns);
return !value;
}
async function handleUnaryOperator(node, ctx, builtIns) {
check(node.children.length === 2, "Expected 2 children for not operator.");
const value = await handleNode(node.child(1), ctx, builtIns);
const op = node.child(0).text;
if (op === "-")
return value * -1;
console.warn(`Unhandled unary operator: ${op}`);
return value;
}
async function handleDictionary(node, ctx, builtIns) {
const dict = new PyDict();
for (const child of node.children) {
if (!child || ["{", ",", "}"].includes(child.type))
continue;
check(child.type === "pair", "Expected a pair type for dict.");
const pair = await handleNode(child, ctx, builtIns);
dict.__put__(pair[0], pair[1]);
}
return dict;
}
async function handleDictionaryPair(node, ctx, builtIns) {
check(node.children.length === 3, "Expected 3 children for dict pair.");
let varName = await handleNode(node.child(0), ctx, builtIns);
let varValue = await handleNode(node.child(2), ctx, builtIns);
check(typeof varName === "string", "Expected varname to be string.");
return [varName, varValue];
}
class Node {
constructor(node) {
this.type = node.type;
this.text = node.text;
if (this.type === "ERROR") {
throw new Error(`Error found in parsing near "${this.text}"`);
}
this.children = [];
for (const child of node.children) {
this.children.push(new Node(child));
}
this.node = node;
}
child(index) {
const child = this.children[index];
if (!child)
throw Error(`No child at index ${index}.`);
return child;
}
log(tab = "", showNode = false) {
console.log(`${tab}--- Node`);
console.log(`${tab} type: ${this.type}`);
console.log(`${tab} text: ${this.text}`);
console.log(`${tab} children:`, this.children);
if (showNode) {
console.log(`${tab} node:`, this.node);
}
}
}
export class PyTuple {
constructor(...args) {
if (args.length === 1 && args[0] instanceof PyTuple) {
args = args[0].__unwrap__(false);
}
if (args.length === 1 && Array.isArray(args[0])) {
args = [...args[0]];
}
this.list = [...args];
}
count(v) {
}
index() {
}
__at__(index) {
index = this.__get_relative_index__(index);
return this.list[index];
}
__len__() {
return this.list.length;
}
__add__(v) {
if (!(v instanceof PyTuple)) {
throw new Error("Can only concatenate tuple to tuple.");
}
return new PyTuple(this.__unwrap__(false).concat(v.__unwrap__(false)));
}
__put__(index, v) {
throw new Error("Tuple does not support item assignment");
}
__get_relative_index__(index) {
if (index >= 0) {
check(this.list.length > index, `Index ${index} out of range.`);
return index;
}
const relIndex = this.list.length + index;
check(relIndex >= 0, `Index ${index} out of range.`);
return relIndex;
}
__unwrap__(deep = true) {
var _a;
const l = [...this.list];
if (deep) {
for (let i = 0; i < l.length; i++) {
l[i] = ((_a = l[i]) === null || _a === void 0 ? void 0 : _a.__unwrap__) ? l[i].__unwrap__(deep) : l[i];
}
}
return l;
}
}
__decorate([
Exposed
], PyTuple.prototype, "count", null);
__decorate([
Exposed
], PyTuple.prototype, "index", null);
export class PyList extends PyTuple {
append(...args) {
this.list.push(...args);
}
clear() {
this.list.length = 0;
}
copy() {
}
count() {
}
extend() {
}
index() {
}
insert() {
}
pop() {
}
remove() {
}
reverse() {
}
sort() {
}
__add__(v) {
if (!(v instanceof PyList)) {
throw new Error("Can only concatenate list to list.");
}
return new PyList(this.__unwrap__(false).concat(v.__unwrap__(false)));
}
__put__(index, v) {
index = this.__get_relative_index__(index);
this.list[index] = v;
}
}
__decorate([
Exposed
], PyList.prototype, "append", null);
__decorate([
Exposed
], PyList.prototype, "clear", null);
__decorate([
Exposed
], PyList.prototype, "copy", null);
__decorate([
Exposed
], PyList.prototype, "count", null);
__decorate([
Exposed
], PyList.prototype, "extend", null);
__decorate([
Exposed
], PyList.prototype, "index", null);
__decorate([
Exposed
], PyList.prototype, "insert", null);
__decorate([
Exposed
], PyList.prototype, "pop", null);
__decorate([
Exposed
], PyList.prototype, "remove", null);
__decorate([
Exposed
], PyList.prototype, "reverse", null);
__decorate([
Exposed
], PyList.prototype, "sort", null);
class PyInt {
}
class PyDict {
constructor(dict) {
_PyDict_dict.set(this, void 0);
__classPrivateFieldSet(this, _PyDict_dict, { ...(dict !== null && dict !== void 0 ? dict : {}) }, "f");
}
clear() { }
copy() { }
fromkeys() { }
get(key) {
return __classPrivateFieldGet(this, _PyDict_dict, "f")[key];
}
items() {
return new PyTuple(Object.entries(__classPrivateFieldGet(this, _PyDict_dict, "f")).map((e) => new PyTuple(e)));
}
keys() { }
pop() { }
popitem() { }
setdefault() { }
update() { }
values() { }
__put__(key, v) {
__classPrivateFieldGet(this, _PyDict_dict, "f")[key] = v;
}
__len__() {
return Object.keys(__classPrivateFieldGet(this, _PyDict_dict, "f")).length;
}
__unwrap__(deep = true) {
var _a;
const d = { ...__classPrivateFieldGet(this, _PyDict_dict, "f") };
if (deep) {
for (let k of Object.keys(d)) {
d[k] = ((_a = d[k]) === null || _a === void 0 ? void 0 : _a.__unwrap__) ? d[k].__unwrap__(deep) : d[k];
}
}
return d;
}
}
_PyDict_dict = new WeakMap();
__decorate([
Exposed
], PyDict.prototype, "clear", null);
__decorate([
Exposed
], PyDict.prototype, "copy", null);
__decorate([
Exposed
], PyDict.prototype, "fromkeys", null);
__decorate([
Exposed
], PyDict.prototype, "get", null);
__decorate([
Exposed
], PyDict.prototype, "items", null);
__decorate([
Exposed
], PyDict.prototype, "keys", null);
__decorate([
Exposed
], PyDict.prototype, "pop", null);
__decorate([
Exposed
], PyDict.prototype, "popitem", null);
__decorate([
Exposed
], PyDict.prototype, "setdefault", null);
__decorate([
Exposed
], PyDict.prototype, "update", null);
__decorate([
Exposed
], PyDict.prototype, "values", null);
function __unwrap__(...args) {
var _a;
for (let i = 0; i < args.length; i++) {
args[i] = ((_a = args[i]) === null || _a === void 0 ? void 0 : _a.__unwrap__) ? args[i].__unwrap__(true) : args[i];
}
return args;
}
function checkAttributeAccessibility(inst, attr) {
var _a, _b, _c, _d, _e, _f;
const instType = typeof inst;
check(instType === "object" || instType === "function", `Instance of type ${instType} does not have attributes.`);
check(!attr.startsWith("__") && !attr.endsWith("__"), `"${attr}" is not accessible.`);
const attrType = typeof inst[attr];
if (attrType === "function") {
const allowedMethods = (_c = (_b = (_a = inst.constructor) === null || _a === void 0 ? void 0 : _a.__ALLOWED_METHODS__) !== null && _b !== void 0 ? _b : inst.__ALLOWED_METHODS__) !== null && _c !== void 0 ? _c : [];
check(allowedMethods.includes(attr), `Method ${attr} is not accessible.`);
}
else {
const allowedProps = (_f = (_e = (_d = inst.constructor) === null || _d === void 0 ? void 0 : _d.__ALLOWED_PROPERTIES__) !== null && _e !== void 0 ? _e : inst.__ALLOWED_PROPERTIES__) !== null && _f !== void 0 ? _f : [];
check(allowedProps.includes(attr), `Property ${attr} is not accessible.`);
}
}
function maybeWrapValue(value) {
if (Array.isArray(value)) {
return new PyList(value);
}
return value;
}
function isInt(value) {
return typeof value === "number" && Math.round(value) === value;
}
function isIntLike(value) {
let is = isInt(value);
if (!is) {
is = typeof value === "string" && !!/^\d+$/.exec(value);
}
return is;
}
export function Exposed(target, key) {
const descriptor = Object.getOwnPropertyDescriptor(target, key);
if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.value) === "function") {
target.constructor.__ALLOWED_METHODS__ = target.constructor.__ALLOWED_METHODS__ || [];
target.constructor.__ALLOWED_METHODS__.push(key);
}
else {
target.constructor.__ALLOWED_PROPERTIES__ = target.constructor.__ALLOWED_PROPERTIES__ || [];
target.constructor.__ALLOWED_PROPERTIES__.push(key);
}
}
|