jsinterp.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import calendar
  4. import itertools
  5. import json
  6. import operator
  7. import re
  8. import time
  9. from functools import update_wrapper, wraps
  10. from .utils import (
  11. error_to_compat_str,
  12. ExtractorError,
  13. float_or_none,
  14. int_or_none,
  15. js_to_json,
  16. remove_quotes,
  17. str_or_none,
  18. unified_timestamp,
  19. variadic,
  20. write_string,
  21. )
  22. from .compat import (
  23. compat_basestring,
  24. compat_chr,
  25. compat_collections_chain_map as ChainMap,
  26. compat_contextlib_suppress,
  27. compat_filter as filter,
  28. compat_int,
  29. compat_integer_types,
  30. compat_itertools_zip_longest as zip_longest,
  31. compat_map as map,
  32. compat_numeric_types,
  33. compat_str,
  34. )
  35. # name JS functions
  36. class function_with_repr(object):
  37. # from yt_dlp/utils.py, but in this module
  38. # repr_ is always set
  39. def __init__(self, func, repr_):
  40. update_wrapper(self, func)
  41. self.func, self.__repr = func, repr_
  42. def __call__(self, *args, **kwargs):
  43. return self.func(*args, **kwargs)
  44. def __repr__(self):
  45. return self.__repr
  46. # name JS operators
  47. def wraps_op(op):
  48. def update_and_rename_wrapper(w):
  49. f = update_wrapper(w, op)
  50. # fn names are str in both Py 2/3
  51. f.__name__ = str('JS_') + f.__name__
  52. return f
  53. return update_and_rename_wrapper
  54. # NB In principle NaN cannot be checked by membership.
  55. # Here all NaN values are actually this one, so _NaN is _NaN,
  56. # although _NaN != _NaN. Ditto Infinity.
  57. _NaN = float('nan')
  58. _Infinity = float('inf')
  59. class JS_Undefined(object):
  60. pass
  61. def _js_bit_op(op, is_shift=False):
  62. def zeroise(x, is_shift_arg=False):
  63. if isinstance(x, compat_integer_types):
  64. return (x % 32) if is_shift_arg else (x & 0xffffffff)
  65. try:
  66. x = float(x)
  67. if is_shift_arg:
  68. x = int(x % 32)
  69. elif x < 0:
  70. x = -compat_int(-x % 0xffffffff)
  71. else:
  72. x = compat_int(x % 0xffffffff)
  73. except (ValueError, TypeError):
  74. # also here for int(NaN), including float('inf') % 32
  75. x = 0
  76. return x
  77. @wraps_op(op)
  78. def wrapped(a, b):
  79. return op(zeroise(a), zeroise(b, is_shift)) & 0xffffffff
  80. return wrapped
  81. def _js_arith_op(op, div=False):
  82. @wraps_op(op)
  83. def wrapped(a, b):
  84. if JS_Undefined in (a, b):
  85. return _NaN
  86. # null, "" --> 0
  87. a, b = (float_or_none(
  88. (x.strip() if isinstance(x, compat_basestring) else x) or 0,
  89. default=_NaN) for x in (a, b))
  90. if _NaN in (a, b):
  91. return _NaN
  92. try:
  93. return op(a, b)
  94. except ZeroDivisionError:
  95. return _NaN if not (div and (a or b)) else _Infinity
  96. return wrapped
  97. _js_arith_add = _js_arith_op(operator.add)
  98. def _js_add(a, b):
  99. if not (isinstance(a, compat_basestring) or isinstance(b, compat_basestring)):
  100. return _js_arith_add(a, b)
  101. if not isinstance(a, compat_basestring):
  102. a = _js_toString(a)
  103. elif not isinstance(b, compat_basestring):
  104. b = _js_toString(b)
  105. return operator.concat(a, b)
  106. _js_mod = _js_arith_op(operator.mod)
  107. __js_exp = _js_arith_op(operator.pow)
  108. def _js_exp(a, b):
  109. if not b:
  110. return 1 # even 0 ** 0 !!
  111. return __js_exp(a, b)
  112. def _js_to_primitive(v):
  113. return (
  114. ','.join(map(_js_toString, v)) if isinstance(v, list)
  115. else '[object Object]' if isinstance(v, dict)
  116. else compat_str(v) if not isinstance(v, (
  117. compat_numeric_types, compat_basestring))
  118. else v
  119. )
  120. # more exact: yt-dlp/yt-dlp#12110
  121. def _js_toString(v):
  122. return (
  123. 'undefined' if v is JS_Undefined
  124. else 'Infinity' if v == _Infinity
  125. else 'NaN' if v is _NaN
  126. else 'null' if v is None
  127. # bool <= int: do this first
  128. else ('false', 'true')[v] if isinstance(v, bool)
  129. else re.sub(r'(?<=\d)\.?0*$', '', '{0:.7f}'.format(v)) if isinstance(v, compat_numeric_types)
  130. else _js_to_primitive(v))
  131. _nullish = frozenset((None, JS_Undefined))
  132. def _js_eq(a, b):
  133. # NaN != any
  134. if _NaN in (a, b):
  135. return False
  136. # Object is Object
  137. if isinstance(a, type(b)) and isinstance(b, (dict, list)):
  138. return operator.is_(a, b)
  139. # general case
  140. if a == b:
  141. return True
  142. # null == undefined
  143. a_b = set((a, b))
  144. if a_b & _nullish:
  145. return a_b <= _nullish
  146. a, b = _js_to_primitive(a), _js_to_primitive(b)
  147. if not isinstance(a, compat_basestring):
  148. a, b = b, a
  149. # Number to String: convert the string to a number
  150. # Conversion failure results in ... false
  151. if isinstance(a, compat_basestring):
  152. return float_or_none(a) == b
  153. return a == b
  154. def _js_neq(a, b):
  155. return not _js_eq(a, b)
  156. def _js_id_op(op):
  157. @wraps_op(op)
  158. def wrapped(a, b):
  159. if _NaN in (a, b):
  160. return op(_NaN, None)
  161. if not isinstance(a, (compat_basestring, compat_numeric_types)):
  162. a, b = b, a
  163. # strings are === if ==
  164. # why 'a' is not 'a': https://stackoverflow.com/a/1504848
  165. if isinstance(a, (compat_basestring, compat_numeric_types)):
  166. return a == b if op(0, 0) else a != b
  167. return op(a, b)
  168. return wrapped
  169. def _js_comp_op(op):
  170. @wraps_op(op)
  171. def wrapped(a, b):
  172. if JS_Undefined in (a, b):
  173. return False
  174. if isinstance(a, compat_basestring):
  175. b = compat_str(b or 0)
  176. elif isinstance(b, compat_basestring):
  177. a = compat_str(a or 0)
  178. return op(a or 0, b or 0)
  179. return wrapped
  180. def _js_ternary(cndn, if_true=True, if_false=False):
  181. """Simulate JS's ternary operator (cndn?if_true:if_false)"""
  182. if cndn in (False, None, 0, '', JS_Undefined, _NaN):
  183. return if_false
  184. return if_true
  185. def _js_unary_op(op):
  186. @wraps_op(op)
  187. def wrapped(_, a):
  188. return op(a)
  189. return wrapped
  190. # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
  191. def _js_typeof(expr):
  192. with compat_contextlib_suppress(TypeError, KeyError):
  193. return {
  194. JS_Undefined: 'undefined',
  195. _NaN: 'number',
  196. _Infinity: 'number',
  197. True: 'boolean',
  198. False: 'boolean',
  199. None: 'object',
  200. }[expr]
  201. for t, n in (
  202. (compat_basestring, 'string'),
  203. (compat_numeric_types, 'number'),
  204. ):
  205. if isinstance(expr, t):
  206. return n
  207. if callable(expr):
  208. return 'function'
  209. # TODO: Symbol, BigInt
  210. return 'object'
  211. # (op, definition) in order of binding priority, tightest first
  212. # avoid dict to maintain order
  213. # definition None => Defined in JSInterpreter._operator
  214. _OPERATORS = (
  215. ('>>', _js_bit_op(operator.rshift, True)),
  216. ('<<', _js_bit_op(operator.lshift, True)),
  217. ('+', _js_add),
  218. ('-', _js_arith_op(operator.sub)),
  219. ('*', _js_arith_op(operator.mul)),
  220. ('%', _js_mod),
  221. ('/', _js_arith_op(operator.truediv, div=True)),
  222. ('**', _js_exp),
  223. )
  224. _LOG_OPERATORS = (
  225. ('|', _js_bit_op(operator.or_)),
  226. ('^', _js_bit_op(operator.xor)),
  227. ('&', _js_bit_op(operator.and_)),
  228. )
  229. _SC_OPERATORS = (
  230. ('?', None),
  231. ('??', None),
  232. ('||', None),
  233. ('&&', None),
  234. )
  235. _UNARY_OPERATORS_X = (
  236. ('void', _js_unary_op(lambda _: JS_Undefined)),
  237. ('typeof', _js_unary_op(_js_typeof)),
  238. )
  239. _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
  240. _COMP_OPERATORS = (
  241. ('===', _js_id_op(operator.is_)),
  242. ('!==', _js_id_op(operator.is_not)),
  243. ('==', _js_eq),
  244. ('!=', _js_neq),
  245. ('<=', _js_comp_op(operator.le)),
  246. ('>=', _js_comp_op(operator.ge)),
  247. ('<', _js_comp_op(operator.lt)),
  248. ('>', _js_comp_op(operator.gt)),
  249. )
  250. _NAME_RE = r'[a-zA-Z_$][\w$]*'
  251. _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  252. _QUOTES = '\'"/'
  253. class JS_Break(ExtractorError):
  254. def __init__(self):
  255. ExtractorError.__init__(self, 'Invalid break')
  256. class JS_Continue(ExtractorError):
  257. def __init__(self):
  258. ExtractorError.__init__(self, 'Invalid continue')
  259. class JS_Throw(ExtractorError):
  260. def __init__(self, e):
  261. self.error = e
  262. ExtractorError.__init__(self, 'Uncaught exception ' + error_to_compat_str(e))
  263. class LocalNameSpace(ChainMap):
  264. def __getitem__(self, key):
  265. try:
  266. return super(LocalNameSpace, self).__getitem__(key)
  267. except KeyError:
  268. return JS_Undefined
  269. def __setitem__(self, key, value):
  270. for scope in self.maps:
  271. if key in scope:
  272. scope[key] = value
  273. return
  274. self.maps[0][key] = value
  275. def __delitem__(self, key):
  276. raise NotImplementedError('Deleting is not supported')
  277. def __repr__(self):
  278. return 'LocalNameSpace({0!r})'.format(self.maps)
  279. class Debugger(object):
  280. ENABLED = False
  281. @staticmethod
  282. def write(*args, **kwargs):
  283. level = kwargs.get('level', 100)
  284. def truncate_string(s, left, right=0):
  285. if s is None or len(s) <= left + right:
  286. return s
  287. return '...'.join((s[:left - 3], s[-right:] if right else ''))
  288. write_string('[debug] JS: {0}{1}\n'.format(
  289. ' ' * (100 - level),
  290. ' '.join(truncate_string(compat_str(x), 50, 50) for x in args)))
  291. @classmethod
  292. def wrap_interpreter(cls, f):
  293. if not cls.ENABLED:
  294. return f
  295. @wraps(f)
  296. def interpret_statement(self, stmt, local_vars, allow_recursion, *args, **kwargs):
  297. if cls.ENABLED and stmt.strip():
  298. cls.write(stmt, level=allow_recursion)
  299. try:
  300. ret, should_ret = f(self, stmt, local_vars, allow_recursion, *args, **kwargs)
  301. except Exception as e:
  302. if cls.ENABLED:
  303. if isinstance(e, ExtractorError):
  304. e = e.orig_msg
  305. cls.write('=> Raises:', e, '<-|', stmt, level=allow_recursion)
  306. raise
  307. if cls.ENABLED and stmt.strip():
  308. if should_ret or repr(ret) != stmt:
  309. cls.write(['->', '=>'][bool(should_ret)], repr(ret), '<-|', stmt, level=allow_recursion)
  310. return ret, should_ret
  311. return interpret_statement
  312. class JSInterpreter(object):
  313. __named_object_counter = 0
  314. _OBJ_NAME = '__youtube_dl_jsinterp_obj'
  315. OP_CHARS = None
  316. def __init__(self, code, objects=None):
  317. self.code, self._functions = code, {}
  318. self._objects = {} if objects is None else objects
  319. if type(self).OP_CHARS is None:
  320. type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
  321. class Exception(ExtractorError):
  322. def __init__(self, msg, *args, **kwargs):
  323. expr = kwargs.pop('expr', None)
  324. msg = str_or_none(msg, default='"None"')
  325. if expr is not None:
  326. msg = '{0} in: {1!r:.100}'.format(msg.rstrip(), expr)
  327. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  328. class JS_Object(object):
  329. def __getitem__(self, key):
  330. if hasattr(self, key):
  331. return getattr(self, key)
  332. raise KeyError(key)
  333. def dump(self):
  334. """Serialise the instance"""
  335. raise NotImplementedError
  336. class JS_RegExp(JS_Object):
  337. RE_FLAGS = {
  338. # special knowledge: Python's re flags are bitmask values, current max 128
  339. # invent new bitmask values well above that for literal parsing
  340. # JS 'u' flag is effectively always set (surrogate pairs aren't seen),
  341. # but \u{...} and \p{...} escapes aren't handled); no additional JS 'v'
  342. # features are supported
  343. # TODO: execute matches with these flags (remaining: d, y)
  344. 'd': 1024, # Generate indices for substring matches
  345. 'g': 2048, # Global search
  346. 'i': re.I, # Case-insensitive search
  347. 'm': re.M, # Multi-line search
  348. 's': re.S, # Allows . to match newline characters
  349. 'u': re.U, # Treat a pattern as a sequence of unicode code points
  350. 'v': re.U, # Like 'u' with extended character class and \p{} syntax
  351. 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
  352. }
  353. def __init__(self, pattern_txt, flags=0):
  354. if isinstance(flags, compat_str):
  355. flags, _ = self.regex_flags(flags)
  356. self.__self = None
  357. pattern_txt = str_or_none(pattern_txt) or '(?:)'
  358. # escape unintended embedded flags
  359. pattern_txt = re.sub(
  360. r'(\(\?)([aiLmsux]*)(-[imsx]+:|(?<!\?)\))',
  361. lambda m: ''.join(
  362. (re.escape(m.group(1)), m.group(2), re.escape(m.group(3)))
  363. if m.group(3) == ')'
  364. else ('(?:', m.group(2), m.group(3))),
  365. pattern_txt)
  366. # Avoid https://github.com/python/cpython/issues/74534
  367. self.source = pattern_txt.replace('[[', r'[\[')
  368. self.__flags = flags
  369. def __instantiate(self):
  370. if self.__self:
  371. return
  372. self.__self = re.compile(self.source, self.__flags)
  373. # Thx: https://stackoverflow.com/questions/44773522/setattr-on-python2-sre-sre-pattern
  374. for name in dir(self.__self):
  375. # Only these? Obviously __class__, __init__.
  376. # PyPy creates a __weakref__ attribute with value None
  377. # that can't be setattr'd but also can't need to be copied.
  378. if name in ('__class__', '__init__', '__weakref__'):
  379. continue
  380. if name == 'flags':
  381. setattr(self, name, getattr(self.__self, name, self.__flags))
  382. else:
  383. setattr(self, name, getattr(self.__self, name))
  384. def __getattr__(self, name):
  385. self.__instantiate()
  386. if name == 'pattern':
  387. self.pattern = self.source
  388. return self.pattern
  389. elif hasattr(self.__self, name):
  390. v = getattr(self.__self, name)
  391. setattr(self, name, v)
  392. return v
  393. elif name in ('groupindex', 'groups'):
  394. return 0 if name == 'groupindex' else {}
  395. else:
  396. flag_attrs = ( # order by 2nd elt
  397. ('hasIndices', 'd'),
  398. ('global', 'g'),
  399. ('ignoreCase', 'i'),
  400. ('multiline', 'm'),
  401. ('dotAll', 's'),
  402. ('unicode', 'u'),
  403. ('unicodeSets', 'v'),
  404. ('sticky', 'y'),
  405. )
  406. for k, c in flag_attrs:
  407. if name == k:
  408. return bool(self.RE_FLAGS[c] & self.__flags)
  409. else:
  410. if name == 'flags':
  411. return ''.join(
  412. (c if self.RE_FLAGS[c] & self.__flags else '')
  413. for _, c in flag_attrs)
  414. raise AttributeError('{0} has no attribute named {1}'.format(self, name))
  415. @classmethod
  416. def regex_flags(cls, expr):
  417. flags = 0
  418. if not expr:
  419. return flags, expr
  420. for idx, ch in enumerate(expr):
  421. if ch not in cls.RE_FLAGS:
  422. break
  423. flags |= cls.RE_FLAGS[ch]
  424. return flags, expr[idx + 1:]
  425. def dump(self):
  426. return '(/{0}/{1})'.format(
  427. re.sub(r'(?<!\\)/', r'\/', self.source),
  428. self.flags)
  429. @staticmethod
  430. def escape(string_):
  431. return re.escape(string_)
  432. class JS_Date(JS_Object):
  433. _t = None
  434. @staticmethod
  435. def __ymd_etc(*args, **kw_is_utc):
  436. # args: year, monthIndex, day, hours, minutes, seconds, milliseconds
  437. is_utc = kw_is_utc.get('is_utc', False)
  438. args = list(args[:7])
  439. args += [0] * (9 - len(args))
  440. args[1] += 1 # month 0..11 -> 1..12
  441. ms = args[6]
  442. for i in range(6, 9):
  443. args[i] = -1 # don't know
  444. if is_utc:
  445. args[-1] = 1
  446. # TODO: [MDN] When a segment overflows or underflows its expected
  447. # range, it usually "carries over to" or "borrows from" the higher segment.
  448. try:
  449. mktime = calendar.timegm if is_utc else time.mktime
  450. return mktime(time.struct_time(args)) * 1000 + ms
  451. except (OverflowError, ValueError):
  452. return None
  453. @classmethod
  454. def UTC(cls, *args):
  455. t = cls.__ymd_etc(*args, is_utc=True)
  456. return _NaN if t is None else t
  457. @staticmethod
  458. def parse(date_str, **kw_is_raw):
  459. is_raw = kw_is_raw.get('is_raw', False)
  460. t = unified_timestamp(str_or_none(date_str), False)
  461. return int(t * 1000) if t is not None else t if is_raw else _NaN
  462. @staticmethod
  463. def now(**kw_is_raw):
  464. is_raw = kw_is_raw.get('is_raw', False)
  465. t = time.time()
  466. return int(t * 1000) if t is not None else t if is_raw else _NaN
  467. def __init__(self, *args):
  468. if not args:
  469. args = [self.now(is_raw=True)]
  470. if len(args) == 1:
  471. if isinstance(args[0], JSInterpreter.JS_Date):
  472. self._t = int_or_none(args[0].valueOf(), default=None)
  473. else:
  474. arg_type = _js_typeof(args[0])
  475. if arg_type == 'string':
  476. self._t = self.parse(args[0], is_raw=True)
  477. elif arg_type == 'number':
  478. self._t = int(args[0])
  479. else:
  480. self._t = self.__ymd_etc(*args)
  481. def toString(self):
  482. try:
  483. return time.strftime('%a %b %0d %Y %H:%M:%S %Z%z', self._t).rstrip()
  484. except TypeError:
  485. return "Invalid Date"
  486. def valueOf(self):
  487. return _NaN if self._t is None else self._t
  488. def dump(self):
  489. return '(new Date({0}))'.format(self.toString())
  490. @classmethod
  491. def __op_chars(cls):
  492. op_chars = set(';,[')
  493. for op in cls._all_operators():
  494. if op[0].isalpha():
  495. continue
  496. op_chars.update(op[0])
  497. return op_chars
  498. def _named_object(self, namespace, obj):
  499. self.__named_object_counter += 1
  500. name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  501. if callable(obj) and not isinstance(obj, function_with_repr):
  502. obj = function_with_repr(obj, 'F<%s>' % (self.__named_object_counter, ))
  503. namespace[name] = obj
  504. return name
  505. @classmethod
  506. def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  507. if not expr:
  508. return
  509. # collections.Counter() is ~10% slower in both 2.7 and 3.9
  510. counters = dict((k, 0) for k in _MATCHING_PARENS.values())
  511. start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  512. in_quote, escaping, after_op, in_regex_char_group = None, False, True, False
  513. skipping = 0
  514. if skip_delims:
  515. skip_delims = variadic(skip_delims)
  516. skip_txt = None
  517. for idx, char in enumerate(expr):
  518. if skip_txt and idx <= skip_txt[1]:
  519. continue
  520. paren_delta = 0
  521. if not in_quote:
  522. if char == '/' and expr[idx:idx + 2] == '/*':
  523. # skip a comment
  524. skip_txt = expr[idx:].find('*/', 2)
  525. skip_txt = [idx, idx + skip_txt + 1] if skip_txt >= 2 else None
  526. if skip_txt:
  527. continue
  528. if char in _MATCHING_PARENS:
  529. counters[_MATCHING_PARENS[char]] += 1
  530. paren_delta = 1
  531. elif char in counters:
  532. counters[char] -= 1
  533. paren_delta = -1
  534. if not escaping:
  535. if char in _QUOTES and in_quote in (char, None):
  536. if in_quote or after_op or char != '/':
  537. in_quote = None if in_quote and not in_regex_char_group else char
  538. elif in_quote == '/' and char in '[]':
  539. in_regex_char_group = char == '['
  540. escaping = not escaping and in_quote and char == '\\'
  541. after_op = not in_quote and (char in cls.OP_CHARS or paren_delta > 0 or (after_op and char.isspace()))
  542. if char != delim[pos] or any(counters.values()) or in_quote:
  543. pos = skipping = 0
  544. continue
  545. elif skipping > 0:
  546. skipping -= 1
  547. continue
  548. elif pos == 0 and skip_delims:
  549. here = expr[idx:]
  550. for s in skip_delims:
  551. if here.startswith(s) and s:
  552. skipping = len(s) - 1
  553. break
  554. if skipping > 0:
  555. continue
  556. if pos < delim_len:
  557. pos += 1
  558. continue
  559. if skip_txt and skip_txt[0] >= start and skip_txt[1] <= idx - delim_len:
  560. yield expr[start:skip_txt[0]] + expr[skip_txt[1] + 1: idx - delim_len]
  561. else:
  562. yield expr[start: idx - delim_len]
  563. skip_txt = None
  564. start, pos = idx + 1, 0
  565. splits += 1
  566. if max_split and splits >= max_split:
  567. break
  568. if skip_txt and skip_txt[0] >= start:
  569. yield expr[start:skip_txt[0]] + expr[skip_txt[1] + 1:]
  570. else:
  571. yield expr[start:]
  572. @classmethod
  573. def _separate_at_paren(cls, expr, delim=None):
  574. if delim is None:
  575. delim = expr and _MATCHING_PARENS[expr[0]]
  576. separated = list(cls._separate(expr, delim, 1))
  577. if len(separated) < 2:
  578. raise cls.Exception('No terminating paren {delim} in {expr!r:.5500}'.format(**locals()))
  579. return separated[0][1:].strip(), separated[1].strip()
  580. @staticmethod
  581. def _all_operators(_cached=[]):
  582. if not _cached:
  583. _cached.extend(itertools.chain(
  584. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  585. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS, _UNARY_OPERATORS_X))
  586. return _cached
  587. def _separate_at_op(self, expr, max_split=None):
  588. for op, _ in self._all_operators():
  589. # hackety: </> have higher priority than <</>>, but don't confuse them
  590. skip_delim = (op + op) if op in '<>*?' else None
  591. if op == '?':
  592. skip_delim = (skip_delim, '?.')
  593. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  594. if len(separated) < 2:
  595. continue
  596. right_expr = separated.pop()
  597. # handle operators that are both unary and binary, minimal BODMAS
  598. if op in ('+', '-'):
  599. # simplify/adjust consecutive instances of these operators
  600. undone = 0
  601. separated = [s.strip() for s in separated]
  602. while len(separated) > 1 and not separated[-1]:
  603. undone += 1
  604. separated.pop()
  605. if op == '-' and undone % 2 != 0:
  606. right_expr = op + right_expr
  607. elif op == '+':
  608. while len(separated) > 1 and set(separated[-1]) <= self.OP_CHARS:
  609. right_expr = separated.pop() + right_expr
  610. if separated[-1][-1:] in self.OP_CHARS:
  611. right_expr = separated.pop() + right_expr
  612. # hanging op at end of left => unary + (strip) or - (push right)
  613. separated.append(right_expr)
  614. dm_ops = ('*', '%', '/', '**')
  615. dm_chars = set(''.join(dm_ops))
  616. def yield_terms(s):
  617. skip = False
  618. for i, term in enumerate(s[:-1]):
  619. if skip:
  620. skip = False
  621. continue
  622. if not (dm_chars & set(term)):
  623. yield term
  624. continue
  625. for dm_op in dm_ops:
  626. bodmas = list(self._separate(term, dm_op, skip_delims=skip_delim))
  627. if len(bodmas) > 1 and not bodmas[-1].strip():
  628. bodmas[-1] = (op if op == '-' else '') + s[i + 1]
  629. yield dm_op.join(bodmas)
  630. skip = True
  631. break
  632. else:
  633. if term:
  634. yield term
  635. if not skip and s[-1]:
  636. yield s[-1]
  637. separated = list(yield_terms(separated))
  638. right_expr = separated.pop() if len(separated) > 1 else None
  639. expr = op.join(separated)
  640. if right_expr is None:
  641. continue
  642. return op, separated, right_expr
  643. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  644. if op in ('||', '&&'):
  645. if (op == '&&') ^ _js_ternary(left_val):
  646. return left_val # short circuiting
  647. elif op == '??':
  648. if left_val not in (None, JS_Undefined):
  649. return left_val
  650. elif op == '?':
  651. right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  652. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  653. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  654. if not opfunc:
  655. return right_val
  656. try:
  657. # print('Eval:', opfunc.__name__, left_val, right_val)
  658. return opfunc(left_val, right_val)
  659. except Exception as e:
  660. raise self.Exception('Failed to evaluate {left_val!r:.50} {op} {right_val!r:.50}'.format(**locals()), expr, cause=e)
  661. def _index(self, obj, idx, allow_undefined=None):
  662. if idx == 'length' and isinstance(obj, list):
  663. return len(obj)
  664. try:
  665. return obj[int(idx)] if isinstance(obj, list) else obj[compat_str(idx)]
  666. except (TypeError, KeyError, IndexError, ValueError) as e:
  667. # allow_undefined is None gives correct behaviour
  668. if allow_undefined or (
  669. allow_undefined is None and not isinstance(e, TypeError)):
  670. return JS_Undefined
  671. raise self.Exception('Cannot get index {idx!r:.100}'.format(**locals()), expr=repr(obj), cause=e)
  672. def _dump(self, obj, namespace):
  673. if obj is JS_Undefined:
  674. return 'undefined'
  675. try:
  676. return json.dumps(obj)
  677. except TypeError:
  678. return self._named_object(namespace, obj)
  679. # used below
  680. _VAR_RET_THROW_RE = re.compile(r'''(?x)
  681. (?:(?P<var>var|const|let)\s+|(?P<ret>return)(?:\s+|(?=["'])|$)|(?P<throw>throw)\s+)
  682. ''')
  683. _COMPOUND_RE = re.compile(r'''(?x)
  684. (?P<try>try)\s*\{|
  685. (?P<if>if)\s*\(|
  686. (?P<switch>switch)\s*\(|
  687. (?P<for>for)\s*\(|
  688. (?P<while>while)\s*\(
  689. ''')
  690. _FINALLY_RE = re.compile(r'finally\s*\{')
  691. _SWITCH_RE = re.compile(r'switch\s*\(')
  692. def _eval_operator(self, op, left_expr, right_expr, expr, local_vars, allow_recursion):
  693. left_val = self.interpret_expression(left_expr, local_vars, allow_recursion)
  694. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion)
  695. @Debugger.wrap_interpreter
  696. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  697. if allow_recursion < 0:
  698. raise self.Exception('Recursion limit reached')
  699. allow_recursion -= 1
  700. # print('At: ' + stmt[:60])
  701. should_return = False
  702. # fails on (eg) if (...) stmt1; else stmt2;
  703. sub_statements = list(self._separate(stmt, ';')) or ['']
  704. expr = stmt = sub_statements.pop().strip()
  705. for sub_stmt in sub_statements:
  706. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  707. if should_return:
  708. return ret, should_return
  709. m = self._VAR_RET_THROW_RE.match(stmt)
  710. if m:
  711. expr = stmt[len(m.group(0)):].strip()
  712. if m.group('throw'):
  713. raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  714. should_return = 'return' if m.group('ret') else False
  715. if not expr:
  716. return None, should_return
  717. if expr[0] in _QUOTES:
  718. inner, outer = self._separate(expr, expr[0], 1)
  719. if expr[0] == '/':
  720. flags, outer = self.JS_RegExp.regex_flags(outer)
  721. inner = self.JS_RegExp(inner[1:], flags=flags)
  722. else:
  723. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  724. if not outer:
  725. return inner, should_return
  726. expr = self._named_object(local_vars, inner) + outer
  727. new_kw, _, obj = expr.partition('new ')
  728. if not new_kw:
  729. for klass, konstr in (('Date', lambda *x: self.JS_Date(*x).valueOf()),
  730. ('RegExp', self.JS_RegExp),
  731. ('Error', self.Exception)):
  732. if not obj.startswith(klass + '('):
  733. continue
  734. left, right = self._separate_at_paren(obj[len(klass):])
  735. argvals = self.interpret_iter(left, local_vars, allow_recursion)
  736. expr = konstr(*argvals)
  737. if expr is None:
  738. raise self.Exception('Failed to parse {klass} {left!r:.100}'.format(**locals()), expr=expr)
  739. expr = self._dump(expr, local_vars) + right
  740. break
  741. else:
  742. raise self.Exception('Unsupported object {obj:.100}'.format(**locals()), expr=expr)
  743. for op, _ in _UNARY_OPERATORS_X:
  744. if not expr.startswith(op):
  745. continue
  746. operand = expr[len(op):]
  747. if not operand or operand[0] != ' ':
  748. continue
  749. separated = self._separate_at_op(operand, max_split=1)
  750. if separated:
  751. next_op, separated, right_expr = separated
  752. separated.append(right_expr)
  753. operand = next_op.join(separated)
  754. return self._eval_operator(op, operand, '', expr, local_vars, allow_recursion), should_return
  755. if expr.startswith('{'):
  756. inner, outer = self._separate_at_paren(expr)
  757. # try for object expression (Map)
  758. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  759. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  760. return dict(
  761. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  762. self.interpret_expression(val_expr, local_vars, allow_recursion))
  763. for key_expr, val_expr in sub_expressions), should_return
  764. # or statement list
  765. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  766. if not outer or should_abort:
  767. return inner, should_abort or should_return
  768. else:
  769. expr = self._dump(inner, local_vars) + outer
  770. if expr.startswith('('):
  771. m = re.match(r'\((?P<d>[a-z])%(?P<e>[a-z])\.length\+(?P=e)\.length\)%(?P=e)\.length', expr)
  772. if m:
  773. # short-cut eval of frequently used `(d%e.length+e.length)%e.length`, worth ~6% on `pytest -k test_nsig`
  774. outer = None
  775. inner, should_abort = self._offset_e_by_d(m.group('d'), m.group('e'), local_vars)
  776. else:
  777. inner, outer = self._separate_at_paren(expr)
  778. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  779. if not outer or should_abort:
  780. return inner, should_abort or should_return
  781. else:
  782. expr = self._dump(inner, local_vars) + outer
  783. if expr.startswith('['):
  784. inner, outer = self._separate_at_paren(expr)
  785. name = self._named_object(local_vars, [
  786. self.interpret_expression(item, local_vars, allow_recursion)
  787. for item in self._separate(inner)])
  788. expr = name + outer
  789. m = self._COMPOUND_RE.match(expr)
  790. md = m.groupdict() if m else {}
  791. if md.get('if'):
  792. cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
  793. if expr.startswith('{'):
  794. if_expr, expr = self._separate_at_paren(expr)
  795. else:
  796. # may lose ... else ... because of ll.368-374
  797. if_expr, expr = self._separate_at_paren(' %s;' % (expr,), delim=';')
  798. else_expr = None
  799. m = re.match(r'else\s*(?P<block>\{)?', expr)
  800. if m:
  801. if m.group('block'):
  802. else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  803. else:
  804. # handle subset ... else if (...) {...} else ...
  805. # TODO: make interpret_statement do this properly, if possible
  806. exprs = list(self._separate(expr[m.end():], delim='}', max_split=2))
  807. if len(exprs) > 1:
  808. if re.match(r'\s*if\s*\(', exprs[0]) and re.match(r'\s*else\b', exprs[1]):
  809. else_expr = exprs[0] + '}' + exprs[1]
  810. expr = (exprs[2] + '}') if len(exprs) == 3 else None
  811. else:
  812. else_expr = exprs[0]
  813. exprs.append('')
  814. expr = '}'.join(exprs[1:])
  815. else:
  816. else_expr = exprs[0]
  817. expr = None
  818. else_expr = else_expr.lstrip() + '}'
  819. cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
  820. ret, should_abort = self.interpret_statement(
  821. if_expr if cndn else else_expr, local_vars, allow_recursion)
  822. if should_abort:
  823. return ret, True
  824. elif md.get('try'):
  825. try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  826. err = None
  827. try:
  828. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  829. if should_abort:
  830. return ret, True
  831. except Exception as e:
  832. # XXX: This works for now, but makes debugging future issues very hard
  833. err = e
  834. pending = (None, False)
  835. m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  836. if m:
  837. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  838. if err:
  839. catch_vars = {}
  840. if m.group('err'):
  841. catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  842. catch_vars = local_vars.new_child(m=catch_vars)
  843. err, pending = None, self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  844. m = self._FINALLY_RE.match(expr)
  845. if m:
  846. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  847. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  848. if should_abort:
  849. return ret, True
  850. ret, should_abort = pending
  851. if should_abort:
  852. return ret, True
  853. if err:
  854. raise err
  855. elif md.get('for') or md.get('while'):
  856. init_or_cond, remaining = self._separate_at_paren(expr[m.end() - 1:])
  857. if remaining.startswith('{'):
  858. body, expr = self._separate_at_paren(remaining)
  859. else:
  860. switch_m = self._SWITCH_RE.match(remaining) # FIXME
  861. if switch_m:
  862. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  863. body, expr = self._separate_at_paren(remaining, '}')
  864. body = 'switch(%s){%s}' % (switch_val, body)
  865. else:
  866. body, expr = remaining, ''
  867. if md.get('for'):
  868. start, cndn, increment = self._separate(init_or_cond, ';')
  869. self.interpret_expression(start, local_vars, allow_recursion)
  870. else:
  871. cndn, increment = init_or_cond, None
  872. while _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  873. try:
  874. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  875. if should_abort:
  876. return ret, True
  877. except JS_Break:
  878. break
  879. except JS_Continue:
  880. pass
  881. if increment:
  882. self.interpret_expression(increment, local_vars, allow_recursion)
  883. elif md.get('switch'):
  884. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  885. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  886. body, expr = self._separate_at_paren(remaining, '}')
  887. items = body.replace('default:', 'case default:').split('case ')[1:]
  888. for default in (False, True):
  889. matched = False
  890. for item in items:
  891. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  892. if default:
  893. matched = matched or case == 'default'
  894. elif not matched:
  895. matched = (case != 'default'
  896. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  897. if not matched:
  898. continue
  899. try:
  900. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  901. if should_abort:
  902. return ret
  903. except JS_Break:
  904. break
  905. if matched:
  906. break
  907. if md:
  908. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  909. return ret, should_abort or should_return
  910. # Comma separated statements
  911. sub_expressions = list(self._separate(expr))
  912. if len(sub_expressions) > 1:
  913. for sub_expr in sub_expressions:
  914. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  915. if should_abort:
  916. return ret, True
  917. return ret, False
  918. for m in re.finditer(r'''(?x)
  919. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  920. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  921. var = m.group('var1') or m.group('var2')
  922. start, end = m.span()
  923. sign = m.group('pre_sign') or m.group('post_sign')
  924. ret = local_vars[var]
  925. local_vars[var] = _js_add(ret, 1 if sign[0] == '+' else -1)
  926. if m.group('pre_sign'):
  927. ret = local_vars[var]
  928. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  929. if not expr:
  930. return None, should_return
  931. m = re.match(r'''(?x)
  932. (?P<assign>
  933. (?P<out>{_NAME_RE})(?:\[(?P<out_idx>(?:.+?\]\s*\[)*.+?)\])?\s*
  934. (?P<op>{_OPERATOR_RE})?
  935. =(?!=)(?P<expr>.*)$
  936. )|(?P<return>
  937. (?!if|return|true|false|null|undefined|NaN|Infinity)(?P<name>{_NAME_RE})$
  938. )|(?P<indexing>
  939. (?P<in>{_NAME_RE})\[(?P<in_idx>(?:.+?\]\s*\[)*.+?)\]$
  940. )|(?P<attribute>
  941. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  942. )|(?P<function>
  943. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  944. )'''.format(**globals()), expr)
  945. md = m.groupdict() if m else {}
  946. if md.get('assign'):
  947. left_val = local_vars.get(m.group('out'))
  948. if not m.group('out_idx'):
  949. local_vars[m.group('out')] = self._operator(
  950. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  951. return local_vars[m.group('out')], should_return
  952. elif left_val in (None, JS_Undefined):
  953. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  954. indexes = re.split(r'\]\s*\[', m.group('out_idx'))
  955. for i, idx in enumerate(indexes, 1):
  956. idx = self.interpret_expression(idx, local_vars, allow_recursion)
  957. if i < len(indexes):
  958. left_val = self._index(left_val, idx)
  959. if isinstance(idx, float):
  960. idx = int(idx)
  961. if isinstance(left_val, list) and len(left_val) <= int_or_none(idx, default=-1):
  962. # JS Array is a sparsely assignable list
  963. # TODO: handle extreme sparsity without memory bloat, eg using auxiliary dict
  964. left_val.extend((idx - len(left_val) + 1) * [JS_Undefined])
  965. left_val[idx] = self._operator(
  966. m.group('op'), self._index(left_val, idx) if m.group('op') else None,
  967. m.group('expr'), expr, local_vars, allow_recursion)
  968. return left_val[idx], should_return
  969. elif expr.isdigit():
  970. return int(expr), should_return
  971. elif expr == 'break':
  972. raise JS_Break()
  973. elif expr == 'continue':
  974. raise JS_Continue()
  975. elif expr == 'undefined':
  976. return JS_Undefined, should_return
  977. elif expr == 'NaN':
  978. return _NaN, should_return
  979. elif expr == 'Infinity':
  980. return _Infinity, should_return
  981. elif md.get('return'):
  982. ret = local_vars[m.group('name')]
  983. # challenge may try to force returning the original value
  984. # use an optional internal var to block this
  985. if should_return == 'return':
  986. if '_ytdl_do_not_return' not in local_vars:
  987. return ret, True
  988. return (ret, True) if ret != local_vars['_ytdl_do_not_return'] else (ret, False)
  989. else:
  990. return ret, should_return
  991. with compat_contextlib_suppress(ValueError):
  992. ret = json.loads(js_to_json(expr)) # strict=True)
  993. if not md.get('attribute'):
  994. return ret, should_return
  995. if md.get('indexing'):
  996. val = local_vars[m.group('in')]
  997. for idx in re.split(r'\]\s*\[', m.group('in_idx')):
  998. idx = self.interpret_expression(idx, local_vars, allow_recursion)
  999. val = self._index(val, idx)
  1000. return val, should_return
  1001. separated = self._separate_at_op(expr)
  1002. if separated:
  1003. op, separated, right_expr = separated
  1004. return self._eval_operator(op, op.join(separated), right_expr, expr, local_vars, allow_recursion), should_return
  1005. if md.get('attribute'):
  1006. variable, member, nullish = m.group('var', 'member', 'nullish')
  1007. if not member:
  1008. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  1009. arg_str = expr[m.end():]
  1010. if arg_str.startswith('('):
  1011. arg_str, remaining = self._separate_at_paren(arg_str)
  1012. else:
  1013. arg_str, remaining = None, arg_str
  1014. def assertion(cndn, msg):
  1015. """ assert, but without risk of getting optimized out """
  1016. if not cndn:
  1017. memb = member
  1018. raise self.Exception('{memb} {msg}'.format(**locals()), expr=expr)
  1019. def eval_method(variable, member):
  1020. if (variable, member) == ('console', 'debug'):
  1021. if Debugger.ENABLED:
  1022. Debugger.write(self.interpret_expression('[{0}]'.format(arg_str), local_vars, allow_recursion))
  1023. return
  1024. types = {
  1025. 'String': compat_str,
  1026. 'Math': float,
  1027. 'Array': list,
  1028. 'Date': self.JS_Date,
  1029. 'RegExp': self.JS_RegExp,
  1030. # 'Error': self.Exception, # has no std static methods
  1031. }
  1032. obj = local_vars.get(variable)
  1033. if obj in (JS_Undefined, None):
  1034. obj = types.get(variable, JS_Undefined)
  1035. if obj is JS_Undefined:
  1036. try:
  1037. if variable not in self._objects:
  1038. self._objects[variable] = self.extract_object(variable)
  1039. obj = self._objects[variable]
  1040. except self.Exception:
  1041. if not nullish:
  1042. raise
  1043. if nullish and obj is JS_Undefined:
  1044. return JS_Undefined
  1045. # Member access
  1046. if arg_str is None:
  1047. return self._index(obj, member)
  1048. # Function call
  1049. argvals = [
  1050. self.interpret_expression(v, local_vars, allow_recursion)
  1051. for v in self._separate(arg_str)]
  1052. # Fixup prototype call
  1053. if isinstance(obj, type):
  1054. new_member, rest = member.partition('.')[0::2]
  1055. if new_member == 'prototype':
  1056. new_member, func_prototype = rest.partition('.')[0::2]
  1057. assertion(argvals, 'takes one or more arguments')
  1058. assertion(isinstance(argvals[0], obj), 'must bind to type {0}'.format(obj))
  1059. if func_prototype == 'call':
  1060. obj = argvals.pop(0)
  1061. elif func_prototype == 'apply':
  1062. assertion(len(argvals) == 2, 'takes two arguments')
  1063. obj, argvals = argvals
  1064. assertion(isinstance(argvals, list), 'second argument must be a list')
  1065. else:
  1066. raise self.Exception('Unsupported Function method ' + func_prototype, expr)
  1067. member = new_member
  1068. if obj is compat_str:
  1069. if member == 'fromCharCode':
  1070. assertion(argvals, 'takes one or more arguments')
  1071. return ''.join(compat_chr(int(n)) for n in argvals)
  1072. raise self.Exception('Unsupported string method ' + member, expr=expr)
  1073. elif obj is float:
  1074. if member == 'pow':
  1075. assertion(len(argvals) == 2, 'takes two arguments')
  1076. return argvals[0] ** argvals[1]
  1077. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  1078. elif obj is self.JS_Date:
  1079. return getattr(obj, member)(*argvals)
  1080. if member == 'split':
  1081. assertion(len(argvals) <= 2, 'takes at most two arguments')
  1082. if len(argvals) > 1:
  1083. limit = argvals[1]
  1084. assertion(isinstance(limit, int) and limit >= 0, 'integer limit >= 0')
  1085. if limit == 0:
  1086. return []
  1087. else:
  1088. limit = 0
  1089. if len(argvals) == 0:
  1090. argvals = [JS_Undefined]
  1091. elif isinstance(argvals[0], self.JS_RegExp):
  1092. # avoid re.split(), similar but not enough
  1093. def where():
  1094. for m in argvals[0].finditer(obj):
  1095. yield m.span(0)
  1096. yield (None, None)
  1097. def splits(limit=limit):
  1098. i = 0
  1099. for j, jj in where():
  1100. if j == jj == 0:
  1101. continue
  1102. if j is None and i >= len(obj):
  1103. break
  1104. yield obj[i:j]
  1105. if jj is None or limit == 1:
  1106. break
  1107. limit -= 1
  1108. i = jj
  1109. return list(splits())
  1110. return (
  1111. obj.split(argvals[0], limit - 1) if argvals[0] and argvals[0] != JS_Undefined
  1112. else list(obj)[:limit or None])
  1113. elif member == 'join':
  1114. assertion(isinstance(obj, list), 'must be applied on a list')
  1115. assertion(len(argvals) <= 1, 'takes at most one argument')
  1116. return (',' if len(argvals) == 0 or argvals[0] in (None, JS_Undefined)
  1117. else argvals[0]).join(
  1118. ('' if x in (None, JS_Undefined) else _js_toString(x))
  1119. for x in obj)
  1120. elif member == 'reverse':
  1121. assertion(not argvals, 'does not take any arguments')
  1122. obj.reverse()
  1123. return obj
  1124. elif member == 'slice':
  1125. assertion(isinstance(obj, (list, compat_str)), 'must be applied on a list or string')
  1126. # From [1]:
  1127. # .slice() - like [:]
  1128. # .slice(n) - like [n:] (not [slice(n)]
  1129. # .slice(m, n) - like [m:n] or [slice(m, n)]
  1130. # [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
  1131. assertion(len(argvals) <= 2, 'takes between 0 and 2 arguments')
  1132. if len(argvals) < 2:
  1133. argvals += (None,)
  1134. return obj[slice(*argvals)]
  1135. elif member == 'splice':
  1136. assertion(isinstance(obj, list), 'must be applied on a list')
  1137. assertion(argvals, 'takes one or more arguments')
  1138. index, how_many = map(int, (argvals + [len(obj)])[:2])
  1139. if index < 0:
  1140. index += len(obj)
  1141. res = [obj.pop(index)
  1142. for _ in range(index, min(index + how_many, len(obj)))]
  1143. obj[index:index] = argvals[2:]
  1144. return res
  1145. elif member in ('shift', 'pop'):
  1146. assertion(isinstance(obj, list), 'must be applied on a list')
  1147. assertion(not argvals, 'does not take any arguments')
  1148. return obj.pop(0 if member == 'shift' else -1) if len(obj) > 0 else JS_Undefined
  1149. elif member == 'unshift':
  1150. assertion(isinstance(obj, list), 'must be applied on a list')
  1151. # not enforced: assertion(argvals, 'takes one or more arguments')
  1152. obj[0:0] = argvals
  1153. return len(obj)
  1154. elif member == 'push':
  1155. # not enforced: assertion(argvals, 'takes one or more arguments')
  1156. obj.extend(argvals)
  1157. return len(obj)
  1158. elif member == 'forEach':
  1159. assertion(argvals, 'takes one or more arguments')
  1160. assertion(len(argvals) <= 2, 'takes at most 2 arguments')
  1161. f, this = (argvals + [''])[:2]
  1162. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  1163. elif member == 'indexOf':
  1164. assertion(argvals, 'takes one or more arguments')
  1165. assertion(len(argvals) <= 2, 'takes at most 2 arguments')
  1166. idx, start = (argvals + [0])[:2]
  1167. try:
  1168. return obj.index(idx, start)
  1169. except ValueError:
  1170. return -1
  1171. elif member == 'charCodeAt':
  1172. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  1173. # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  1174. idx = argvals[0] if len(argvals) > 0 and isinstance(argvals[0], int) else 0
  1175. if idx >= len(obj):
  1176. return None
  1177. return ord(obj[idx])
  1178. elif member in ('replace', 'replaceAll'):
  1179. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  1180. assertion(len(argvals) == 2, 'takes exactly two arguments')
  1181. # TODO: argvals[1] callable, other Py vs JS edge cases
  1182. if isinstance(argvals[0], self.JS_RegExp):
  1183. # access JS member with Py reserved name
  1184. count = 0 if self._index(argvals[0], 'global') else 1
  1185. assertion(member != 'replaceAll' or count == 0,
  1186. 'replaceAll must be called with a global RegExp')
  1187. return argvals[0].sub(argvals[1], obj, count=count)
  1188. count = ('replaceAll', 'replace').index(member)
  1189. return re.sub(re.escape(argvals[0]), argvals[1], obj, count=count)
  1190. idx = int(member) if isinstance(obj, list) else member
  1191. return obj[idx](argvals, allow_recursion=allow_recursion)
  1192. if remaining:
  1193. ret, should_abort = self.interpret_statement(
  1194. self._named_object(local_vars, eval_method(variable, member)) + remaining,
  1195. local_vars, allow_recursion)
  1196. return ret, should_return or should_abort
  1197. else:
  1198. return eval_method(variable, member), should_return
  1199. elif md.get('function'):
  1200. fname = m.group('fname')
  1201. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  1202. for v in self._separate(m.group('args'))]
  1203. if fname in local_vars:
  1204. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  1205. elif fname not in self._functions:
  1206. self._functions[fname] = self.extract_function(fname)
  1207. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  1208. raise self.Exception(
  1209. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  1210. def interpret_expression(self, expr, local_vars, allow_recursion):
  1211. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  1212. if should_return:
  1213. raise self.Exception('Cannot return from an expression', expr)
  1214. return ret
  1215. def interpret_iter(self, list_txt, local_vars, allow_recursion):
  1216. for v in self._separate(list_txt):
  1217. yield self.interpret_expression(v, local_vars, allow_recursion)
  1218. def extract_object(self, objname):
  1219. _FUNC_NAME_RE = r'''(?:{n}|"{n}"|'{n}')'''.format(n=_NAME_RE)
  1220. obj = {}
  1221. fields = next(filter(None, (
  1222. obj_m.group('fields') for obj_m in re.finditer(
  1223. r'''(?xs)
  1224. {0}\s*\.\s*{1}|{1}\s*=\s*\{{\s*
  1225. (?P<fields>({2}\s*:\s*function\s*\(.*?\)\s*\{{.*?}}(?:,\s*)?)*)
  1226. }}\s*;
  1227. '''.format(_NAME_RE, re.escape(objname), _FUNC_NAME_RE),
  1228. self.code))), None)
  1229. if not fields:
  1230. raise self.Exception('Could not find object ' + objname)
  1231. # Currently, it only supports function definitions
  1232. for f in re.finditer(
  1233. r'''(?x)
  1234. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  1235. ''' % (_FUNC_NAME_RE, _NAME_RE),
  1236. fields):
  1237. argnames = self.build_arglist(f.group('args'))
  1238. name = remove_quotes(f.group('key'))
  1239. obj[name] = function_with_repr(self.build_function(argnames, f.group('code')), 'F<{0}>'.format(name))
  1240. return obj
  1241. @staticmethod
  1242. def _offset_e_by_d(d, e, local_vars):
  1243. """ Short-cut eval: (d%e.length+e.length)%e.length """
  1244. try:
  1245. d = local_vars[d]
  1246. e = local_vars[e]
  1247. e = len(e)
  1248. return _js_mod(_js_mod(d, e) + e, e), False
  1249. except Exception:
  1250. return None, True
  1251. def extract_function_code(self, funcname):
  1252. """ @returns argnames, code """
  1253. func_m = re.search(
  1254. r'''(?xs)
  1255. (?:
  1256. function\s+%(name)s|
  1257. [{;,]\s*%(name)s\s*=\s*function|
  1258. (?:var|const|let)\s+%(name)s\s*=\s*function
  1259. )\s*
  1260. \((?P<args>[^)]*)\)\s*
  1261. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  1262. self.code)
  1263. if func_m is None:
  1264. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  1265. code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
  1266. return self.build_arglist(func_m.group('args')), code
  1267. def extract_function(self, funcname, *global_stack):
  1268. return function_with_repr(
  1269. self.extract_function_from_code(*itertools.chain(
  1270. self.extract_function_code(funcname), global_stack)),
  1271. 'F<%s>' % (funcname,))
  1272. def extract_function_from_code(self, argnames, code, *global_stack):
  1273. local_vars = {}
  1274. start = None
  1275. while True:
  1276. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code[start:])
  1277. if mobj is None:
  1278. break
  1279. start, body_start = ((start or 0) + x for x in mobj.span())
  1280. body, remaining = self._separate_at_paren(code[body_start - 1:])
  1281. name = self._named_object(local_vars, self.extract_function_from_code(
  1282. [x.strip() for x in mobj.group('args').split(',')],
  1283. body, local_vars, *global_stack))
  1284. code = code[:start] + name + remaining
  1285. return self.build_function(argnames, code, local_vars, *global_stack)
  1286. def call_function(self, funcname, *args, **kw_global_vars):
  1287. return self.extract_function(funcname)(args, kw_global_vars)
  1288. @classmethod
  1289. def build_arglist(cls, arg_text):
  1290. if not arg_text:
  1291. return []
  1292. def valid_arg(y):
  1293. y = y.strip()
  1294. if not y:
  1295. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  1296. return y
  1297. return [valid_arg(x) for x in cls._separate(arg_text)]
  1298. def build_function(self, argnames, code, *global_stack):
  1299. global_stack = list(global_stack) or [{}]
  1300. argnames = tuple(argnames)
  1301. def resf(args, kwargs=None, allow_recursion=100):
  1302. kwargs = kwargs or {}
  1303. global_stack[0].update(zip_longest(argnames, args, fillvalue=JS_Undefined))
  1304. global_stack[0].update(kwargs)
  1305. var_stack = LocalNameSpace(*global_stack)
  1306. ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  1307. if should_abort:
  1308. return ret
  1309. return resf