// Convert analyzed data to javascript. Everything has already been calculated
// before this stage, which just does the final conversion to JavaScript.
// Main function
function JSify(data, functionsOnly, givenFunctions, givenGlobalVariables) {
// Does simple 'macro' substitution, using Django-like syntax,
// {{{ code }}} will be replaced with |eval(code)|.
function processMacros(text) {
return text.replace(/{{{[^}]+}}}/g, function(str) {
str = str.substr(3, str.length-6);
return eval(str).toString();
});
}
substrate = new Substrate('JSifyer');
var GLOBAL_VARIABLES = functionsOnly ? givenGlobalVariables : data.globalVariables;
Functions.currFunctions = functionsOnly ? givenFunctions : {};
// Now that analysis has completed, we can get around to handling unparsedFunctions
(functionsOnly ? data.functions : data.unparsedFunctions.concat(data.functions)).forEach(function(func) {
// Save just what we need, to save memory - whether there are varargs, and the # of parameters
Functions.currFunctions[func.ident] = {
hasVarArgs: func.hasVarArgs,
numParams: func.params.length
};
});
for (var i = 0; i < data.unparsedFunctions.length; i++) {
var func = data.unparsedFunctions[i];
dprint('unparsedFunctions', '====================\n// Processing |' + func.ident + '|, ' + i + '/' + data.unparsedFunctions.length);
//var t = Date.now();
func.JS = JSify(analyzer(intertyper(func.lines, true, func.lineNum-1)), true, Functions.currFunctions, GLOBAL_VARIABLES);
//t = (Date.now()-t)/1000;
//dprint('unparsedFunctions', 'unparsedFunction took ' + t + ' seconds.');
delete func.lines; // clean up memory as much as possible
}
if (data.unparsedFunctions.length > 0) {
// We are now doing the final JS generation
dprint('unparsedFunctions', '== Completed unparsedFunctions ==\n');
Debugging.clear(); // Save some memory, before the final heavy lifting
}
// Actors
// type
substrate.addActor('Type', {
processItem: function(item) {
var type = Types.types[item.name_];
var niceName = toNiceIdent(item.name_);
// We might export all of Types.types, cleaner that way, but do not want slowdowns in accessing flatteners
item.JS = 'var ' + niceName + '___SIZE = ' + Types.types[item.name_].flatSize + '; // ' + item.name_ + '\n';
if (type.needsFlattening && !type.flatFactor) {
item.JS += 'var ' + niceName + '___FLATTENER = ' + JSON.stringify(Types.types[item.name_].flatIndexes) + ';';
}
return [item];
}
});
function makeEmptyStruct(type) {
var ret = [];
var typeData = Types.types[type];
assertTrue(typeData);
for (var i = 0; i < typeData.flatSize; i++) {
ret.push(0);
}
return ret;
}
function alignStruct(values, type) {
var typeData = Types.types[type];
assertTrue(typeData);
var ret = [];
var i = 0, soFar = 0;
while (i < values.length) {
// Pad until the right place
var padded = typeData.flatFactor ? typeData.flatFactor*i : typeData.flatIndexes[i];
while (soFar < padded) {
ret.push(0);
soFar++;
}
// Add current value(s)
var currValue = flatten(values[i]);