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

Typing improvements #9548

Merged
merged 9 commits into from
Aug 28, 2024
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
2 changes: 1 addition & 1 deletion ports/espressif/bindings/espulp/ULP.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
#include "py/objproperty.h"

//| class ULP:
//| def __init__(self, arch: Architecture = Architecture.FSM):
//| def __init__(self, arch: Architecture = Architecture.FSM) -> None:
//| """The ultra-low-power processor.
//|
//| Raises an exception if another ULP has been instantiated. This
Expand Down
4 changes: 3 additions & 1 deletion shared-bindings/_bleio/CharacteristicBuffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,11 @@ static void check_for_deinit(bleio_characteristic_buffer_obj_t *self) {
//| :rtype: bytes or None"""
//| ...
//|
//| def readinto(self, buf: WriteableBuffer) -> Optional[int]:
//| def readinto(self, buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]:
//| """Read bytes into the ``buf``. Read at most ``len(buf)`` bytes.
//|
//| You may reduce this maximum read using the ``nbytes`` argument.
//|
//| :return: number of bytes read and stored into ``buf``
//| :rtype: int or None (on a non-blocking error)"""
//| ...
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/_bleio/ScanEntry.c
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
//| """Cannot be instantiated directly. Use `_bleio.Adapter.start_scan`."""
//| ...
//|
//| def matches(self, prefixes: ScanEntry, *, match_all: bool = True) -> bool:
//| def matches(self, prefixes: ReadableBuffer, *, match_all: bool = True) -> bool:
//| """Returns True if the ScanEntry matches all prefixes when ``match_all`` is True. This is stricter
//| than the scan filtering which accepts any advertisements that match any of the prefixes
//| where ``match_all`` is False."""
Expand Down
8 changes: 6 additions & 2 deletions shared-bindings/bitmapfilter/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//| mul: float | None = None,
//| add: float = 0,
//| mask: displayio.Bitmap | None = None,
//| threshold=False,
//| threshold: bool = False,
//| offset: int = 0,
//| invert: bool = False,
//| ) -> displayio.Bitmap:
Expand Down Expand Up @@ -406,7 +406,11 @@ static mp_obj_t bitmapfilter_mix(size_t n_args, const mp_obj_t *pos_args, mp_map
}
MP_DEFINE_CONST_FUN_OBJ_KW(bitmapfilter_mix_obj, 0, bitmapfilter_mix);

//| def solarize(bitmap, threshold: float = 0.5, mask: displayio.Bitmap | None = None):
//| def solarize(
//| bitmap: displayio.Bitmap,
//| threshold: float = 0.5,
//| mask: displayio.Bitmap | None = None,
//| ) -> displayio.Bitmap:
//| """Create a "solarization" effect on an image
//|
//| This filter inverts pixels with brightness values above ``threshold``, while leaving
Expand Down
6 changes: 5 additions & 1 deletion shared-bindings/codeop/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ static const char *get_arg_str(mp_obj_t arg, qstr name) {

//| """Utilities to compile possibly incomplete Python source code."""
//|
//| from types import CodeType
//|

//| def compile_command(source: str, filename: str = "<input>", symbol: str = "single"):
//| def compile_command(
//| source: str, filename: str = "<input>", symbol: str = "single"
//| ) -> CodeType:
//| """Compile a command and determine whether it is incomplete
//|
//| The 'completeness' determination is slightly different than in standard Python
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/dotclockframebuffer/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
//| mosi_bit: int,
//| clk_bit: int,
//| reset_bit: Optional[int],
//| ):
//| ) -> None:
//| """Send a displayio-style initialization sequence over an I2C I/O expander
//|
//| This function is highly generic in order to support various I/O expanders.
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/floppyio/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
//| buffer: WriteableBuffer,
//| data: digitalio.DigitalInOut,
//| index: digitalio.DigitalInOut,
//| index_wait=0.220,
//| index_wait: float = 0.220,
//| ) -> int:
//| """Read flux transition information into the buffer.
//|
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/memorymap/AddressRange.c
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
//| """
//|

//| def __init__(self, *, start, length) -> None:
//| def __init__(self, *, start: int, length: int) -> None:
//| """Constructs an address range starting at ``start`` and ending at
//| ``start + length``. An exception will be raised if any of the
//| addresses are invalid or protected."""
Expand Down
4 changes: 2 additions & 2 deletions shared-bindings/rotaryio/IncrementalEncoder.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

//| class IncrementalEncoder:
//| """IncrementalEncoder determines the relative rotational position based on two series of pulses.
//| It assumes that the encoder's common pin(s) are connected to ground,and enables pull-ups on
//| pin_a and pin_b."""
//| It assumes that the encoder's common pin(s) are connected to ground,and enables pull-ups on
//| pin_a and pin_b."""
//|
//| def __init__(
//| self, pin_a: microcontroller.Pin, pin_b: microcontroller.Pin, divisor: int = 4
Expand Down
8 changes: 4 additions & 4 deletions shared-bindings/synthio/LFO.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ static const uint16_t triangle[] = {0, 32767, 0, -32767};
//| scale: BlockInput = 1.0,
//| offset: BlockInput = 0.0,
//| phase_offset: BlockInput = 0.0,
//| once=False,
//| interpolate=True
//| ):
//| once: bool = False,
//| interpolate: bool = True,
//| ) -> None:
//| pass
static const mp_arg_t lfo_properties[] = {
{ MP_QSTR_waveform, MP_ARG_OBJ, {.u_obj = MP_ROM_NONE } },
Expand Down Expand Up @@ -268,7 +268,7 @@ MP_PROPERTY_GETTER(synthio_lfo_value_obj,


//|
//| def retrigger(self):
//| def retrigger(self) -> None:
//| """Reset the LFO's internal index to the start of the waveform. Most useful when it its `once` property is `True`."""
//|
static mp_obj_t synthio_lfo_retrigger(mp_obj_t self_in) {
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/synthio/Math.c
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ MAKE_ENUM_TYPE(synthio, MathOperation, synthio_math_operation,
//| a: BlockInput,
//| b: BlockInput = 0.0,
//| c: BlockInput = 1.0,
//| ):
//| ) -> None:
//| pass
static const mp_arg_t math_properties[] = {
{ MP_QSTR_operation, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = NULL } },
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/synthio/Synthesizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(synthio_synthesizer_release_obj, synthio_synthe
//| self,
//| release: NoteOrNoteSequence = (),
//| press: NoteOrNoteSequence = (),
//| retrigger=LFOOrLFOSequence,
//| retrigger: LFOOrLFOSequence = (),
//| ) -> None:
//| """Start notes, stop them, and/or re-trigger some LFOs.
//|
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/usb/core/Device.c
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(usb_core_device_get_manufacturer_obj, usb_core_device_
MP_PROPERTY_GETTER(usb_core_device_manufacturer_obj,
(mp_obj_t)&usb_core_device_get_manufacturer_obj);

//| def set_configuration(self, configuration=1):
//| def set_configuration(self, configuration: int = 1) -> None:
//| """Set the active configuration.
//|
//| The configuration parameter is the bConfigurationValue field of the
Expand Down
2 changes: 1 addition & 1 deletion shared-bindings/usb_video/USBFramebuffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ static void check_for_deinit(usb_video_uvcframebuffer_obj_t *self) {
//| it also supports the ``WritableBuffer`` protocol and can be accessed
//| as an array of ``H`` (unsigned 16-bit values)."""
//|
//| def __new__(self):
//| def __init__(self) -> None:
//| """Returns the singleton framebuffer object, if USB video is enabled"""
static mp_obj_t usb_video_uvcframebuffer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
static const mp_arg_t allowed_args[] = {};
Expand Down
36 changes: 32 additions & 4 deletions tools/board_stubs/build_board_specific_stubs/board_stub_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def get_board_pins(pin_filename):
continue

board_member = search.group(1)
extra_typing = None

board_type_search = re.search(r"MP_ROM_PTR\(&pin_(.*?)\)", line)
if board_type_search:
Expand All @@ -38,8 +39,18 @@ def get_board_pins(pin_filename):
board_type_search = re.search(
r"MP_ROM_PTR\(&(.*?)\[0\].[display|epaper_display]", line
)

if board_type_search is None:
board_type_search = re.search(r"MP_ROM_PTR\(&(.*?)_tuple", line)
if board_type_search is not None:
extra_typing = "Tuple[Any]"
if board_type_search is None:
board_type_search = re.search(r"MP_ROM_PTR\(&(.*?)_dict", line)
if board_type_search is not None:
extra_typing = "Dict[str, Any]"

if board_type_search is None:
records.append(["unmapped", None, line])
records.append(["unmapped", None, line, extra_typing])
continue

board_type = board_type_search.group(1)
Expand All @@ -56,7 +67,7 @@ def get_board_pins(pin_filename):
if extra_search:
extra = extra_search.group(1)

records.append([board_type, board_member, extra])
records.append([board_type, board_member, extra, extra_typing])

return records

Expand All @@ -69,8 +80,10 @@ def create_board_stubs(board_id, records, mappings, board_filename):
needs_busio = False
needs_displayio = False
needs_microcontroller = False
needs_dict = False
needs_tuple = False

for board_type, board_member, extra in records:
for board_type, board_member, extra, extra_typing in records:
if board_type == "pin":
needs_microcontroller = True
comment = f" # {extra}"
Expand Down Expand Up @@ -121,6 +134,13 @@ def create_board_stubs(board_id, records, mappings, board_filename):
member_data += f"{board_member}: {class_name}\n"
members.append(member_data)

elif extra_typing is not None:
if "Dict" in extra_typing:
needs_dict = True
elif "Tuple" in extra_typing:
needs_tuple = True
members.append(f"{board_member}: {extra_typing}\n")

elif board_type == "unmapped":
unmapped.append(extra)

Expand Down Expand Up @@ -152,6 +172,14 @@ def create_board_stubs(board_id, records, mappings, board_filename):
if needs_microcontroller:
boards_file.write("import microcontroller\n")

if needs_dict:
if needs_tuple:
boards_file.write("from typing import Any, Dict, Tuple\n")
else:
boards_file.write("from typing import Any, Dict\n")
elif needs_tuple:
boards_file.write("from typing import Any, Tuple\n")

boards_file.write("\n\n")
boards_file.write("# Board Info:\n")
boards_file.write("board_id: str\n")
Expand Down Expand Up @@ -200,7 +228,7 @@ def process(board_mappings, export_dir):
records = get_board_pins(pin_filename)
create_board_stubs(board_id, records, mappings, f"{sub_dir}/__init__.pyi")

for board_type, board_member, extra in records:
for board_type, board_member, extra, extra_typing in records:
if board_type == "pin":
total_pins += 1
elif board_type == "unmapped":
Expand Down