|
1 | | -/** |
2 | | - * @file AssemblyScript demangler. |
3 | | - */ |
4 | | - |
5 | 1 | module.exports = demangle; |
6 | 2 |
|
7 | | -/** |
8 | | - * Demangles module exports to a friendly object structure compatible with WebIDL and TypeScript |
9 | | - * definitions. |
10 | | - */ |
| 3 | +/** Demangles AssemblyScript module exports to a friendly object structure. */ |
11 | 4 | function demangle(exports) { |
12 | 5 | var root = {}; |
13 | | - for (let i in exports) { |
14 | | - if (exports.hasOwnProperty(i)) { |
15 | | - // TODO |
| 6 | + for (let internalName in exports) { |
| 7 | + if (!exports.hasOwnProperty(internalName)) continue; |
| 8 | + let elem = exports[internalName]; |
| 9 | + let parts = internalName.split("."); |
| 10 | + let curr = root; |
| 11 | + while (parts.length > 1) { |
| 12 | + let part = parts.shift(); |
| 13 | + if (!curr.hasOwnProperty(part)) curr[part] = {}; |
| 14 | + curr = curr[part]; |
| 15 | + } |
| 16 | + let name = parts[0]; |
| 17 | + let hash = name.indexOf("#"); |
| 18 | + if (hash >= 0) { |
| 19 | + let className = name.substring(0, hash); |
| 20 | + let classElem = curr[className]; |
| 21 | + if (typeof classElem === "undefined" || !classElem.prototype) { |
| 22 | + let ctor = function(...args) { |
| 23 | + return ctor.wrap(ctor.prototype.constructor(...args)); |
| 24 | + }; |
| 25 | + ctor.prototype = {}; |
| 26 | + ctor.wrap = function(thisValue) { |
| 27 | + return Object.create(ctor.prototype, { "this": { value: thisValue, writable: false } }); |
| 28 | + }; |
| 29 | + if (classElem) Object.getOwnPropertyNames(classElem).forEach(name => |
| 30 | + Object.defineProperty(ctor, name, Object.getOwnPropertyDescriptor(classElem, name)) |
| 31 | + ); |
| 32 | + curr[className] = ctor; |
| 33 | + } |
| 34 | + name = name.substring(hash + 1); |
| 35 | + curr = curr[className].prototype; |
| 36 | + if (/^(get|set):/.test(name)) { |
| 37 | + if (!curr.hasOwnProperty(name = name.substring(4))) { |
| 38 | + let getter = exports[internalName.replace("set:", "get:")]; |
| 39 | + let setter = exports[internalName.replace("get:", "set:")]; |
| 40 | + Object.defineProperty(curr, name, { |
| 41 | + get: function() { return getter(this.this); }, |
| 42 | + set: function(value) { setter(this.this, value); } |
| 43 | + }); |
| 44 | + } |
| 45 | + } else curr[name] = function(...args) { return elem(this.this, ...args); }; |
| 46 | + } else { |
| 47 | + if (/^(get|set):/.test(name)) { |
| 48 | + if (!curr.hasOwnProperty(name = name.substring(4))) { |
| 49 | + Object.defineProperty(curr, name, { |
| 50 | + get: exports[internalName.replace("set:", "get:")], |
| 51 | + set: exports[internalName.replace("get:", "set:")] |
| 52 | + }); |
| 53 | + } |
| 54 | + } else curr[name] = elem; |
16 | 55 | } |
17 | 56 | } |
18 | 57 | return root; |
|
0 commit comments