// Copyright (C) 2009 Andy Chu // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // $Id$ // // JavaScript implementation of json-template. // // This is predefined in tests, shouldn't be defined anywhere else. TODO: Do // something nicer. var log = log || function() {}; var repr = repr || function() {}; // The "module" exported by this script is called "jsontemplate": var jsontemplate = function() { // Regex escaping for metacharacters function EscapeMeta(meta) { return meta.replace(/([\{\}\(\)\[\]\|\^\$\-\+\?])/g, '\\$1'); } var token_re_cache = {}; function _MakeTokenRegex(meta_left, meta_right) { var key = meta_left + meta_right; var regex = token_re_cache[key]; if (regex === undefined) { var str = '(' + EscapeMeta(meta_left) + '.*?' + EscapeMeta(meta_right) + '\n?)'; regex = new RegExp(str, 'g'); } return regex; } // // Formatters // function HtmlEscape(s) { return s.replace(/&/g,'&'). replace(/>/g,'>'). replace(//g,'>'). replace(/ 1) ? p : s; } function _Cycle(value, unused_context, args) { // Cycle between various values on consecutive integers. // @index starts from 1, so use 1-based indexing. return args[(value - 1) % args.length]; } var DEFAULT_FORMATTERS = { 'html': HtmlEscape, 'htmltag': HtmlTagEscape, 'html-attr-value': HtmlTagEscape, 'str': ToString, 'raw': function(x) { return x; }, 'AbsUrl': function(value, context) { // TODO: Normalize leading/trailing slashes return context.get('base-url') + '/' + value; } }; var DEFAULT_PREDICATES = { 'singular?': function(x) { return x == 1; }, 'plural?': function(x) { return x > 1; }, 'Debug?': function(unused, context) { try { return context.get('debug'); } catch(err) { if (err.name == 'UndefinedVariable') { return false; } else { throw err; } } } }; var FunctionRegistry = function() { return { lookup: function(user_str) { return [null, null]; } }; }; var SimpleRegistry = function(obj) { return { lookup: function(user_str) { var func = obj[user_str] || null; return [func, null]; } }; }; var CallableRegistry = function(callable) { return { lookup: function(user_str) { var func = callable(user_str); return [func, null]; } }; }; // Default formatters which can't be expressed in DEFAULT_FORMATTERS var PrefixRegistry = function(functions) { return { lookup: function(user_str) { for (var i = 0; i < functions.length; i++) { var name = functions[i].name, func = functions[i].func; if (user_str.slice(0, name.length) == name) { // Delimiter is usually a space, but could be something else var args; var splitchar = user_str.charAt(name.length); if (splitchar === '') { args = []; // No arguments } else { args = user_str.split(splitchar).slice(1); } return [func, args]; } } return [null, null]; // No formatter } }; }; var ChainedRegistry = function(registries) { return { lookup: function(user_str) { for (var i=0; i 1) { for (var i=1; i 0) { // TODO: check that items is an array; apparently this is hard in JavaScript //if type(items) is not list: // raise EvaluationError('Expected a list; got %s' % type(items)) // Execute the statements in the block for every item in the list. // Execute the alternate block on every iteration except the last. Each // item could be an atom (string, integer, etc.) or a dictionary. var last_index = items.length - 1; var statements = block.Statements(); var alt_statements = block.Statements('alternate'); for (var i=0; context.next() !== undefined; i++) { _Execute(statements, context, callback); if (i != last_index) { _Execute(alt_statements, context, callback); } } } else { _Execute(block.Statements('or'), context, callback); } context.Pop(); } var _SECTION_RE = /(repeated)?\s*(section)\s+(\S+)?/; var _OR_RE = /or(?:\s+(.+))?/; var _IF_RE = /if(?:\s+(.+))?/; // Turn a object literal, function, or Registry into a Registry function MakeRegistry(obj) { if (!obj) { // if null/undefined, use a totally empty FunctionRegistry return new FunctionRegistry(); } else if (typeof obj === 'function') { return new CallableRegistry(obj); } else if (obj.lookup !== undefined) { // TODO: Is this a good pattern? There is a namespace conflict where get // could be either a formatter or a method on a FunctionRegistry. // instanceof might be more robust. return obj; } else if (typeof obj === 'object') { return new SimpleRegistry(obj); } } // TODO: The compile function could be in a different module, in case we want to // compile on the server side. function _Compile(template_str, options) { var more_formatters = MakeRegistry(options.more_formatters); // default formatters with arguments var default_formatters = PrefixRegistry([ {name: 'pluralize', func: _Pluralize}, {name: 'cycle', func: _Cycle} ]); var all_formatters = new ChainedRegistry([ more_formatters, SimpleRegistry(DEFAULT_FORMATTERS), default_formatters ]); var more_predicates = MakeRegistry(options.more_predicates); // TODO: Add defaults var all_predicates = new ChainedRegistry([ more_predicates, SimpleRegistry(DEFAULT_PREDICATES) ]); // We want to allow an explicit null value for default_formatter, which means // that an error is raised if no formatter is specified. var default_formatter; if (options.default_formatter === undefined) { default_formatter = 'str'; } else { default_formatter = options.default_formatter; } function GetFormatter(format_str) { var pair = all_formatters.lookup(format_str); if (!pair[0]) { throw { name: 'BadFormatter', message: format_str + ' is not a valid formatter' }; } return pair; } function GetPredicate(pred_str) { var pair = all_predicates.lookup(pred_str); if (!pair[0]) { throw { name: 'BadPredicate', message: pred_str + ' is not a valid predicate' }; } return pair; } var format_char = options.format_char || '|'; if (format_char != ':' && format_char != '|') { throw { name: 'ConfigurationError', message: 'Only format characters : and | are accepted' }; } var meta = options.meta || '{}'; var n = meta.length; if (n % 2 == 1) { throw { name: 'ConfigurationError', message: meta + ' has an odd number of metacharacters' }; } var meta_left = meta.substring(0, n/2); var meta_right = meta.substring(n/2, n); var token_re = _MakeTokenRegex(meta_left, meta_right); var current_block = _Section({}); var stack = [current_block]; var strip_num = meta_left.length; // assume they're the same length var token_match; var last_index = 0; while (true) { token_match = token_re.exec(template_str); if (token_match === null) { break; } else { var token = token_match[0]; } // Add the previous literal to the program if (token_match.index > last_index) { var tok = template_str.slice(last_index, token_match.index); current_block.Append(tok); } last_index = token_re.lastIndex; var had_newline = false; if (token.slice(-1) == '\n') { token = token.slice(null, -1); had_newline = true; } token = token.slice(strip_num, -strip_num); if (token.charAt(0) == '#') { continue; // comment } if (token.charAt(0) == '.') { // Keyword token = token.substring(1, token.length); var literal = { 'meta-left': meta_left, 'meta-right': meta_right, 'space': ' ', 'tab': '\t', 'newline': '\n' }[token]; if (literal !== undefined) { current_block.Append(literal); continue; } var new_block, func; var section_match = token.match(_SECTION_RE); if (section_match) { var repeated = section_match[1]; var section_name = section_match[3]; if (repeated) { func = _DoRepeatedSection; new_block = _RepeatedSection({section_name: section_name}); } else { func = _DoSection; new_block = _Section({section_name: section_name}); } current_block.Append([func, new_block]); stack.push(new_block); current_block = new_block; continue; } var pred_str, pred; // Check {.or pred?} before {.pred?} var or_match = token.match(_OR_RE); if (or_match) { pred_str = or_match[1]; pred = pred_str ? GetPredicate(pred_str) : null; current_block.NewOrClause(pred); continue; } // Match either {.pred?} or {.if pred?} var matched = false; var if_match = token.match(_IF_RE); if (if_match) { pred_str = if_match[1]; matched = true; } else if (token.charAt(token.length-1) == '?') { pred_str = token; matched = true; } if (matched) { pred = pred_str ? GetPredicate(pred_str) : null; new_block = _PredicateSection(); new_block.NewOrClause(pred); current_block.Append([_DoPredicates, new_block]); stack.push(new_block); current_block = new_block; continue; } if (token == 'alternates with') { current_block.AlternatesWith(); continue; } if (token == 'end') { // End the block stack.pop(); if (stack.length > 0) { current_block = stack[stack.length-1]; } else { throw { name: 'TemplateSyntaxError', message: 'Got too many {end} statements' }; } continue; } } // A variable substitution var parts = token.split(format_char); var formatters; var name; if (parts.length == 1) { if (default_formatter === null) { throw { name: 'MissingFormatter', message: 'This template requires explicit formatters.' }; } // If no formatter is specified, use the default. formatters = [GetFormatter(default_formatter)]; name = token; } else { formatters = []; for (var j=1; j