1 from __future__ import unicode_literals
2
3 import itertools
4 import json
5 import math
6 import operator
7 import re
8
9 from .utils import (
10 error_to_compat_str,
11 ExtractorError,
12 js_to_json,
13 remove_quotes,
14 unified_timestamp,
15 )
16 from .compat import (
17 compat_collections_chain_map as ChainMap,
18 compat_itertools_zip_longest as zip_longest,
19 compat_str,
20 )
21
22
23 def _js_bit_op(op):
24
25 def wrapped(a, b):
26 def zeroise(x):
27 return 0 if x in (None, JS_Undefined) else x
28 return op(zeroise(a), zeroise(b))
29
30 return wrapped
31
32
33 def _js_arith_op(op):
34
35 def wrapped(a, b):
36 if JS_Undefined in (a, b):
37 return float('nan')
38 return op(a or 0, b or 0)
39
40 return wrapped
41
42
43 def _js_div(a, b):
44 if JS_Undefined in (a, b) or not (a and b):
45 return float('nan')
46 return float('inf') if not b else operator.truediv(a or 0, b)
47
48
49 def _js_mod(a, b):
50 if JS_Undefined in (a, b) or not b:
51 return float('nan')
52 return (a or 0) % b
53
54
55 def _js_exp(a, b):
56 if not b:
57 return 1 # even 0 ** 0 !!
58 elif JS_Undefined in (a, b):
59 return float('nan')
60 return (a or 0) ** b
61
62
63 def _js_eq_op(op):
64
65 def wrapped(a, b):
66 if set((a, b)) <= set((None, JS_Undefined)):
67 return op(a, a)
68 return op(a, b)
69
70 return wrapped
71
72
73 def _js_comp_op(op):
74
75 def wrapped(a, b):
76 if JS_Undefined in (a, b):
77 return False
78 return op(a or 0, b or 0)
79
80 return wrapped
81
82
83 def _js_ternary(cndn, if_true=True, if_false=False):
84 """Simulate JS's ternary operator (cndn?if_true:if_false)"""
85 if cndn in (False, None, 0, '', JS_Undefined):
86 return if_false
87 try:
88 if math.isnan(cndn): # NB: NaN cannot be checked by membership
89 return if_false
90 except TypeError:
91 pass
92 return if_true
93
94
95 # (op, definition) in order of binding priority, tightest first
96 # avoid dict to maintain order
97 # definition None => Defined in JSInterpreter._operator
98 _OPERATORS = (
99 ('>>', _js_bit_op(operator.rshift)),
100 ('<<', _js_bit_op(operator.lshift)),
101 ('+', _js_arith_op(operator.add)),
102 ('-', _js_arith_op(operator.sub)),
103 ('*', _js_arith_op(operator.mul)),
104 ('/', _js_div),
105 ('%', _js_mod),
106 ('**', _js_exp),
107 )
108
109 _COMP_OPERATORS = (
110 ('===', operator.is_),
111 ('==', _js_eq_op(operator.eq)),
112 ('!==', operator.is_not),
113 ('!=', _js_eq_op(operator.ne)),
114 ('<=', _js_comp_op(operator.le)),
115 ('>=', _js_comp_op(operator.ge)),
116 ('<', _js_comp_op(operator.lt)),
117 ('>', _js_comp_op(operator.gt)),
118 )
119
120 _LOG_OPERATORS = (
121 ('|', _js_bit_op(operator.or_)),
122 ('^', _js_bit_op(operator.xor)),
123 ('&', _js_bit_op(operator.and_)),
124 )
125
126 _SC_OPERATORS = (
127 ('?', None),
128 ('??', None),
129 ('||', None),
130 ('&&', None),
131 )
132
133 _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
134
135 _NAME_RE = r'[a-zA-Z_$][\w$]*'
136 _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
137 _QUOTES = '\'"/'
138
139
140 class JS_Undefined(object):
141 pass
142
143
144 class JS_Break(ExtractorError):
145 def __init__(self):
146 ExtractorError.__init__(self, 'Invalid break')
147
148
149 class JS_Continue(ExtractorError):
150 def __init__(self):
151 ExtractorError.__init__(self, 'Invalid continue')
152
153
154 class JS_Throw(ExtractorError):
155 def __init__(self, e):
156 self.error = e
157 ExtractorError.__init__(self, 'Uncaught exception ' + error_to_compat_str(e))
158
159
160 class LocalNameSpace(ChainMap):
161 def __getitem__(self, key):
162 try:
163 return super(LocalNameSpace, self).__getitem__(key)
164 except KeyError:
165 return JS_Undefined
166
167 def __setitem__(self, key, value):
168 for scope in self.maps:
169 if key in scope:
170 scope[key] = value
171 return
172 self.maps[0][key] = value
173
174 def __delitem__(self, key):
175 raise NotImplementedError('Deleting is not supported')
176
177 def __repr__(self):
178 return 'LocalNameSpace%s' % (self.maps, )
179
180
181 class JSInterpreter(object):
182 __named_object_counter = 0
183
184 _RE_FLAGS = {
185 # special knowledge: Python's re flags are bitmask values, current max 128
186 # invent new bitmask values well above that for literal parsing
187 # TODO: new pattern class to execute matches with these flags
188 'd': 1024, # Generate indices for substring matches
189 'g': 2048, # Global search
190 'i': re.I, # Case-insensitive search
191 'm': re.M, # Multi-line search
192 's': re.S, # Allows . to match newline characters
193 'u': re.U, # Treat a pattern as a sequence of unicode code points
194 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
195 }
196
197 _EXC_NAME = '__youtube_dl_exception__'
198 _OBJ_NAME = '__youtube_dl_jsinterp_obj'
199
200 OP_CHARS = None
201
202 def __init__(self, code, objects=None):
203 self.code, self._functions = code, {}
204 self._objects = {} if objects is None else objects
205 if type(self).OP_CHARS is None:
206 type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
207
208 class Exception(ExtractorError):
209 def __init__(self, msg, *args, **kwargs):
210 expr = kwargs.pop('expr', None)
211 if expr is not None:
212 msg = '{0} in: {1!r}'.format(msg.rstrip(), expr[:100])
213 super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
214
215 @classmethod
216 def __op_chars(cls):
217 op_chars = set(';,')
218 for op in cls._all_operators():
219 for c in op[0]:
220 op_chars.add(c)
221 return op_chars
222
223 def _named_object(self, namespace, obj):
224 self.__named_object_counter += 1
225 name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
226 namespace[name] = obj
227 return name
228
229 @classmethod
230 def _regex_flags(cls, expr):
231 flags = 0
232 if not expr:
233 return flags, expr
234 for idx, ch in enumerate(expr):
235 if ch not in cls._RE_FLAGS:
236 break
237 flags |= cls._RE_FLAGS[ch]
238 return flags, expr[idx + 1:]
239
240 @classmethod
241 def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
242 if not expr:
243 return
244 counters = {k: 0 for k in _MATCHING_PARENS.values()}
245 start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
246 in_quote, escaping, skipping = None, False, 0
247 after_op, in_regex_char_group, skip_re = True, False, 0
248
249 for idx, char in enumerate(expr):
250 if skip_re > 0:
251 skip_re -= 1
252 continue
253 if not in_quote:
254 if char in _MATCHING_PARENS:
255 counters[_MATCHING_PARENS[char]] += 1
256 elif char in counters:
257 counters[char] -= 1
258 if not escaping and char in _QUOTES and in_quote in (char, None):
259 if in_quote or after_op or char != '/':
260 in_quote = None if in_quote and not in_regex_char_group else char
261 elif in_quote == '/' and char in '[]':
262 in_regex_char_group = char == '['
263 escaping = not escaping and in_quote and char == '\\'
264 after_op = not in_quote and char in cls.OP_CHARS or (char == ' ' and after_op)
265
266 if char != delim[pos] or any(counters.values()) or in_quote:
267 pos = skipping = 0
268 continue
269 elif skipping > 0:
270 skipping -= 1
271 continue
272 elif pos == 0 and skip_delims:
273 here = expr[idx:]
274 for s in skip_delims if isinstance(skip_delims, (list, tuple)) else [skip_delims]:
275 if here.startswith(s) and s:
276 skipping = len(s) - 1
277 break
278 if skipping > 0:
279 continue
280 if pos < delim_len:
281 pos += 1
282 continue
283 yield expr[start: idx - delim_len]
284 start, pos = idx + 1, 0
285 splits += 1
286 if max_split and splits >= max_split:
287 break
288 yield expr[start:]
289
290 @classmethod
291 def _separate_at_paren(cls, expr, delim):
292 separated = list(cls._separate(expr, delim, 1))
293
294 if len(separated) < 2:
295 raise cls.Exception('No terminating paren {delim} in {expr}'.format(**locals()))
296 return separated[0][1:].strip(), separated[1].strip()
297
298 @staticmethod
299 def _all_operators():
300 return itertools.chain(
301 # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
302 _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
303
304 def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
305 if op in ('||', '&&'):
306 if (op == '&&') ^ _js_ternary(left_val):
307 return left_val # short circuiting
308 elif op == '??':
309 if left_val not in (None, JS_Undefined):
310 return left_val
311 elif op == '?':
312 right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
313
314 right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
315 opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
316 if not opfunc:
317 return right_val
318
319 try:
320 return opfunc(left_val, right_val)
321 except Exception as e:
322 raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e)
323
324 def _index(self, obj, idx, allow_undefined=False):
325 if idx == 'length':
326 return len(obj)
327 try:
328 return obj[int(idx)] if isinstance(obj, list) else obj[idx]
329 except Exception as e:
330 if allow_undefined:
331 return JS_Undefined
332 raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e)
333
334 def _dump(self, obj, namespace):
335 try:
336 return json.dumps(obj)
337 except TypeError:
338 return self._named_object(namespace, obj)
339
340 def interpret_statement(self, stmt, local_vars, allow_recursion=100):
341 if allow_recursion < 0:
342 raise self.Exception('Recursion limit reached')
343 allow_recursion -= 1
344
345 should_return = False
346 sub_statements = list(self._separate(stmt, ';')) or ['']
347 expr = stmt = sub_statements.pop().strip()
348 for sub_stmt in sub_statements:
349 ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
350 if should_return:
351 return ret, should_return
352
353 m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$)|(?P<throw>throw\s+)', stmt)
354 if m:
355 expr = stmt[len(m.group(0)):].strip()
356 if m.group('throw'):
357 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
358 should_return = not m.group('var')
359 if not expr:
360 return None, should_return
361
362 if expr[0] in _QUOTES:
363 inner, outer = self._separate(expr, expr[0], 1)
364 if expr[0] == '/':
365 flags, outer = self._regex_flags(outer)
366 inner = re.compile(inner[1:], flags=flags) # , strict=True))
367 else:
368 inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
369 if not outer:
370 return inner, should_return
371 expr = self._named_object(local_vars, inner) + outer
372
373 if expr.startswith('new '):
374 obj = expr[4:]
375 if obj.startswith('Date('):
376 left, right = self._separate_at_paren(obj[4:], ')')
377 expr = unified_timestamp(
378 self.interpret_expression(left, local_vars, allow_recursion), False)
379 if not expr:
380 raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr)
381 expr = self._dump(int(expr * 1000), local_vars) + right
382 else:
383 raise self.Exception('Unsupported object {obj}'.format(**locals()), expr=expr)
384
385 if expr.startswith('void '):
386 left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
387 return None, should_return
388
389 if expr.startswith('{'):
390 inner, outer = self._separate_at_paren(expr, '}')
391 # try for object expression (Map)
392 sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
393 if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
394 return dict(
395 (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
396 self.interpret_expression(val_expr, local_vars, allow_recursion))
397 for key_expr, val_expr in sub_expressions), should_return
398 # or statement list
399 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
400 if not outer or should_abort:
401 return inner, should_abort or should_return
402 else:
403 expr = self._dump(inner, local_vars) + outer
404
405 if expr.startswith('('):
406 inner, outer = self._separate_at_paren(expr, ')')
407 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
408 if not outer or should_abort:
409 return inner, should_abort or should_return
410 else:
411 expr = self._dump(inner, local_vars) + outer
412
413 if expr.startswith('['):
414 inner, outer = self._separate_at_paren(expr, ']')
415 name = self._named_object(local_vars, [
416 self.interpret_expression(item, local_vars, allow_recursion)
417 for item in self._separate(inner)])
418 expr = name + outer
419
420 m = re.match(r'''(?x)
421 (?P<try>try|finally)\s*|
422 (?P<catch>catch\s*(?P<err>\(\s*{_NAME_RE}\s*\)))|
423 (?P<switch>switch)\s*\(|
424 (?P<for>for)\s*\(|
425 '''.format(**globals()), expr)
426 md = m.groupdict() if m else {}
427 if md.get('try'):
428 if expr[m.end()] == '{':
429 try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
430 else:
431 try_expr, expr = expr[m.end() - 1:], ''
432 try:
433 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
434 if should_abort:
435 return ret, True
436 except JS_Throw as e:
437 local_vars[self._EXC_NAME] = e.error
438 except Exception as e:
439 # XXX: This works for now, but makes debugging future issues very hard
440 local_vars[self._EXC_NAME] = e
441 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
442 return ret, should_abort or should_return
443
444 elif md.get('catch'):
445 catch_expr, expr = self._separate_at_paren(expr[m.end():], '}')
446 if self._EXC_NAME in local_vars:
447 catch_vars = local_vars.new_child({m.group('err'): local_vars.pop(self._EXC_NAME)})
448 ret, should_abort = self.interpret_statement(catch_expr, catch_vars, allow_recursion)
449 if should_abort:
450 return ret, True
451
452 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
453 return ret, should_abort or should_return
454
455 elif md.get('for'):
456 constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
457 if remaining.startswith('{'):
458 body, expr = self._separate_at_paren(remaining, '}')
459 else:
460 switch_m = re.match(r'switch\s*\(', remaining) # FIXME
461 if switch_m:
462 switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
463 body, expr = self._separate_at_paren(remaining, '}')
464 body = 'switch(%s){%s}' % (switch_val, body)
465 else:
466 body, expr = remaining, ''
467 start, cndn, increment = self._separate(constructor, ';')
468 self.interpret_expression(start, local_vars, allow_recursion)
469 while True:
470 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
471 break
472 try:
473 ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
474 if should_abort:
475 return ret, True
476 except JS_Break:
477 break
478 except JS_Continue:
479 pass
480 self.interpret_expression(increment, local_vars, allow_recursion)
481 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
482 return ret, should_abort or should_return
483
484 elif md.get('switch'):
485 switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
486 switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
487 body, expr = self._separate_at_paren(remaining, '}')
488 items = body.replace('default:', 'case default:').split('case ')[1:]
489 for default in (False, True):
490 matched = False
491 for item in items:
492 case, stmt = (i.strip() for i in self._separate(item, ':', 1))
493 if default:
494 matched = matched or case == 'default'
495 elif not matched:
496 matched = (case != 'default'
497 and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
498 if not matched:
499 continue
500 try:
501 ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
502 if should_abort:
503 return ret
504 except JS_Break:
505 break
506 if matched:
507 break
508 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
509 return ret, should_abort or should_return
510
511 # Comma separated statements
512 sub_expressions = list(self._separate(expr))
513 if len(sub_expressions) > 1:
514 for sub_expr in sub_expressions:
515 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
516 if should_abort:
517 return ret, True
518 return ret, False
519
520 for m in re.finditer(r'''(?x)
521 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
522 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
523 var = m.group('var1') or m.group('var2')
524 start, end = m.span()
525 sign = m.group('pre_sign') or m.group('post_sign')
526 ret = local_vars[var]
527 local_vars[var] += 1 if sign[0] == '+' else -1
528 if m.group('pre_sign'):
529 ret = local_vars[var]
530 expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
531
532 if not expr:
533 return None, should_return
534
535 m = re.match(r'''(?x)
536 (?P<assign>
537 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
538 (?P<op>{_OPERATOR_RE})?
539 =(?!=)(?P<expr>.*)$
540 )|(?P<return>
541 (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
542 )|(?P<indexing>
543 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
544 )|(?P<attribute>
545 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
546 )|(?P<function>
547 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
548 )'''.format(**globals()), expr)
549 md = m.groupdict() if m else {}
550 if md.get('assign'):
551 left_val = local_vars.get(m.group('out'))
552
553 if not m.group('index'):
554 local_vars[m.group('out')] = self._operator(
555 m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
556 return local_vars[m.group('out')], should_return
557 elif left_val in (None, JS_Undefined):
558 raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
559
560 idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
561 if not isinstance(idx, (int, float)):
562 raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
563 idx = int(idx)
564 left_val[idx] = self._operator(
565 m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
566 return left_val[idx], should_return
567
568 elif expr.isdigit():
569 return int(expr), should_return
570
571 elif expr == 'break':
572 raise JS_Break()
573 elif expr == 'continue':
574 raise JS_Continue()
575
576 elif expr == 'undefined':
577 return JS_Undefined, should_return
578
579 elif md.get('return'):
580 return local_vars[m.group('name')], should_return
581
582 try:
583 ret = json.loads(js_to_json(expr)) # strict=True)
584 if not md.get('attribute'):
585 return ret, should_return
586 except ValueError:
587 pass
588
589 if md.get('indexing'):
590 val = local_vars[m.group('in')]
591 idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
592 return self._index(val, idx), should_return
593
594 for op, _ in self._all_operators():
595 # hackety: </> have higher priority than <</>>, but don't confuse them
596 skip_delim = (op + op) if op in '<>*?' else None
597 if op == '?':
598 skip_delim = (skip_delim, '?.')
599 separated = list(self._separate(expr, op, skip_delims=skip_delim))
600 if len(separated) < 2:
601 continue
602
603 right_expr = separated.pop()
604 while op == '-' and len(separated) > 1 and not separated[-1].strip():
605 right_expr = '-' + right_expr
606 separated.pop()
607 left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
608 return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
609
610 if md.get('attribute'):
611 variable, member, nullish = m.group('var', 'member', 'nullish')
612 if not member:
613 member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
614 arg_str = expr[m.end():]
615 if arg_str.startswith('('):
616 arg_str, remaining = self._separate_at_paren(arg_str, ')')
617 else:
618 arg_str, remaining = None, arg_str
619
620 def assertion(cndn, msg):
621 """ assert, but without risk of getting optimized out """
622 if not cndn:
623 raise ExtractorError('{member} {msg}'.format(**locals()), expr=expr)
624
625 def eval_method():
626 if (variable, member) == ('console', 'debug'):
627 return
628 types = {
629 'String': compat_str,
630 'Math': float,
631 }
632 obj = local_vars.get(variable)
633 if obj in (JS_Undefined, None):
634 obj = types.get(variable, JS_Undefined)
635 if obj is JS_Undefined:
636 try:
637 if variable not in self._objects:
638 self._objects[variable] = self.extract_object(variable)
639 obj = self._objects[variable]
640 except self.Exception:
641 if not nullish:
642 raise
643
644 if nullish and obj is JS_Undefined:
645 return JS_Undefined
646
647 # Member access
648 if arg_str is None:
649 return self._index(obj, member, nullish)
650
651 # Function call
652 argvals = [
653 self.interpret_expression(v, local_vars, allow_recursion)
654 for v in self._separate(arg_str)]
655
656 if obj == compat_str:
657 if member == 'fromCharCode':
658 assertion(argvals, 'takes one or more arguments')
659 return ''.join(map(chr, argvals))
660 raise self.Exception('Unsupported string method ' + member, expr=expr)
661 elif obj == float:
662 if member == 'pow':
663 assertion(len(argvals) == 2, 'takes two arguments')
664 return argvals[0] ** argvals[1]
665 raise self.Exception('Unsupported Math method ' + member, expr=expr)
666
667 if member == 'split':
668 assertion(argvals, 'takes one or more arguments')
669 assertion(len(argvals) == 1, 'with limit argument is not implemented')
670 return obj.split(argvals[0]) if argvals[0] else list(obj)
671 elif member == 'join':
672 assertion(isinstance(obj, list), 'must be applied on a list')
673 assertion(len(argvals) == 1, 'takes exactly one argument')
674 return argvals[0].join(obj)
675 elif member == 'reverse':
676 assertion(not argvals, 'does not take any arguments')
677 obj.reverse()
678 return obj
679 elif member == 'slice':
680 assertion(isinstance(obj, list), 'must be applied on a list')
681 assertion(len(argvals) == 1, 'takes exactly one argument')
682 return obj[argvals[0]:]
683 elif member == 'splice':
684 assertion(isinstance(obj, list), 'must be applied on a list')
685 assertion(argvals, 'takes one or more arguments')
686 index, howMany = map(int, (argvals + [len(obj)])[:2])
687 if index < 0:
688 index += len(obj)
689 add_items = argvals[2:]
690 res = []
691 for i in range(index, min(index + howMany, len(obj))):
692 res.append(obj.pop(index))
693 for i, item in enumerate(add_items):
694 obj.insert(index + i, item)
695 return res
696 elif member == 'unshift':
697 assertion(isinstance(obj, list), 'must be applied on a list')
698 assertion(argvals, 'takes one or more arguments')
699 for item in reversed(argvals):
700 obj.insert(0, item)
701 return obj
702 elif member == 'pop':
703 assertion(isinstance(obj, list), 'must be applied on a list')
704 assertion(not argvals, 'does not take any arguments')
705 if not obj:
706 return
707 return obj.pop()
708 elif member == 'push':
709 assertion(argvals, 'takes one or more arguments')
710 obj.extend(argvals)
711 return obj
712 elif member == 'forEach':
713 assertion(argvals, 'takes one or more arguments')
714 assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
715 f, this = (argvals + [''])[:2]
716 return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
717 elif member == 'indexOf':
718 assertion(argvals, 'takes one or more arguments')
719 assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
720 idx, start = (argvals + [0])[:2]
721 try:
722 return obj.index(idx, start)
723 except ValueError:
724 return -1
725
726 idx = int(member) if isinstance(obj, list) else member
727 return obj[idx](argvals, allow_recursion=allow_recursion)
728
729 if remaining:
730 ret, should_abort = self.interpret_statement(
731 self._named_object(local_vars, eval_method()) + remaining,
732 local_vars, allow_recursion)
733 return ret, should_return or should_abort
734 else:
735 return eval_method(), should_return
736
737 elif md.get('function'):
738 fname = m.group('fname')
739 argvals = [self.interpret_expression(v, local_vars, allow_recursion)
740 for v in self._separate(m.group('args'))]
741 if fname in local_vars:
742 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
743 elif fname not in self._functions:
744 self._functions[fname] = self.extract_function(fname)
745 return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
746
747 raise self.Exception(
748 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
749
750 def interpret_expression(self, expr, local_vars, allow_recursion):
751 ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
752 if should_return:
753 raise self.Exception('Cannot return from an expression', expr)
754 return ret
755
756 def extract_object(self, objname):
757 _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
758 obj = {}
759 obj_m = re.search(
760 r'''(?x)
761 (?<!this\.)%s\s*=\s*{\s*
762 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
763 }\s*;
764 ''' % (re.escape(objname), _FUNC_NAME_RE),
765 self.code)
766 if not obj_m:
767 raise self.Exception('Could not find object ' + objname)
768 fields = obj_m.group('fields')
769 # Currently, it only supports function definitions
770 fields_m = re.finditer(
771 r'''(?x)
772 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
773 ''' % (_FUNC_NAME_RE, _NAME_RE),
774 fields)
775 for f in fields_m:
776 argnames = self.build_arglist(f.group('args'))
777 obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
778
779 return obj
780
781 def extract_function_code(self, funcname):
782 """ @returns argnames, code """
783 func_m = re.search(
784 r'''(?xs)
785 (?:
786 function\s+%(name)s|
787 [{;,]\s*%(name)s\s*=\s*function|
788 (?:var|const|let)\s+%(name)s\s*=\s*function
789 )\s*
790 \((?P<args>[^)]*)\)\s*
791 (?P<code>{.+})''' % {'name': re.escape(funcname)},
792 self.code)
793 code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
794 if func_m is None:
795 raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
796 return self.build_arglist(func_m.group('args')), code
797
798 def extract_function(self, funcname):
799 return self.extract_function_from_code(*self.extract_function_code(funcname))
800
801 def extract_function_from_code(self, argnames, code, *global_stack):
802 local_vars = {}
803 while True:
804 mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
805 if mobj is None:
806 break
807 start, body_start = mobj.span()
808 body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
809 name = self._named_object(
810 local_vars,
811 self.extract_function_from_code(
812 self.build_arglist(mobj.group('args')),
813 body, local_vars, *global_stack))
814 code = code[:start] + name + remaining
815 return self.build_function(argnames, code, local_vars, *global_stack)
816
817 def call_function(self, funcname, *args):
818 return self.extract_function(funcname)(args)
819
820 @classmethod
821 def build_arglist(cls, arg_text):
822 if not arg_text:
823 return []
824
825 def valid_arg(y):
826 y = y.strip()
827 if not y:
828 raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
829 return y
830
831 return [valid_arg(x) for x in cls._separate(arg_text)]
832
833 def build_function(self, argnames, code, *global_stack):
834 global_stack = list(global_stack) or [{}]
835 argnames = tuple(argnames)
836
837 def resf(args, kwargs={}, allow_recursion=100):
838 global_stack[0].update(
839 zip_longest(argnames, args, fillvalue=None))
840 global_stack[0].update(kwargs)
841 var_stack = LocalNameSpace(*global_stack)
842 ret, should_abort = self.interpret_statement(code.replace('\n', ''), var_stack, allow_recursion - 1)
843 if should_abort:
844 return ret
845 return resf
|