|
| 1 | +const { Transform } = require("assemblyscript/cli/transform"); |
| 2 | +const assemblyscript = require("assemblyscript"); |
| 3 | + |
| 4 | +function isInternalElement(element) { |
| 5 | + return element.internalName.startsWith("~"); |
| 6 | +} |
| 7 | + |
| 8 | +function elementHasFlag(el, flag) { |
| 9 | + return (el.flags & flag) != 0; |
| 10 | +} |
| 11 | + |
| 12 | +function typeName(type) { |
| 13 | + return type.name.text ?? type.name.identifier.text; |
| 14 | +} |
| 15 | + |
| 16 | +const marker = "__asbind_type_data"; |
| 17 | + |
| 18 | +class AsBindTransform extends Transform { |
| 19 | + afterInitialize(program) { |
| 20 | + const exportedFunctions = [...program.elementsByDeclaration.values()] |
| 21 | + .filter(el => |
| 22 | + elementHasFlag(el, assemblyscript.CommonFlags.MODULE_EXPORT) |
| 23 | + ) |
| 24 | + .filter(el => !isInternalElement(el)) |
| 25 | + .filter( |
| 26 | + el => |
| 27 | + el.declaration.kind === assemblyscript.NodeKind.FUNCTIONDECLARATION |
| 28 | + ); |
| 29 | + const importedFunctions = [...program.elementsByDeclaration.values()] |
| 30 | + .filter(el => elementHasFlag(el, assemblyscript.CommonFlags.DECLARE)) |
| 31 | + .filter(el => !isInternalElement(el)) |
| 32 | + .filter( |
| 33 | + v => v.declaration.kind === assemblyscript.NodeKind.FUNCTIONDECLARATION |
| 34 | + ); |
| 35 | + const typeData = { |
| 36 | + importedFunction: Object.fromEntries( |
| 37 | + importedFunctions.map(func => [ |
| 38 | + func.name, |
| 39 | + { |
| 40 | + returnType: typeName(func.declaration.signature.returnType), |
| 41 | + parameters: func.declaration.signature.parameters.map(parameter => |
| 42 | + typeName(parameter.type) |
| 43 | + ) |
| 44 | + } |
| 45 | + ]) |
| 46 | + ), |
| 47 | + exportedFunctions: Object.fromEntries( |
| 48 | + exportedFunctions.map(func => [ |
| 49 | + func.name, |
| 50 | + { |
| 51 | + returnType: typeName(func.declaration.signature.returnType), |
| 52 | + parameters: func.declaration.signature.parameters.map(parameter => |
| 53 | + typeName(parameter.type) |
| 54 | + ) |
| 55 | + } |
| 56 | + ]) |
| 57 | + ) |
| 58 | + }; |
| 59 | + const typeDataExport = [...program.elementsByDeclaration.values()].find( |
| 60 | + v => v.name === marker |
| 61 | + ); |
| 62 | + if (!typeDataExport) { |
| 63 | + throw Error("Could not find type data export"); |
| 64 | + } |
| 65 | + typeDataExport.declaration.initializer = new assemblyscript.StringLiteralExpression( |
| 66 | + JSON.stringify(typeData) |
| 67 | + ); |
| 68 | + } |
| 69 | +} |
| 70 | +module.exports = AsBindTransform; |
0 commit comments