plural.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. """
  2. babel.numbers
  3. ~~~~~~~~~~~~~
  4. CLDR Plural support. See UTS #35.
  5. :copyright: (c) 2013-2025 by the Babel Team.
  6. :license: BSD, see LICENSE for more details.
  7. """
  8. from __future__ import annotations
  9. import decimal
  10. import re
  11. from collections.abc import Iterable, Mapping
  12. from typing import Any, Callable, Literal
  13. _plural_tags = ('zero', 'one', 'two', 'few', 'many', 'other')
  14. _fallback_tag = 'other'
  15. def extract_operands(source: float | decimal.Decimal) -> tuple[decimal.Decimal | int, int, int, int, int, int, Literal[0], Literal[0]]:
  16. """Extract operands from a decimal, a float or an int, according to `CLDR rules`_.
  17. The result is an 8-tuple (n, i, v, w, f, t, c, e), where those symbols are as follows:
  18. ====== ===============================================================
  19. Symbol Value
  20. ------ ---------------------------------------------------------------
  21. n absolute value of the source number (integer and decimals).
  22. i integer digits of n.
  23. v number of visible fraction digits in n, with trailing zeros.
  24. w number of visible fraction digits in n, without trailing zeros.
  25. f visible fractional digits in n, with trailing zeros.
  26. t visible fractional digits in n, without trailing zeros.
  27. c compact decimal exponent value: exponent of the power of 10 used in compact decimal formatting.
  28. e currently, synonym for ‘c’. however, may be redefined in the future.
  29. ====== ===============================================================
  30. .. _`CLDR rules`: https://www.unicode.org/reports/tr35/tr35-61/tr35-numbers.html#Operands
  31. :param source: A real number
  32. :type source: int|float|decimal.Decimal
  33. :return: A n-i-v-w-f-t-c-e tuple
  34. :rtype: tuple[decimal.Decimal, int, int, int, int, int, int, int]
  35. """
  36. n = abs(source)
  37. i = int(n)
  38. if isinstance(n, float):
  39. if i == n:
  40. n = i
  41. else:
  42. # Cast the `float` to a number via the string representation.
  43. # This is required for Python 2.6 anyway (it will straight out fail to
  44. # do the conversion otherwise), and it's highly unlikely that the user
  45. # actually wants the lossless conversion behavior (quoting the Python
  46. # documentation):
  47. # > If value is a float, the binary floating point value is losslessly
  48. # > converted to its exact decimal equivalent.
  49. # > This conversion can often require 53 or more digits of precision.
  50. # Should the user want that behavior, they can simply pass in a pre-
  51. # converted `Decimal` instance of desired accuracy.
  52. n = decimal.Decimal(str(n))
  53. if isinstance(n, decimal.Decimal):
  54. dec_tuple = n.as_tuple()
  55. exp = dec_tuple.exponent
  56. fraction_digits = dec_tuple.digits[exp:] if exp < 0 else ()
  57. trailing = ''.join(str(d) for d in fraction_digits)
  58. no_trailing = trailing.rstrip('0')
  59. v = len(trailing)
  60. w = len(no_trailing)
  61. f = int(trailing or 0)
  62. t = int(no_trailing or 0)
  63. else:
  64. v = w = f = t = 0
  65. c = e = 0 # TODO: c and e are not supported
  66. return n, i, v, w, f, t, c, e
  67. class PluralRule:
  68. """Represents a set of language pluralization rules. The constructor
  69. accepts a list of (tag, expr) tuples or a dict of `CLDR rules`_. The
  70. resulting object is callable and accepts one parameter with a positive or
  71. negative number (both integer and float) for the number that indicates the
  72. plural form for a string and returns the tag for the format:
  73. >>> rule = PluralRule({'one': 'n is 1'})
  74. >>> rule(1)
  75. 'one'
  76. >>> rule(2)
  77. 'other'
  78. Currently the CLDR defines these tags: zero, one, two, few, many and
  79. other where other is an implicit default. Rules should be mutually
  80. exclusive; for a given numeric value, only one rule should apply (i.e.
  81. the condition should only be true for one of the plural rule elements.
  82. .. _`CLDR rules`: https://www.unicode.org/reports/tr35/tr35-33/tr35-numbers.html#Language_Plural_Rules
  83. """
  84. __slots__ = ('abstract', '_func')
  85. def __init__(self, rules: Mapping[str, str] | Iterable[tuple[str, str]]) -> None:
  86. """Initialize the rule instance.
  87. :param rules: a list of ``(tag, expr)``) tuples with the rules
  88. conforming to UTS #35 or a dict with the tags as keys
  89. and expressions as values.
  90. :raise RuleError: if the expression is malformed
  91. """
  92. if isinstance(rules, Mapping):
  93. rules = rules.items()
  94. found = set()
  95. self.abstract: list[tuple[str, Any]] = []
  96. for key, expr in sorted(rules):
  97. if key not in _plural_tags:
  98. raise ValueError(f"unknown tag {key!r}")
  99. elif key in found:
  100. raise ValueError(f"tag {key!r} defined twice")
  101. found.add(key)
  102. ast = _Parser(expr).ast
  103. if ast:
  104. self.abstract.append((key, ast))
  105. def __repr__(self) -> str:
  106. rules = self.rules
  107. args = ", ".join([f"{tag}: {rules[tag]}" for tag in _plural_tags if tag in rules])
  108. return f"<{type(self).__name__} {args!r}>"
  109. @classmethod
  110. def parse(cls, rules: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> PluralRule:
  111. """Create a `PluralRule` instance for the given rules. If the rules
  112. are a `PluralRule` object, that object is returned.
  113. :param rules: the rules as list or dict, or a `PluralRule` object
  114. :raise RuleError: if the expression is malformed
  115. """
  116. if isinstance(rules, PluralRule):
  117. return rules
  118. return cls(rules)
  119. @property
  120. def rules(self) -> Mapping[str, str]:
  121. """The `PluralRule` as a dict of unicode plural rules.
  122. >>> rule = PluralRule({'one': 'n is 1'})
  123. >>> rule.rules
  124. {'one': 'n is 1'}
  125. """
  126. _compile = _UnicodeCompiler().compile
  127. return {tag: _compile(ast) for tag, ast in self.abstract}
  128. @property
  129. def tags(self) -> frozenset[str]:
  130. """A set of explicitly defined tags in this rule. The implicit default
  131. ``'other'`` rules is not part of this set unless there is an explicit
  132. rule for it.
  133. """
  134. return frozenset(i[0] for i in self.abstract)
  135. def __getstate__(self) -> list[tuple[str, Any]]:
  136. return self.abstract
  137. def __setstate__(self, abstract: list[tuple[str, Any]]) -> None:
  138. self.abstract = abstract
  139. def __call__(self, n: float | decimal.Decimal) -> str:
  140. if not hasattr(self, '_func'):
  141. self._func = to_python(self)
  142. return self._func(n)
  143. def to_javascript(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> str:
  144. """Convert a list/dict of rules or a `PluralRule` object into a JavaScript
  145. function. This function depends on no external library:
  146. >>> to_javascript({'one': 'n is 1'})
  147. "(function(n) { return (n == 1) ? 'one' : 'other'; })"
  148. Implementation detail: The function generated will probably evaluate
  149. expressions involved into range operations multiple times. This has the
  150. advantage that external helper functions are not required and is not a
  151. big performance hit for these simple calculations.
  152. :param rule: the rules as list or dict, or a `PluralRule` object
  153. :raise RuleError: if the expression is malformed
  154. """
  155. to_js = _JavaScriptCompiler().compile
  156. result = ['(function(n) { return ']
  157. for tag, ast in PluralRule.parse(rule).abstract:
  158. result.append(f"{to_js(ast)} ? {tag!r} : ")
  159. result.append('%r; })' % _fallback_tag)
  160. return ''.join(result)
  161. def to_python(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> Callable[[float | decimal.Decimal], str]:
  162. """Convert a list/dict of rules or a `PluralRule` object into a regular
  163. Python function. This is useful in situations where you need a real
  164. function and don't are about the actual rule object:
  165. >>> func = to_python({'one': 'n is 1', 'few': 'n in 2..4'})
  166. >>> func(1)
  167. 'one'
  168. >>> func(3)
  169. 'few'
  170. >>> func = to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
  171. >>> func(11)
  172. 'one'
  173. >>> func(15)
  174. 'few'
  175. :param rule: the rules as list or dict, or a `PluralRule` object
  176. :raise RuleError: if the expression is malformed
  177. """
  178. namespace = {
  179. 'IN': in_range_list,
  180. 'WITHIN': within_range_list,
  181. 'MOD': cldr_modulo,
  182. 'extract_operands': extract_operands,
  183. }
  184. to_python_func = _PythonCompiler().compile
  185. result = [
  186. 'def evaluate(n):',
  187. ' n, i, v, w, f, t, c, e = extract_operands(n)',
  188. ]
  189. for tag, ast in PluralRule.parse(rule).abstract:
  190. # the str() call is to coerce the tag to the native string. It's
  191. # a limited ascii restricted set of tags anyways so that is fine.
  192. result.append(f" if ({to_python_func(ast)}): return {str(tag)!r}")
  193. result.append(f" return {_fallback_tag!r}")
  194. code = compile('\n'.join(result), '<rule>', 'exec')
  195. eval(code, namespace)
  196. return namespace['evaluate']
  197. def to_gettext(rule: Mapping[str, str] | Iterable[tuple[str, str]] | PluralRule) -> str:
  198. """The plural rule as gettext expression. The gettext expression is
  199. technically limited to integers and returns indices rather than tags.
  200. >>> to_gettext({'one': 'n is 1', 'two': 'n is 2'})
  201. 'nplurals=3; plural=((n == 1) ? 0 : (n == 2) ? 1 : 2);'
  202. :param rule: the rules as list or dict, or a `PluralRule` object
  203. :raise RuleError: if the expression is malformed
  204. """
  205. rule = PluralRule.parse(rule)
  206. used_tags = rule.tags | {_fallback_tag}
  207. _compile = _GettextCompiler().compile
  208. _get_index = [tag for tag in _plural_tags if tag in used_tags].index
  209. result = [f"nplurals={len(used_tags)}; plural=("]
  210. for tag, ast in rule.abstract:
  211. result.append(f"{_compile(ast)} ? {_get_index(tag)} : ")
  212. result.append(f"{_get_index(_fallback_tag)});")
  213. return ''.join(result)
  214. def in_range_list(num: float | decimal.Decimal, range_list: Iterable[Iterable[float | decimal.Decimal]]) -> bool:
  215. """Integer range list test. This is the callback for the "in" operator
  216. of the UTS #35 pluralization rule language:
  217. >>> in_range_list(1, [(1, 3)])
  218. True
  219. >>> in_range_list(3, [(1, 3)])
  220. True
  221. >>> in_range_list(3, [(1, 3), (5, 8)])
  222. True
  223. >>> in_range_list(1.2, [(1, 4)])
  224. False
  225. >>> in_range_list(10, [(1, 4)])
  226. False
  227. >>> in_range_list(10, [(1, 4), (6, 8)])
  228. False
  229. """
  230. return num == int(num) and within_range_list(num, range_list)
  231. def within_range_list(num: float | decimal.Decimal, range_list: Iterable[Iterable[float | decimal.Decimal]]) -> bool:
  232. """Float range test. This is the callback for the "within" operator
  233. of the UTS #35 pluralization rule language:
  234. >>> within_range_list(1, [(1, 3)])
  235. True
  236. >>> within_range_list(1.0, [(1, 3)])
  237. True
  238. >>> within_range_list(1.2, [(1, 4)])
  239. True
  240. >>> within_range_list(8.8, [(1, 4), (7, 15)])
  241. True
  242. >>> within_range_list(10, [(1, 4)])
  243. False
  244. >>> within_range_list(10.5, [(1, 4), (20, 30)])
  245. False
  246. """
  247. return any(min_ <= num <= max_ for min_, max_ in range_list)
  248. def cldr_modulo(a: float, b: float) -> float:
  249. """Javaish modulo. This modulo operator returns the value with the sign
  250. of the dividend rather than the divisor like Python does:
  251. >>> cldr_modulo(-3, 5)
  252. -3
  253. >>> cldr_modulo(-3, -5)
  254. -3
  255. >>> cldr_modulo(3, 5)
  256. 3
  257. """
  258. reverse = 0
  259. if a < 0:
  260. a *= -1
  261. reverse = 1
  262. if b < 0:
  263. b *= -1
  264. rv = a % b
  265. if reverse:
  266. rv *= -1
  267. return rv
  268. class RuleError(Exception):
  269. """Raised if a rule is malformed."""
  270. _VARS = {
  271. 'n', # absolute value of the source number.
  272. 'i', # integer digits of n.
  273. 'v', # number of visible fraction digits in n, with trailing zeros.*
  274. 'w', # number of visible fraction digits in n, without trailing zeros.*
  275. 'f', # visible fraction digits in n, with trailing zeros.*
  276. 't', # visible fraction digits in n, without trailing zeros.*
  277. 'c', # compact decimal exponent value: exponent of the power of 10 used in compact decimal formatting.
  278. 'e', # currently, synonym for `c`. however, may be redefined in the future.
  279. }
  280. _RULES: list[tuple[str | None, re.Pattern[str]]] = [
  281. (None, re.compile(r'\s+', re.UNICODE)),
  282. ('word', re.compile(fr'\b(and|or|is|(?:with)?in|not|mod|[{"".join(_VARS)}])\b')),
  283. ('value', re.compile(r'\d+')),
  284. ('symbol', re.compile(r'%|,|!=|=')),
  285. ('ellipsis', re.compile(r'\.{2,3}|\u2026', re.UNICODE)), # U+2026: ELLIPSIS
  286. ]
  287. def tokenize_rule(s: str) -> list[tuple[str, str]]:
  288. s = s.split('@')[0]
  289. result: list[tuple[str, str]] = []
  290. pos = 0
  291. end = len(s)
  292. while pos < end:
  293. for tok, rule in _RULES:
  294. match = rule.match(s, pos)
  295. if match is not None:
  296. pos = match.end()
  297. if tok:
  298. result.append((tok, match.group()))
  299. break
  300. else:
  301. raise RuleError(f"malformed CLDR pluralization rule. Got unexpected {s[pos]!r}")
  302. return result[::-1]
  303. def test_next_token(
  304. tokens: list[tuple[str, str]],
  305. type_: str,
  306. value: str | None = None,
  307. ) -> list[tuple[str, str]] | bool:
  308. return tokens and tokens[-1][0] == type_ and \
  309. (value is None or tokens[-1][1] == value)
  310. def skip_token(tokens: list[tuple[str, str]], type_: str, value: str | None = None):
  311. if test_next_token(tokens, type_, value):
  312. return tokens.pop()
  313. def value_node(value: int) -> tuple[Literal['value'], tuple[int]]:
  314. return 'value', (value, )
  315. def ident_node(name: str) -> tuple[str, tuple[()]]:
  316. return name, ()
  317. def range_list_node(
  318. range_list: Iterable[Iterable[float | decimal.Decimal]],
  319. ) -> tuple[Literal['range_list'], Iterable[Iterable[float | decimal.Decimal]]]:
  320. return 'range_list', range_list
  321. def negate(rv: tuple[Any, ...]) -> tuple[Literal['not'], tuple[tuple[Any, ...]]]:
  322. return 'not', (rv,)
  323. class _Parser:
  324. """Internal parser. This class can translate a single rule into an abstract
  325. tree of tuples. It implements the following grammar::
  326. condition = and_condition ('or' and_condition)*
  327. ('@integer' samples)?
  328. ('@decimal' samples)?
  329. and_condition = relation ('and' relation)*
  330. relation = is_relation | in_relation | within_relation
  331. is_relation = expr 'is' ('not')? value
  332. in_relation = expr (('not')? 'in' | '=' | '!=') range_list
  333. within_relation = expr ('not')? 'within' range_list
  334. expr = operand (('mod' | '%') value)?
  335. operand = 'n' | 'i' | 'f' | 't' | 'v' | 'w'
  336. range_list = (range | value) (',' range_list)*
  337. value = digit+
  338. digit = 0|1|2|3|4|5|6|7|8|9
  339. range = value'..'value
  340. samples = sampleRange (',' sampleRange)* (',' ('…'|'...'))?
  341. sampleRange = decimalValue '~' decimalValue
  342. decimalValue = value ('.' value)?
  343. - Whitespace can occur between or around any of the above tokens.
  344. - Rules should be mutually exclusive; for a given numeric value, only one
  345. rule should apply (i.e. the condition should only be true for one of
  346. the plural rule elements).
  347. - The in and within relations can take comma-separated lists, such as:
  348. 'n in 3,5,7..15'.
  349. - Samples are ignored.
  350. The translator parses the expression on instantiation into an attribute
  351. called `ast`.
  352. """
  353. def __init__(self, string):
  354. self.tokens = tokenize_rule(string)
  355. if not self.tokens:
  356. # If the pattern is only samples, it's entirely possible
  357. # no stream of tokens whatsoever is generated.
  358. self.ast = None
  359. return
  360. self.ast = self.condition()
  361. if self.tokens:
  362. raise RuleError(f"Expected end of rule, got {self.tokens[-1][1]!r}")
  363. def expect(self, type_, value=None, term=None):
  364. token = skip_token(self.tokens, type_, value)
  365. if token is not None:
  366. return token
  367. if term is None:
  368. term = repr(value is None and type_ or value)
  369. if not self.tokens:
  370. raise RuleError(f"expected {term} but end of rule reached")
  371. raise RuleError(f"expected {term} but got {self.tokens[-1][1]!r}")
  372. def condition(self):
  373. op = self.and_condition()
  374. while skip_token(self.tokens, 'word', 'or'):
  375. op = 'or', (op, self.and_condition())
  376. return op
  377. def and_condition(self):
  378. op = self.relation()
  379. while skip_token(self.tokens, 'word', 'and'):
  380. op = 'and', (op, self.relation())
  381. return op
  382. def relation(self):
  383. left = self.expr()
  384. if skip_token(self.tokens, 'word', 'is'):
  385. return skip_token(self.tokens, 'word', 'not') and 'isnot' or 'is', \
  386. (left, self.value())
  387. negated = skip_token(self.tokens, 'word', 'not')
  388. method = 'in'
  389. if skip_token(self.tokens, 'word', 'within'):
  390. method = 'within'
  391. else:
  392. if not skip_token(self.tokens, 'word', 'in'):
  393. if negated:
  394. raise RuleError('Cannot negate operator based rules.')
  395. return self.newfangled_relation(left)
  396. rv = 'relation', (method, left, self.range_list())
  397. return negate(rv) if negated else rv
  398. def newfangled_relation(self, left):
  399. if skip_token(self.tokens, 'symbol', '='):
  400. negated = False
  401. elif skip_token(self.tokens, 'symbol', '!='):
  402. negated = True
  403. else:
  404. raise RuleError('Expected "=" or "!=" or legacy relation')
  405. rv = 'relation', ('in', left, self.range_list())
  406. return negate(rv) if negated else rv
  407. def range_or_value(self):
  408. left = self.value()
  409. if skip_token(self.tokens, 'ellipsis'):
  410. return left, self.value()
  411. else:
  412. return left, left
  413. def range_list(self):
  414. range_list = [self.range_or_value()]
  415. while skip_token(self.tokens, 'symbol', ','):
  416. range_list.append(self.range_or_value())
  417. return range_list_node(range_list)
  418. def expr(self):
  419. word = skip_token(self.tokens, 'word')
  420. if word is None or word[1] not in _VARS:
  421. raise RuleError('Expected identifier variable')
  422. name = word[1]
  423. if skip_token(self.tokens, 'word', 'mod'):
  424. return 'mod', ((name, ()), self.value())
  425. elif skip_token(self.tokens, 'symbol', '%'):
  426. return 'mod', ((name, ()), self.value())
  427. return ident_node(name)
  428. def value(self):
  429. return value_node(int(self.expect('value')[1]))
  430. def _binary_compiler(tmpl):
  431. """Compiler factory for the `_Compiler`."""
  432. return lambda self, left, right: tmpl % (self.compile(left), self.compile(right))
  433. def _unary_compiler(tmpl):
  434. """Compiler factory for the `_Compiler`."""
  435. return lambda self, x: tmpl % self.compile(x)
  436. compile_zero = lambda x: '0'
  437. class _Compiler:
  438. """The compilers are able to transform the expressions into multiple
  439. output formats.
  440. """
  441. def compile(self, arg):
  442. op, args = arg
  443. return getattr(self, f"compile_{op}")(*args)
  444. compile_n = lambda x: 'n'
  445. compile_i = lambda x: 'i'
  446. compile_v = lambda x: 'v'
  447. compile_w = lambda x: 'w'
  448. compile_f = lambda x: 'f'
  449. compile_t = lambda x: 't'
  450. compile_c = lambda x: 'c'
  451. compile_e = lambda x: 'e'
  452. compile_value = lambda x, v: str(v)
  453. compile_and = _binary_compiler('(%s && %s)')
  454. compile_or = _binary_compiler('(%s || %s)')
  455. compile_not = _unary_compiler('(!%s)')
  456. compile_mod = _binary_compiler('(%s %% %s)')
  457. compile_is = _binary_compiler('(%s == %s)')
  458. compile_isnot = _binary_compiler('(%s != %s)')
  459. def compile_relation(self, method, expr, range_list):
  460. raise NotImplementedError()
  461. class _PythonCompiler(_Compiler):
  462. """Compiles an expression to Python."""
  463. compile_and = _binary_compiler('(%s and %s)')
  464. compile_or = _binary_compiler('(%s or %s)')
  465. compile_not = _unary_compiler('(not %s)')
  466. compile_mod = _binary_compiler('MOD(%s, %s)')
  467. def compile_relation(self, method, expr, range_list):
  468. ranges = ",".join([f"({self.compile(a)}, {self.compile(b)})" for (a, b) in range_list[1]])
  469. return f"{method.upper()}({self.compile(expr)}, [{ranges}])"
  470. class _GettextCompiler(_Compiler):
  471. """Compile into a gettext plural expression."""
  472. compile_i = _Compiler.compile_n
  473. compile_v = compile_zero
  474. compile_w = compile_zero
  475. compile_f = compile_zero
  476. compile_t = compile_zero
  477. def compile_relation(self, method, expr, range_list):
  478. rv = []
  479. expr = self.compile(expr)
  480. for item in range_list[1]:
  481. if item[0] == item[1]:
  482. rv.append(f"({expr} == {self.compile(item[0])})")
  483. else:
  484. min, max = map(self.compile, item)
  485. rv.append(f"({expr} >= {min} && {expr} <= {max})")
  486. return f"({' || '.join(rv)})"
  487. class _JavaScriptCompiler(_GettextCompiler):
  488. """Compiles the expression to plain of JavaScript."""
  489. # XXX: presently javascript does not support any of the
  490. # fraction support and basically only deals with integers.
  491. compile_i = lambda x: 'parseInt(n, 10)'
  492. compile_v = compile_zero
  493. compile_w = compile_zero
  494. compile_f = compile_zero
  495. compile_t = compile_zero
  496. def compile_relation(self, method, expr, range_list):
  497. code = _GettextCompiler.compile_relation(
  498. self, method, expr, range_list)
  499. if method == 'in':
  500. expr = self.compile(expr)
  501. code = f"(parseInt({expr}, 10) == {expr} && {code})"
  502. return code
  503. class _UnicodeCompiler(_Compiler):
  504. """Returns a unicode pluralization rule again."""
  505. # XXX: this currently spits out the old syntax instead of the new
  506. # one. We can change that, but it will break a whole bunch of stuff
  507. # for users I suppose.
  508. compile_is = _binary_compiler('%s is %s')
  509. compile_isnot = _binary_compiler('%s is not %s')
  510. compile_and = _binary_compiler('%s and %s')
  511. compile_or = _binary_compiler('%s or %s')
  512. compile_mod = _binary_compiler('%s mod %s')
  513. def compile_not(self, relation):
  514. return self.compile_relation(*relation[1], negated=True)
  515. def compile_relation(self, method, expr, range_list, negated=False):
  516. ranges = []
  517. for item in range_list[1]:
  518. if item[0] == item[1]:
  519. ranges.append(self.compile(item[0]))
  520. else:
  521. ranges.append(f"{self.compile(item[0])}..{self.compile(item[1])}")
  522. return f"{self.compile(expr)}{' not' if negated else ''} {method} {','.join(ranges)}"