Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JS Set #60

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 0 additions & 1 deletion pscript/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,6 @@
Not currently supported:

* import (maybe we should translate an import to ``require()``?)
* the ``set`` class (JS has no set, but we could create one?)
* slicing with steps (JS does not support this)
* Generators, i.e. ``yield`` (not widely supported in JS)

Expand Down
51 changes: 47 additions & 4 deletions pscript/parser1.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,40 @@ def parse_List(self, node):
def parse_Tuple(self, node):
return self.parse_List(node) # tuple = ~ list in JS

def parse_Set(self, node):
use_make_set_func = False
code = ['new Set([']
for child in node.element_nodes:
if isinstance(child, (ast.Num, ast.NameConstant)):
result = self.parse(child)
assert len(result) == 1
if result[0] in code:
use_make_set_func = True
break
code += result
elif (isinstance(child, ast.Str) and isidentifier1.match(child.value) and
child.value[0] not in '0123456789'):
if child.value in code:
use_make_set_func = True
break
code += child.value
else:
use_make_set_func = True
break
code.append(', ')

if use_make_set_func:
func_args = []
for child in node.element_nodes:
func_args += [unify(self.parse(child))]
self.use_std_function('create_set', [])
return stdlib.FUNCTION_PREFIX + 'create_set(' + ', '.join(func_args) + ')'

if node.element_nodes:
code.pop(-1) # skip last comma
code.append('])')
return code

def parse_Dict(self, node):
# Oh JS; without the outer braces, it would only be an Object if used
# in an assignment ...
Expand Down Expand Up @@ -321,9 +355,6 @@ def parse_Dict(self, node):
return stdlib.FUNCTION_PREFIX + 'create_dict(' + ', '.join(func_args) + ')'
return code

def parse_Set(self, node):
raise JSError('No Set in JS')

## Variables

def push_scope_prefix(self, prefix):
Expand Down Expand Up @@ -408,7 +439,19 @@ def parse_BinOp(self, node):
return ["Math.pow(", left, ", ", right, ")"]
elif node.op == node.OPS.FloorDiv:
return ["Math.floor(", left, "/", right, ")"]


C = ast.Set
if (isinstance(node.left_node, C) and
isinstance(node.right_node, C)):
if node.op == node.OPS.BitOr:
return self.use_std_function('op_set_union', [left, right])
if node.op == node.OPS.BitAnd:
return self.use_std_function('op_set_intersection', [left, right])
if node.op == node.OPS.BitXor:
return self.use_std_function('op_set_sym_difference', [left, right])
if node.op == node.OPS.Sub:
return self.use_std_function('op_set_difference', [left, right])
Comment on lines +443 to +453
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit unsure about this. It allows set operations on literal sets only. The use is rather limited because in most cases you'd just directly write the result. But more importantly, it may fool users into thinking that operators work for sets, which is not the case (except for literals).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm happy to drop these for the moment. They are not in my actual use case. I just included them to outline how they could be implemented on top of the JS Set.


op = ' %s ' % self.BINARY_OP[node.op]
return [left, op, right]

Expand Down
66 changes: 66 additions & 0 deletions pscript/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,14 @@ def get_all_std_names():
}
}"""

FUNCTIONS['create_set'] = """function () {
var s = new Set();
for (var i=0; i<arguments.length; i+=2) {
if (!s.has(arguments[i]) && !FUNCTION_PREFIXop_contains(arguments[i], s)) { s.add(arguments[i]) };
almarklein marked this conversation as resolved.
Show resolved Hide resolved
}
return s;
}"""

FUNCTIONS['create_dict'] = """function () {
var d = {};
for (var i=0; i<arguments.length; i+=2) { d[arguments[i]] = arguments[i+1]; }
Expand Down Expand Up @@ -224,6 +232,16 @@ def get_all_std_names():
return r;
}"""

FUNCTIONS['set'] = """function (x) { // nargs: 0 1
var s = new Set();
if (!x) { return s; };
if (typeof x==="object" && !Array.isArray(x)) {x = Object.keys(x)}
for (var i=0; i<x.length; i++) {
if (!s.has(x[i]) && !FUNCTION_PREFIXop_contains(x[i], s)) { s.add(x[i]) };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can do just s.add here, because JS's set filters duplicates by itself.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, right, nested data ...

}
return s;
}"""

FUNCTIONS['range'] = """function (start, end, step) {
var i, res = [];
var val = start;
Expand Down Expand Up @@ -398,6 +416,7 @@ def get_all_std_names():
FUNCTIONS['truthy'] = """function (v) {
if (v === null || typeof v !== "object") {return v;}
else if (v.length !== undefined) {return v.length ? v : false;}
else if (v.size !== undefined) {return v.size ? v : false;}
else if (v.byteLength !== undefined) {return v.byteLength ? v : false;}
else if (v.constructor !== Object) {return true;}
else {return Object.getOwnPropertyNames(v).length ? v : false;}
Expand All @@ -411,6 +430,10 @@ def get_all_std_names():
return a == b;
}

if (a && a.constructor === Set && b && b.constructor === Set) {
a = Array.from(a);
b = Array.from(b);
almarklein marked this conversation as resolved.
Show resolved Hide resolved
}
if (a == null || b == null) {
} else if (Array.isArray(a) && Array.isArray(b)) {
var i = 0, iseq = a.length == b.length;
Expand All @@ -427,6 +450,10 @@ def get_all_std_names():
}"""

FUNCTIONS['op_contains'] = """function op_contains (a, b) { // nargs: 2
if (b && b.constructor === Set) {
if (b.has(a)) return true;
b = Array.from(b);
}
if (b == null) {
} else if (Array.isArray(b)) {
for (var i=0; i<b.length; i++) {if (FUNCTION_PREFIXop_equals(a, b[i]))
Expand Down Expand Up @@ -458,6 +485,45 @@ def get_all_std_names():
} return a * b;
}"""

FUNCTIONS['op_set_union'] = """function (a, b) { // nargs: 2
let _union = new Set(a)
for (let elem of b) {
if (!_union.has(elem) && !FUNCTION_PREFIXop_contains(elem, _union)) { _union.add(elem) };
almarklein marked this conversation as resolved.
Show resolved Hide resolved
}
return _union;
}"""

FUNCTIONS['op_set_intersection'] = """function (a, b) { // nargs: 2
let _intersection = new Set();
for (let elem of b) {
if (a.has(elem) && FUNCTION_PREFIXop_contains(elem, a)) {
_intersection.add(elem);
}
}
return _intersection;
}"""

FUNCTIONS['op_set_sym_difference'] = """function (a, b) { // nargs: 2
let _difference = new Set(a)
for (let elem of b) {
if (_difference.has(elem) && FUNCTION_PREFIXop_contains(elem, _difference)) {
_difference.delete(elem);
} else {
_difference.add(elem);
}
}
return _difference;
}"""

FUNCTIONS['op_set_difference'] = """function (a, b) { // nargs: 2
let _difference = new Set(a)
for (let elem of b) {
if (_difference.has(elem) && FUNCTION_PREFIXop_contains(elem, _difference)) {
_difference.delete(elem);
}
}
return _difference;
}"""

## ----- Methods

Expand Down
55 changes: 50 additions & 5 deletions pscript/tests/test_parser1.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@ def test_comparisons(self):
assert evalpy('3 in [1,2,3,4]') == 'true'
assert evalpy('9 in [1,2,3,4]') == 'false'
assert evalpy('9 not in [1,2,3,4]') == 'true'

assert evalpy('3 in {1,2,3,4}') == 'true'
assert evalpy('9 in {1,2,3,4}') == 'false'
assert evalpy('9 not in {1,2,3,4}') == 'true'

assert evalpy('"bar" in {"foo": 3}') == 'false'
assert evalpy('"foo" in {"foo": 3}') == 'true'
Expand All @@ -203,6 +207,17 @@ def test_deep_comparisons(self):
assert evalpy('[2, 3] == [2, 3]') == 'true'
assert evalpy('a=' + arr + 'b=' + arr + 'a==b') == 'true'

# Set
arr = '{(1,2), (3,4), (5,6), (1,2), (7,8)}\n'
#assert evalpy('a=' + arr + 'a == {(1,2), (3,4), (5,6), (7,8)}') == 'true'
assert evalpy('a=' + arr + '(1,2) in a') == 'true'
assert evalpy('a=' + arr + '(7,8) in a') == 'true'
assert evalpy('a=' + arr + '(3,5) in a') == 'false'
assert evalpy('a=' + arr + '3 in a') == 'false'

assert evalpy('{2, 3} == {2, 3}') == 'true'
assert evalpy('a=' + arr + 'b=' + arr + 'a==b') == 'true'

# Dict
dct = '{"a":7, 3:"foo", "bar": 1, "9": 3}\n'
assert evalpy('d=' + dct + '"a" in d') == 'true'
Expand Down Expand Up @@ -249,7 +264,7 @@ def test_truthfulness_of_basic_types(self):
assert evalpy('None is undefined') == 'false'
assert evalpy('undefined is undefined') == 'true'

def test_truthfulness_of_array_and_dict(self):
def test_truthfulness_of_containers(self):

# Arrays
assert evalpy('bool([1])') == 'true'
Expand All @@ -268,9 +283,27 @@ def test_truthfulness_of_array_and_dict(self):
assert evalpy('[2] or 42') == '[ 2 ]'
assert evalpy('[] or 42') == '42'

# Set
assert evalpy('bool({1})') == 'true'
assert evalpy('bool(set())') == 'false'
#
assert evalpy('"T" if ({1, 2, 3}) else "F"') == 'T'
assert evalpy('"T" if (set()) else "F"') == 'F'
#
assert evalpy('if {1}: "T"\nelse: "F"') == 'T'
assert evalpy('if set(): "T"\nelse: "F"') == 'F'
#
assert evalpy('if {1} and 1: "T"\nelse: "F"') == 'T'
assert evalpy('if set() and 1: "T"\nelse: "F"') == 'F'
assert evalpy('if set() or 1: "T"\nelse: "F"') == 'T'
#
assert evalpy('set() or 42') == '42'
assert evalpy('{2} or 42') == 'Set(1) { 2 }'

# Dicts
assert evalpy('bool({1:2})') == 'true'
assert evalpy('bool({})') == 'false'
assert evalpy('bool(dict())') == 'false'
#
assert evalpy('"T" if ({"foo": 3}) else "F"') == 'T'
assert evalpy('"T" if ({}) else "F"') == 'F'
Expand All @@ -285,9 +318,9 @@ def test_truthfulness_of_array_and_dict(self):
assert evalpy('{1:2} or 42') == "{ '1': 2 }"
assert evalpy('{} or 42') == '42'
assert evalpy('{} or 0') == '0'
assert evalpy('None or []') == '[]'


# Eval extra types
assert evalpy('None or []') == '[]'
assert evalpy('null or 42') == '42'
assert evalpy('ArrayBuffer(4) or 42') != '42'

Expand All @@ -298,8 +331,20 @@ def test_truthfulness_of_array_and_dict(self):
assert py2js('if True: pass').count('_truthy') == 0
assert py2js('if a == 3: pass').count('_truthy') == 0
assert py2js('if a is 3: pass').count('_truthy') == 0



def test_set_operations(self):
setA = '{1, 2, 3, 4}'
setB = '{3, 4, 5, 6}'

assert evalpy(setA + '|' + setB) == 'Set(6) { 1, 2, 3, 4, 5, 6 }'
assert evalpy(setA + '&' + setB) == 'Set(2) { 3, 4 }'
assert evalpy(setA + '^' + setB) == 'Set(4) { 1, 2, 5, 6 }'
assert evalpy(setA + '-' + setB) == 'Set(2) { 1, 2 }'

setC = '{2, 3}'

assert evalpy(setA + '>=' + setC) == 'true'

def test_indexing_and_slicing(self):
c = 'a = [1, 2, 3, 4, 5]\n'

Expand Down