Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/src/lib/gettext.py
1398 views
1
# vim:fileencoding=utf-8
2
# License: BSD Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
3
4
# noqa: eol-semicolon
5
6
# The Plural-Forms parser {{{
7
# From: https://github.com/SlexAxton/Jed/blob/master/jed.js licensed under the WTFPL
8
9
Jed = {}
10
11
vr'''
12
Jed.PF = {};
13
14
Jed.PF.parse = function ( p ) {
15
var plural_str = Jed.PF.extractPluralExpr( p );
16
return Jed.PF.parser.parse.call(Jed.PF.parser, plural_str);
17
};
18
19
Jed.PF.compile = function ( p ) {
20
// Handle trues and falses as 0 and 1
21
function imply( val ) {
22
return (val === true ? 1 : val ? val : 0);
23
}
24
25
var ast = Jed.PF.parse( p );
26
return function ( n ) {
27
return imply( Jed.PF.interpreter( ast )( n ) );
28
};
29
};
30
31
Jed.PF.interpreter = function ( ast ) {
32
return function ( n ) {
33
var res;
34
switch ( ast.type ) {
35
case 'GROUP':
36
return Jed.PF.interpreter( ast.expr )( n );
37
case 'TERNARY':
38
if ( Jed.PF.interpreter( ast.expr )( n ) ) {
39
return Jed.PF.interpreter( ast.truthy )( n );
40
}
41
return Jed.PF.interpreter( ast.falsey )( n );
42
case 'OR':
43
return Jed.PF.interpreter( ast.left )( n ) || Jed.PF.interpreter( ast.right )( n );
44
case 'AND':
45
return Jed.PF.interpreter( ast.left )( n ) && Jed.PF.interpreter( ast.right )( n );
46
case 'LT':
47
return Jed.PF.interpreter( ast.left )( n ) < Jed.PF.interpreter( ast.right )( n );
48
case 'GT':
49
return Jed.PF.interpreter( ast.left )( n ) > Jed.PF.interpreter( ast.right )( n );
50
case 'LTE':
51
return Jed.PF.interpreter( ast.left )( n ) <= Jed.PF.interpreter( ast.right )( n );
52
case 'GTE':
53
return Jed.PF.interpreter( ast.left )( n ) >= Jed.PF.interpreter( ast.right )( n );
54
case 'EQ':
55
return Jed.PF.interpreter( ast.left )( n ) == Jed.PF.interpreter( ast.right )( n );
56
case 'NEQ':
57
return Jed.PF.interpreter( ast.left )( n ) != Jed.PF.interpreter( ast.right )( n );
58
case 'MOD':
59
return Jed.PF.interpreter( ast.left )( n ) % Jed.PF.interpreter( ast.right )( n );
60
case 'VAR':
61
return n;
62
case 'NUM':
63
return ast.val;
64
default:
65
throw new Error("Invalid Token found.");
66
}
67
};
68
};
69
70
Jed.PF.extractPluralExpr = function ( p ) {
71
// trim first
72
p = p.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
73
74
if (! /;\s*$/.test(p)) {
75
p = p.concat(';');
76
}
77
78
var nplurals_re = /nplurals\=(\d+);/,
79
plural_re = /plural\=(.*);/,
80
nplurals_matches = p.match( nplurals_re ),
81
res = {},
82
plural_matches;
83
84
// Find the nplurals number
85
if ( nplurals_matches.length > 1 ) {
86
res.nplurals = nplurals_matches[1];
87
}
88
else {
89
throw new Error('nplurals not found in plural_forms string: ' + p );
90
}
91
92
// remove that data to get to the formula
93
p = p.replace( nplurals_re, "" );
94
plural_matches = p.match( plural_re );
95
96
if (!( plural_matches && plural_matches.length > 1 ) ) {
97
throw new Error('`plural` expression not found: ' + p);
98
}
99
return plural_matches[ 1 ];
100
};
101
102
/* Jison generated parser */
103
Jed.PF.parser = (function(){
104
105
var parser = {trace: function trace() { },
106
yy: {},
107
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},
108
terminals_: {2:"error",5:"EOF",6:"?",7:":",8:"||",9:"&&",10:"<",11:"<=",12:">",13:">=",14:"!=",15:"==",16:"%",17:"(",18:")",19:"n",20:"NUMBER"},
109
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]],
110
performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
111
112
var $0 = $$.length - 1;
113
switch (yystate) {
114
case 1: return { type : 'GROUP', expr: $$[$0-1] };
115
case 2:this.$ = { type: 'TERNARY', expr: $$[$0-4], truthy : $$[$0-2], falsey: $$[$0] };
116
break;
117
case 3:this.$ = { type: "OR", left: $$[$0-2], right: $$[$0] };
118
break;
119
case 4:this.$ = { type: "AND", left: $$[$0-2], right: $$[$0] };
120
break;
121
case 5:this.$ = { type: 'LT', left: $$[$0-2], right: $$[$0] };
122
break;
123
case 6:this.$ = { type: 'LTE', left: $$[$0-2], right: $$[$0] };
124
break;
125
case 7:this.$ = { type: 'GT', left: $$[$0-2], right: $$[$0] };
126
break;
127
case 8:this.$ = { type: 'GTE', left: $$[$0-2], right: $$[$0] };
128
break;
129
case 9:this.$ = { type: 'NEQ', left: $$[$0-2], right: $$[$0] };
130
break;
131
case 10:this.$ = { type: 'EQ', left: $$[$0-2], right: $$[$0] };
132
break;
133
case 11:this.$ = { type: 'MOD', left: $$[$0-2], right: $$[$0] };
134
break;
135
case 12:this.$ = { type: 'GROUP', expr: $$[$0-1] };
136
break;
137
case 13:this.$ = { type: 'VAR' };
138
break;
139
case 14:this.$ = { type: 'NUM', val: Number(yytext) };
140
break;
141
}
142
},
143
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]}],
144
defaultActions: {6:[2,1]},
145
parseError: function parseError(str, hash) {
146
throw new Error(str);
147
},
148
parse: function parse(input) {
149
var self = this,
150
stack = [0],
151
vstack = [null], // semantic value stack
152
lstack = [], // location stack
153
table = this.table,
154
yytext = '',
155
yylineno = 0,
156
yyleng = 0,
157
recovering = 0,
158
TERROR = 2,
159
EOF = 1;
160
161
//this.reductionCount = this.shiftCount = 0;
162
163
this.lexer.setInput(input);
164
this.lexer.yy = this.yy;
165
this.yy.lexer = this.lexer;
166
if (typeof this.lexer.yylloc == 'undefined')
167
this.lexer.yylloc = {};
168
var yyloc = this.lexer.yylloc;
169
lstack.push(yyloc);
170
171
if (typeof this.yy.parseError === 'function')
172
this.parseError = this.yy.parseError;
173
174
function popStack (n) {
175
stack.length = stack.length - 2*n;
176
vstack.length = vstack.length - n;
177
lstack.length = lstack.length - n;
178
}
179
180
function lex() {
181
var token;
182
token = self.lexer.lex() || 1; // $end = 1
183
// if token isn't its numeric value, convert
184
if (typeof token !== 'number') {
185
token = self.symbols_[token] || token;
186
}
187
return token;
188
}
189
190
var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected, errStr;
191
while (true) {
192
// retreive state number from top of stack
193
state = stack[stack.length-1];
194
195
// use default actions if available
196
if (this.defaultActions[state]) {
197
action = this.defaultActions[state];
198
} else {
199
if (symbol === null || symbol === undefined)
200
symbol = lex();
201
// read action for current state and first input
202
action = table[state] && table[state][symbol];
203
}
204
205
// handle parse error
206
_handle_error:
207
if (typeof action === 'undefined' || !action.length || !action[0]) {
208
209
if (!recovering) {
210
// Report error
211
expected = [];
212
for (p in table[state]) if (this.terminals_[p] && p > 2) {
213
expected.push("'"+this.terminals_[p]+"'");
214
}
215
errStr = '';
216
if (this.lexer.showPosition) {
217
errStr = 'Parse error on line '+(yylineno+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+expected.join(', ') + ", got '" + this.terminals_[symbol]+ "'";
218
} else {
219
errStr = 'Parse error on line '+(yylineno+1)+": Unexpected " +
220
(symbol == 1 /*EOF*/ ? "end of input" :
221
("'"+(this.terminals_[symbol] || symbol)+"'"));
222
}
223
this.parseError(errStr,
224
{text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
225
}
226
227
// just recovered from another error
228
if (recovering == 3) {
229
if (symbol == EOF) {
230
throw new Error(errStr || 'Parsing halted.');
231
}
232
233
// discard current lookahead and grab another
234
yyleng = this.lexer.yyleng;
235
yytext = this.lexer.yytext;
236
yylineno = this.lexer.yylineno;
237
yyloc = this.lexer.yylloc;
238
symbol = lex();
239
}
240
241
// try to recover from error
242
while (1) {
243
// check for error recovery rule in this state
244
if ((TERROR.toString()) in table[state]) {
245
break;
246
}
247
if (state === 0) {
248
throw new Error(errStr || 'Parsing halted.');
249
}
250
popStack(1);
251
state = stack[stack.length-1];
252
}
253
254
preErrorSymbol = symbol; // save the lookahead token
255
symbol = TERROR; // insert generic error symbol as new lookahead
256
state = stack[stack.length-1];
257
action = table[state] && table[state][TERROR];
258
recovering = 3; // allow 3 real symbols to be shifted before reporting a new error
259
}
260
261
// this shouldn't happen, unless resolve defaults are off
262
if (action[0] instanceof Array && action.length > 1) {
263
throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);
264
}
265
266
switch (action[0]) {
267
268
case 1: // shift
269
//this.shiftCount++;
270
271
stack.push(symbol);
272
vstack.push(this.lexer.yytext);
273
lstack.push(this.lexer.yylloc);
274
stack.push(action[1]); // push state
275
symbol = null;
276
if (!preErrorSymbol) { // normal execution/no error
277
yyleng = this.lexer.yyleng;
278
yytext = this.lexer.yytext;
279
yylineno = this.lexer.yylineno;
280
yyloc = this.lexer.yylloc;
281
if (recovering > 0)
282
recovering--;
283
} else { // error just occurred, resume old lookahead f/ before error
284
symbol = preErrorSymbol;
285
preErrorSymbol = null;
286
}
287
break;
288
289
case 2: // reduce
290
//this.reductionCount++;
291
292
len = this.productions_[action[1]][1];
293
294
// perform semantic action
295
yyval.$ = vstack[vstack.length-len]; // default to $$ = $1
296
// default location, uses first token for firsts, last for lasts
297
yyval._$ = {
298
first_line: lstack[lstack.length-(len||1)].first_line,
299
last_line: lstack[lstack.length-1].last_line,
300
first_column: lstack[lstack.length-(len||1)].first_column,
301
last_column: lstack[lstack.length-1].last_column
302
};
303
r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
304
305
if (typeof r !== 'undefined') {
306
return r;
307
}
308
309
// pop off stack
310
if (len) {
311
stack = stack.slice(0,-1*len*2);
312
vstack = vstack.slice(0, -1*len);
313
lstack = lstack.slice(0, -1*len);
314
}
315
316
stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)
317
vstack.push(yyval.$);
318
lstack.push(yyval._$);
319
// goto new state = table[STATE][NONTERMINAL]
320
newState = table[stack[stack.length-2]][stack[stack.length-1]];
321
stack.push(newState);
322
break;
323
324
case 3: // accept
325
return true;
326
}
327
328
}
329
330
return true;
331
}};/* Jison generated lexer */
332
var lexer = (function(){
333
334
var lexer = ({EOF:1,
335
parseError:function parseError(str, hash) {
336
if (this.yy.parseError) {
337
this.yy.parseError(str, hash);
338
} else {
339
throw new Error(str);
340
}
341
},
342
setInput:function (input) {
343
this._input = input;
344
this._more = this._less = this.done = false;
345
this.yylineno = this.yyleng = 0;
346
this.yytext = this.matched = this.match = '';
347
this.conditionStack = ['INITIAL'];
348
this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
349
return this;
350
},
351
input:function () {
352
var ch = this._input[0];
353
this.yytext+=ch;
354
this.yyleng++;
355
this.match+=ch;
356
this.matched+=ch;
357
var lines = ch.match(/\n/);
358
if (lines) this.yylineno++;
359
this._input = this._input.slice(1);
360
return ch;
361
},
362
unput:function (ch) {
363
this._input = ch + this._input;
364
return this;
365
},
366
more:function () {
367
this._more = true;
368
return this;
369
},
370
pastInput:function () {
371
var past = this.matched.substr(0, this.matched.length - this.match.length);
372
return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
373
},
374
upcomingInput:function () {
375
var next = this.match;
376
if (next.length < 20) {
377
next += this._input.substr(0, 20-next.length);
378
}
379
return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
380
},
381
showPosition:function () {
382
var pre = this.pastInput();
383
var c = new Array(pre.length + 1).join("-");
384
return pre + this.upcomingInput() + "\n" + c+"^";
385
},
386
next:function () {
387
if (this.done) {
388
return this.EOF;
389
}
390
if (!this._input) this.done = true;
391
392
var token,
393
match,
394
col,
395
lines;
396
if (!this._more) {
397
this.yytext = '';
398
this.match = '';
399
}
400
var rules = this._currentRules();
401
for (var i=0;i < rules.length; i++) {
402
match = this._input.match(this.rules[rules[i]]);
403
if (match) {
404
lines = match[0].match(/\n.*/g);
405
if (lines) this.yylineno += lines.length;
406
this.yylloc = {first_line: this.yylloc.last_line,
407
last_line: this.yylineno+1,
408
first_column: this.yylloc.last_column,
409
last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length};
410
this.yytext += match[0];
411
this.match += match[0];
412
this.matches = match;
413
this.yyleng = this.yytext.length;
414
this._more = false;
415
this._input = this._input.slice(match[0].length);
416
this.matched += match[0];
417
token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]);
418
if (token) return token;
419
else return;
420
}
421
}
422
if (this._input === "") {
423
return this.EOF;
424
} else {
425
this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
426
{text: "", token: null, line: this.yylineno});
427
}
428
},
429
lex:function lex() {
430
var r = this.next();
431
if (typeof r !== 'undefined') {
432
return r;
433
} else {
434
return this.lex();
435
}
436
},
437
begin:function begin(condition) {
438
this.conditionStack.push(condition);
439
},
440
popState:function popState() {
441
return this.conditionStack.pop();
442
},
443
_currentRules:function _currentRules() {
444
return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
445
},
446
topState:function () {
447
return this.conditionStack[this.conditionStack.length-2];
448
},
449
pushState:function begin(condition) {
450
this.begin(condition);
451
}});
452
lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
453
454
var YYSTATE=YY_START;
455
switch($avoiding_name_collisions) {
456
case 0:/* skip whitespace */
457
break;
458
case 1:return 20
459
break;
460
case 2:return 19
461
break;
462
case 3:return 8
463
break;
464
case 4:return 9
465
break;
466
case 5:return 6
467
break;
468
case 6:return 7
469
break;
470
case 7:return 11
471
break;
472
case 8:return 13
473
break;
474
case 9:return 10
475
break;
476
case 10:return 12
477
break;
478
case 11:return 14
479
break;
480
case 12:return 15
481
break;
482
case 13:return 16
483
break;
484
case 14:return 17
485
break;
486
case 15:return 18
487
break;
488
case 16:return 5
489
break;
490
case 17:return 'INVALID'
491
break;
492
}
493
};
494
lexer.rules = [/^\s+/,/^[0-9]+(\.[0-9]+)?\b/,/^n\b/,/^\|\|/,/^&&/,/^\?/,/^:/,/^<=/,/^>=/,/^</,/^>/,/^!=/,/^==/,/^%/,/^\(/,/^\)/,/^$/,/^./];
495
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;})()
496
parser.lexer = lexer;
497
return parser;
498
})();
499
'''
500
plural_forms_parser = Jed.PF
501
# }}}
502
503
def _get_plural_forms_function(plural_forms_string):
504
return plural_forms_parser.compile(plural_forms_string or "nplurals=2; plural=(n != 1);")
505
506
_gettext = def(text): return text
507
508
_ngettext = def(text, plural, n): return text if n is 1 else plural
509
510
def gettext(text):
511
return _gettext(text)
512
513
def ngettext(text, plural, n):
514
return _ngettext(text, plural, n)
515
516
def install(translation_data):
517
t = new Translations(translation_data)
518
t.install()
519
for func in register_callback.install_callbacks:
520
try:
521
func(t)
522
except:
523
pass
524
return t
525
526
has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty)
527
528
def register_callback(func):
529
# Register callbacks that will be called when new translation data is
530
# installed
531
register_callback.install_callbacks.push(func)
532
register_callback.install_callbacks = v'[]'
533
534
empty_translation_data = {'entries': {}}
535
536
class Translations:
537
538
def __init__(self, translation_data):
539
translation_data = translation_data or empty_translation_data
540
func = _get_plural_forms_function(translation_data.plural_forms)
541
self.translations = [[translation_data, func]]
542
self.language = translation_data['language']
543
544
def add_fallback(self, fallback):
545
fallback = fallback or empty_translation_data
546
func = _get_plural_forms_function(fallback.plural_forms)
547
self.translations.push([fallback, func])
548
549
def gettext(self, text):
550
for t in self.translations:
551
m = t[0].entries
552
if has_prop(m, text):
553
return m[text][0]
554
return text
555
556
def ngettext(self, text, plural, n):
557
for t in self.translations:
558
m = t[0].entries
559
if has_prop(m, text):
560
idx = t[1](n)
561
return m[text][idx] or (text if n is 1 else plural)
562
return text if n is 1 else plural
563
564
def install(self):
565
nonlocal _gettext, _ngettext
566
_gettext = def ():
567
return self.gettext.apply(self, arguments)
568
_ngettext = def ():
569
return self.ngettext.apply(self, arguments)
570
571