Refactoring and performance enhancements on the VM compiler

This commit is contained in:
wycats
2010-12-21 09:47:27 -08:00
parent d87ae129c0
commit 16ed2cd3f1
+174 -125
View File
@@ -1,5 +1,8 @@
var Handlebars = {};
Handlebars.Utils = require("handlebars/utils").Utils;
Handlebars.parse = require("handlebars/compiler").Handlebars.parse;
Handlebars.logger = require("handlebars/compiler").Handlebars.logger;
Handlebars.log = require("handlebars/compiler").Handlebars.log;
// BEGIN(BROWSER)
Handlebars.Compiler = function() {};
@@ -7,13 +10,13 @@ Handlebars.JavaScriptCompiler = function() {};
(function(Compiler, JavaScriptCompiler) {
Compiler.OPCODE_MAP = {
invokeContent: 1,
appendContent: 1,
getContext: 2,
lookupWithFallback: 3,
lookup: 4,
append: 5,
invokeMustache: 6,
escape: 7,
appendEscaped: 7,
pushString: 8,
truthyOrFallback: 9,
functionOrFallback: 10,
@@ -24,7 +27,7 @@ Handlebars.JavaScriptCompiler = function() {};
};
Compiler.MULTI_PARAM_OPCODES = {
invokeContent: 1,
appendContent: 1,
getContext: 1,
lookupWithFallback: 1,
lookup: 1,
@@ -38,9 +41,9 @@ Handlebars.JavaScriptCompiler = function() {};
invokeInverse: 1
};
Compiler.DISASSEMBLE_MAP = {}
Compiler.DISASSEMBLE_MAP = {};
for(prop in Compiler.OPCODE_MAP) {
for(var prop in Compiler.OPCODE_MAP) {
var value = Compiler.OPCODE_MAP[prop];
Compiler.DISASSEMBLE_MAP[value] = prop;
}
@@ -83,7 +86,7 @@ Handlebars.JavaScriptCompiler = function() {};
}
}
return out.join("\n")
return out.join("\n");
},
guid: 0,
@@ -118,6 +121,8 @@ Handlebars.JavaScriptCompiler = function() {};
var result = new Compiler().compile(program);
var guid = this.guid++;
this.usePartial = this.usePartial || result.usePartial;
this.children[guid] = result;
for(var i=0, l=result.depths.list.length; i<l; i++) {
@@ -132,7 +137,7 @@ Handlebars.JavaScriptCompiler = function() {};
block: function(block) {
var mustache = block.mustache;
var params = mustache.params, depth, child, inverse;
var params = mustache.params, depth, child, inverse, inverseGuid;
this.pushParams(params);
@@ -142,7 +147,7 @@ Handlebars.JavaScriptCompiler = function() {};
var programGuid = this.compileProgram(block.program);
if(block.program.inverse) {
var inverseGuid = this.compileProgram(block.program.inverse);
inverseGuid = this.compileProgram(block.program.inverse);
}
if(block.program.inverse) {
@@ -164,6 +169,7 @@ Handlebars.JavaScriptCompiler = function() {};
partial: function(partial) {
var id = partial.id;
this.usePartial = true;
if(partial.context) {
this.ID(partial.context);
@@ -176,7 +182,7 @@ Handlebars.JavaScriptCompiler = function() {};
},
content: function(content) {
this.opcode('invokeContent', content.string);
this.opcode('appendContent', content.string);
},
mustache: function(mustache) {
@@ -187,9 +193,11 @@ Handlebars.JavaScriptCompiler = function() {};
this.opcode('invokeMustache', params.length, mustache.id.original);
if(mustache.escaped) { this.opcode('escape') }
this.opcode('append');
if(mustache.escaped) {
this.opcode('appendEscaped');
} else {
this.opcode('append');
}
},
ID: function(id) {
@@ -239,69 +247,107 @@ Handlebars.JavaScriptCompiler = function() {};
this.depths.list.push(depth);
}
}
}
};
JavaScriptCompiler.prototype = {
compile: function(environment) {
this.preamble();
this.stackSlot = 0
this.stackVars = [];
this.environment = environment;
this.preamble();
this.stackSlot = 0;
this.stackVars = [];
this.registers = {list: []};
this.compileChildren(environment);
Handlebars.log(Handlebars.logger.DEBUG, environment.disassemble() + "\n\n");
var opcodes = environment.opcodes;
var opcode, name;
var declareName, declareVal;
var opcodes = environment.opcodes, opcode, name, declareName, declareVal;
for(var i=0, l=opcodes.length; i<l; i++) {
opcode = opcodes[i];
this.i = 0;
if(opcode === 'DECLARE') {
declareName = opcodes[++i];
declareVal = opcodes[++i];
this[declareName] = declareVal;
for(l=opcodes.length; this.i<l; this.i++) {
opcode = this.nextOpcode(0);
if(opcode[0] === 'DECLARE') {
this.i = this.i + 2;
this[opcode[1]] = opcode[2];
} else {
name = Compiler.DISASSEMBLE_MAP[opcode];
var extraParams = Compiler.multiParamSize(opcode);
var codes = [];
for(var j=0; j<extraParams; j++) {
codes.push(opcodes[++i]);
}
this[name].apply(this, codes);
this.i = this.i + opcode[1].length;
this[opcode[0]].apply(this, opcode[1]);
}
}
return this.createFunction();
},
nextOpcode: function(n) {
var opcodes = this.environment.opcodes, opcode = opcodes[this.i + n], name, val;
var extraParams, codes;
if(opcode === 'DECLARE') {
name = opcodes[this.i + 1];
val = opcodes[this.i + 2];
return ['DECLARE', name, val];
} else {
name = Compiler.DISASSEMBLE_MAP[opcode];
extraParams = Compiler.multiParamSize(opcode);
codes = [];
for(var j=0; j<extraParams; j++) {
codes.push(opcodes[this.i + j + 1 + n]);
}
return [name, codes];
}
},
eat: function(opcode) {
this.i = this.i + opcode.length;
},
preamble: function() {
var out = [];
out.push("var buffer = '';");
out.push("var currentContext = context, tmp1, tmp2;");
out.push("helpers = helpers || Handlebars.helpers; partials = partials || Handlebars.partials;");
out.push("");
out.push("var buffer = '', currentContext = context");
var copies = "helpers = helpers || Handlebars.helpers;";
if(this.environment.usePartial) { copies = copies + " partials = partials || Handlebars.partials;"; }
out.push(copies);
// track the last context pushed into place to allow skipping the
// getContext opcode when it would be a noop
this.lastContext = 0;
this.locals = 3;
this.source = out;
},
createFunction: function() {
var container = {};
var container = {
escapeExpression: Handlebars.Utils.escapeExpression,
invokePartial: Handlebars.VM.invokePartial,
programs: [],
program: function(i, helpers, partials) {
var programWrapper = this.programs[i];
if(programWrapper) {
return programWrapper;
} else {
programWrapper = this.programs[i] = Handlebars.VM.program(this.children[i], helpers, partials);
return programWrapper;
}
},
programWithDepth: Handlebars.VM.programWithDepth,
noop: Handlebars.VM.noop
};
var locals = this.stackVars.concat(this.registers.list);
if(this.stackVars.length > 0) {
this.source[this.locals] = "var " + this.stackVars.join(", ") + ";";
if(locals.length > 0) {
this.source[0] = this.source[0] + ", " + locals.join(", ");
}
this.source.push("return buffer;")
this.source[0] = this.source[0] + ";";
this.source.push("return buffer;");
var params = ["context", "helpers", "partials"];
@@ -309,10 +355,12 @@ Handlebars.JavaScriptCompiler = function() {};
params.push("depth" + this.environment.depths.list[i]);
}
if(params.length === 3 && !this.environment.usePartial) { params.pop(); }
params.push(this.source.join("\n"));
var fn = Function.apply(this, params);
fn.displayName = "Handlebars.js"
fn.displayName = "Handlebars.js";
Handlebars.log(Handlebars.logger.DEBUG, fn.toString() + "\n\n");
@@ -322,20 +370,31 @@ Handlebars.JavaScriptCompiler = function() {};
return function(context, helpers, partials, depth) {
try {
return container.render.apply(container, arguments)
return container.render.apply(container, arguments);
} catch(e) {
throw e;
}
}
};
},
invokeContent: function(content) {
appendContent: function(content) {
this.source.push("buffer = buffer + " + this.quotedString(content) + ";");
},
append: function() {
var local = this.popStack();
this.source.push("buffer = buffer + ((" + local + " || " + local + " === 0) ? " + local + " : '');");
this.source.push("if(" + local + " || " + local + " === 0) { buffer = buffer + " + local + "; }");
},
appendEscaped: function() {
var opcode = this.nextOpcode(1), extra = "";
if(opcode[0] === 'appendContent') {
extra = " + " + this.quotedString(opcode[1][0]);
this.eat(opcode);
}
this.source.push("buffer = buffer + this.escapeExpression(" + this.popStack() + ")" + extra + ";");
},
getContext: function(depth) {
@@ -347,7 +406,6 @@ Handlebars.JavaScriptCompiler = function() {};
} else {
this.source.push("currentContext = depth" + depth + ";");
}
// TODO: handle depths other than 0
}
},
@@ -363,7 +421,7 @@ Handlebars.JavaScriptCompiler = function() {};
if(name) {
this.pushStack(this.nameLookup('currentContext', name));
var topStack = this.topStack();
this.source.push("if(" + topStack + " == null) { " + topStack + " = " + this.nameLookup('helpers', name) + "; }");
this.source.push("if(" + topStack + " === undefined) { " + topStack + " = " + this.nameLookup('helpers', name) + "; }");
} else {
this.pushStack("currentContext");
}
@@ -383,49 +441,32 @@ Handlebars.JavaScriptCompiler = function() {};
},
invokeMustache: function(paramSize, original) {
this.source.push("tmp1 = " + this.popStack() + ";");
this.source.push("tmp2 = (typeof tmp1 === 'function');");
var params = ["context"], fn, slot;
var params = ["context"];
fn = this.popStack();
for(var i=0; i<paramSize; i++) {
params.push(this.popStack());
}
var slot = "stack" + ++this.stackSlot;
var paramString = params.join(", ");
var helperMissing = ["context"].concat(this.quotedString(original)).concat(params.slice(1));
slot = this.nextStack();
if(paramSize === 0) {
this.source.push("if(tmp2) { " + slot + " = tmp1.call(" + paramString + "); } else { " + slot + " = tmp1; }");
// TODO: This case is not listed in the mustache spec. Is it important?
this.source.push("if(typeof " + fn + " === 'function') { " + slot + " = " + fn + ".call(" + paramString + "); }");
} else {
this.source.push("if(tmp2) { " + slot + " = tmp1.call(" + paramString + "); } else { " + slot + " = helpers.helperMissing.call(" + helperMissing + ") }");
this.source.push("if(typeof " + fn + " === 'function') { " + slot + " = " + fn + ".call(" + paramString + "); } else { " + slot + " = helpers.helperMissing.call(" + helperMissing + ") }");
}
},
invokeProgram: function(guid, paramSize) {
var inverse = this.inverse;
var inverse = this.programExpression(this.inverse);
if(inverse != null) {
var programParams = ["this.children[" + inverse + "]", "helpers", "partials"];
var depths = this.environment.rawChildren[guid + 1].depths.list;
for(var i=0, l = depths.length; i<l; i++) {
depth = depths[i];
if(depth === 1) { programParams.push("context"); }
else { programParams.push("depth" + (depth - 1)); }
}
this.source.push("tmp2 = Handlebars.VM.program(" + programParams.join(", ") + ");");
} else {
this.source.push("tmp2 = Handlebars.VM.noop;");
}
var id = this.topStack();
var fn = this.popStack();
var id = fn;
var params = ["context"];
var blockMissingParams = ["context", id];
@@ -436,62 +477,26 @@ Handlebars.JavaScriptCompiler = function() {};
blockMissingParams.push(param);
}
programParams = ["this.children[" + guid + "]", "helpers", "partials"];
var depths = this.environment.rawChildren[guid].depths.list, depth;
var mainProgram = this.programExpression(guid);
for(var i=0, l= depths.length; i<l; i++) {
depth = depths[i];
if(depth === 1) { programParams.push("context"); }
else { programParams.push("depth" + (depth - 1)); }
}
if(depths.length === 0) {
this.source.push("tmp1 = Handlebars.VM.program(" + programParams.join(", ") + ")");
} else {
this.source.push("tmp1 = Handlebars.VM.programWithDepth(" + programParams.join(", ") + ")");
}
params.push("tmp1");
params.push("tmp2");
blockMissingParams.push("tmp1");
blockMissingParams.push("tmp2");
params.push(mainProgram, inverse);
blockMissingParams.push(mainProgram, inverse);
var nextStack = this.nextStack();
this.source.push("if(typeof " + id + " === 'function') { " + nextStack + " = " + id + ".call(" + params.join(", ") + "); }")
this.source.push("if(typeof " + id + " === 'function') { " + nextStack + " = " + id + ".call(" + params.join(", ") + "); }");
this.source.push("else { " + nextStack + " = helpers.blockHelperMissing.call(" + blockMissingParams.join(", ") + "); }");
},
invokeInverse: function(guid) {
var depths = this.environment.rawChildren[guid].depths.list;
var program = this.programExpression(guid);
programParams = ["this.children[" + guid + "]", "helpers", "partials"];
for(var i=0, l = depths.length; i<l; i++) {
depth = depths[i];
if(depth === 1) { programParams.push("context"); }
else { programParams.push("depth" + (depth - 1)); }
}
if(depths.length === 0) {
this.source.push("tmp1 = Handlebars.VM.program(" + programParams.join(", ") + ")");
} else {
this.source.push("tmp1 = Handlebars.VM.programWithDepth(" + programParams.join(", ") + ")");
}
var blockMissingParams = ["context", this.topStack(), "Handlebars.VM.noop", "tmp1"];
var blockMissingParams = ["context", this.topStack(), "this.noop", program];
this.pushStack("helpers.blockHelperMissing.call(" + blockMissingParams.join(", ") + ")");
},
invokePartial: function(context) {
this.pushStack("Handlebars.VM.invokePartial(" + this.nameLookup('partials', context) + ", '" + context + "', " + this.popStack() + ", helpers, partials);");
},
escape: function() {
this.source.push(this.topStack() + " = Handlebars.Utils.escapeExpression(" + this.topStack() + ");");
// TODO: Escaping
this.pushStack("this.invokePartial(" + this.nameLookup('partials', context) + ", '" + context + "', " + this.popStack() + ", helpers, partials);");
},
// HELPERS
@@ -511,6 +516,50 @@ Handlebars.JavaScriptCompiler = function() {};
environment.children = compiled;
},
programExpression: function(guid) {
if(guid == null) { return "this.noop"; }
var programParams = [guid, "helpers", "partials"];
var depths = this.environment.rawChildren[guid].depths.list;
for(var i=0, l = depths.length; i<l; i++) {
depth = depths[i];
if(depth === 1) { programParams.push("context"); }
else { programParams.push("depth" + (depth - 1)); }
}
if(!this.environment.usePartial) {
if(programParams[3]) {
programParams[2] = "null";
} else {
programParams.pop();
}
}
if(depths.length === 0) {
return "this.program(" + programParams.join(", ") + ")";
} else {
programParams[0] = "this.children[" + guid + "]";
return "this.programWithDepth(" + programParams.join(", ") + ")";
}
return "this.program(" + programParams.join(", ") + ")";
},
register: function(name, val) {
this.useRegister(name);
this.source.push(name + " = " + val + ";");
},
useRegister: function(name) {
if(!this.registers[name]) {
this.registers[name] = true;
this.registers.list.push(name);
}
},
pushStack: function(item) {
this.source.push(this.nextStack() + " = " + item + ";");
return "stack" + this.stackSlot;
@@ -537,7 +586,7 @@ Handlebars.JavaScriptCompiler = function() {};
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r') + '"';
}
}
};
var reservedWords = ("break case catch continue default delete do else finally " +
"for function if in instanceof new return switch this throw " +
@@ -549,19 +598,19 @@ Handlebars.JavaScriptCompiler = function() {};
compilerWords[reservedWords[i]] = true;
}
})(Handlebars.Compiler, Handlebars.JavaScriptCompiler)
})(Handlebars.Compiler, Handlebars.JavaScriptCompiler);
Handlebars.VM = {
programWithDepth: function(fn, helpers, partials, depth) {
var args = [].slice.call(arguments, 1);
return function(context) {
return fn.apply(this, [context].concat(args));
}
};
},
program: function(fn, helpers, partials) {
return function(context) {
return fn(context, helpers, partials);
}
};
},
noop: function() {},
compile: function(string) {
@@ -571,7 +620,7 @@ Handlebars.VM = {
},
invokePartial: function(partial, name, context, helpers, partials) {
if(partial instanceof Function) {
return partial(context, helpers, partials)
return partial(context, helpers, partials);
} else {
partials[name] = Handlebars.VM.compile(partial);
return partials[name](context, helpers, partials);