jed.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /**
  2. * @preserve jed.js https://github.com/SlexAxton/Jed
  3. */
  4. /*
  5. -----------
  6. A gettext compatible i18n library for modern JavaScript Applications
  7. by Alex Sexton - AlexSexton [at] gmail - @SlexAxton
  8. MIT License
  9. A jQuery Foundation project - requires CLA to contribute -
  10. https://contribute.jquery.org/CLA/
  11. Jed offers the entire applicable GNU gettext spec'd set of
  12. functions, but also offers some nicer wrappers around them.
  13. The api for gettext was written for a language with no function
  14. overloading, so Jed allows a little more of that.
  15. Many thanks to Joshua I. Miller - unrtst@cpan.org - who wrote
  16. gettext.js back in 2008. I was able to vet a lot of my ideas
  17. against his. I also made sure Jed passed against his tests
  18. in order to offer easy upgrades -- jsgettext.berlios.de
  19. */
  20. (function (root, undef) {
  21. // Set up some underscore-style functions, if you already have
  22. // underscore, feel free to delete this section, and use it
  23. // directly, however, the amount of functions used doesn't
  24. // warrant having underscore as a full dependency.
  25. // Underscore 1.3.0 was used to port and is licensed
  26. // under the MIT License by Jeremy Ashkenas.
  27. var ArrayProto = Array.prototype,
  28. ObjProto = Object.prototype,
  29. slice = ArrayProto.slice,
  30. hasOwnProp = ObjProto.hasOwnProperty,
  31. nativeForEach = ArrayProto.forEach,
  32. breaker = {};
  33. // We're not using the OOP style _ so we don't need the
  34. // extra level of indirection. This still means that you
  35. // sub out for real `_` though.
  36. var _ = {
  37. forEach : function( obj, iterator, context ) {
  38. var i, l, key;
  39. if ( obj === null ) {
  40. return;
  41. }
  42. if ( nativeForEach && obj.forEach === nativeForEach ) {
  43. obj.forEach( iterator, context );
  44. }
  45. else if ( obj.length === +obj.length ) {
  46. for ( i = 0, l = obj.length; i < l; i++ ) {
  47. if ( i in obj && iterator.call( context, obj[i], i, obj ) === breaker ) {
  48. return;
  49. }
  50. }
  51. }
  52. else {
  53. for ( key in obj) {
  54. if ( hasOwnProp.call( obj, key ) ) {
  55. if ( iterator.call (context, obj[key], key, obj ) === breaker ) {
  56. return;
  57. }
  58. }
  59. }
  60. }
  61. },
  62. extend : function( obj ) {
  63. this.forEach( slice.call( arguments, 1 ), function ( source ) {
  64. for ( var prop in source ) {
  65. obj[prop] = source[prop];
  66. }
  67. });
  68. return obj;
  69. }
  70. };
  71. // END Miniature underscore impl
  72. // Jed is a constructor function
  73. var Jed = function ( options ) {
  74. // Some minimal defaults
  75. this.defaults = {
  76. "locale_data" : {
  77. "messages" : {
  78. "" : {
  79. "domain" : "messages",
  80. "lang" : "en",
  81. "plural_forms" : "nplurals=2; plural=(n != 1);"
  82. }
  83. // There are no default keys, though
  84. }
  85. },
  86. // The default domain if one is missing
  87. "domain" : "messages",
  88. // enable debug mode to log untranslated strings to the console
  89. "debug" : false
  90. };
  91. // Mix in the sent options with the default options
  92. this.options = _.extend( {}, this.defaults, options );
  93. this.textdomain( this.options.domain );
  94. if ( options.domain && ! this.options.locale_data[ this.options.domain ] ) {
  95. throw new Error('Text domain set to non-existent domain: `' + options.domain + '`');
  96. }
  97. };
  98. // The gettext spec sets this character as the default
  99. // delimiter for context lookups.
  100. // e.g.: context\u0004key
  101. // If your translation company uses something different,
  102. // just change this at any time and it will use that instead.
  103. Jed.context_delimiter = String.fromCharCode( 4 );
  104. function getPluralFormFunc ( plural_form_string ) {
  105. return Jed.PF.compile( plural_form_string || "nplurals=2; plural=(n != 1);");
  106. }
  107. function Chain( key, i18n ){
  108. this._key = key;
  109. this._i18n = i18n;
  110. }
  111. // Create a chainable api for adding args prettily
  112. _.extend( Chain.prototype, {
  113. onDomain : function ( domain ) {
  114. this._domain = domain;
  115. return this;
  116. },
  117. withContext : function ( context ) {
  118. this._context = context;
  119. return this;
  120. },
  121. ifPlural : function ( num, pkey ) {
  122. this._val = num;
  123. this._pkey = pkey;
  124. return this;
  125. },
  126. fetch : function ( sArr ) {
  127. if ( {}.toString.call( sArr ) != '[object Array]' ) {
  128. sArr = [].slice.call(arguments, 0);
  129. }
  130. return ( sArr && sArr.length ? Jed.sprintf : function(x){ return x; } )(
  131. this._i18n.dcnpgettext(this._domain, this._context, this._key, this._pkey, this._val),
  132. sArr
  133. );
  134. }
  135. });
  136. // Add functions to the Jed prototype.
  137. // These will be the functions on the object that's returned
  138. // from creating a `new Jed()`
  139. // These seem redundant, but they gzip pretty well.
  140. _.extend( Jed.prototype, {
  141. // The sexier api start point
  142. translate : function ( key ) {
  143. return new Chain( key, this );
  144. },
  145. textdomain : function ( domain ) {
  146. if ( ! domain ) {
  147. return this._textdomain;
  148. }
  149. this._textdomain = domain;
  150. },
  151. gettext : function ( key ) {
  152. return this.dcnpgettext.call( this, undef, undef, key );
  153. },
  154. dgettext : function ( domain, key ) {
  155. return this.dcnpgettext.call( this, domain, undef, key );
  156. },
  157. dcgettext : function ( domain , key /*, category */ ) {
  158. // Ignores the category anyways
  159. return this.dcnpgettext.call( this, domain, undef, key );
  160. },
  161. ngettext : function ( skey, pkey, val ) {
  162. return this.dcnpgettext.call( this, undef, undef, skey, pkey, val );
  163. },
  164. dngettext : function ( domain, skey, pkey, val ) {
  165. return this.dcnpgettext.call( this, domain, undef, skey, pkey, val );
  166. },
  167. dcngettext : function ( domain, skey, pkey, val/*, category */) {
  168. return this.dcnpgettext.call( this, domain, undef, skey, pkey, val );
  169. },
  170. pgettext : function ( context, key ) {
  171. return this.dcnpgettext.call( this, undef, context, key );
  172. },
  173. dpgettext : function ( domain, context, key ) {
  174. return this.dcnpgettext.call( this, domain, context, key );
  175. },
  176. dcpgettext : function ( domain, context, key/*, category */) {
  177. return this.dcnpgettext.call( this, domain, context, key );
  178. },
  179. npgettext : function ( context, skey, pkey, val ) {
  180. return this.dcnpgettext.call( this, undef, context, skey, pkey, val );
  181. },
  182. dnpgettext : function ( domain, context, skey, pkey, val ) {
  183. return this.dcnpgettext.call( this, domain, context, skey, pkey, val );
  184. },
  185. // The most fully qualified gettext function. It has every option.
  186. // Since it has every option, we can use it from every other method.
  187. // This is the bread and butter.
  188. // Technically there should be one more argument in this function for 'Category',
  189. // but since we never use it, we might as well not waste the bytes to define it.
  190. dcnpgettext : function ( domain, context, singular_key, plural_key, val ) {
  191. // Set some defaults
  192. plural_key = plural_key || singular_key;
  193. // Use the global domain default if one
  194. // isn't explicitly passed in
  195. domain = domain || this._textdomain;
  196. var fallback;
  197. // Handle special cases
  198. // No options found
  199. if ( ! this.options ) {
  200. // There's likely something wrong, but we'll return the correct key for english
  201. // We do this by instantiating a brand new Jed instance with the default set
  202. // for everything that could be broken.
  203. fallback = new Jed();
  204. return fallback.dcnpgettext.call( fallback, undefined, undefined, singular_key, plural_key, val );
  205. }
  206. // No translation data provided
  207. if ( ! this.options.locale_data ) {
  208. throw new Error('No locale data provided.');
  209. }
  210. if ( ! this.options.locale_data[ domain ] ) {
  211. throw new Error('Domain `' + domain + '` was not found.');
  212. }
  213. if ( ! this.options.locale_data[ domain ][ "" ] ) {
  214. throw new Error('No locale meta information provided.');
  215. }
  216. // Make sure we have a truthy key. Otherwise we might start looking
  217. // into the empty string key, which is the options for the locale
  218. // data.
  219. if ( ! singular_key ) {
  220. throw new Error('No translation key found.');
  221. }
  222. var key = context ? context + Jed.context_delimiter + singular_key : singular_key,
  223. locale_data = this.options.locale_data,
  224. dict = locale_data[ domain ],
  225. defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""],
  226. pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"],
  227. val_list,
  228. res;
  229. var val_idx;
  230. if (val === undefined) {
  231. // No value passed in; assume singular key lookup.
  232. val_idx = 0;
  233. } else {
  234. // Value has been passed in; use plural-forms calculations.
  235. // Handle invalid numbers, but try casting strings for good measure
  236. if ( typeof val != 'number' ) {
  237. val = parseInt( val, 10 );
  238. if ( isNaN( val ) ) {
  239. throw new Error('The number that was passed in is not a number.');
  240. }
  241. }
  242. val_idx = getPluralFormFunc(pluralForms)(val);
  243. }
  244. // Throw an error if a domain isn't found
  245. if ( ! dict ) {
  246. throw new Error('No domain named `' + domain + '` could be found.');
  247. }
  248. val_list = dict[ key ];
  249. // If there is no match, then revert back to
  250. // english style singular/plural with the keys passed in.
  251. if ( ! val_list || val_idx > val_list.length ) {
  252. if (this.options.missing_key_callback) {
  253. this.options.missing_key_callback(key, domain);
  254. }
  255. res = [ singular_key, plural_key ];
  256. // collect untranslated strings
  257. if (this.options.debug===true) {
  258. console.log(res[ getPluralFormFunc(pluralForms)( val ) ]);
  259. }
  260. return res[ getPluralFormFunc()( val ) ];
  261. }
  262. res = val_list[ val_idx ];
  263. // This includes empty strings on purpose
  264. if ( ! res ) {
  265. res = [ singular_key, plural_key ];
  266. return res[ getPluralFormFunc()( val ) ];
  267. }
  268. return res;
  269. }
  270. });
  271. // We add in sprintf capabilities for post translation value interolation
  272. // This is not internally used, so you can remove it if you have this
  273. // available somewhere else, or want to use a different system.
  274. // We _slightly_ modify the normal sprintf behavior to more gracefully handle
  275. // undefined values.
  276. /**
  277. sprintf() for JavaScript 0.7-beta1
  278. http://www.diveintojavascript.com/projects/javascript-sprintf
  279. Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
  280. All rights reserved.
  281. Redistribution and use in source and binary forms, with or without
  282. modification, are permitted provided that the following conditions are met:
  283. * Redistributions of source code must retain the above copyright
  284. notice, this list of conditions and the following disclaimer.
  285. * Redistributions in binary form must reproduce the above copyright
  286. notice, this list of conditions and the following disclaimer in the
  287. documentation and/or other materials provided with the distribution.
  288. * Neither the name of sprintf() for JavaScript nor the
  289. names of its contributors may be used to endorse or promote products
  290. derived from this software without specific prior written permission.
  291. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  292. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  293. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  294. DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY
  295. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  296. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  297. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  298. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  299. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  300. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  301. */
  302. var sprintf = (function() {
  303. function get_type(variable) {
  304. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  305. }
  306. function str_repeat(input, multiplier) {
  307. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  308. return output.join('');
  309. }
  310. var str_format = function() {
  311. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  312. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  313. }
  314. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  315. };
  316. str_format.format = function(parse_tree, argv) {
  317. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  318. for (i = 0; i < tree_length; i++) {
  319. node_type = get_type(parse_tree[i]);
  320. if (node_type === 'string') {
  321. output.push(parse_tree[i]);
  322. }
  323. else if (node_type === 'array') {
  324. match = parse_tree[i]; // convenience purposes only
  325. if (match[2]) { // keyword argument
  326. arg = argv[cursor];
  327. for (k = 0; k < match[2].length; k++) {
  328. if (!arg.hasOwnProperty(match[2][k])) {
  329. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  330. }
  331. arg = arg[match[2][k]];
  332. }
  333. }
  334. else if (match[1]) { // positional argument (explicit)
  335. arg = argv[match[1]];
  336. }
  337. else { // positional argument (implicit)
  338. arg = argv[cursor++];
  339. }
  340. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  341. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  342. }
  343. // Jed EDIT
  344. if ( typeof arg == 'undefined' || arg === null ) {
  345. arg = '';
  346. }
  347. // Jed EDIT
  348. switch (match[8]) {
  349. case 'b': arg = arg.toString(2); break;
  350. case 'c': arg = String.fromCharCode(arg); break;
  351. case 'd': arg = parseInt(arg, 10); break;
  352. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  353. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  354. case 'o': arg = arg.toString(8); break;
  355. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  356. case 'u': arg = Math.abs(arg); break;
  357. case 'x': arg = arg.toString(16); break;
  358. case 'X': arg = arg.toString(16).toUpperCase(); break;
  359. }
  360. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  361. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  362. pad_length = match[6] - String(arg).length;
  363. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  364. output.push(match[5] ? arg + pad : pad + arg);
  365. }
  366. }
  367. return output.join('');
  368. };
  369. str_format.cache = {};
  370. str_format.parse = function(fmt) {
  371. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  372. while (_fmt) {
  373. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  374. parse_tree.push(match[0]);
  375. }
  376. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  377. parse_tree.push('%');
  378. }
  379. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  380. if (match[2]) {
  381. arg_names |= 1;
  382. var field_list = [], replacement_field = match[2], field_match = [];
  383. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  384. field_list.push(field_match[1]);
  385. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  386. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  387. field_list.push(field_match[1]);
  388. }
  389. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  390. field_list.push(field_match[1]);
  391. }
  392. else {
  393. throw('[sprintf] huh?');
  394. }
  395. }
  396. }
  397. else {
  398. throw('[sprintf] huh?');
  399. }
  400. match[2] = field_list;
  401. }
  402. else {
  403. arg_names |= 2;
  404. }
  405. if (arg_names === 3) {
  406. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  407. }
  408. parse_tree.push(match);
  409. }
  410. else {
  411. throw('[sprintf] huh?');
  412. }
  413. _fmt = _fmt.substring(match[0].length);
  414. }
  415. return parse_tree;
  416. };
  417. return str_format;
  418. })();
  419. var vsprintf = function(fmt, argv) {
  420. argv.unshift(fmt);
  421. return sprintf.apply(null, argv);
  422. };
  423. Jed.parse_plural = function ( plural_forms, n ) {
  424. plural_forms = plural_forms.replace(/n/g, n);
  425. return Jed.parse_expression(plural_forms);
  426. };
  427. Jed.sprintf = function ( fmt, args ) {
  428. if ( {}.toString.call( args ) == '[object Array]' ) {
  429. return vsprintf( fmt, [].slice.call(args) );
  430. }
  431. return sprintf.apply(this, [].slice.call(arguments) );
  432. };
  433. Jed.prototype.sprintf = function () {
  434. return Jed.sprintf.apply(this, arguments);
  435. };
  436. // END sprintf Implementation
  437. // Start the Plural forms section
  438. // This is a full plural form expression parser. It is used to avoid
  439. // running 'eval' or 'new Function' directly against the plural
  440. // forms.
  441. //
  442. // This can be important if you get translations done through a 3rd
  443. // party vendor. I encourage you to use this instead, however, I
  444. // also will provide a 'precompiler' that you can use at build time
  445. // to output valid/safe function representations of the plural form
  446. // expressions. This means you can build this code out for the most
  447. // part.
  448. Jed.PF = {};
  449. Jed.PF.parse = function ( p ) {
  450. var plural_str = Jed.PF.extractPluralExpr( p );
  451. return Jed.PF.parser.parse.call(Jed.PF.parser, plural_str);
  452. };
  453. Jed.PF.compile = function ( p ) {
  454. // Handle trues and falses as 0 and 1
  455. function imply( val ) {
  456. return (val === true ? 1 : val ? val : 0);
  457. }
  458. var ast = Jed.PF.parse( p );
  459. return function ( n ) {
  460. return imply( Jed.PF.interpreter( ast )( n ) );
  461. };
  462. };
  463. Jed.PF.interpreter = function ( ast ) {
  464. return function ( n ) {
  465. var res;
  466. switch ( ast.type ) {
  467. case 'GROUP':
  468. return Jed.PF.interpreter( ast.expr )( n );
  469. case 'TERNARY':
  470. if ( Jed.PF.interpreter( ast.expr )( n ) ) {
  471. return Jed.PF.interpreter( ast.truthy )( n );
  472. }
  473. return Jed.PF.interpreter( ast.falsey )( n );
  474. case 'OR':
  475. return Jed.PF.interpreter( ast.left )( n ) || Jed.PF.interpreter( ast.right )( n );
  476. case 'AND':
  477. return Jed.PF.interpreter( ast.left )( n ) && Jed.PF.interpreter( ast.right )( n );
  478. case 'LT':
  479. return Jed.PF.interpreter( ast.left )( n ) < Jed.PF.interpreter( ast.right )( n );
  480. case 'GT':
  481. return Jed.PF.interpreter( ast.left )( n ) > Jed.PF.interpreter( ast.right )( n );
  482. case 'LTE':
  483. return Jed.PF.interpreter( ast.left )( n ) <= Jed.PF.interpreter( ast.right )( n );
  484. case 'GTE':
  485. return Jed.PF.interpreter( ast.left )( n ) >= Jed.PF.interpreter( ast.right )( n );
  486. case 'EQ':
  487. return Jed.PF.interpreter( ast.left )( n ) == Jed.PF.interpreter( ast.right )( n );
  488. case 'NEQ':
  489. return Jed.PF.interpreter( ast.left )( n ) != Jed.PF.interpreter( ast.right )( n );
  490. case 'MOD':
  491. return Jed.PF.interpreter( ast.left )( n ) % Jed.PF.interpreter( ast.right )( n );
  492. case 'VAR':
  493. return n;
  494. case 'NUM':
  495. return ast.val;
  496. default:
  497. throw new Error("Invalid Token found.");
  498. }
  499. };
  500. };
  501. Jed.PF.extractPluralExpr = function ( p ) {
  502. // trim first
  503. p = p.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  504. if (! /;\s*$/.test(p)) {
  505. p = p.concat(';');
  506. }
  507. var nplurals_re = /nplurals\=(\d+);/,
  508. plural_re = /plural\=(.*);/,
  509. nplurals_matches = p.match( nplurals_re ),
  510. res = {},
  511. plural_matches;
  512. // Find the nplurals number
  513. if ( nplurals_matches.length > 1 ) {
  514. res.nplurals = nplurals_matches[1];
  515. }
  516. else {
  517. throw new Error('nplurals not found in plural_forms string: ' + p );
  518. }
  519. // remove that data to get to the formula
  520. p = p.replace( nplurals_re, "" );
  521. plural_matches = p.match( plural_re );
  522. if (!( plural_matches && plural_matches.length > 1 ) ) {
  523. throw new Error('`plural` expression not found: ' + p);
  524. }
  525. return plural_matches[ 1 ];
  526. };
  527. /* Jison generated parser */
  528. Jed.PF.parser = (function(){
  529. var parser = {trace: function trace() { },
  530. yy: {},
  531. symbols_: {"error":2,"expressions":3,"e":4,"EOF":5,"?":6,":":7,"||":8,"&&":9,"<":10,"<=":11,">":12,">=":13,"!=":14,"==":15,"%":16,"(":17,")":18,"n":19,"NUMBER":20,"$accept":0,"$end":1},
  532. terminals_: {2:"error",5:"EOF",6:"?",7:":",8:"||",9:"&&",10:"<",11:"<=",12:">",13:">=",14:"!=",15:"==",16:"%",17:"(",18:")",19:"n",20:"NUMBER"},
  533. productions_: [0,[3,2],[4,5],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,1],[4,1]],
  534. performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
  535. var $0 = $$.length - 1;
  536. switch (yystate) {
  537. case 1: return { type : 'GROUP', expr: $$[$0-1] };
  538. break;
  539. case 2:this.$ = { type: 'TERNARY', expr: $$[$0-4], truthy : $$[$0-2], falsey: $$[$0] };
  540. break;
  541. case 3:this.$ = { type: "OR", left: $$[$0-2], right: $$[$0] };
  542. break;
  543. case 4:this.$ = { type: "AND", left: $$[$0-2], right: $$[$0] };
  544. break;
  545. case 5:this.$ = { type: 'LT', left: $$[$0-2], right: $$[$0] };
  546. break;
  547. case 6:this.$ = { type: 'LTE', left: $$[$0-2], right: $$[$0] };
  548. break;
  549. case 7:this.$ = { type: 'GT', left: $$[$0-2], right: $$[$0] };
  550. break;
  551. case 8:this.$ = { type: 'GTE', left: $$[$0-2], right: $$[$0] };
  552. break;
  553. case 9:this.$ = { type: 'NEQ', left: $$[$0-2], right: $$[$0] };
  554. break;
  555. case 10:this.$ = { type: 'EQ', left: $$[$0-2], right: $$[$0] };
  556. break;
  557. case 11:this.$ = { type: 'MOD', left: $$[$0-2], right: $$[$0] };
  558. break;
  559. case 12:this.$ = { type: 'GROUP', expr: $$[$0-1] };
  560. break;
  561. case 13:this.$ = { type: 'VAR' };
  562. break;
  563. case 14:this.$ = { type: 'NUM', val: Number(yytext) };
  564. break;
  565. }
  566. },
  567. table: [{3:1,4:2,17:[1,3],19:[1,4],20:[1,5]},{1:[3]},{5:[1,6],6:[1,7],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16]},{4:17,17:[1,3],19:[1,4],20:[1,5]},{5:[2,13],6:[2,13],7:[2,13],8:[2,13],9:[2,13],10:[2,13],11:[2,13],12:[2,13],13:[2,13],14:[2,13],15:[2,13],16:[2,13],18:[2,13]},{5:[2,14],6:[2,14],7:[2,14],8:[2,14],9:[2,14],10:[2,14],11:[2,14],12:[2,14],13:[2,14],14:[2,14],15:[2,14],16:[2,14],18:[2,14]},{1:[2,1]},{4:18,17:[1,3],19:[1,4],20:[1,5]},{4:19,17:[1,3],19:[1,4],20:[1,5]},{4:20,17:[1,3],19:[1,4],20:[1,5]},{4:21,17:[1,3],19:[1,4],20:[1,5]},{4:22,17:[1,3],19:[1,4],20:[1,5]},{4:23,17:[1,3],19:[1,4],20:[1,5]},{4:24,17:[1,3],19:[1,4],20:[1,5]},{4:25,17:[1,3],19:[1,4],20:[1,5]},{4:26,17:[1,3],19:[1,4],20:[1,5]},{4:27,17:[1,3],19:[1,4],20:[1,5]},{6:[1,7],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[1,28]},{6:[1,7],7:[1,29],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16]},{5:[2,3],6:[2,3],7:[2,3],8:[2,3],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,3]},{5:[2,4],6:[2,4],7:[2,4],8:[2,4],9:[2,4],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,4]},{5:[2,5],6:[2,5],7:[2,5],8:[2,5],9:[2,5],10:[2,5],11:[2,5],12:[2,5],13:[2,5],14:[2,5],15:[2,5],16:[1,16],18:[2,5]},{5:[2,6],6:[2,6],7:[2,6],8:[2,6],9:[2,6],10:[2,6],11:[2,6],12:[2,6],13:[2,6],14:[2,6],15:[2,6],16:[1,16],18:[2,6]},{5:[2,7],6:[2,7],7:[2,7],8:[2,7],9:[2,7],10:[2,7],11:[2,7],12:[2,7],13:[2,7],14:[2,7],15:[2,7],16:[1,16],18:[2,7]},{5:[2,8],6:[2,8],7:[2,8],8:[2,8],9:[2,8],10:[2,8],11:[2,8],12:[2,8],13:[2,8],14:[2,8],15:[2,8],16:[1,16],18:[2,8]},{5:[2,9],6:[2,9],7:[2,9],8:[2,9],9:[2,9],10:[2,9],11:[2,9],12:[2,9],13:[2,9],14:[2,9],15:[2,9],16:[1,16],18:[2,9]},{5:[2,10],6:[2,10],7:[2,10],8:[2,10],9:[2,10],10:[2,10],11:[2,10],12:[2,10],13:[2,10],14:[2,10],15:[2,10],16:[1,16],18:[2,10]},{5:[2,11],6:[2,11],7:[2,11],8:[2,11],9:[2,11],10:[2,11],11:[2,11],12:[2,11],13:[2,11],14:[2,11],15:[2,11],16:[2,11],18:[2,11]},{5:[2,12],6:[2,12],7:[2,12],8:[2,12],9:[2,12],10:[2,12],11:[2,12],12:[2,12],13:[2,12],14:[2,12],15:[2,12],16:[2,12],18:[2,12]},{4:30,17:[1,3],19:[1,4],20:[1,5]},{5:[2,2],6:[1,7],7:[2,2],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,2]}],
  568. defaultActions: {6:[2,1]},
  569. parseError: function parseError(str, hash) {
  570. throw new Error(str);
  571. },
  572. parse: function parse(input) {
  573. var self = this,
  574. stack = [0],
  575. vstack = [null], // semantic value stack
  576. lstack = [], // location stack
  577. table = this.table,
  578. yytext = '',
  579. yylineno = 0,
  580. yyleng = 0,
  581. recovering = 0,
  582. TERROR = 2,
  583. EOF = 1;
  584. //this.reductionCount = this.shiftCount = 0;
  585. this.lexer.setInput(input);
  586. this.lexer.yy = this.yy;
  587. this.yy.lexer = this.lexer;
  588. if (typeof this.lexer.yylloc == 'undefined')
  589. this.lexer.yylloc = {};
  590. var yyloc = this.lexer.yylloc;
  591. lstack.push(yyloc);
  592. if (typeof this.yy.parseError === 'function')
  593. this.parseError = this.yy.parseError;
  594. function popStack (n) {
  595. stack.length = stack.length - 2*n;
  596. vstack.length = vstack.length - n;
  597. lstack.length = lstack.length - n;
  598. }
  599. function lex() {
  600. var token;
  601. token = self.lexer.lex() || 1; // $end = 1
  602. // if token isn't its numeric value, convert
  603. if (typeof token !== 'number') {
  604. token = self.symbols_[token] || token;
  605. }
  606. return token;
  607. }
  608. var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected;
  609. while (true) {
  610. // retreive state number from top of stack
  611. state = stack[stack.length-1];
  612. // use default actions if available
  613. if (this.defaultActions[state]) {
  614. action = this.defaultActions[state];
  615. } else {
  616. if (symbol == null)
  617. symbol = lex();
  618. // read action for current state and first input
  619. action = table[state] && table[state][symbol];
  620. }
  621. // handle parse error
  622. _handle_error:
  623. if (typeof action === 'undefined' || !action.length || !action[0]) {
  624. if (!recovering) {
  625. // Report error
  626. expected = [];
  627. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  628. expected.push("'"+this.terminals_[p]+"'");
  629. }
  630. var errStr = '';
  631. if (this.lexer.showPosition) {
  632. errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'";
  633. } else {
  634. errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
  635. (symbol == 1 /*EOF*/ ? "end of input" :
  636. ("'"+(this.terminals_[symbol] || symbol)+"'"));
  637. }
  638. this.parseError(errStr,
  639. {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
  640. }
  641. // just recovered from another error
  642. if (recovering == 3) {
  643. if (symbol == EOF) {
  644. throw new Error(errStr || 'Parsing halted.');
  645. }
  646. // discard current lookahead and grab another
  647. yyleng = this.lexer.yyleng;
  648. yytext = this.lexer.yytext;
  649. yylineno = this.lexer.yylineno;
  650. yyloc = this.lexer.yylloc;
  651. symbol = lex();
  652. }
  653. // try to recover from error
  654. while (1) {
  655. // check for error recovery rule in this state
  656. if ((TERROR.toString()) in table[state]) {
  657. break;
  658. }
  659. if (state == 0) {
  660. throw new Error(errStr || 'Parsing halted.');
  661. }
  662. popStack(1);
  663. state = stack[stack.length-1];
  664. }
  665. preErrorSymbol = symbol; // save the lookahead token
  666. symbol = TERROR; // insert generic error symbol as new lookahead
  667. state = stack[stack.length-1];
  668. action = table[state] && table[state][TERROR];
  669. recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
  670. }
  671. // this shouldn't happen, unless resolve defaults are off
  672. if (action[0] instanceof Array && action.length > 1) {
  673. throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);
  674. }
  675. switch (action[0]) {
  676. case 1: // shift
  677. //this.shiftCount++;
  678. stack.push(symbol);
  679. vstack.push(this.lexer.yytext);
  680. lstack.push(this.lexer.yylloc);
  681. stack.push(action[1]); // push state
  682. symbol = null;
  683. if (!preErrorSymbol) { // normal execution/no error
  684. yyleng = this.lexer.yyleng;
  685. yytext = this.lexer.yytext;
  686. yylineno = this.lexer.yylineno;
  687. yyloc = this.lexer.yylloc;
  688. if (recovering > 0)
  689. recovering--;
  690. } else { // error just occurred, resume old lookahead f/ before error
  691. symbol = preErrorSymbol;
  692. preErrorSymbol = null;
  693. }
  694. break;
  695. case 2: // reduce
  696. //this.reductionCount++;
  697. len = this.productions_[action[1]][1];
  698. // perform semantic action
  699. yyval.$ = vstack[vstack.length-len]; // default to $$ = $1
  700. // default location, uses first token for firsts, last for lasts
  701. yyval._$ = {
  702. first_line: lstack[lstack.length-(len||1)].first_line,
  703. last_line: lstack[lstack.length-1].last_line,
  704. first_column: lstack[lstack.length-(len||1)].first_column,
  705. last_column: lstack[lstack.length-1].last_column
  706. };
  707. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  708. if (typeof r !== 'undefined') {
  709. return r;
  710. }
  711. // pop off stack
  712. if (len) {
  713. stack = stack.slice(0,-1*len*2);
  714. vstack = vstack.slice(0, -1*len);
  715. lstack = lstack.slice(0, -1*len);
  716. }
  717. stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)
  718. vstack.push(yyval.$);
  719. lstack.push(yyval._$);
  720. // goto new state = table[STATE][NONTERMINAL]
  721. newState = table[stack[stack.length-2]][stack[stack.length-1]];
  722. stack.push(newState);
  723. break;
  724. case 3: // accept
  725. return true;
  726. }
  727. }
  728. return true;
  729. }};/* Jison generated lexer */
  730. var lexer = (function(){
  731. var lexer = ({EOF:1,
  732. parseError:function parseError(str, hash) {
  733. if (this.yy.parseError) {
  734. this.yy.parseError(str, hash);
  735. } else {
  736. throw new Error(str);
  737. }
  738. },
  739. setInput:function (input) {
  740. this._input = input;
  741. this._more = this._less = this.done = false;
  742. this.yylineno = this.yyleng = 0;
  743. this.yytext = this.matched = this.match = '';
  744. this.conditionStack = ['INITIAL'];
  745. this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
  746. return this;
  747. },
  748. input:function () {
  749. var ch = this._input[0];
  750. this.yytext+=ch;
  751. this.yyleng++;
  752. this.match+=ch;
  753. this.matched+=ch;
  754. var lines = ch.match(/\n/);
  755. if (lines) this.yylineno++;
  756. this._input = this._input.slice(1);
  757. return ch;
  758. },
  759. unput:function (ch) {
  760. this._input = ch + this._input;
  761. return this;
  762. },
  763. more:function () {
  764. this._more = true;
  765. return this;
  766. },
  767. pastInput:function () {
  768. var past = this.matched.substr(0, this.matched.length - this.match.length);
  769. return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
  770. },
  771. upcomingInput:function () {
  772. var next = this.match;
  773. if (next.length < 20) {
  774. next += this._input.substr(0, 20-next.length);
  775. }
  776. return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
  777. },
  778. showPosition:function () {
  779. var pre = this.pastInput();
  780. var c = new Array(pre.length + 1).join("-");
  781. return pre + this.upcomingInput() + "\n" + c+"^";
  782. },
  783. next:function () {
  784. if (this.done) {
  785. return this.EOF;
  786. }
  787. if (!this._input) this.done = true;
  788. var token,
  789. match,
  790. col,
  791. lines;
  792. if (!this._more) {
  793. this.yytext = '';
  794. this.match = '';
  795. }
  796. var rules = this._currentRules();
  797. for (var i=0;i < rules.length; i++) {
  798. match = this._input.match(this.rules[rules[i]]);
  799. if (match) {
  800. lines = match[0].match(/\n.*/g);
  801. if (lines) this.yylineno += lines.length;
  802. this.yylloc = {first_line: this.yylloc.last_line,
  803. last_line: this.yylineno+1,
  804. first_column: this.yylloc.last_column,
  805. last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}
  806. this.yytext += match[0];
  807. this.match += match[0];
  808. this.matches = match;
  809. this.yyleng = this.yytext.length;
  810. this._more = false;
  811. this._input = this._input.slice(match[0].length);
  812. this.matched += match[0];
  813. token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]);
  814. if (token) return token;
  815. else return;
  816. }
  817. }
  818. if (this._input === "") {
  819. return this.EOF;
  820. } else {
  821. this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
  822. {text: "", token: null, line: this.yylineno});
  823. }
  824. },
  825. lex:function lex() {
  826. var r = this.next();
  827. if (typeof r !== 'undefined') {
  828. return r;
  829. } else {
  830. return this.lex();
  831. }
  832. },
  833. begin:function begin(condition) {
  834. this.conditionStack.push(condition);
  835. },
  836. popState:function popState() {
  837. return this.conditionStack.pop();
  838. },
  839. _currentRules:function _currentRules() {
  840. return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
  841. },
  842. topState:function () {
  843. return this.conditionStack[this.conditionStack.length-2];
  844. },
  845. pushState:function begin(condition) {
  846. this.begin(condition);
  847. }});
  848. lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
  849. var YYSTATE=YY_START;
  850. switch($avoiding_name_collisions) {
  851. case 0:/* skip whitespace */
  852. break;
  853. case 1:return 20
  854. break;
  855. case 2:return 19
  856. break;
  857. case 3:return 8
  858. break;
  859. case 4:return 9
  860. break;
  861. case 5:return 6
  862. break;
  863. case 6:return 7
  864. break;
  865. case 7:return 11
  866. break;
  867. case 8:return 13
  868. break;
  869. case 9:return 10
  870. break;
  871. case 10:return 12
  872. break;
  873. case 11:return 14
  874. break;
  875. case 12:return 15
  876. break;
  877. case 13:return 16
  878. break;
  879. case 14:return 17
  880. break;
  881. case 15:return 18
  882. break;
  883. case 16:return 5
  884. break;
  885. case 17:return 'INVALID'
  886. break;
  887. }
  888. };
  889. lexer.rules = [/^\s+/,/^[0-9]+(\.[0-9]+)?\b/,/^n\b/,/^\|\|/,/^&&/,/^\?/,/^:/,/^<=/,/^>=/,/^</,/^>/,/^!=/,/^==/,/^%/,/^\(/,/^\)/,/^$/,/^./];
  890. lexer.conditions = {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],"inclusive":true}};return lexer;})()
  891. parser.lexer = lexer;
  892. return parser;
  893. })();
  894. // End parser
  895. // Handle node, amd, and global systems
  896. if (typeof exports !== 'undefined') {
  897. if (typeof module !== 'undefined' && module.exports) {
  898. exports = module.exports = Jed;
  899. }
  900. exports.Jed = Jed;
  901. }
  902. else {
  903. if (typeof define === 'function' && define.amd) {
  904. define(function() {
  905. return Jed;
  906. });
  907. }
  908. // Leak a global regardless of module system
  909. root['Jed'] = Jed;
  910. }
  911. })(this);