Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import ast
import asyncio
import builtins
import copy
import functools
import importlib
import inspect
import keyword
import logging
import operator
import sys
import time
import traceback
Expand Down Expand Up @@ -427,6 +429,24 @@ def unwrap_stop_iteration(exc):
return exc


# the in-place operator function for each augmented assignment operator
AUGASSIGN_OPS = {
ast.Add: operator.iadd,
ast.Sub: operator.isub,
ast.Mult: operator.imul,
ast.MatMult: operator.imatmul,
ast.Div: operator.itruediv,
ast.FloorDiv: operator.ifloordiv,
ast.Mod: operator.imod,
ast.Pow: operator.ipow,
ast.LShift: operator.ilshift,
ast.RShift: operator.irshift,
ast.BitOr: operator.ior,
ast.BitXor: operator.ixor,
ast.BitAnd: operator.iand,
}


# special methods that pyscript leaves as they are: it calls __init__ and __new__ itself, __del__
# runs whenever the object is freed, Python calls __getattribute__, __setattr__ and __delattr__ for
# every attribute access, which pyscript handles itself (eg, for @property), and the async ones
Expand Down Expand Up @@ -1662,11 +1682,27 @@ async def ast_assign(self, arg):
await self.recurse_assign(target, rhs)

async def ast_augassign(self, arg):
"""Execute augmented assignment statement (lhs <BinOp>= value)."""
arg.target.ctx = ast.Load()
new_val = await self.aeval(ast.BinOp(left=arg.target, op=arg.op, right=arg.value))
arg.target.ctx = ast.Store()
await self.recurse_assign(arg.target, new_val)
"""Execute augmented assignment statement (lhs <op>= value)."""
#
# as in Python, evaluate the target's object and index once, update the value in place
# if it supports that (eg, list +=), and store the result back
#
target = arg.target
if isinstance(target, ast.Subscript):
obj, index = await self.aeval(target.value), await self.aeval(target.slice)
target = ast.copy_location(
ast.Subscript(value=ast.Constant(obj), slice=ast.Constant(index)), target
)
elif isinstance(target, ast.Attribute) and await self.ast_attribute_collapse(target) is None:
obj = await self.aeval(target.value)
target = ast.copy_location(ast.Attribute(value=ast.Constant(obj), attr=target.attr), target)
else:
# a name, or a state variable or its attribute
target = copy.copy(target)
target.ctx = ast.Load()
new_val = AUGASSIGN_OPS[type(arg.op)](await self.aeval(target), await self.aeval(arg.value))
target.ctx = ast.Store()
await self.recurse_assign(target, new_val)

async def ast_annassign(self, arg):
"""Execute type hint assignment statement and track __annotations__."""
Expand Down
102 changes: 102 additions & 0 deletions tests/test_unit_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,108 @@
["x: int = [10, 20]; x", [10, 20]],
["Foo = type('Foo', (), {'x': 100}); Foo.x = 10; Foo.x", 10],
["Foo = type('Foo', (), {'x': 100}); Foo.x += 10; Foo.x", 110],
# augmented assignment updates in place, evaluates the target once, and calls __iadd__ etc
["x = [1, 2]; y = x; x += [3]; [x, y, x is y]", [[1, 2, 3], [1, 2, 3], True]],
["x = [1]; x += (2, 3); x", [1, 2, 3]],
["d = {'a': 1}; e = d; d |= {'b': 2}; [e, d is e]", [{"a": 1, "b": 2}, True]],
[
"s = {1, 2, 3}; t = s; s -= {1}; s |= {9}; s &= {2, 9}; s ^= {5}; [sorted(t), s is t]",
[[2, 5, 9], True],
],
["a = 7; a -= 2; a *= 3; a //= 4; a %= 3; a **= 3; b = 7.0; b /= 2; [a, b]", [0, 3.5]],
["a = 8; a <<= 2; a >>= 1; a |= 1; a ^= 3; a &= 6; a", 2],
["s = 'a'; t = s; s += 'b'; t = (1,); u = t; t += (2,); [s, t, u]", ["ab", (1, 2), (1,)]],
["import collections; q = collections.deque([1]); q += [2, 3]; list(q)", [1, 2, 3]],
["x = [1, 2, 3, 4]; x[1:3] += [9]; x", [1, 2, 3, 9, 4]],
["d = {'a': [1]}; inner = d['a']; d['a'] += [2]; [inner, d['a'] is inner]", [[1, 2], True]],
[
"""
calls = []
def key():
calls.append('key')
return 'k'
class Obj:
pass
obj = Obj()
obj.items = [1]
def get_obj():
calls.append('obj')
return obj
counts = {'k': 0}
counts[key()] += 1
get_obj().items += [2]
[counts, obj.items, calls]
""",
[{"k": 1}, [1, 2], ["key", "obj"]],
],
[
"""
class Obj:
pass
obj = Obj()
obj.items = [1]
alias = obj.items
obj.items += [2]
obj.sub = Obj()
obj.sub.n = 1
obj.sub.n += 5
[alias, obj.items is alias, obj.sub.n]
""",
[[1, 2], True, 6],
],
[
"""
calls = []
class Prop:
def __init__(self):
self._items = [1]
@property
def items(self):
calls.append('get')
return self._items
@items.setter
def items(self, value):
calls.append('set')
self._items = value
p = Prop()
p.items += [2]
[p._items, calls]
""",
[[1, 2], ["get", "set"]],
],
[
"""
class InPlace:
def __init__(self):
self.n = 0
def __iadd__(self, other):
self.n += other
return self
class Plain:
def __init__(self, n):
self.n = n
def __add__(self, other):
return Plain(self.n + other)
a = InPlace()
a_alias = a
a += 5
b = Plain(1)
b_alias = b
b += 5
[a_alias.n, a is a_alias, b.n, b_alias.n]
""",
[5, True, 6, 1],
],
[
"""
def add_tag(tags):
tags += ['new']
return tags
tags = ['a']
[add_tag(tags) is tags, tags]
""",
[True, ["a", "new"]],
],
[
"""
from enum import IntEnum
Expand Down
Loading