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
11 changes: 8 additions & 3 deletions www/src/Lib/cmath.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,12 +680,17 @@ def tanh(x):
return complex(_real, _imag)

# For compliance with CPython, set all functions as built-in
# (cosmetic: makes type(cmath.sin) look like a builtin function; skip it
# if the implementation cannot construct builtin_function_or_method)
FunctionType = type(_takes_complex)
locs = locals()
keys = list(locs.keys())
for f in keys:
if type(locs[f]) is FunctionType and not f.startswith("_"):
locals()[f] = type(abs)(locals()[f])
try:
for f in keys:
if type(locs[f]) is FunctionType and not f.startswith("_"):
locals()[f] = type(abs)(locals()[f])
except TypeError:
pass

pi = math.pi
e = math.e
Expand Down
162 changes: 162 additions & 0 deletions www/src/Lib/ctypes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
"""Minimal pure-Python subset of ctypes for Brython.

Brython runs in a JavaScript engine and cannot load native libraries, so
this module only provides what pure-Python packages commonly use to probe
the platform: the fundamental C type classes, sizeof()/alignment(), and
byref/pointer stubs. Loading shared libraries raises OSError.

Sizes follow a 32-bit (wasm32-like) data model, matching what CPython
reports on WebAssembly platforms.
"""

class _SimpleCData:
_size_ = 4
_align_ = 4

def __init__(self, value=None):
self.value = value

def __repr__(self):
return f"{type(self).__name__}({self.value!r})"


class c_bool(_SimpleCData):
_type_ = "?"
_size_ = 1
_align_ = 1

class c_char(_SimpleCData):
_type_ = "c"
_size_ = 1
_align_ = 1

class c_byte(_SimpleCData):
_type_ = "b"
_size_ = 1
_align_ = 1

class c_ubyte(_SimpleCData):
_type_ = "B"
_size_ = 1
_align_ = 1

class c_short(_SimpleCData):
_type_ = "h"
_size_ = 2
_align_ = 2

class c_ushort(_SimpleCData):
_type_ = "H"
_size_ = 2
_align_ = 2

class c_int(_SimpleCData):
_type_ = "i"

class c_uint(_SimpleCData):
_type_ = "I"

class c_long(_SimpleCData):
_type_ = "l"

class c_ulong(_SimpleCData):
_type_ = "L"

class c_longlong(_SimpleCData):
_type_ = "q"
_size_ = 8
_align_ = 8

class c_ulonglong(_SimpleCData):
_type_ = "Q"
_size_ = 8
_align_ = 8

class c_size_t(_SimpleCData):
_type_ = "N"

class c_ssize_t(_SimpleCData):
_type_ = "n"

class c_float(_SimpleCData):
_type_ = "f"

class c_double(_SimpleCData):
_type_ = "d"
_size_ = 8
_align_ = 8

class c_char_p(_SimpleCData):
_type_ = "z"

class c_wchar_p(_SimpleCData):
_type_ = "Z"

class c_wchar(_SimpleCData):
_type_ = "u"

class c_void_p(_SimpleCData):
_type_ = "P"

c_int8 = c_byte
c_uint8 = c_ubyte
c_int16 = c_short
c_uint16 = c_ushort
c_int32 = c_int
c_uint32 = c_uint
c_int64 = c_longlong
c_uint64 = c_ulonglong


def sizeof(obj_or_type):
if isinstance(obj_or_type, type):
return getattr(obj_or_type, "_size_", 4)
return getattr(type(obj_or_type), "_size_", 4)

def alignment(obj_or_type):
if isinstance(obj_or_type, type):
return getattr(obj_or_type, "_align_", 4)
return getattr(type(obj_or_type), "_align_", 4)

def byref(obj, offset=0):
raise NotImplementedError("ctypes.byref is not supported in Brython")

def pointer(obj):
raise NotImplementedError("ctypes.pointer is not supported in Brython")

def POINTER(cls):
raise NotImplementedError("ctypes.POINTER is not supported in Brython")

def cast(obj, typ):
raise NotImplementedError("ctypes.cast is not supported in Brython")

def create_string_buffer(init, size=None):
raise NotImplementedError(
"ctypes.create_string_buffer is not supported in Brython")


class ArgumentError(Exception):
pass


class CDLL:
def __init__(self, name, *args, **kw):
raise OSError(
"ctypes cannot load shared libraries in Brython: %r" % (name,))

PyDLL = CDLL
OleDLL = CDLL
WinDLL = CDLL


class LibraryLoader:
def __init__(self, dlltype):
self._dlltype = dlltype

def LoadLibrary(self, name):
return self._dlltype(name)

__getattr__ = LoadLibrary

cdll = LibraryLoader(CDLL)
pydll = LibraryLoader(PyDLL)
42 changes: 34 additions & 8 deletions www/src/ast_to_js.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,21 @@ function make_scope_name(scopes, scope) {
return scope_name
}

function make_globals_name(scopes) {
// Name of the JS object that holds the global namespace.
// This is normally the root scope's namespace object (at module level,
// locals and globals are the same object), but code run by exec() or
// eval() may have distinct globals and locals: the globals object is
// then referenced by namespaces.global_name (cf. py_eval_exec.js).
// Using the root locals object in that case gave functions defined in
// exec() a global namespace that ignored the "globals" argument.
var ns = scopes.namespaces
if (ns && ns.exec_locals !== ns.exec_globals) {
return ns.global_name
}
return make_scope_name(scopes, scopes[0])
}

function make_search_namespaces(scopes) {
var namespaces = []
for (var scope of scopes.slice().reverse()) {
Expand All @@ -288,6 +303,13 @@ function make_search_namespaces(scopes) {
namespaces.push('$B.exec_scope')
}
namespaces.push(make_scope_name(scopes, scope))
var ns = scopes.namespaces
if (scope.is_exec_scope && ns &&
ns.exec_locals !== ns.exec_globals) {
// exec()/eval() with distinct globals and locals: unbound names
// must also be searched in the globals object, after locals
namespaces.push(ns.global_name)
}
}
namespaces.push('_b_')
return namespaces
Expand Down Expand Up @@ -930,7 +952,7 @@ function make_comp(scopes) {
var comp = {ast:this, id, type, varnames,
module_name: scopes[0].name,
locals_name: make_scope_name(scopes),
globals_name: make_scope_name(scopes, scopes[0])}
globals_name: make_globals_name(scopes)}

indent()
if (prefix.length > plen + tab.length) {
Expand Down Expand Up @@ -1604,7 +1626,7 @@ $B.ast.AugAssign.prototype.to_js = function(scopes) {
// The left part of the assignment must be an attribute of a
// namespace (global or local), not a call to $B.resolve
let left_scope = scope.resolve == 'global' ?
make_scope_name(scopes, scopes[0]) : 'locals'
make_globals_name(scopes) : 'locals'
js = prefix + `${left_scope}.${this.target.id} = $B.augm_assign(` +
make_ref(this.target.id, scopes, scope, this.target) + `, '${iop}', ${value})`
} else {
Expand Down Expand Up @@ -1818,7 +1840,7 @@ $B.ast.ClassDef.prototype.to_js = function(scopes) {
locals_name = 'locals_' + qualified_scope_name(scopes, class_scope),
ref = this.name + make_id(),
glob = scopes[0].name,
globals_name = make_scope_name(scopes, scopes[0]),
globals_name = make_globals_name(scopes),
decorators = [],
decorated = false
for (let dec of this.decorator_list) {
Expand Down Expand Up @@ -2358,7 +2380,7 @@ function transform_args(scopes) {

function type_param_in_def(tp, ref, scopes) {
var gname = scopes[0].name,
globals_name = make_scope_name(scopes, scopes[0])
globals_name = make_globals_name(scopes)
var js = ''
var name,
param_type = tp.constructor.$name
Expand Down Expand Up @@ -2435,7 +2457,7 @@ $B.ast.FunctionDef.prototype.to_js = function(scopes) {
var func_name_scope = bind(this.name, scopes)

var gname = scopes[0].name,
globals_name = make_scope_name(scopes, scopes[0])
globals_name = make_globals_name(scopes)

var decorators = [],
decorated = false,
Expand Down Expand Up @@ -2934,7 +2956,7 @@ $B.ast.GeneratorExp.prototype.to_js = function(scopes) {
var comp = {ast:this, id, type: 'genexpr', varnames,
module_name: scopes[0].name,
locals_name: make_scope_name(scopes),
globals_name: make_scope_name(scopes, scopes[0])}
globals_name: make_globals_name(scopes)}

indent()
var head = init_comprehension(comp, scopes)
Expand Down Expand Up @@ -4103,8 +4125,12 @@ $B.ast.UnaryOp.prototype.to_js = function(scopes) {
return -operand + ''
}
}
var method = opclass2dunder[this.op.constructor.$name]
return `$B.$call($B.$getattr($B.get_class(locals.$result = ${operand}), '${method}'), locals.$result)`
var method = opclass2dunder[this.op.constructor.$name],
op_repr = {UAdd: '+', USub: '-', Invert: '~'}[this.op.constructor.$name]
// Use CPython-like slot dispatch: resolve the method on the type with
// the descriptor protocol, so that dunders defined as zero-argument
// staticmethods (as in sympy.core.numbers) are called without arguments.
return `$B.call_special_unary(${operand}, '${method}', 'unary ${op_repr}')`
}

$B.ast.While.prototype.to_js = function(scopes) {
Expand Down
8 changes: 8 additions & 0 deletions www/src/libs/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ array.bf_getbuffer = function(_self, flag) {

array.mp_subscript = function(_self, key) {
if (_self.obj) {
if ($B.is_int(key) && key < 0) {
// Python semantics: negative indices count from the end
key = _self.obj.length + Number(key)
}
if (_self.obj[key] !== undefined) {
return _self.obj[key]
} else if ($B.$isinstance(key, _b_.slice)) {
Expand Down Expand Up @@ -120,6 +124,10 @@ array.bf_release_buffer = function(_self, buffer) {

array.mp_ass_subscript = function(_self, index, value) {
if ($B.is_int(index)) {
if (index < 0) {
// Python semantics: negative indices count from the end
index = _self.obj.length + Number(index)
}
if (_self.obj[index] === undefined) {
$B.RAISE(_b_.IndexError, "array index out of range")
}
Expand Down
4 changes: 3 additions & 1 deletion www/src/libs/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,9 @@ function lcm() {
}
gcd = gcd2(a, b)
product = $B.rich_op('__mul__', a, b)
a = $B.$getattr(product, "__floordiv__")(gcd)
// product may be a JS number (Brython small int) or a long_int:
// use rich_op, which handles both, instead of getattr on the value
a = $B.rich_op('__floordiv__', product, gcd)
}
return a
}
Expand Down
Loading