circuitpython/lib/utils
Jeff Epler 238e121236 protocols: Allow them to be (optionally) type-safe
Protocols are nice, but there is no way for C code to verify whether
a type's "protocol" structure actually implements some particular
protocol.  As a result, you can pass an object that implements the
"vfs" protocol to one that expects the "stream" protocol, and the
opposite of awesomeness ensues.

This patch adds an OPTIONAL (but enabled by default) protocol identifier
as the first member of any protocol structure.  This identifier is
simply a unique QSTR chosen by the protocol designer and used by each
protocol implementer.  When checking for protocol support, instead of
just checking whether the object's type has a non-NULL protocol field,
use `mp_proto_get` which implements the protocol check when possible.

The existing protocols are now named:
    protocol_framebuf
    protocol_i2c
    protocol_pin
    protocol_stream
    protocol_spi
    protocol_vfs
(most of these are unused in CP and are just inherited from MP; vfs and
stream are definitely used though)

I did not find any crashing examples, but here's one to give a flavor of what
is improved, using `micropython_coverage`.  Before the change,
the vfs "ioctl" protocol is invoked, and the result is not intelligible
as json (but it could have resulted in a hard fault, potentially):

    >>> import uos, ujson
    >>> u = uos.VfsPosix('/tmp')
    >>> ujson.load(u)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: syntax error in JSON

After the change, the vfs object is correctly detected as not supporting
the stream protocol:
    >>> ujson.load(p)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OSError: stream operation not supported
2019-12-04 09:29:57 -06:00
..
buffer_helper.c More size_t usage 2019-08-27 12:49:46 -07:00
buffer_helper.h More size_t usage 2019-08-27 12:49:46 -07:00
context_manager_helpers.c
context_manager_helpers.h Initial merge of micropython v1.9.2 into circuitpython 2.0.0 (in development) master. 2017-08-25 22:17:07 -04:00
interrupt_char.c Refine _bleio 2019-10-21 18:57:03 -07:00
interrupt_char.h Add i2cslave.I2CSlave bindings 2018-08-16 17:11:20 +02:00
printf.c lib/utils/printf: Exclude __GI_vsnprintf alias for gcc 9 and above. 2019-05-11 00:31:40 -05:00
pyexec.c Hide the traceback for the ReloadException. 2019-05-08 14:53:20 -07:00
pyexec.h WIP: after merge; before testing 2018-07-11 16:45:30 -04:00
stdout_helpers.c Fix output overflow and make help translatable 2018-11-09 16:41:08 -08:00
sys_stdio_mphal.c protocols: Allow them to be (optionally) type-safe 2019-12-04 09:29:57 -06:00