From 976bddd1020ba3f214ce1c42642d384da9352aed Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Mon, 17 Sep 2012 08:09:33 -0700 Subject: [PATCH] Update for Handlebars 1.0.rc.1 --- benchmarks/runner.js | 2 +- ...1.0.0.beta.6.js => handlebars-1.0.rc.1.js} | 1196 +++++++++++------ .../ember-handlebars/lib/helpers/binding.js | 2 +- tests/index.html | 4 +- 4 files changed, 787 insertions(+), 417 deletions(-) rename lib/{handlebars-1.0.0.beta.6.js => handlebars-1.0.rc.1.js} (51%) diff --git a/benchmarks/runner.js b/benchmarks/runner.js index 879722f6cfb..6930bed2b90 100644 --- a/benchmarks/runner.js +++ b/benchmarks/runner.js @@ -15,7 +15,7 @@ function makeiframe(emberPath, suitePath, suiteCode, profile, callback) { write("" + name + ""); write(""); write(""); - write(""); + write(""); write(""); write(""); write(""); diff --git a/lib/handlebars-1.0.0.beta.6.js b/lib/handlebars-1.0.rc.1.js similarity index 51% rename from lib/handlebars-1.0.0.beta.6.js rename to lib/handlebars-1.0.rc.1.js index 83119ff88da..05346370a20 100644 --- a/lib/handlebars-1.0.0.beta.6.js +++ b/lib/handlebars-1.0.rc.1.js @@ -1,7 +1,11 @@ // lib/handlebars/base.js -var Handlebars = {}; -Handlebars.VERSION = "1.0.beta.6"; +/*jshint eqnull:true*/ +this.Handlebars = {}; + +(function(Handlebars) { + +Handlebars.VERSION = "1.0.rc.1"; Handlebars.helpers = {}; Handlebars.partials = {}; @@ -40,25 +44,36 @@ Handlebars.registerHelper('blockHelperMissing', function(context, options) { return inverse(this); } else if(type === "[object Array]") { if(context.length > 0) { - for(var i=0, j=context.length; i 0) { for(var i=0, j=context.length; i 2) { expected.push("'" + this.terminals_[p] + "'"); } - var errStr = ""; if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'"; + errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); } @@ -269,6 +294,9 @@ parse: function parse(input) { len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; + if (ranges) { + yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; + } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; @@ -290,13 +318,13 @@ parse: function parse(input) { } return true; } -};/* Jison generated lexer */ +}; +/* Jison generated lexer */ var lexer = (function(){ - var lexer = ({EOF:1, parseError:function parseError(str, hash) { - if (this.yy.parseError) { - this.yy.parseError(str, hash); + if (this.yy.parser) { + this.yy.parser.parseError(str, hash); } else { throw new Error(str); } @@ -308,27 +336,64 @@ setInput:function (input) { this.yytext = this.matched = this.match = ''; this.conditionStack = ['INITIAL']; this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; + if (this.options.ranges) this.yylloc.range = [0,0]; + this.offset = 0; return this; }, input:function () { var ch = this._input[0]; - this.yytext+=ch; + this.yytext += ch; this.yyleng++; - this.match+=ch; - this.matched+=ch; - var lines = ch.match(/\n/); - if (lines) this.yylineno++; + this.offset++; + this.match += ch; + this.matched += ch; + var lines = ch.match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno++; + this.yylloc.last_line++; + } else { + this.yylloc.last_column++; + } + if (this.options.ranges) this.yylloc.range[1]++; + this._input = this._input.slice(1); return ch; }, unput:function (ch) { + var len = ch.length; + var lines = ch.split(/(?:\r\n?|\n)/g); + this._input = ch + this._input; + this.yytext = this.yytext.substr(0, this.yytext.length-len-1); + //this.yyleng -= len; + this.offset -= len; + var oldLines = this.match.split(/(?:\r\n?|\n)/g); + this.match = this.match.substr(0, this.match.length-1); + this.matched = this.matched.substr(0, this.matched.length-1); + + if (lines.length-1) this.yylineno -= lines.length-1; + var r = this.yylloc.range; + + this.yylloc = {first_line: this.yylloc.first_line, + last_line: this.yylineno+1, + first_column: this.yylloc.first_column, + last_column: lines ? + (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: + this.yylloc.first_column - len + }; + + if (this.options.ranges) { + this.yylloc.range = [r[0], r[0] + this.yyleng - len]; + } return this; }, more:function () { this._more = true; return this; }, +less:function (n) { + this.unput(this.match.slice(n)); + }, pastInput:function () { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); @@ -353,6 +418,8 @@ next:function () { var token, match, + tempMatch, + index, col, lines; if (!this._more) { @@ -361,30 +428,39 @@ next:function () { } var rules = this._currentRules(); for (var i=0;i < rules.length; i++) { - match = this._input.match(this.rules[rules[i]]); - if (match) { - lines = match[0].match(/\n.*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = {first_line: this.yylloc.last_line, - last_line: this.yylineno+1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length} - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]); - if (token) return token; - else return; + tempMatch = this._input.match(this.rules[rules[i]]); + if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { + match = tempMatch; + index = i; + if (!this.options.flex) break; } } + if (match) { + lines = match[0].match(/(?:\r\n?|\n).*/g); + if (lines) this.yylineno += lines.length; + this.yylloc = {first_line: this.yylloc.last_line, + last_line: this.yylineno+1, + first_column: this.yylloc.last_column, + last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + if (this.options.ranges) { + this.yylloc.range = [this.offset, this.offset += this.yyleng]; + } + this._more = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); + if (this.done && this._input) this.done = false; + if (token) return token; + else return; + } if (this._input === "") { return this.EOF; } else { - this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), + return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), {text: "", token: null, line: this.yylineno}); } }, @@ -411,6 +487,7 @@ topState:function () { pushState:function begin(condition) { this.begin(condition); }}); +lexer.options = {}; lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { var YYSTATE=YY_START @@ -423,7 +500,11 @@ case 0: break; case 1: return 14; break; -case 2: this.popState(); return 14; +case 2: + if(yy_.yytext.slice(-1) !== "\\") this.popState(); + if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1); + return 14; + break; case 3: return 24; break; @@ -443,13 +524,13 @@ case 10: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.popState(); return break; case 11: return 22; break; -case 12: return 34; +case 12: return 35; break; -case 13: return 33; +case 13: return 34; break; -case 14: return 33; +case 14: return 34; break; -case 15: return 36; +case 15: return 37; break; case 16: /*ignore whitespace*/ break; @@ -457,40 +538,47 @@ case 17: this.popState(); return 18; break; case 18: this.popState(); return 18; break; -case 19: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 28; +case 19: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 29; +break; +case 20: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 29; break; -case 20: return 30; +case 21: yy_.yytext = yy_.yytext.substr(1); return 27; break; -case 21: return 30; +case 22: return 31; break; -case 22: return 29; +case 23: return 31; break; -case 23: return 33; +case 24: return 30; break; -case 24: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 33; +case 25: return 34; break; -case 25: return 'INVALID'; +case 26: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 34; break; -case 26: return 5; +case 27: return 'INVALID'; +break; +case 28: return 5; break; } }; -lexer.rules = [/^[^\x00]*?(?=(\{\{))/,/^[^\x00]+/,/^[^\x00]{2,}?(?=(\{\{))/,/^\{\{>/,/^\{\{#/,/^\{\{\//,/^\{\{\^/,/^\{\{\s*else\b/,/^\{\{\{/,/^\{\{&/,/^\{\{![\s\S]*?\}\}/,/^\{\{/,/^=/,/^\.(?=[} ])/,/^\.\./,/^[\/.]/,/^\s+/,/^\}\}\}/,/^\}\}/,/^"(\\["]|[^"])*"/,/^true(?=[}\s])/,/^false(?=[}\s])/,/^[0-9]+(?=[}\s])/,/^[a-zA-Z0-9_$-]+(?=[=}\s\/.])/,/^\[[^\]]*\]/,/^./,/^$/]; -lexer.conditions = {"mu":{"rules":[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"INITIAL":{"rules":[0,1,26],"inclusive":true}};return lexer;})() +lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|$)))/,/^(?:\{\{>)/,/^(?:\{\{#)/,/^(?:\{\{\/)/,/^(?:\{\{\^)/,/^(?:\{\{\s*else\b)/,/^(?:\{\{\{)/,/^(?:\{\{&)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{)/,/^(?:=)/,/^(?:\.(?=[} ]))/,/^(?:\.\.)/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}\}\})/,/^(?:\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@[a-zA-Z]+)/,/^(?:true(?=[}\s]))/,/^(?:false(?=[}\s]))/,/^(?:[0-9]+(?=[}\s]))/,/^(?:[a-zA-Z0-9_$-]+(?=[=}\s\/.]))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; +lexer.conditions = {"mu":{"rules":[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"INITIAL":{"rules":[0,1,28],"inclusive":true}}; +return lexer;})() parser.lexer = lexer; -return parser; +function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; +return new Parser; })(); if (typeof require !== 'undefined' && typeof exports !== 'undefined') { exports.parser = handlebars; +exports.Parser = handlebars.Parser; exports.parse = function () { return handlebars.parse.apply(handlebars, arguments); } exports.main = function commonjsMain(args) { if (!args[1]) throw new Error('Usage: '+args[0]+' FILE'); + var source, cwd; if (typeof process !== 'undefined') { - var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8"); + source = require('fs').readFileSync(require('path').resolve(args[1]), "utf8"); } else { - var cwd = require("file").path(require("file").cwd()); - var source = cwd.join(args[1]).read({charset: "utf-8"}); + source = require("file").path(require("file").cwd()).join(args[1]).read({charset: "utf-8"}); } return exports.parser.parse(source); } @@ -531,12 +619,26 @@ Handlebars.log = function(level, str) { Handlebars.logger.log(level, str); }; if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); } }; - Handlebars.AST.MustacheNode = function(params, hash, unescaped) { + Handlebars.AST.MustacheNode = function(rawParams, hash, unescaped) { this.type = "mustache"; - this.id = params[0]; - this.params = params.slice(1); - this.hash = hash; this.escaped = !unescaped; + this.hash = hash; + + var id = this.id = rawParams[0]; + var params = this.params = rawParams.slice(1); + + // a mustache is an eligible helper if: + // * its id is simple (a single part, not `this` or `..`) + var eligibleHelper = this.eligibleHelper = id.isSimple; + + // a mustache is definitely a helper if: + // * it is an eligible helper, and + // * it has at least one parameter or hash segment + this.isHelper = eligibleHelper && (params.length || hash); + + // if a mustache is an eligible helper but not a definite + // helper, it is ambiguous, and will be resolved in a later + // pass or at runtime. }; Handlebars.AST.PartialNode = function(id, context) { @@ -554,18 +656,16 @@ Handlebars.log = function(level, str) { Handlebars.logger.log(level, str); }; } }; - Handlebars.AST.BlockNode = function(mustache, program, close) { + Handlebars.AST.BlockNode = function(mustache, program, inverse, close) { verifyMatch(mustache.id, close); this.type = "block"; this.mustache = mustache; this.program = program; - }; + this.inverse = inverse; - Handlebars.AST.InverseNode = function(mustache, program, close) { - verifyMatch(mustache.id, close); - this.type = "inverse"; - this.mustache = mustache; - this.program = program; + if (this.inverse && !this.program) { + this.isInverse = true; + } }; Handlebars.AST.ContentNode = function(string) { @@ -595,7 +695,15 @@ Handlebars.log = function(level, str) { Handlebars.logger.log(level, str); }; this.parts = dig; this.string = dig.join('.'); this.depth = depth; - this.isSimple = (dig.length === 1) && (depth === 0); + + // an ID is simple if it only has one part, and that part is not + // `..` or `this`. + this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; + }; + + Handlebars.AST.DataNode = function(id) { + this.type = "DATA"; + this.id = id; }; Handlebars.AST.StringNode = function(string) { @@ -629,7 +737,7 @@ Handlebars.Exception = function(message) { this.message = tmp.message; }; -Handlebars.Exception.prototype = new Error; +Handlebars.Exception.prototype = new Error(); // Build out our basic SafeString type Handlebars.SafeString = function(string) { @@ -641,6 +749,7 @@ Handlebars.SafeString.prototype.toString = function() { (function() { var escape = { + "&": "&", "<": "<", ">": ">", '"': """, @@ -648,7 +757,7 @@ Handlebars.SafeString.prototype.toString = function() { "`": "`" }; - var badChars = /&(?!\w+;)|[<>"'`]/g; + var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { @@ -684,88 +793,38 @@ Handlebars.SafeString.prototype.toString = function() { }; })();; // lib/handlebars/compiler/compiler.js + +/*jshint eqnull:true*/ Handlebars.Compiler = function() {}; Handlebars.JavaScriptCompiler = function() {}; (function(Compiler, JavaScriptCompiler) { - Compiler.OPCODE_MAP = { - appendContent: 1, - getContext: 2, - lookupWithHelpers: 3, - lookup: 4, - append: 5, - invokeMustache: 6, - appendEscaped: 7, - pushString: 8, - truthyOrFallback: 9, - functionOrFallback: 10, - invokeProgram: 11, - invokePartial: 12, - push: 13, - assignToHash: 15, - pushStringParam: 16 - }; - - Compiler.MULTI_PARAM_OPCODES = { - appendContent: 1, - getContext: 1, - lookupWithHelpers: 2, - lookup: 1, - invokeMustache: 3, - pushString: 1, - truthyOrFallback: 1, - functionOrFallback: 1, - invokeProgram: 3, - invokePartial: 1, - push: 1, - assignToHash: 1, - pushStringParam: 1 - }; - - Compiler.DISASSEMBLE_MAP = {}; - - for(var prop in Compiler.OPCODE_MAP) { - var value = Compiler.OPCODE_MAP[prop]; - Compiler.DISASSEMBLE_MAP[value] = prop; - } - - Compiler.multiParamSize = function(code) { - return Compiler.MULTI_PARAM_OPCODES[Compiler.DISASSEMBLE_MAP[code]]; - }; + // the foundHelper register will disambiguate helper lookup from finding a + // function in a context. This is necessary for mustache compatibility, which + // requires that context functions in blocks are evaluated by blockHelperMissing, + // and then proceed as if the resulting value was provided to blockHelperMissing. Compiler.prototype = { compiler: Compiler, disassemble: function() { - var opcodes = this.opcodes, opcode, nextCode; - var out = [], str, name, value; + var opcodes = this.opcodes, opcode, out = [], params, param; - for(var i=0, l=opcodes.length; i 0) { this.source[1] = this.source[1] + ", " + locals.join(", "); @@ -1130,7 +1269,7 @@ Handlebars.JavaScriptCompiler = function() {}; // Generate minimizer alias mappings if (!this.isChild) { - var aliases = [] + var aliases = []; for (var alias in this.context.aliases) { this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; } @@ -1166,10 +1305,64 @@ Handlebars.JavaScriptCompiler = function() {}; } }, + // [blockValue] + // + // On stack, before: hash, inverse, program, value + // On stack, after: return value of blockHelperMissing + // + // The purpose of this opcode is to take a block of the form + // `{{#foo}}...{{/foo}}`, resolve the value of `foo`, and + // replace it on the stack with the result of properly + // invoking blockHelperMissing. + blockValue: function() { + this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; + + var params = ["depth0"]; + this.setupParams(0, params); + + this.replaceStack(function(current) { + params.splice(1, 0, current); + return current + " = blockHelperMissing.call(" + params.join(", ") + ")"; + }); + }, + + // [ambiguousBlockValue] + // + // On stack, before: hash, inverse, program, value + // Compiler value, before: lastHelper=value of last found helper, if any + // On stack, after, if no lastHelper: same as [blockValue] + // On stack, after, if lastHelper: value + ambiguousBlockValue: function() { + this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; + + var params = ["depth0"]; + this.setupParams(0, params); + + var current = this.topStack(); + params.splice(1, 0, current); + + this.source.push("if (!" + this.lastHelper + ") { " + current + " = blockHelperMissing.call(" + params.join(", ") + "); }"); + }, + + // [appendContent] + // + // On stack, before: ... + // On stack, after: ... + // + // Appends the string value of `content` to the current buffer appendContent: function(content) { this.source.push(this.appendToBuffer(this.quotedString(content))); }, + // [append] + // + // On stack, before: value, ... + // On stack, after: ... + // + // Coerces `value` to a String and appends it to the current buffer. + // + // If `value` is truthy, or 0, it is coerced into a string and appended + // Otherwise, the empty string is appended append: function() { var local = this.popStack(); this.source.push("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }"); @@ -1178,163 +1371,242 @@ Handlebars.JavaScriptCompiler = function() {}; } }, + // [appendEscaped] + // + // On stack, before: value, ... + // On stack, after: ... + // + // Escape `value` and append it to the buffer appendEscaped: function() { - var opcode = this.nextOpcode(1), extra = ""; + var opcode = this.nextOpcode(), extra = ""; this.context.aliases.escapeExpression = 'this.escapeExpression'; - if(opcode[0] === 'appendContent') { - extra = " + " + this.quotedString(opcode[1][0]); + if(opcode && opcode.opcode === 'appendContent') { + extra = " + " + this.quotedString(opcode.args[0]); this.eat(opcode); } this.source.push(this.appendToBuffer("escapeExpression(" + this.popStack() + ")" + extra)); }, + // [getContext] + // + // On stack, before: ... + // On stack, after: ... + // Compiler value, after: lastContext=depth + // + // Set the value of the `lastContext` compiler value to the depth getContext: function(depth) { if(this.lastContext !== depth) { this.lastContext = depth; } }, - lookupWithHelpers: function(name, isScoped) { - if(name) { - var topStack = this.nextStack(); - - this.usingKnownHelper = false; - - var toPush; - if (!isScoped && this.options.knownHelpers[name]) { - toPush = topStack + " = " + this.nameLookup('helpers', name, 'helper'); - this.usingKnownHelper = true; - } else if (isScoped || this.options.knownHelpersOnly) { - toPush = topStack + " = " + this.nameLookup('depth' + this.lastContext, name, 'context'); - } else { - this.register('foundHelper', this.nameLookup('helpers', name, 'helper')); - toPush = topStack + " = foundHelper || " + this.nameLookup('depth' + this.lastContext, name, 'context'); - } - - toPush += ';'; - this.source.push(toPush); - } else { - this.pushStack('depth' + this.lastContext); - } + // [lookupOnContext] + // + // On stack, before: ... + // On stack, after: currentContext[name], ... + // + // Looks up the value of `name` on the current context and pushes + // it onto the stack. + lookupOnContext: function(name) { + this.pushStack(this.nameLookup('depth' + this.lastContext, name, 'context')); + }, + + // [pushContext] + // + // On stack, before: ... + // On stack, after: currentContext, ... + // + // Pushes the value of the current context onto the stack. + pushContext: function() { + this.pushStackLiteral('depth' + this.lastContext); + }, + + // [resolvePossibleLambda] + // + // On stack, before: value, ... + // On stack, after: resolved value, ... + // + // If the `value` is a lambda, replace it on the stack by + // the return value of the lambda + resolvePossibleLambda: function() { + this.context.aliases.functionType = '"function"'; + + this.replaceStack(function(current) { + return "typeof " + current + " === functionType ? " + current + "() : " + current; + }); }, + // [lookup] + // + // On stack, before: value, ... + // On stack, after: value[name], ... + // + // Replace the value on the stack with the result of looking + // up `name` on `value` lookup: function(name) { - var topStack = this.topStack(); - this.source.push(topStack + " = (" + topStack + " === null || " + topStack + " === undefined || " + topStack + " === false ? " + - topStack + " : " + this.nameLookup(topStack, name, 'context') + ");"); + this.replaceStack(function(current) { + return current + " == null || " + current + " === false ? " + current + " : " + this.nameLookup(current, name, 'context'); + }); }, + // [lookupData] + // + // On stack, before: ... + // On stack, after: data[id], ... + // + // Push the result of looking up `id` on the current data + lookupData: function(id) { + this.pushStack(this.nameLookup('data', id, 'data')); + }, + + // [pushStringParam] + // + // On stack, before: ... + // On stack, after: string, currentContext, ... + // + // This opcode is designed for use in string mode, which + // provides the string value of a parameter along with its + // depth rather than resolving it immediately. pushStringParam: function(string) { - this.pushStack('depth' + this.lastContext); + this.pushStackLiteral('depth' + this.lastContext); this.pushString(string); }, + // [pushString] + // + // On stack, before: ... + // On stack, after: quotedString(string), ... + // + // Push a quoted version of `string` onto the stack pushString: function(string) { - this.pushStack(this.quotedString(string)); - }, - - push: function(name) { - this.pushStack(name); - }, - - invokeMustache: function(paramSize, original, hasHash) { - this.populateParams(paramSize, this.quotedString(original), "{}", null, hasHash, function(nextStack, helperMissingString, id) { - if (!this.usingKnownHelper) { - this.context.aliases.helperMissing = 'helpers.helperMissing'; - this.context.aliases.undef = 'void 0'; - this.source.push("else if(" + id + "=== undef) { " + nextStack + " = helperMissing.call(" + helperMissingString + "); }"); - if (nextStack !== id) { - this.source.push("else { " + nextStack + " = " + id + "; }"); - } - } - }); - }, - - invokeProgram: function(guid, paramSize, hasHash) { - var inverse = this.programExpression(this.inverse); - var mainProgram = this.programExpression(guid); - - this.populateParams(paramSize, null, mainProgram, inverse, hasHash, function(nextStack, helperMissingString, id) { - if (!this.usingKnownHelper) { - this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; - this.source.push("else { " + nextStack + " = blockHelperMissing.call(" + helperMissingString + "); }"); - } - }); - }, - - populateParams: function(paramSize, helperId, program, inverse, hasHash, fn) { - var needsRegister = hasHash || this.options.stringParams || inverse || this.options.data; - var id = this.popStack(), nextStack; - var params = [], param, stringParam, stringOptions; - - if (needsRegister) { - this.register('tmp1', program); - stringOptions = 'tmp1'; + this.pushStackLiteral(this.quotedString(string)); + }, + + // [push] + // + // On stack, before: ... + // On stack, after: expr, ... + // + // Push an expression onto the stack + push: function(expr) { + this.pushStack(expr); + }, + + // [pushLiteral] + // + // On stack, before: ... + // On stack, after: value, ... + // + // Pushes a value onto the stack. This operation prevents + // the compiler from creating a temporary variable to hold + // it. + pushLiteral: function(value) { + this.pushStackLiteral(value); + }, + + // [pushProgram] + // + // On stack, before: ... + // On stack, after: program(guid), ... + // + // Push a program expression onto the stack. This takes + // a compile-time guid and converts it into a runtime-accessible + // expression. + pushProgram: function(guid) { + if (guid != null) { + this.pushStackLiteral(this.programExpression(guid)); } else { - stringOptions = '{ hash: {} }'; - } - - if (needsRegister) { - var hash = (hasHash ? this.popStack() : '{}'); - this.source.push('tmp1.hash = ' + hash + ';'); + this.pushStackLiteral(null); } - - if(this.options.stringParams) { - this.source.push('tmp1.contexts = [];'); - } - - for(var i=0; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } return "stack" + this.stackSlot; }, popStack: function() { - return "stack" + this.stackSlot--; + var item = this.compileStack.pop(); + + if (item instanceof Literal) { + return item.value; + } else { + this.stackSlot--; + return item; + } }, topStack: function() { - return "stack" + this.stackSlot; + var item = this.compileStack[this.compileStack.length - 1]; + + if (item instanceof Literal) { + return item.value; + } else { + return item; + } }, quotedString: function(str) { @@ -1420,6 +1729,67 @@ Handlebars.JavaScriptCompiler = function() {}; .replace(/"/g, '\\"') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') + '"'; + }, + + setupHelper: function(paramSize, name) { + var params = []; + this.setupParams(paramSize, params); + var foundHelper = this.nameLookup('helpers', name, 'helper'); + + return { + params: params, + name: foundHelper, + callParams: ["depth0"].concat(params).join(", "), + helperMissingParams: ["depth0", this.quotedString(name)].concat(params).join(", ") + }; + }, + + // the params and contexts arguments are passed in arrays + // to fill in + setupParams: function(paramSize, params) { + var options = [], contexts = [], param, inverse, program; + + options.push("hash:" + this.popStack()); + + inverse = this.popStack(); + program = this.popStack(); + + // Avoid setting fn and inverse if neither are set. This allows + // helpers to do a check for `if (options.fn)` + if (program || inverse) { + if (!program) { + this.context.aliases.self = "this"; + program = "self.noop"; + } + + if (!inverse) { + this.context.aliases.self = "this"; + inverse = "self.noop"; + } + + options.push("inverse:" + inverse); + options.push("fn:" + program); + } + + for(var i=0; i