Skip to content

Commit

Permalink
Merge duplicate programs
Browse files Browse the repository at this point in the history
  • Loading branch information
kpdecker committed Jan 21, 2013
1 parent 969b418 commit b661977
Showing 1 changed file with 43 additions and 6 deletions.
49 changes: 43 additions & 6 deletions lib/handlebars/compiler/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ Handlebars.JavaScriptCompiler = function() {};

return out.join("\n");
},
equals: function(other) {
var len = this.opcodes.length;
if (other.opcodes.length !== len) {
return false;
}

for (var i = 0; i < len; i++) {
var opcode = this.opcodes[i],
otherOpcode = other.opcodes[i];
if (opcode.opcode !== otherOpcode.opcode || opcode.args.length !== otherOpcode.args.length) {
return false;
}
for (var j = 0; j < opcode.args.length; j++) {
if (opcode.args[j] !== otherOpcode.args[j]) {
return false;
}
}
}
return true;
},

guid: 0,

Expand Down Expand Up @@ -417,6 +437,7 @@ Handlebars.JavaScriptCompiler = function() {};
this.isChild = !!context;
this.context = context || {
programs: [],
environments: [],
aliases: { }
};

Expand Down Expand Up @@ -452,7 +473,7 @@ Handlebars.JavaScriptCompiler = function() {};
return opcodes[this.i + 1];
},

eat: function(opcode) {
eat: function() {
this.i = this.i + 1;
},

Expand Down Expand Up @@ -905,11 +926,27 @@ Handlebars.JavaScriptCompiler = function() {};
child = children[i];
compiler = new this.compiler();

this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
var index = this.context.programs.length;
child.index = index;
child.name = 'program' + index;
this.context.programs[index] = compiler.compile(child, options, this.context);
var index = this.matchExistingProgram(child);

if (index == null) {
this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
index = this.context.programs.length;
child.index = index;
child.name = 'program' + index;
this.context.programs[index] = compiler.compile(child, options, this.context);
this.context.environments[index] = child;
} else {
child.index = index;
child.name = 'program' + index;
}
}
},
matchExistingProgram: function(child) {
for (var i = 0, len = this.context.environments.length; i < len; i++) {
var environment = this.context.environments[i];
if (environment && environment.equals(child)) {
return i;
}
}
},

Expand Down

0 comments on commit b661977

Please sign in to comment.