UNPKG

lysergic

Version:

Synaptic's neural network compiler

89 lines 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const nodes_1 = require("./ast/nodes"); class Heap { constructor(options = {}) { this.options = options; this.buffer = null; this.memory = null; this.allocationCount = 0; this.variables = {}; } alloc(key, value, tag = null) { if (!(key in this.variables)) { this.variables[key] = new nodes_1.Variable(this.allocationCount++, key, value, tag); } this.variables[key].initialValue = value || 0; if (this.memory) { this.memory[this.variables[key].position] = value || 0; } return this.variables[key]; } setVariable(key, ...indexes) { let value = indexes.pop(); const variableKey = key + indexes.map($ => `[${$}]`).join(''); return this.alloc(variableKey, value); } getVariable(key, ...indexes) { const variableKey = key + indexes.map($ => `[${$}]`).join(''); let variable = this.variables[variableKey]; if (!variable) { console.dir(this.variables); throw new Error(variableKey + ' is not declared'); } return variable; } getValue(key, ...indexes) { const variableKey = key + indexes.map($ => `[${$}]`).join(''); let variable = this.variables[variableKey]; if (!variable) { console.dir(this.variables); throw new Error(variableKey + ' is not declared'); } if (this.memory) return this.memory[variable.position]; return variable.initialValue; } hasVariable(key, ...indexes) { return !!this.variables[key + indexes.map($ => `[${$}]`).join('')]; } sortVariables() { const variables = this.variables; let keys = Object.keys(variables).map($ => ({ original: variables[$], standard: $.replace(/\[(\d+)\]/g, function (a, $) { return '[' + ('00000000' + $).substr(-9) + ']'; }) })); keys.sort((a, b) => { if (a.standard > b.standard) return 1; return -1; }); this.variables = {}; keys.forEach(($, $$) => { this.variables[$.original.key] = $.original; }); } async build({ minHeapSize = 0x10000, buffer } = {}) { this.sortVariables(); const variables = this.getVariables(); variables.forEach($ => { if (($.position + 1) > this.allocationCount) this.allocationCount = $.position + 1; }); this.buffer = buffer || new ArrayBuffer(Math.max(this.allocationCount * 8, minHeapSize)); this.memory = new Float64Array(this.buffer); variables .forEach(variable => { if (typeof variable.initialValue === 'number') { this.memory[variable.id] = variable.initialValue; } }); } getVariables() { return Object.keys(this.variables).map(key => this.variables[key]); } } exports.Heap = Heap; //# sourceMappingURL=Heap.js.map