cython¶
The Cython target, cython, generates the idiomatic API of the Python target
as a module compiled with Cython. It also generates a .pxd that declares
the C API for Cython code. The files are written to <output>/cython:
<prefix>.pyxThe module. Where the prefix is the name of a module of the standard library, such as
zlib, the file is<prefix>_.pyx, as in the Python target.<prefix>.pyiThe stub of the module: the types of its functions, classes and constants, which a type checker cannot read from a compiled module. The stub is formatted by black and imports
disjoint_basefromtyping_extensions.<prefix>.pxd,lib<prefix>.hThe C API for Cython, see The C API for Cython, and the header it declares, as the C target emits it.
<prefix>_check.pyThe check program, not part of the API. It prints a zeroed instance of every record as YAML or JSON.
<prefix>_check.pyxThe check of the
.pxd, not part of the API. It assigns each name that the.pxddeclares to a variable of the type the.pxdgives it.
The check needs Cython in the Python environment of yace, and a C compiler. It runs these steps:
Translate
<prefix>_check.pyxand compile the C with the header. A declaration of the.pxdthat disagrees with the header fails to compile. The type of a bit-field is not checked, as a bit-field has no address.Translate the module and compile it, without linking the library. A wrong conversion of a pointer or an integer is an error.
Run the check program. It imports the module, with the functions of the library resolved only when called, and calls none of them. yace parses the output as YAML and as JSON.
The check does not check the stub. The tests of yace compare the stub with the module using mypy’s stubtest.
The module¶
The module has the same API as the idiomatic layer of the Python target, see
python: the same names, parameters, results and errors. Code
written against one runs against the other, and
Python consumers applies to both. The module has no raw
layer; Cython code calls C through the .pxd. The two modules differ in
these ways:
- Records
A struct or union with fields is an extension type that holds the C struct. A record inside another record, as a field or an element of an array field, is a view of the C memory and keeps the outer record alive. A pointer to a record that the library returns is a view too, and one to a
constrecord a copy, unless the record ends in a flexible array. An array field is amemoryviewof the C memory. An array ofcharisbytes, up to the first NUL. A pointer field is anintaddress, orNonefor NULL. A string set to a field is kept alive by the record that holds the C memory, and by any record it is copied to. A record or array field of a packed record is read as a copy, as its address may be unaligned. The pretty-printers,str()andrepr()are those of the Python target.- Arrays
An array argument is any object with the buffer protocol whose elements match the size and kind of the C type: an
array.array, amemoryview,bytesforuint8_t, or a NumPy array. C reads and writes the buffer without a copy. Any other sequence, such as a list, is copied into anarray.array, and an[in,out]one is copied back. Avoid *@arrparamtakes any buffer, DLPack tensor or CUDA array, as in the Python target. An[out]array is returned as anarray.arrayof the given capacity, truncated to the count written; avoid *one as abytearray. An array of records or of strings is copied. An[out]array of pointers to records is a list of views of the records, which C is given back as the same records, or of copies where the records areconst, as the Python target returns them.- Buffers
Bufferis an extension type, which gives its memory through the buffer protocol as theBufferof the Python target does, and is made by the functions that allocate one only.- Registrations
Registrationis an extension type, which holds a view of the memory it registers, as theRegistrationof the Python target does, and is made by the functions that register memory only.- Handles
A handle is an extension type. Its destructor is called from
__dealloc__when the last reference goes. A handle is made by the API only, not by calling its class.- Pointers
A pointer to a type the module has no class for, such as
void *orFILE *, is anintaddress, orNonefor NULL. A callback without@lifetimeis the address of a C function.- Enumerations
Each enum is made by calling
enum.IntEnum, as a member may have a name Cython reserves, such asDEF.- Names
A name that the
.pxdalso declares, a Python builtin such aslen, or a name Cython reserves such asinclude, is defined under another name and bound to its own name in the module’s globals. A class named as something the.pxddeclares gets a trailing_and is bound to its own name too. A field named as a Python keyword or a name Cython reserves gets a trailing_:class_, orclass__where a fieldclass_exists. Where the module defines a Python name the stub uses, such aslistforfoo_list(), the stub imports that name as_list.
The module is built as a Cython extension, linked against the library. With
meson-python, the pyproject.toml of the package names the build backend:
[build-system]
build-backend = "mesonpy"
requires = ["meson-python", "Cython"]
[project]
name = "foo"
version = "1.0.0"
The meson.build beside it builds the module, finds the library through its
pkg-config file, and installs the stub, the .pxd and the header beside the
module, so type checkers find the types and Cython code can cimport the C API:
project('foo', 'c', 'cython')
py = import('python').find_installation(pure: false)
foo = dependency('foo')
py.extension_module(
'foo',
'output/cython/foo.pyx',
dependencies: foo,
include_directories: 'output/cython',
install: true,
)
py.install_sources(
'output/cython/foo.pyi',
'output/cython/foo.pxd',
'output/cython/libfoo.h',
)
pip install . builds and installs the package, and python -m build
makes its sdist and wheel.
The module is not built for the limited API of Python, which would let one
build run on every CPython from 3.12. Under the limited API of 3.12, every
change of a reference count and every conversion of an integer is a function
call into Python. Built for it, cython-idiomatic in the table under
Performance takes 84.0 ns per point for calls and
111.8 ns with a callback.
The C API for Cython¶
<prefix>.pxd declares the C API, its records, enums, defines and functions,
in a cdef extern block of lib<prefix>.h. The block is nogil, so
Cython code can call the functions without the GIL:
cimport foo as lib
def count(int times):
cdef lib.foo_handle *handle = NULL
if lib.foo_open(b"loop", &handle):
raise OSError("foo_open() failed")
...
The .pxd has the name of the module and sits beside it, so cimport foo
finds the declarations and import foo the module. Cimporting it under
another name, such as lib, also works for a prefix that Cython reserves,
such as api.
The names are those of the C API, except for three kinds: names Cython
reserves, such as include; Python builtins, such as len, which would
hide the builtin from the module; and tags of records and enums that share a
name with a function, define, enum member or typedef, which C keeps apart and
Cython does not. These are declared with a trailing _ and their C name:
int include_ "include"(int cdef_). A flexible array member is left out, as
Cython has none, and a comment says so.
An extension that uses the .pxd is built with <output>/cython on the
include path of both Cython and the C compiler, and linked against the
library. meson does not pass include_directories to Cython, so the
meson.build gives Cython the path too:
py.extension_module(
'loop',
'loop.pyx',
dependencies: foo,
include_directories: 'output/cython',
cython_args: ['-I', meson.current_source_dir() / 'output/cython'],
install: true,
)
examples/libfoo/checks/cython builds check.pyx, which calls libfoo
this way.
Performance¶
Benchmark measures calls of libfoo from every target against C. On a Ryzen 7 7840U under WSL2, summing the 8 points of libfoo 200000 times, best of 5 runs, in nanoseconds per point:
target |
calls |
callback |
|---|---|---|
|
1.9 |
2.1 |
|
384.9 |
204.2 |
|
580.3 |
412.4 |
|
1.3 |
1.5 |
|
56.9 |
84.5 |
cython-idiomatic runs the Python loops of python-idiomatic against the
module of this target. cython-raw is a loop in Cython that calls C through
the .pxd.
Example¶
yace output/foo.yaml --emit cython --output output
output/cython
├── check.json
├── check.yaml
├── cython.log
├── foo.c
├── foo.cpython-312-x86_64-linux-gnu.so
├── foo.pxd
├── foo.pyi
├── foo.pyx
├── foo_check.py
├── foo_check.pyx
├── libfoo.h
└── pxd_check.c
1 directory, 12 files
examples/libfoo/checks/python/idiomatic.py, the check of the idiomatic
layer of the Python target, also runs against the module.
Bindings¶
# cython: language_level=3, binding=True, auto_pickle=False, autotestdict=False
"""
libfoo
Bindings of the C API, compiled with Cython: records as extension types
holding the C struct, arrays as buffers, and handles releasing the C handle
when the last reference goes. The C API itself is foo.pxd, which
Cython code cimports.
Generated by yace from foo.h; do not edit.
"""
#
# SPDX-License-Identifier: GPL-2.0-only
cimport cython
from cpython.buffer cimport (
PyBUF_C_CONTIGUOUS,
PyBUF_FORMAT,
PyBUF_ND,
PyBUF_SIMPLE,
PyBUF_STRIDES,
PyBUF_WRITABLE,
PyBuffer_FillInfo,
PyBuffer_Release,
PyObject_CheckBuffer,
PyObject_GetBuffer,
)
from cpython.object cimport PyObject_Length
from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid
from libc.stdint cimport (
int32_t,
int64_t,
uint8_t,
uint16_t,
uint32_t,
uint64_t,
uintptr_t,
)
from libc.stdlib cimport calloc, free
from libc.string cimport memcpy, memset
import array as _array
import builtins as _builtins
import enum
import itertools as _itertools
import json as _json
import os as _os
import sys as _sys
cdef object _str_in(object value):
"""Return 'value' encoded where it is a str, for a 'const char *' parameter"""
return value.encode() if isinstance(value, str) else value
cdef object _str_out(const char *value):
return None if value == NULL else (<bytes>value).decode(errors="replace")
cdef const char *_cstr(object value) except? NULL:
"""Return the pointer to the bytes 'value', or NULL for None"""
if value is None:
return NULL
return <const char *>value
cdef object _addr(uintptr_t value):
"""Return the address 'value' of a pointer, or None for NULL"""
return None if value == 0 else value
cdef inline Py_ssize_t _bound(Py_ssize_t count, Py_ssize_t capacity):
"""Return 'count', the number of elements written, limited to the range
from 0 to 'capacity'"""
return 0 if count < 0 else (capacity if count > capacity else count)
cdef void *_calloc(Py_ssize_t count, size_t size) except NULL:
cdef void *made = calloc(count if count > 0 else 1, size)
if made == NULL:
raise MemoryError()
return made
# The struct formats accepted for each kind of element: signed, unsigned,
# floating, bool, enum, pointer. _acquire() also accepts any one-byte format.
_FORMATS = {
b"i": b"bhilqn",
b"u": b"BHILQN",
b"f": b"fd",
b"b": b"?",
b"e": b"bhilqnBHILQN",
b"p": b"PBHILQN",
}
_CODES = {b"i": "bhilq", b"u": "BHILQ", b"f": "fd", b"b": "B", b"e": "bhilq", b"p": "BHILQ"}
def _code(kind, itemsize):
"""Return the array.array type code for elements of 'kind' and 'itemsize'
bytes"""
for code in _CODES[kind]:
if _array.array(code).itemsize == itemsize:
return code
raise TypeError(f"no array.array of elements of {itemsize} bytes")
cdef object _zeroed(bytes kind, Py_ssize_t itemsize, object count):
"""Return an array.array of 'count' zeroed elements. 'count' is a Python
int, so that computing the size in bytes cannot overflow."""
made = _array.array(_code(kind, itemsize))
made.frombytes(bytes(itemsize * (count if count > 0 else 0)))
return made
# DLPack: the tensor of a capsule named "dltensor" or "dltensor_versioned"
cdef struct _DLDevice:
int32_t device_type
int32_t device_id
cdef struct _DLDataType:
uint8_t code
uint8_t bits
uint16_t lanes
cdef struct _DLTensor:
void *data
_DLDevice device
int32_t ndim
_DLDataType dtype
int64_t *shape
int64_t *strides
uint64_t byte_offset
cdef struct _DLManagedTensor:
_DLTensor dl_tensor
void *manager_ctx
void *deleter
cdef struct _DLManagedTensorVersioned:
uint32_t version[2]
void *manager_ctx
void *deleter
uint64_t flags
_DLTensor dl_tensor
cdef object _compact(object shape, object strides, Py_ssize_t itemsize):
"""The size in bytes of an array of 'shape' laid out by 'strides', in
elements, or by rows where 'strides' is None; ValueError where the array is
not one contiguous range of memory in row order"""
nbytes = itemsize
for extent in shape:
nbytes *= extent
if strides is not None and nbytes:
expected = 1
for extent, stride in zip(reversed(shape), reversed(strides)):
if extent != 1 and stride != expected:
raise ValueError("the array is not contiguous")
expected *= extent
return nbytes
cdef class _Device:
"""The memory of a DLPack tensor or a CUDA array, which may be a device's,
through the buffer protocol: for passing its address to C, not for
reading"""
cdef uintptr_t address
cdef Py_ssize_t nbytes
cdef bint readonly
cdef object keep
def __getbuffer__(self, Py_buffer *view, int flags):
PyBuffer_FillInfo(view, self, <void *>self.address, self.nbytes, self.readonly, flags)
cdef _Device _device(object obj):
"""The memory of 'obj', a DLPack tensor or a CUDA array, held by the
capsule of the tensor, which is not consumed, or by the array"""
cdef _Device made = _Device.__new__(_Device)
cdef _DLTensor *tensor
cdef _DLManagedTensorVersioned *versioned
if hasattr(obj, "__dlpack__"):
try:
capsule = obj.__dlpack__(max_version=(1, 0))
except TypeError:
capsule = obj.__dlpack__()
if PyCapsule_IsValid(capsule, "dltensor_versioned"):
versioned = <_DLManagedTensorVersioned *>PyCapsule_GetPointer(
capsule, "dltensor_versioned"
)
tensor = &versioned.dl_tensor
made.readonly = versioned.flags & 1
else:
tensor = &(<_DLManagedTensor *>PyCapsule_GetPointer(capsule, "dltensor")).dl_tensor
shape = [tensor.shape[i] for i in range(tensor.ndim)]
strides = None
if tensor.strides != NULL:
strides = [tensor.strides[i] for i in range(tensor.ndim)]
itemsize = (tensor.dtype.bits * tensor.dtype.lanes + 7) // 8
made.nbytes = _compact(shape, strides, itemsize)
made.address = <uintptr_t>tensor.data + tensor.byte_offset
made.keep = capsule
return made
interface = obj.__cuda_array_interface__
address, readonly = interface["data"]
itemsize = int(interface["typestr"][2:])
strides = interface.get("strides")
if strides is not None:
if any(stride % itemsize for stride in strides):
raise ValueError("the array is not contiguous")
strides = [stride // itemsize for stride in strides]
made.nbytes = _compact(interface["shape"], strides, itemsize)
made.address = address
made.readonly = readonly
made.keep = obj
return made
cdef object _acquire(
object obj, Py_buffer *view, bytes kind, Py_ssize_t itemsize, bint writable
):
"""Get the buffer of 'obj' into 'view' and return the object whose buffer
'view' holds. The buffer must have elements of 'kind' and 'itemsize' bytes;
kind 'v' accepts any bytes, and the memory of a DLPack tensor or a CUDA
array. An object that is not a buffer, such as a list, is copied into an
array.array, or into bytes for kind 'v', and the copy is returned. Kind
'v' with 'writable' raises a TypeError for such an object."""
cdef int flags = PyBUF_C_CONTIGUOUS | (PyBUF_WRITABLE if writable else 0)
made = False
if not PyObject_CheckBuffer(obj) and kind == b"v" and (
hasattr(obj, "__dlpack__") or hasattr(obj, "__cuda_array_interface__")
):
obj = _device(obj)
if not PyObject_CheckBuffer(obj):
if kind == b"v" and writable:
raise TypeError(f"expected a writable buffer, not {type(obj).__name__}")
obj = bytes(obj) if kind == b"v" else _array.array(_code(kind, itemsize), obj)
made = True
if kind == b"v":
PyObject_GetBuffer(obj, view, flags)
return obj
PyObject_GetBuffer(obj, view, flags | PyBUF_FORMAT)
fmt = b"B" if view.format == NULL else <bytes>view.format
if fmt[:1] in (b"@", b"="):
fmt = fmt[1:]
if view.itemsize == itemsize and (
made or (len(fmt) == 1 and (fmt in _FORMATS[kind] or (itemsize == 1 and fmt in b"bBc")))
):
return obj
PyBuffer_Release(view)
raise TypeError(
f"expected a buffer of elements of {itemsize} bytes, of format"
f" {_FORMATS[kind].decode()!r}, not of {view.itemsize}, of format {fmt.decode()!r}"
)
cdef class _Records:
"""A contiguous copy of a sequence of records, which C takes as an array"""
cdef char *buf
cdef Py_ssize_t n
cdef Py_ssize_t size
cdef list items
def __dealloc__(self):
free(self.buf)
cdef write_back(self):
"""Copy the array, which C wrote, back into the records"""
cdef Py_ssize_t i
for i in range(self.n):
memcpy((<_Record>self.items[i])._yace_vp, self.buf + i * self.size, self.size)
cdef _Records _records(object seq, type cls, Py_ssize_t size):
cdef _Records made = _Records.__new__(_Records)
cdef Py_ssize_t i
if seq is None:
return made
made.items = list(seq)
made.n = len(made.items)
made.size = size
made.buf = <char *>_calloc(made.n, size)
for i in range(made.n):
item = made.items[i]
if not isinstance(item, cls):
raise TypeError(f"expected {cls.__name__}, not {type(item).__name__}")
memcpy(made.buf + i * size, (<_Record>item)._yace_vp, size)
return made
cdef class _Strings:
"""The encoded strings of a sequence and an array of pointers to them,
which C takes as an array of strings"""
cdef const char **ptrs
cdef Py_ssize_t n
cdef list kept
def __dealloc__(self):
free(self.ptrs)
cdef _Strings _strings(object seq):
cdef _Strings made = _Strings.__new__(_Strings)
cdef Py_ssize_t i
if seq is None:
return made
made.kept = [_str_in(item) for item in seq]
made.n = len(made.kept)
made.ptrs = <const char **>_calloc(made.n, sizeof(char *))
for i in range(made.n):
made.ptrs[i] = <const char *>made.kept[i]
return made
cdef class _Memory:
"""A buffer over an array field of a record. The buffer keeps the record
alive."""
cdef void *buf
cdef object owner
cdef const char *format
cdef Py_ssize_t itemsize
cdef Py_ssize_t length
cdef int ndim
cdef Py_ssize_t shape[8]
cdef Py_ssize_t strides[8]
def __getbuffer__(self, Py_buffer *view, int flags):
view.buf = self.buf
view.obj = self
view.len = self.length
view.readonly = 0
view.itemsize = self.itemsize
view.format = <char *>self.format if flags & PyBUF_FORMAT else NULL
view.ndim = self.ndim
view.shape = self.shape if flags & PyBUF_ND else NULL
view.strides = self.strides if flags & PyBUF_STRIDES else NULL
view.suboffsets = NULL
view.internal = NULL
def __releasebuffer__(self, Py_buffer *view):
pass
cdef object _memory(object owner, void *buf, const char *fmt, Py_ssize_t itemsize, tuple shape):
cdef _Memory made = _Memory.__new__(_Memory)
cdef int i
made.buf = buf
made.owner = owner
made.format = fmt
made.itemsize = itemsize
made.ndim = len(shape)
made.length = itemsize
for i in range(made.ndim):
made.shape[i] = shape[i]
made.length *= shape[i]
made.strides[made.ndim - 1] = itemsize
for i in range(made.ndim - 2, -1, -1):
made.strides[i] = made.strides[i + 1] * made.shape[i + 1]
return memoryview(made)
cdef _check_length(object value, Py_ssize_t length):
if len(value) != length:
raise ValueError(f"expected {length} elements, not {len(value)}")
cdef _set_items(object view, object value):
"""Write the nested sequence 'value', which must have the shape of 'view',
to the array 'view'. The items are written through a one-dimensional cast,
because a multi-dimensional memoryview does not support assigning a
sub-view."""
items = [value]
for length in view.shape:
nested = []
for item in items:
_check_length(item, length)
nested.extend(item)
items = nested
flat = view.cast("B").cast(view.format)
for i, item in enumerate(items):
flat[i] = item
cdef object _chars(const char *value, Py_ssize_t length):
"""Return the bytes of the char array 'value' of 'length', up to its first
NUL"""
cdef Py_ssize_t i = 0
while i < length and value[i] != 0:
i += 1
return value[:i]
cdef _set_chars(char *dest, Py_ssize_t length, object value):
value = _str_in(value)
cdef const char *src = value # raises TypeError before the field is cleared
if len(value) > length:
raise ValueError(f"bytes too long ({len(value)}, maximum length {length})")
memset(dest, 0, length)
memcpy(dest, src, len(value))
cdef char _char_in(object value) except? -1:
if isinstance(value, (bytes, bytearray)):
if len(value) != 1:
raise ValueError(f"expected one byte, not {len(value)}")
value = value[0]
return <char><unsigned char>value
def _plain(value, kind=None):
"""Return 'value', of a field printed as 'kind', as the plain value that
the pretty-printers print"""
if isinstance(value, _Record):
return _Record.to_dict(value)
if isinstance(value, bytes):
if kind == "char":
return value[0]
return value.split(b"\0", 1)[0].decode(errors="replace")
if isinstance(value, memoryview):
value = value.tolist()
if isinstance(value, (list, tuple)):
return [_plain(item, kind) for item in value]
if kind == "pointer":
return None if not value else f"0x{value:x}"
if isinstance(value, float):
return float(format(value, "g"))
return value
class _Bits(dict):
"""The value of a field of bits and its parts by name. _yaml() prints a
_Bits on one line."""
def _yaml(data, indent):
lines = []
for key, value in data.items():
if isinstance(value, _Bits):
parts = ", ".join(f"{name}: {part:#x}" for name, part in value.items())
lines.append(f"{'':{indent}}{key}: " + "{" + parts + "}\n")
elif isinstance(value, dict):
lines.append(f"{'':{indent}}{key}:\n{_yaml(value, indent + 2)}")
else:
lines.append(f"{'':{indent}}{key}: {_json.dumps(value)}\n")
return "".join(lines)
class FooPr(enum.IntFlag):
"""Output formats of the pretty-printers"""
FOO_PR_DEF = 0x0 #: The default, YAML
FOO_PR_YAML = 0x1 #: YAML
FOO_PR_TERSE = 0x2 #: Terse; the generated printers print YAML
FOO_PR_JSON = 0x4 #: JSON, on one line
globals().update({
"FOO_PR_DEF": FooPr.FOO_PR_DEF,
"FOO_PR_YAML": FooPr.FOO_PR_YAML,
"FOO_PR_TERSE": FooPr.FOO_PR_TERSE,
"FOO_PR_JSON": FooPr.FOO_PR_JSON,
})
def _repr(value, enum=None):
"""Return the text that __repr__() shows for the field value 'value': an
array as a list, and a value that is a member of 'enum' by the name of the
member"""
if isinstance(value, memoryview):
value = value.tolist()
if isinstance(value, (list, tuple)):
return "[" + ", ".join(_repr(item, enum) for item in value) + "]"
if enum is not None:
try:
return f"{enum.__name__}.{enum(value).name}"
except ValueError:
pass
return repr(value)
cdef class _Record:
"""The pretty-printers of a struct or union. The module calls them through
_Record, because a field named as a printer hides the printer on its class."""
cdef void *_yace_vp # the C record
cdef object _yace_owner # of a view: the object that holds the C record
cdef dict _yace_kept # what the pointers point to, by address and size
_yace_name = ""
_yace_fields = () # the C name of each field, and its attribute
_yace_kinds = {} # how a field is printed where its value does not say
_yace_masks = {} # the parts of each field of bits: name, mask and shift
_yace_enums = {} # the enum of each field typed as one
cdef _Record _yace_root(self):
"""The record holding the C memory that this record is a view of"""
cdef _Record root = self
while isinstance(root._yace_owner, _Record):
root = <_Record>root._yace_owner
return root
cdef _yace_keep(self, void *at, size_t size, object value):
"""Keep 'value' for the 'size' bytes at 'at', in place of what was kept
for them, for as long as the record holding the C memory. None keeps
nothing."""
cdef _Record root = self._yace_root()
cdef uintptr_t lo = <uintptr_t>at
if root._yace_kept is None:
if value is None:
return
root._yace_kept = {}
for key in [k for k in root._yace_kept if lo <= k[0] and k[0] + k[1] <= lo + size]:
del root._yace_kept[key]
if value is not None:
root._yace_kept[(lo, size)] = value
cdef object _yace_held(self, void *at, size_t size):
"""Return a tuple of what is kept for the 'size' bytes at 'at', or None"""
cdef _Record root = self._yace_root()
cdef uintptr_t lo = <uintptr_t>at
if not root._yace_kept:
return None
found = [v for k, v in root._yace_kept.items() if k[0] < lo + size and lo < k[0] + k[1]]
return tuple(found) or None
cdef _yace_adopt(self, void *at, _Record src, void *src_at, size_t size):
"""Keep, for the 'size' bytes at 'at', what 'src' keeps for the 'size'
bytes at 'src_at'. The bytes at 'at' were copied from 'src_at'."""
self._yace_keep(at, size, src._yace_held(src_at, size))
def to_dict(self):
"""The fields, by name, as plain values: pointers as hex strings, a
field of bits as its value and its parts"""
cls = type(self)
found = {}
for name, attr in cls._yace_fields:
value = _plain(getattr(self, attr), cls._yace_kinds.get(name))
if name in cls._yace_masks:
value = _Bits(
{"val": value},
**{part: (value & mask) >> lo for part, mask, lo in cls._yace_masks[name]},
)
found[name] = value
return found
@classmethod
def fpr(cls, stream, obj, flags=FooPr.FOO_PR_DEF):
"""Print 'obj', a record or None, to 'stream'
Returns:
The number of characters written
"""
if flags & FooPr.FOO_PR_JSON:
text = _json.dumps(None if obj is None else _Record.to_dict(obj)) + "\n"
elif obj is None:
text = f"{cls._yace_name}: ~\n"
else:
text = f"{cls._yace_name}:\n{_yaml(_Record.to_dict(obj), 2)}"
stream.write(text)
return len(text)
@classmethod
def pr(cls, obj, flags=FooPr.FOO_PR_DEF):
"""Print 'obj' to stdout, as fpr()"""
return _Record.fpr.__func__(cls, _sys.stdout, obj, flags)
def __str__(self):
return f"{self._yace_name}:\n{_yaml(_Record.to_dict(self), 2)}"
def __repr__(self):
"""Return the record as a call of its constructor, with each field by
name. A union shows every member, because the member in use is not
known."""
cls = type(self)
fields = []
for name, attr in cls._yace_fields:
value = getattr(self, attr)
fields.append(f"{attr}={_repr(value, cls._yace_enums.get(name))}")
return f"{cls.__name__}({', '.join(fields)})"
_KEPT = {} # the closures kept, by the key given to C as their context
_KEYS = _itertools.count(1)
cdef object _key():
return next(_KEYS)
def _check(ret, *partial):
"""Raise an OSError where 'ret' is a negative errno. With 'partial', the
OSError holds that value as 'partial': what the call wrote before it
failed."""
if ret < 0:
error = OSError(-ret, _str_out(foo_errmsg()) or _os.strerror(-ret))
if partial:
error.partial = partial[0]
raise error
globals().update({
"FOO_NAME": "foo", #: Name of the library
"FOO_MAGIC": 0xacdc, #: A hexadecimal constant
"FOO_VERSION_MAJOR": 1, #: Major version
"FOO_VERSION_MINOR": 2, #: Minor version
"FOO_VERSION_PATCH": 3, #: Patch version
"FOO_POINTS_MAX": 8, #: Points a handle holds at most
"FOO_DEFAULT_SHAPE_SIDES": 8, #: A constant, by name
"FOO_STATUS_CODE_PENDING": 0x1, #: A count is submitted and not yet completed; bit 0 of 'code'
"FOO_STATUS_CODE_POINTS": 0xff0, #: Points held; bits 11:4 of 'code'
"FOO_STATUS_CODE_FULL": 0x8000, #: The handle holds FOO_POINTS_MAX points; bit 15 of 'code'
})
# Made by calling IntEnum, because a member may have a name that Cython reserves
FooShape = enum.IntEnum(
"FooShape",
[
("FOO_SHAPE_NONE", -1), #: No figure
("FOO_SHAPE_POINT", 0), #: A single point
("FOO_SHAPE_LINE", 1), #: Two points
("FOO_SHAPE_POLYGON", 2), #: Three points or more
],
module=__name__,
)
FooShape.__doc__ = """Kinds of figure"""
globals().update({
"FOO_SHAPE_NONE": FooShape["FOO_SHAPE_NONE"],
"FOO_SHAPE_POINT": FooShape["FOO_SHAPE_POINT"],
"FOO_SHAPE_LINE": FooShape["FOO_SHAPE_LINE"],
"FOO_SHAPE_POLYGON": FooShape["FOO_SHAPE_POLYGON"],
})
# Made by calling IntEnum, because a member may have a name that Cython reserves
FooOption = enum.IntEnum(
"FooOption",
[
("FOO_OPTION_CLOSED", 1), #: The last corner connects to the first
("FOO_OPTION_FILLED", 2), #: The inside is filled
],
module=__name__,
)
FooOption.__doc__ = """Options of a figure, combined as bits"""
globals().update({
"FOO_OPTION_CLOSED": FooOption["FOO_OPTION_CLOSED"],
"FOO_OPTION_FILLED": FooOption["FOO_OPTION_FILLED"],
})
cdef class FooPoint(_Record):
"""A point on the plane
Attributes:
x: Horizontal position
y: Vertical position
"""
_yace_name = "foo_point"
_yace_fields = (("x", "x"), ("y", "y"))
cdef foo_point *_yace_p
cdef foo_point _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, x=None, y=None):
if x is not None:
self.x = x
if y is not None:
self.y = y
@staticmethod
cdef FooPoint _view(foo_point *ptr, object owner):
cdef FooPoint made = FooPoint.__new__(FooPoint)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooPoint _copy(foo_point value):
cdef FooPoint made = FooPoint.__new__(FooPoint)
made._yace_c = value
return made
@property
def x(self):
"""Horizontal position"""
return self._yace_p.x
@x.setter
def x(self, value):
self._yace_p.x = value
@property
def y(self):
"""Vertical position"""
return self._yace_p.y
@y.setter
def y(self, value):
self._yace_p.y = value
cdef class FooVisitor(_Record):
"""A callback and its argument
Attributes:
visit: Called for each point
arg: Given to 'visit'
"""
_yace_name = "foo_visitor"
_yace_fields = (("visit", "visit"), ("arg", "arg"))
_yace_kinds = {'visit': 'pointer', 'arg': 'pointer'}
cdef foo_visitor *_yace_p
cdef foo_visitor _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, visit=None, arg=None):
if visit is not None:
self.visit = visit
if arg is not None:
self.arg = arg
@staticmethod
cdef FooVisitor _view(foo_visitor *ptr, object owner):
cdef FooVisitor made = FooVisitor.__new__(FooVisitor)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooVisitor _copy(foo_visitor value):
cdef FooVisitor made = FooVisitor.__new__(FooVisitor)
made._yace_c = value
return made
@property
def visit(self):
"""Called for each point"""
return _addr(<uintptr_t>self._yace_p.visit)
@visit.setter
def visit(self, value):
self._yace_p.visit = <foo_visit_cb><uintptr_t>(value or 0)
@property
def arg(self):
"""Given to 'visit'"""
return _addr(<uintptr_t>self._yace_p.arg)
@arg.setter
def arg(self, value):
self._yace_p.arg = <void *><uintptr_t>(value or 0)
cdef class FooScalars(_Record):
"""A value of every kind of scalar
Attributes:
flag: bool
letter: char
schar: signed char
uchar: unsigned char
s: short
us: unsigned short
i: int
ui: unsigned int
l: long
ul: unsigned long
ll: long long
ull: unsigned long long
f: float
d: double
i8: int8_t
i16: int16_t
i32: int32_t
i64: int64_t
u8: uint8_t
u16: uint16_t
u32: uint32_t
u64: uint64_t
iptr: intptr_t
uptr: uintptr_t
size: size_t
ssize: ssize_t
diff: ptrdiff_t
"""
_yace_name = "foo_scalars"
_yace_fields = (("flag", "flag"), ("letter", "letter"), ("schar", "schar"), ("uchar", "uchar"), ("s", "s"), ("us", "us"), ("i", "i"), ("ui", "ui"), ("l", "l"), ("ul", "ul"), ("ll", "ll"), ("ull", "ull"), ("f", "f"), ("d", "d"), ("i8", "i8"), ("i16", "i16"), ("i32", "i32"), ("i64", "i64"), ("u8", "u8"), ("u16", "u16"), ("u32", "u32"), ("u64", "u64"), ("iptr", "iptr"), ("uptr", "uptr"), ("size", "size"), ("ssize", "ssize"), ("diff", "diff"))
_yace_kinds = {'letter': 'char'}
cdef foo_scalars *_yace_p
cdef foo_scalars _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, flag=None, letter=None, schar=None, uchar=None, s=None, us=None, i=None, ui=None, l=None, ul=None, ll=None, ull=None, f=None, d=None, i8=None, i16=None, i32=None, i64=None, u8=None, u16=None, u32=None, u64=None, iptr=None, uptr=None, size=None, ssize=None, diff=None):
if flag is not None:
self.flag = flag
if letter is not None:
self.letter = letter
if schar is not None:
self.schar = schar
if uchar is not None:
self.uchar = uchar
if s is not None:
self.s = s
if us is not None:
self.us = us
if i is not None:
self.i = i
if ui is not None:
self.ui = ui
if l is not None:
self.l = l
if ul is not None:
self.ul = ul
if ll is not None:
self.ll = ll
if ull is not None:
self.ull = ull
if f is not None:
self.f = f
if d is not None:
self.d = d
if i8 is not None:
self.i8 = i8
if i16 is not None:
self.i16 = i16
if i32 is not None:
self.i32 = i32
if i64 is not None:
self.i64 = i64
if u8 is not None:
self.u8 = u8
if u16 is not None:
self.u16 = u16
if u32 is not None:
self.u32 = u32
if u64 is not None:
self.u64 = u64
if iptr is not None:
self.iptr = iptr
if uptr is not None:
self.uptr = uptr
if size is not None:
self.size = size
if ssize is not None:
self.ssize = ssize
if diff is not None:
self.diff = diff
@staticmethod
cdef FooScalars _view(foo_scalars *ptr, object owner):
cdef FooScalars made = FooScalars.__new__(FooScalars)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooScalars _copy(foo_scalars value):
cdef FooScalars made = FooScalars.__new__(FooScalars)
made._yace_c = value
return made
@property
def flag(self):
"""bool"""
return self._yace_p.flag
@flag.setter
def flag(self, value):
self._yace_p.flag = value
@property
def letter(self):
"""char"""
return bytes([<unsigned char>self._yace_p.letter])
@letter.setter
def letter(self, value):
self._yace_p.letter = _char_in(value)
@property
def schar(self):
"""signed char"""
return self._yace_p.schar
@schar.setter
def schar(self, value):
self._yace_p.schar = value
@property
def uchar(self):
"""unsigned char"""
return self._yace_p.uchar
@uchar.setter
def uchar(self, value):
self._yace_p.uchar = value
@property
def s(self):
"""short"""
return self._yace_p.s
@s.setter
def s(self, value):
self._yace_p.s = value
@property
def us(self):
"""unsigned short"""
return self._yace_p.us
@us.setter
def us(self, value):
self._yace_p.us = value
@property
def i(self):
"""int"""
return self._yace_p.i
@i.setter
def i(self, value):
self._yace_p.i = value
@property
def ui(self):
"""unsigned int"""
return self._yace_p.ui
@ui.setter
def ui(self, value):
self._yace_p.ui = value
@property
def l(self):
"""long"""
return self._yace_p.l
@l.setter
def l(self, value):
self._yace_p.l = value
@property
def ul(self):
"""unsigned long"""
return self._yace_p.ul
@ul.setter
def ul(self, value):
self._yace_p.ul = value
@property
def ll(self):
"""long long"""
return self._yace_p.ll
@ll.setter
def ll(self, value):
self._yace_p.ll = value
@property
def ull(self):
"""unsigned long long"""
return self._yace_p.ull
@ull.setter
def ull(self, value):
self._yace_p.ull = value
@property
def f(self):
"""float"""
return self._yace_p.f
@f.setter
def f(self, value):
self._yace_p.f = value
@property
def d(self):
"""double"""
return self._yace_p.d
@d.setter
def d(self, value):
self._yace_p.d = value
@property
def i8(self):
"""int8_t"""
return self._yace_p.i8
@i8.setter
def i8(self, value):
self._yace_p.i8 = value
@property
def i16(self):
"""int16_t"""
return self._yace_p.i16
@i16.setter
def i16(self, value):
self._yace_p.i16 = value
@property
def i32(self):
"""int32_t"""
return self._yace_p.i32
@i32.setter
def i32(self, value):
self._yace_p.i32 = value
@property
def i64(self):
"""int64_t"""
return self._yace_p.i64
@i64.setter
def i64(self, value):
self._yace_p.i64 = value
@property
def u8(self):
"""uint8_t"""
return self._yace_p.u8
@u8.setter
def u8(self, value):
self._yace_p.u8 = value
@property
def u16(self):
"""uint16_t"""
return self._yace_p.u16
@u16.setter
def u16(self, value):
self._yace_p.u16 = value
@property
def u32(self):
"""uint32_t"""
return self._yace_p.u32
@u32.setter
def u32(self, value):
self._yace_p.u32 = value
@property
def u64(self):
"""uint64_t"""
return self._yace_p.u64
@u64.setter
def u64(self, value):
self._yace_p.u64 = value
@property
def iptr(self):
"""intptr_t"""
return self._yace_p.iptr
@iptr.setter
def iptr(self, value):
self._yace_p.iptr = value
@property
def uptr(self):
"""uintptr_t"""
return self._yace_p.uptr
@uptr.setter
def uptr(self, value):
self._yace_p.uptr = value
@property
def size(self):
"""size_t"""
return self._yace_p.size
@size.setter
def size(self, value):
self._yace_p.size = value
@property
def ssize(self):
"""ssize_t"""
return self._yace_p.ssize
@ssize.setter
def ssize(self, value):
self._yace_p.ssize = value
@property
def diff(self):
"""ptrdiff_t"""
return self._yace_p.diff
@diff.setter
def diff(self, value):
self._yace_p.diff = value
cdef class FooFigure(_Record):
"""A figure: its kind, where it is, and its corners
Attributes:
shape: One of enum foo_shape
options: Bits of enum foo_option
origin: Where the figure is
corners: The corners, relative to 'origin'
ncorners: How many of 'corners' are used
name: Name of the figure
grid: A two-dimensional array
label: A string, NULL when there is none
scale: Scale of the figure
area: Area of the figure
"""
_yace_name = "foo_figure"
_yace_fields = (("shape", "shape"), ("options", "options"), ("origin", "origin"), ("corners", "corners"), ("ncorners", "ncorners"), ("name", "name"), ("grid", "grid"), ("label", "label"), ("scale", "scale"), ("area", "area"))
cdef foo_figure *_yace_p
cdef foo_figure _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, shape=None, options=None, origin=None, corners=None, ncorners=None, name=None, grid=None, label=None, scale=None, area=None):
if shape is not None:
self.shape = shape
if options is not None:
self.options = options
if origin is not None:
self.origin = origin
if corners is not None:
self.corners = corners
if ncorners is not None:
self.ncorners = ncorners
if name is not None:
self.name = name
if grid is not None:
self.grid = grid
if label is not None:
self.label = label
if scale is not None:
self.scale = scale
if area is not None:
self.area = area
@staticmethod
cdef FooFigure _view(foo_figure *ptr, object owner):
cdef FooFigure made = FooFigure.__new__(FooFigure)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooFigure _copy(foo_figure value):
cdef FooFigure made = FooFigure.__new__(FooFigure)
made._yace_c = value
return made
@property
def shape(self):
"""One of enum foo_shape"""
return self._yace_p.shape
@shape.setter
def shape(self, value):
self._yace_p.shape = value
@property
def options(self):
"""Bits of enum foo_option"""
return self._yace_p.options
@options.setter
def options(self, value):
self._yace_p.options = value
@property
def origin(self):
"""Where the figure is"""
return FooPoint._view(&self._yace_p.origin, self)
@origin.setter
def origin(self, value):
self._yace_p.origin = (<FooPoint?>value)._yace_p[0]
@property
def corners(self):
"""The corners, relative to 'origin'"""
cdef Py_ssize_t i
return tuple([FooPoint._view(&self._yace_p.corners[i], self) for i in range(4)])
@corners.setter
def corners(self, value):
cdef Py_ssize_t i
_check_length(value, 4)
for i, item in enumerate(value):
self._yace_p.corners[i] = (<FooPoint?>item)._yace_p[0]
@property
def ncorners(self):
"""How many of 'corners' are used"""
return self._yace_p.ncorners
@ncorners.setter
def ncorners(self, value):
self._yace_p.ncorners = value
@property
def name(self):
"""Name of the figure"""
return _chars(<const char *>self._yace_p.name, 16)
@name.setter
def name(self, value):
_set_chars(<char *>self._yace_p.name, 16, value)
@property
def grid(self):
"""A two-dimensional array"""
return _memory(self, <void *>self._yace_p.grid, b"h", sizeof(int16_t), (2, 3,))
@grid.setter
def grid(self, value):
_set_items(self.grid, value)
@property
def label(self):
"""A string, NULL when there is none"""
return _str_out(self._yace_p.label)
@label.setter
def label(self, value):
value = _str_in(value)
cdef const char *made = _cstr(value)
self._yace_keep(&self._yace_p.label, sizeof(self._yace_p.label), value)
self._yace_p.label = <const char *>made
@property
def scale(self):
"""Scale of the figure"""
return self._yace_p.scale
@scale.setter
def scale(self, value):
self._yace_p.scale = value
@property
def area(self):
"""Area of the figure"""
return self._yace_p.area
@area.setter
def area(self, value):
self._yace_p.area = value
cdef class FooValue(_Record):
"""A 32-bit value, read as signed, as unsigned, or as the 'x' of a point
Attributes:
i: Signed
u: Unsigned
point: A point, its 'x' sharing the bits of 'i'
"""
_yace_name = "foo_value"
_yace_fields = (("i", "i"), ("u", "u"), ("point", "point"))
cdef foo_value *_yace_p
cdef foo_value _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, i=None, u=None, point=None):
if i is not None:
self.i = i
if u is not None:
self.u = u
if point is not None:
self.point = point
@staticmethod
cdef FooValue _view(foo_value *ptr, object owner):
cdef FooValue made = FooValue.__new__(FooValue)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooValue _copy(foo_value value):
cdef FooValue made = FooValue.__new__(FooValue)
made._yace_c = value
return made
@property
def i(self):
"""Signed"""
return self._yace_p.i
@i.setter
def i(self, value):
self._yace_p.i = value
@property
def u(self):
"""Unsigned"""
return self._yace_p.u
@u.setter
def u(self, value):
self._yace_p.u = value
@property
def point(self):
"""A point, its 'x' sharing the bits of 'i'"""
return FooPoint._view(&self._yace_p.point, self)
@point.setter
def point(self, value):
self._yace_p.point = (<FooPoint?>value)._yace_p[0]
cdef class FooWire(_Record):
"""A record laid out without padding, as a wire format is: no field after the first is aligned
Attributes:
kind: One of enum foo_shape
length: At offset 1
at: A point, at offset 5
pair: An array, at offset 13
"""
_yace_name = "foo_wire"
_yace_fields = (("kind", "kind"), ("length", "length"), ("at", "at"), ("pair", "pair"))
cdef foo_wire *_yace_p
cdef foo_wire _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, kind=None, length=None, at=None, pair=None):
if kind is not None:
self.kind = kind
if length is not None:
self.length = length
if at is not None:
self.at = at
if pair is not None:
self.pair = pair
@staticmethod
cdef FooWire _view(foo_wire *ptr, object owner):
cdef FooWire made = FooWire.__new__(FooWire)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooWire _copy(foo_wire value):
cdef FooWire made = FooWire.__new__(FooWire)
made._yace_c = value
return made
@property
def kind(self):
"""One of enum foo_shape"""
return self._yace_p.kind
@kind.setter
def kind(self, value):
self._yace_p.kind = value
@property
def length(self):
"""At offset 1"""
return self._yace_p.length
@length.setter
def length(self, value):
self._yace_p.length = value
@property
def at(self):
"""A point, at offset 5"""
cdef FooPoint made
made = FooPoint._copy(self._yace_p.at)
return made
@at.setter
def at(self, value):
self._yace_p.at = (<FooPoint?>value)._yace_p[0]
@property
def pair(self):
"""An array, at offset 13"""
cdef Py_ssize_t i
return [self._yace_p.pair[i] for i in range(2)]
@pair.setter
def pair(self, value):
cdef Py_ssize_t i
_check_length(value, 2)
for i, item in enumerate(value):
self._yace_p.pair[i] = item
cdef class FooStatus(_Record):
"""The status of a handle, its code a field of bits
Attributes:
code: Status code, see FOO_STATUS_CODE_*
max: Points the handle holds at most
"""
_yace_name = "foo_status"
_yace_fields = (("code", "code"), ("max", "max"))
_yace_masks = {
"code": (("pending", 0x1, 0), ("points", 0xff0, 4), ("full", 0x8000, 15),),
}
cdef foo_status *_yace_p
cdef foo_status _yace_c
def __cinit__(self, *args, **kwargs):
memset(&self._yace_c, 0, sizeof(self._yace_c))
self._yace_p = &self._yace_c
self._yace_vp = self._yace_p
def __init__(self, code=None, max=None):
if code is not None:
self.code = code
if max is not None:
self.max = max
@staticmethod
cdef FooStatus _view(foo_status *ptr, object owner):
cdef FooStatus made = FooStatus.__new__(FooStatus)
made._yace_p = ptr
made._yace_vp = ptr
made._yace_owner = owner
return made
@staticmethod
cdef FooStatus _copy(foo_status value):
cdef FooStatus made = FooStatus.__new__(FooStatus)
made._yace_c = value
return made
@property
def code(self):
"""Status code, see FOO_STATUS_CODE_*"""
return self._yace_p.code
@code.setter
def code(self, value):
self._yace_p.code = value
@property
def max(self):
"""Points the handle holds at most"""
return self._yace_p.max
@max.setter
def max(self, value):
self._yace_p.max = value
@property
def code_pending(self):
"""A count is submitted and not yet completed; bit 0 of 'code'"""
return (self.code & 0x1) >> 0
@code_pending.setter
def code_pending(self, value):
if not 0 <= value <= 0x1:
raise ValueError(f"code_pending is 1 bit, not {value}")
self.code = (self.code & ~0x1) | (value << 0)
@property
def code_points(self):
"""Points held; bits 11:4 of 'code'"""
return (self.code & 0xff0) >> 4
@code_points.setter
def code_points(self, value):
if not 0 <= value <= 0xff:
raise ValueError(f"code_points is 8 bits, not {value}")
self.code = (self.code & ~0xff0) | (value << 4)
@property
def code_full(self):
"""The handle holds FOO_POINTS_MAX points; bit 15 of 'code'"""
return (self.code & 0x8000) >> 15
@code_full.setter
def code_full(self, value):
if not 0 <= value <= 0x1:
raise ValueError(f"code_full is 1 bit, not {value}")
self.code = (self.code & ~0x8000) | (value << 15)
cdef void _kept0(void *a0, const foo_point *a1) noexcept with gil:
_KEPT[<uintptr_t>a0](None if a1 == NULL else FooPoint._view(<foo_point *>a1, None))
cdef int _call1(void *a0, const foo_point *a1) noexcept with gil:
return (<object>a0)(None if a1 == NULL else FooPoint._view(<foo_point *>a1, None))
cdef void _kept2(void *a0, size_t a1) noexcept with gil:
_KEPT.pop(<uintptr_t>a0)(a1)
@cython.no_gc_clear
cdef class Handle:
"""A collection of points, opened with foo_open() and closed with foo_close()
Wraps a pointer to struct foo_handle, which it releases
with close(), also on leaving a with-block or when
collected, when it owns it.
"""
cdef foo_handle *_handle
cdef bint _owned
cdef readonly list _keys
def __cinit__(self):
self._keys = []
def __init__(self):
raise TypeError("a handle is made by calling the API")
@staticmethod
cdef Handle _wrap(foo_handle *ptr, bint owned):
cdef Handle made = Handle.__new__(Handle)
made._handle = ptr
made._owned = owned
return made
cdef foo_handle *_get(self) except NULL:
if self._handle == NULL:
raise ValueError("the handle is closed")
return self._handle
cdef _release(self):
for key in self._keys:
_KEPT.pop(key, None)
self._keys = []
def __enter__(self):
return self
def __exit__(self, *exc):
if self._owned and self._handle != NULL:
self.close()
def __dealloc__(self):
if self._owned and self._handle != NULL:
foo_close(self._handle)
self._release()
def name(self):
"""The name the handle was opened with
Returns:
The name, owned by the handle
Calls foo_name().
"""
cdef const foo_handle *_ptr = self._get()
cdef const char *ret
ret = foo_name(_ptr)
return _str_out(ret)
def point_add(self, point):
"""Add a point to the handle
Args:
point: The point to add, copied
Raises:
OSError: foo_point_add() returns: 0 on success, -ENOSPC when the handle holds FOO_POINTS_MAX points
Calls foo_point_add().
"""
cdef foo_handle *_ptr = self._get()
cdef int ret
ret = foo_point_add(_ptr, (<FooPoint?>point)._yace_p)
_check(ret)
def point_add_many(self, points):
"""Add points to the handle, as many as it has room for
Args:
points: The points to add, copied
Raises:
OSError: foo_point_add_many() returns: The number of points added, -ENOSPC when there was room for none
Calls foo_point_add_many().
"""
cdef foo_handle *_ptr = self._get()
cdef _Records points_r
cdef size_t points_len_n
cdef ssize_t ret
points_r = _records(points, FooPoint, sizeof(foo_point))
points_len_n = <object>(points_r.n)
ret = foo_point_add_many(_ptr, <const foo_point *>points_r.buf, points_len_n)
_check(ret)
return ret
def point_count(self):
"""The number of points held
Returns:
The number of points
Calls foo_point_count().
"""
cdef const foo_handle *_ptr = self._get()
cdef size_t ret
ret = foo_point_count(_ptr)
return ret
def point_get(self, idx):
"""A point held by the handle
Args:
idx: Index of the point
Returns:
The point, NULL when 'idx' is past the last one
Calls foo_point_get().
"""
cdef const foo_handle *_ptr = self._get()
cdef const foo_point *ret
ret = foo_point_get(_ptr, idx)
return None if ret == NULL else FooPoint._copy(ret[0])
def point_copy(self, points_len):
"""Copy the points held, as many as fit
Args:
points_len: The number of points that fit
Raises:
OSError: foo_point_copy() returns: The number of points copied
Calls foo_point_copy().
"""
cdef const foo_handle *_ptr = self._get()
cdef foo_point *points = NULL
cdef ssize_t ret
try:
points = <foo_point *>_calloc(points_len, sizeof(foo_point))
ret = foo_point_copy(_ptr, <foo_point *>points, points_len)
points_items = [FooPoint._copy(points[i]) for i in range(_bound(ret, points_len))]
finally:
free(points)
_check(ret)
return points_items
def point_watch(self, added):
"""Watch the points added to the handle, from now until it is closed
Args:
added: Called with each point added, until the handle is closed
Raises:
OSError: foo_point_watch() returns: 0 on success, -EBUSY when the handle is watched already
Calls foo_point_watch().
"""
cdef foo_handle *_ptr = self._get()
cdef int ret
added_key = None
if added is not None:
added_key = _key()
_KEPT[added_key] = added
self._keys.append(added_key)
ret = foo_point_watch(_ptr, NULL if added_key is None else <foo_added_cb>_kept0, NULL if added_key is None else <void *><uintptr_t>added_key)
if ret < 0 and added_key is not None:
_KEPT.pop(added_key, None)
self._keys.remove(added_key)
_check(ret)
def point_visit(self, visit):
"""Visit the points in the order they were added
Args:
visit: Called for each point, until it returns non-zero
Raises:
OSError: foo_point_visit() returns: The number of points visited, -EINVAL when 'visit' is NULL
Calls foo_point_visit().
"""
cdef foo_handle *_ptr = self._get()
cdef ssize_t ret
ret = foo_point_visit(_ptr, NULL if visit is None else <foo_visit_cb>_call1, NULL if visit is None else <void *>visit)
_check(ret)
return ret
def point_visit_with(self, visitor):
"""Visit the points with a visitor; as foo_point_visit()
Args:
visitor: The callback and its argument
Raises:
OSError: foo_point_visit_with() returns: The number of points visited, -EINVAL when the callback is NULL
Calls foo_point_visit_with().
"""
cdef foo_handle *_ptr = self._get()
cdef ssize_t ret
ret = foo_point_visit_with(_ptr, (<FooVisitor?>visitor)._yace_p)
_check(ret)
return ret
def count_submit(self, done):
"""Submit a count of the points, completed by foo_count_complete()
Args:
done: Called once, by foo_count_complete(), with the number of points
Raises:
OSError: foo_count_submit() returns: 0, -EBUSY when a count is submitted and not yet completed
Calls foo_count_submit().
"""
cdef foo_handle *_ptr = self._get()
cdef int ret
done_key = None
if done is not None:
done_key = _key()
_KEPT[done_key] = done
ret = foo_count_submit(_ptr, NULL if done_key is None else <foo_done_cb>_kept2, NULL if done_key is None else <void *><uintptr_t>done_key)
if ret < 0 and done_key is not None:
_KEPT.pop(done_key, None)
_check(ret)
def count_complete(self):
"""Complete the count submitted, if any, calling its callback
Returns:
The number of counts completed, 0 or 1
Calls foo_count_complete().
"""
cdef foo_handle *_ptr = self._get()
cdef size_t ret
ret = foo_count_complete(_ptr)
return ret
def status_get(self):
"""The status of the handle
Calls foo_status_get().
"""
cdef const foo_handle *_ptr = self._get()
cdef FooStatus status = FooStatus.__new__(FooStatus)
foo_status_get(_ptr, status._yace_p)
return status
def close(self):
"""Close a handle
Calls foo_close().
"""
if self._handle != NULL:
foo_close(self._handle)
self._handle = NULL
self._release()
def _yace_open(name):
"""Open a handle holding no points
Args:
name: Name of the handle, copied
Raises:
OSError: foo_open() returns: 0 on success, -EINVAL when 'name' or 'handle' is NULL, -ENOMEM when memory ran out
Calls foo_open().
"""
cdef object name_b = _str_in(name)
cdef foo_handle *handle = NULL
cdef int ret
ret = foo_open(<const char *>_cstr(name_b), &handle)
_check(ret)
return Handle._wrap(handle, True)
_yace_open.__name__ = _yace_open.__qualname__ = "open"
globals()["open"] = _yace_open
del globals()["_yace_open"]
def version():
"""The version of the library
Returns:
The version, as "MAJOR.MINOR.PATCH"
Calls foo_version().
"""
cdef const char *ret
ret = foo_version()
return _str_out(ret)
def errmsg():
"""Why the call that failed last on the calling thread failed
A function that returns a negative errno keeps a message saying what the errno does not, such as the name of the handle that is full. The meta names this function as 'errmsg', so that the error of a binding holds the message.
Returns:
The message, owned by the library and valid until the next call fails on the calling thread; "" when no call has failed
Calls foo_errmsg().
"""
cdef const char *ret
ret = foo_errmsg()
return _str_out(ret)
def scalars_fill():
"""Fill in a value of every kind of scalar, the limits of the fixed-width ones
Calls foo_scalars_fill().
"""
cdef FooScalars scalars = FooScalars.__new__(FooScalars)
foo_scalars_fill(scalars._yace_p)
return scalars
def figure_fill(shape):
"""Fill in a figure of the given shape
Args:
shape: One of enum foo_shape
Raises:
OSError: foo_figure_fill() returns: 0 on success, -EINVAL when 'shape' is none of enum foo_shape
Calls foo_figure_fill().
"""
cdef FooFigure figure = FooFigure.__new__(FooFigure)
cdef int ret
ret = foo_figure_fill(figure._yace_p, shape)
_check(ret)
return figure
def value_set(i_):
"""Set a value, clearing the bits it does not use
Args:
i_: What to set it to
Calls foo_value_set().
"""
cdef FooValue value = FooValue.__new__(FooValue)
foo_value_set(value._yace_p, i_)
return value
def wire_fill():
"""Fill in a packed record
Calls foo_wire_fill().
"""
cdef FooWire wire = FooWire.__new__(FooWire)
foo_wire_fill(wire._yace_p)
return wire
"""
libfoo
The types of foo, the module compiled with Cython, for type checkers
and editors, which cannot read them from the compiled module.
Generated by yace from foo.h; do not edit.
"""
#
# SPDX-License-Identifier: GPL-2.0-only
import array
import enum
from collections.abc import Buffer, Callable, Sequence
from typing import IO, Any, Protocol, Self
from typing_extensions import disjoint_base
FOO_NAME: str
FOO_MAGIC: int
FOO_VERSION_MAJOR: int
FOO_VERSION_MINOR: int
FOO_VERSION_PATCH: int
FOO_POINTS_MAX: int
FOO_DEFAULT_SHAPE_SIDES: int
FOO_STATUS_CODE_PENDING: int
FOO_STATUS_CODE_POINTS: int
FOO_STATUS_CODE_FULL: int
class FooPr(enum.IntFlag):
"""Output formats of the pretty-printers"""
FOO_PR_DEF = 0x0
FOO_PR_YAML = 0x1
FOO_PR_TERSE = 0x2
FOO_PR_JSON = 0x4
FOO_PR_DEF: FooPr
FOO_PR_YAML: FooPr
FOO_PR_TERSE: FooPr
FOO_PR_JSON: FooPr
class FooShape(enum.IntEnum):
"""Kinds of figure"""
FOO_SHAPE_NONE = -1
FOO_SHAPE_POINT = 0
FOO_SHAPE_LINE = 1
FOO_SHAPE_POLYGON = 2
FOO_SHAPE_NONE: FooShape
FOO_SHAPE_POINT: FooShape
FOO_SHAPE_LINE: FooShape
FOO_SHAPE_POLYGON: FooShape
class FooOption(enum.IntEnum):
"""Options of a figure, combined as bits"""
FOO_OPTION_CLOSED = 1
FOO_OPTION_FILLED = 2
FOO_OPTION_CLOSED: FooOption
FOO_OPTION_FILLED: FooOption
@disjoint_base
class _Record:
"""The pretty-printers of a struct or union"""
def to_dict(self) -> dict[str, Any]: ...
@classmethod
def fpr(cls, stream: IO[str], obj: _Record | None, flags: int = ...) -> int: ...
@classmethod
def pr(cls, obj: _Record | None, flags: int = ...) -> int: ...
class _SupportsDLPack(Protocol):
def __dlpack__(self, *args: Any, **kwargs: Any) -> object: ...
class _SupportsCudaArrayInterface(Protocol):
@property
def __cuda_array_interface__(self) -> dict[str, Any]: ...
@disjoint_base
class FooPoint(_Record):
"""A point on the plane"""
def __init__(self, x: int | None = None, y: int | None = None) -> None: ...
@property
def x(self) -> int:
"""Horizontal position"""
@x.setter
def x(self, value: int) -> None: ...
@property
def y(self) -> int:
"""Vertical position"""
@y.setter
def y(self, value: int) -> None: ...
@disjoint_base
class FooVisitor(_Record):
"""A callback and its argument"""
def __init__(self, visit: int | None = None, arg: int | None = None) -> None: ...
@property
def visit(self) -> int | None:
"""Called for each point"""
@visit.setter
def visit(self, value: int | None) -> None: ...
@property
def arg(self) -> int | None:
"""Given to 'visit'"""
@arg.setter
def arg(self, value: int | None) -> None: ...
@disjoint_base
class FooScalars(_Record):
"""A value of every kind of scalar"""
def __init__(
self,
flag: bool | None = None,
letter: bytes | int | None = None,
schar: int | None = None,
uchar: int | None = None,
s: int | None = None,
us: int | None = None,
i: int | None = None,
ui: int | None = None,
l: int | None = None,
ul: int | None = None,
ll: int | None = None,
ull: int | None = None,
f: float | None = None,
d: float | None = None,
i8: int | None = None,
i16: int | None = None,
i32: int | None = None,
i64: int | None = None,
u8: int | None = None,
u16: int | None = None,
u32: int | None = None,
u64: int | None = None,
iptr: int | None = None,
uptr: int | None = None,
size: int | None = None,
ssize: int | None = None,
diff: int | None = None,
) -> None: ...
@property
def flag(self) -> bool:
"""bool"""
@flag.setter
def flag(self, value: bool) -> None: ...
@property
def letter(self) -> bytes:
"""char"""
@letter.setter
def letter(self, value: bytes | int) -> None: ...
@property
def schar(self) -> int:
"""signed char"""
@schar.setter
def schar(self, value: int) -> None: ...
@property
def uchar(self) -> int:
"""unsigned char"""
@uchar.setter
def uchar(self, value: int) -> None: ...
@property
def s(self) -> int:
"""short"""
@s.setter
def s(self, value: int) -> None: ...
@property
def us(self) -> int:
"""unsigned short"""
@us.setter
def us(self, value: int) -> None: ...
@property
def i(self) -> int:
"""int"""
@i.setter
def i(self, value: int) -> None: ...
@property
def ui(self) -> int:
"""unsigned int"""
@ui.setter
def ui(self, value: int) -> None: ...
@property
def l(self) -> int:
"""long"""
@l.setter
def l(self, value: int) -> None: ...
@property
def ul(self) -> int:
"""unsigned long"""
@ul.setter
def ul(self, value: int) -> None: ...
@property
def ll(self) -> int:
"""long long"""
@ll.setter
def ll(self, value: int) -> None: ...
@property
def ull(self) -> int:
"""unsigned long long"""
@ull.setter
def ull(self, value: int) -> None: ...
@property
def f(self) -> float:
"""float"""
@f.setter
def f(self, value: float) -> None: ...
@property
def d(self) -> float:
"""double"""
@d.setter
def d(self, value: float) -> None: ...
@property
def i8(self) -> int:
"""int8_t"""
@i8.setter
def i8(self, value: int) -> None: ...
@property
def i16(self) -> int:
"""int16_t"""
@i16.setter
def i16(self, value: int) -> None: ...
@property
def i32(self) -> int:
"""int32_t"""
@i32.setter
def i32(self, value: int) -> None: ...
@property
def i64(self) -> int:
"""int64_t"""
@i64.setter
def i64(self, value: int) -> None: ...
@property
def u8(self) -> int:
"""uint8_t"""
@u8.setter
def u8(self, value: int) -> None: ...
@property
def u16(self) -> int:
"""uint16_t"""
@u16.setter
def u16(self, value: int) -> None: ...
@property
def u32(self) -> int:
"""uint32_t"""
@u32.setter
def u32(self, value: int) -> None: ...
@property
def u64(self) -> int:
"""uint64_t"""
@u64.setter
def u64(self, value: int) -> None: ...
@property
def iptr(self) -> int:
"""intptr_t"""
@iptr.setter
def iptr(self, value: int) -> None: ...
@property
def uptr(self) -> int:
"""uintptr_t"""
@uptr.setter
def uptr(self, value: int) -> None: ...
@property
def size(self) -> int:
"""size_t"""
@size.setter
def size(self, value: int) -> None: ...
@property
def ssize(self) -> int:
"""ssize_t"""
@ssize.setter
def ssize(self, value: int) -> None: ...
@property
def diff(self) -> int:
"""ptrdiff_t"""
@diff.setter
def diff(self, value: int) -> None: ...
@disjoint_base
class FooFigure(_Record):
"""A figure: its kind, where it is, and its corners"""
def __init__(
self,
shape: int | None = None,
options: int | None = None,
origin: FooPoint | None = None,
corners: Sequence[FooPoint] | None = None,
ncorners: int | None = None,
name: str | bytes | None = None,
grid: Sequence[Sequence[int]] | None = None,
label: str | bytes | None = None,
scale: float | None = None,
area: float | None = None,
) -> None: ...
@property
def shape(self) -> int:
"""One of enum foo_shape"""
@shape.setter
def shape(self, value: int) -> None: ...
@property
def options(self) -> int:
"""Bits of enum foo_option"""
@options.setter
def options(self, value: int) -> None: ...
@property
def origin(self) -> FooPoint:
"""Where the figure is"""
@origin.setter
def origin(self, value: FooPoint) -> None: ...
@property
def corners(self) -> tuple[FooPoint, ...]:
"""The corners, relative to 'origin'"""
@corners.setter
def corners(self, value: Sequence[FooPoint]) -> None: ...
@property
def ncorners(self) -> int:
"""How many of 'corners' are used"""
@ncorners.setter
def ncorners(self, value: int) -> None: ...
@property
def name(self) -> bytes:
"""Name of the figure"""
@name.setter
def name(self, value: str | bytes) -> None: ...
@property
def grid(self) -> memoryview:
"""A two-dimensional array"""
@grid.setter
def grid(self, value: Sequence[Sequence[int]]) -> None: ...
@property
def label(self) -> str | None:
"""A string, NULL when there is none"""
@label.setter
def label(self, value: str | bytes | None) -> None: ...
@property
def scale(self) -> float:
"""Scale of the figure"""
@scale.setter
def scale(self, value: float) -> None: ...
@property
def area(self) -> float:
"""Area of the figure"""
@area.setter
def area(self, value: float) -> None: ...
@disjoint_base
class FooValue(_Record):
"""A 32-bit value, read as signed, as unsigned, or as the 'x' of a point"""
def __init__(
self, i: int | None = None, u: int | None = None, point: FooPoint | None = None
) -> None: ...
@property
def i(self) -> int:
"""Signed"""
@i.setter
def i(self, value: int) -> None: ...
@property
def u(self) -> int:
"""Unsigned"""
@u.setter
def u(self, value: int) -> None: ...
@property
def point(self) -> FooPoint:
"""A point, its 'x' sharing the bits of 'i'"""
@point.setter
def point(self, value: FooPoint) -> None: ...
@disjoint_base
class FooWire(_Record):
"""A record laid out without padding, as a wire format is: no field after the first is aligned"""
def __init__(
self,
kind: int | None = None,
length: int | None = None,
at: FooPoint | None = None,
pair: Sequence[int] | None = None,
) -> None: ...
@property
def kind(self) -> int:
"""One of enum foo_shape"""
@kind.setter
def kind(self, value: int) -> None: ...
@property
def length(self) -> int:
"""At offset 1"""
@length.setter
def length(self, value: int) -> None: ...
@property
def at(self) -> FooPoint:
"""A point, at offset 5"""
@at.setter
def at(self, value: FooPoint) -> None: ...
@property
def pair(self) -> list[int]:
"""An array, at offset 13"""
@pair.setter
def pair(self, value: Sequence[int]) -> None: ...
@disjoint_base
class FooStatus(_Record):
"""The status of a handle, its code a field of bits"""
def __init__(self, code: int | None = None, max: int | None = None) -> None: ...
@property
def code(self) -> int:
"""Status code, see FOO_STATUS_CODE_*"""
@code.setter
def code(self, value: int) -> None: ...
@property
def max(self) -> int:
"""Points the handle holds at most"""
@max.setter
def max(self, value: int) -> None: ...
@property
def code_pending(self) -> int:
"""A count is submitted and not yet completed; bit 0 of 'code'"""
@code_pending.setter
def code_pending(self, value: int) -> None: ...
@property
def code_points(self) -> int:
"""Points held; bits 11:4 of 'code'"""
@code_points.setter
def code_points(self, value: int) -> None: ...
@property
def code_full(self) -> int:
"""The handle holds FOO_POINTS_MAX points; bit 15 of 'code'"""
@code_full.setter
def code_full(self, value: int) -> None: ...
@disjoint_base
class Handle:
"""A collection of points, opened with foo_open() and closed with foo_close()"""
def __enter__(self) -> Self: ...
def __exit__(self, *exc: object) -> None: ...
def name(self) -> str | None:
"""The name the handle was opened with
Returns:
The name, owned by the handle
Calls foo_name().
"""
def point_add(self, point: FooPoint) -> None:
"""Add a point to the handle
Args:
point: The point to add, copied
Raises:
OSError: foo_point_add() returns: 0 on success, -ENOSPC when the handle holds FOO_POINTS_MAX points
Calls foo_point_add().
"""
def point_add_many(self, points: Sequence[FooPoint]) -> int:
"""Add points to the handle, as many as it has room for
Args:
points: The points to add, copied
Raises:
OSError: foo_point_add_many() returns: The number of points added, -ENOSPC when there was room for none
Calls foo_point_add_many().
"""
def point_count(self) -> int:
"""The number of points held
Returns:
The number of points
Calls foo_point_count().
"""
def point_get(self, idx: int) -> FooPoint | None:
"""A point held by the handle
Args:
idx: Index of the point
Returns:
The point, NULL when 'idx' is past the last one
Calls foo_point_get().
"""
def point_copy(self, points_len: int) -> list[FooPoint]:
"""Copy the points held, as many as fit
Args:
points_len: The number of points that fit
Raises:
OSError: foo_point_copy() returns: The number of points copied
Calls foo_point_copy().
"""
def point_watch(self, added: Callable[[FooPoint | None], None]) -> None:
"""Watch the points added to the handle, from now until it is closed
Args:
added: Called with each point added, until the handle is closed
Raises:
OSError: foo_point_watch() returns: 0 on success, -EBUSY when the handle is watched already
Calls foo_point_watch().
"""
def point_visit(self, visit: Callable[[FooPoint | None], int]) -> int:
"""Visit the points in the order they were added
Args:
visit: Called for each point, until it returns non-zero
Raises:
OSError: foo_point_visit() returns: The number of points visited, -EINVAL when 'visit' is NULL
Calls foo_point_visit().
"""
def point_visit_with(self, visitor: FooVisitor) -> int:
"""Visit the points with a visitor; as foo_point_visit()
Args:
visitor: The callback and its argument
Raises:
OSError: foo_point_visit_with() returns: The number of points visited, -EINVAL when the callback is NULL
Calls foo_point_visit_with().
"""
def count_submit(self, done: Callable[[int], None]) -> None:
"""Submit a count of the points, completed by foo_count_complete()
Args:
done: Called once, by foo_count_complete(), with the number of points
Raises:
OSError: foo_count_submit() returns: 0, -EBUSY when a count is submitted and not yet completed
Calls foo_count_submit().
"""
def count_complete(self) -> int:
"""Complete the count submitted, if any, calling its callback
Returns:
The number of counts completed, 0 or 1
Calls foo_count_complete().
"""
def status_get(self) -> FooStatus:
"""The status of the handle
Calls foo_status_get().
"""
def close(self) -> None:
"""Close a handle
Calls foo_close().
"""
def open(name: str | bytes) -> Handle:
"""Open a handle holding no points
Args:
name: Name of the handle, copied
Raises:
OSError: foo_open() returns: 0 on success, -EINVAL when 'name' or 'handle' is NULL, -ENOMEM when memory ran out
Calls foo_open().
"""
def version() -> str | None:
"""The version of the library
Returns:
The version, as "MAJOR.MINOR.PATCH"
Calls foo_version().
"""
def errmsg() -> str | None:
"""Why the call that failed last on the calling thread failed
A function that returns a negative errno keeps a message saying what the errno does not, such as the name of the handle that is full. The meta names this function as 'errmsg', so that the error of a binding holds the message.
Returns:
The message, owned by the library and valid until the next call fails on the calling thread; "" when no call has failed
Calls foo_errmsg().
"""
def scalars_fill() -> FooScalars:
"""Fill in a value of every kind of scalar, the limits of the fixed-width ones
Calls foo_scalars_fill().
"""
def figure_fill(shape: int) -> FooFigure:
"""Fill in a figure of the given shape
Args:
shape: One of enum foo_shape
Raises:
OSError: foo_figure_fill() returns: 0 on success, -EINVAL when 'shape' is none of enum foo_shape
Calls foo_figure_fill().
"""
def value_set(i_: int) -> FooValue:
"""Set a value, clearing the bits it does not use
Args:
i_: What to set it to
Calls foo_value_set().
"""
def wire_fill() -> FooWire:
"""Fill in a packed record
Calls foo_wire_fill().
"""
# libfoo: the C API for Cython, as libfoo.h, beside this file,
# declares it. Import it with 'cimport foo as lib' and call its
# functions as 'lib.<name>()', also without the GIL. The C compiler then needs
# this directory on its include path.
#
# Generated by yace from foo.h; do not edit.
#
# SPDX-License-Identifier: GPL-2.0-only
from libc.stdint cimport int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t, intptr_t, uintptr_t
from libc.stddef cimport ptrdiff_t
cdef extern from "libfoo.h" nogil:
ctypedef bint _Bool
const char *FOO_NAME
const long long FOO_MAGIC
const long long FOO_VERSION_MAJOR
const long long FOO_VERSION_MINOR
const long long FOO_VERSION_PATCH
const long long FOO_POINTS_MAX
const long long FOO_DEFAULT_SHAPE_SIDES
const long long FOO_STATUS_CODE_PENDING
const long long FOO_STATUS_CODE_POINTS
const long long FOO_STATUS_CODE_FULL
enum foo_shape:
FOO_SHAPE_NONE
FOO_SHAPE_POINT
FOO_SHAPE_LINE
FOO_SHAPE_POLYGON
enum foo_option:
FOO_OPTION_CLOSED
FOO_OPTION_FILLED
struct foo_handle
struct foo_point
struct foo_visitor
struct foo_scalars
struct foo_figure
union foo_value
struct foo_wire
struct foo_status
ctypedef int (*foo_visit_cb)(void *, const foo_point *)
ctypedef void (*foo_done_cb)(void *, size_t)
ctypedef void (*foo_added_cb)(void *, const foo_point *)
struct foo_point:
int32_t x
int32_t y
struct foo_visitor:
foo_visit_cb visit
void *arg
struct foo_scalars:
_Bool flag
char letter
signed char schar
unsigned char uchar
short s
unsigned short us
int i
unsigned int ui
long l
unsigned long ul
long long ll
unsigned long long ull
float f
double d
int8_t i8
int16_t i16
int32_t i32
int64_t i64
uint8_t u8
uint16_t u16
uint32_t u32
uint64_t u64
intptr_t iptr
uintptr_t uptr
size_t size
ssize_t ssize
ptrdiff_t diff
struct foo_figure:
uint32_t shape
uint32_t options
foo_point origin
foo_point corners[4]
uint8_t ncorners
char name[16]
int16_t grid[2][3]
const char *label
float scale
double area
union foo_value:
int32_t i
uint32_t u
foo_point point
packed struct foo_wire:
uint8_t kind
uint32_t length
foo_point at
uint16_t pair[2]
struct foo_status:
uint16_t code
uint16_t max
const char *foo_version()
const char *foo_errmsg()
int foo_open(const char *name, foo_handle **handle)
void foo_close(foo_handle *handle)
const char *foo_name(const foo_handle *handle)
int foo_point_add(foo_handle *handle, const foo_point *point)
ssize_t foo_point_add_many(foo_handle *handle, const foo_point *points, size_t points_len)
size_t foo_point_count(const foo_handle *handle)
const foo_point *foo_point_get(const foo_handle *handle, size_t idx)
ssize_t foo_point_copy(const foo_handle *handle, foo_point *points, size_t points_len)
int foo_point_watch(foo_handle *handle, foo_added_cb added, void *arg)
ssize_t foo_point_visit(foo_handle *handle, foo_visit_cb visit, void *arg)
ssize_t foo_point_visit_with(foo_handle *handle, const foo_visitor *visitor)
int foo_count_submit(foo_handle *handle, foo_done_cb done, void *arg)
size_t foo_count_complete(foo_handle *handle)
void foo_status_get(const foo_handle *handle, foo_status *status)
void foo_scalars_fill(foo_scalars *scalars)
int foo_figure_fill(foo_figure *figure, uint32_t shape)
void foo_value_set(foo_value *value, int32_t i)
void foo_wire_fill(foo_wire *wire)
Implementation¶
The Cython target emits the idiomatic API of the Python target as a module
compiled with Cython, and the C API for Cython as a .pxd. The target also
checks what it emitted.
Emits, into <output>/cython:
<prefix>.pyx, the module, or<prefix>_.pyxwhere the prefix names a module of Python’s standard library, such aszlib<prefix>.pyi, the stub of the module: the types of what it defines<prefix>.pxd, the C API for Cython. The module uses the declarations of the.pxd, and other Cython code cimports the.pxdto call Clib<prefix>.h, the C header that the.pxddeclares, as the C target emits it<prefix>_check.py, the check program, which prints a zeroed record of each type<prefix>_check.pyx, the check of the.pxd
The check translates the module with Cython, compiles the module without
linking the library, and runs the check program. The check program calls no
function of the library. The check also compiles the C that Cython generates
from <prefix>_check.pyx with the header, so a declaration in the .pxd
that disagrees with the header fails to compile.
- class yace.targets.cython.target.Cython(output: Path, include: List[Path] | None = None, options: Dict[str, str] | None = None)¶
- yace.targets.cython.target.build(out: Path, prefix: str, log: List[str], include: List[Path] | None = None, link: List[str] | None = None) List[str]¶
Translate and compile the check of the .pxd and the module ‘prefix’ in ‘out’, and return what failed. The module links ‘link’; without ‘link’, the module links no library. Each command and its output is appended to ‘log’.
- yace.targets.cython.target.check_cflags(cc: str) List[str]¶
Return CHECK_CFLAGS, with DISCARDED_QUALIFIERS added where the compiler ‘cc’ accepts that option
- yace.targets.cython.target.define_type(value) str¶
The Python type of the value of a define
- yace.targets.cython.target.link_args(link: List[str] | None) List[str]¶
Return the linker arguments of the module, linking ‘link’. Without ‘link’, each function of the library is resolved when first called. On macOS, the symbols of Python are resolved when the module is loaded.
Code of the Cython module of the bindings. The module provides the idiomatic
API of the Python target, compiled, and calls C through the .pxd instead
of through ctypes. A record is an extension type that holds the C struct, an
array is a buffer, and a handle is an extension type that releases the C
handle when its last reference is dropped. See yace.targets.idiom
for how each idiom is derived from the header.
Cython pairs the module with the .pxd of the same name, so the C names
that the .pxd declares are names of the module. A Python name that the
.pxd also declares is defined under another name and then bound to the
Python name in the module’s globals.
- yace.targets.cython.pyxgen.bind(defined: str, name: str) str¶
Return the code that binds the function defined as ‘defined’ to ‘name’ in the module’s globals. The function cannot be defined as ‘name’, because ‘name’ is declared by the .pxd, a builtin, or reserved by Cython.
- yace.targets.cython.pyxgen.kind_of(fmt: str) str¶
Return the kind of element that the struct format ‘fmt’ describes: ‘i’ signed, ‘u’ unsigned, ‘f’ floating, ‘b’ bool or ‘p’ pointer. A buffer given for an array must have elements of the kind of the array.
The stub of the Cython module, <prefix>.pyi. The stub gives the types of
what the module defines, because a type checker or an editor cannot read the
types from the compiled module. Each annotation is the type that the code
generated by yace.targets.cython.pyxgen takes or returns, and the
stub is rendered from the same Renderer as the module.
- yace.targets.cython.pyigen.optional(annotation: str, nullable: bool = True) str¶
Return ‘annotation’, with ‘| None’ added where ‘nullable’
Cython code for the IR: the names of the C API in a .pxd, and the Cython
spelling of each IR type. The .pxd declares the C API as the C target’s
header does, so Cython code cimports it and calls C directly; the check, a
.pyx cimporting every name, checks each declaration against the header.
- class yace.targets.cython.cygen.Check(pxd: Pxd)¶
The body of a function, never called, assigning each name the .pxd declares, cimported as ‘c’, to what Cython takes its type to be, or its address to a pointer to that; the C compiler, given the header, then fails where a declaration disagrees with it
- local(typ, value: str = '', spec: str = 'noexcept nogil') str¶
A local of ‘typ’ assigned ‘value’; a function type in ‘typ’ has ‘spec’, as Cython gives that to what the .pxd declares of the C API, except to a field of a function pointer, which Cython does not declare nogil
- class yace.targets.cython.cygen.Names(model: Model)¶
The names of the C API in the .pxd: the C names, but for those Cython reserves, and the tags of records and enums that share a name with something else, as C keeps tags apart and Cython does not
- cname(name: str, cname: str) str¶
‘name’ as declared in the .pxd, with its C name where that differs
- decl(typ, inner: str = '', qual: str = '', spec: str = '') str¶
The Cython declaration of ‘inner’ as a ‘typ’; with ‘qual’, such as ‘c.’, the names of the API are those of the .pxd cimported as it, and ‘spec’, such as ‘noexcept’, follows each function type
- of(name: str) str¶
The .pxd name of the function, typedef, define or enum member ‘name’
- tag(name: str) str¶
The .pxd name of the record or enum ‘name’
- typedef(name: str) str¶
The .pxd name of the typedef ‘name’, or of the type it aliases
- unique(name: str, own: bool = False) str¶
Return ‘name’, with ‘_’ appended until the name is not reserved, not a builtin and not taken. With ‘own’, ‘name’ is already among the taken names as itself and is kept. A builtin is avoided because the names of the .pxd are names of the module paired with the .pxd: a .pxd name ‘len’ would hide the builtin len() from the code of the module.
- class yace.targets.cython.cygen.Pxd(model: Model)¶
The declarations of the .pxd, in the order the C target’s header has them: enums, records declared, typedefs, records defined, functions
- lines() List[str]¶
The declarations, indented for the ‘cdef extern’ block
- yace.targets.cython.cygen.field_name(name: str) str¶
The .pxd name of a field, in the namespace of its record
- yace.targets.cython.cygen.spelled_function(typ) bool¶
Whether ‘typ’ spells out a function type, rather than by a typedef