Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
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
4 changes: 2 additions & 2 deletions .github/workflows/examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ jobs:
steps:
- uses: actions/checkout@v5
- name: Build
run: make -C examples/embedding -f micropython_embed.mk && make -C examples/embedding
run: tools/ci.sh embedding_build
- name: Run
run: ./examples/embedding/embed | grep "hello world"
run: tools/ci.sh embedding_run_tests
14 changes: 14 additions & 0 deletions .github/workflows/ports_unix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,20 @@ jobs:
if: failure()
run: tests/run-tests.py --print-failures

repr_e:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Install packages
run: tools/ci.sh unix_32bit_setup
- name: Build
run: tools/ci.sh unix_repr_e_build
- name: Run main test suite
run: tools/ci.sh unix_repr_e_run_tests
- name: Print failures
if: failure()
run: tests/run-tests.py --print-failures

gil_enabled:
runs-on: ubuntu-latest
steps:
Expand Down
3 changes: 3 additions & 0 deletions docs/develop/memorymgt.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ See ``py/mpconfig.h`` for the specific details of the available representations.

**Pointer tagging**

This section describes how objects are stored in ``OBJ_REPR_A``. Terser descriptions of other object
representations are in ``py/mpconfig.h``.

Because pointers are word-aligned, when they are stored in an ``mp_obj_t`` the
lower bits of this object handle will be zero. For example on a 32-bit architecture
the lower 2 bits will be zero:
Expand Down
4 changes: 4 additions & 0 deletions ports/cc3200/bootmgr/bootloader.mk
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ $(BUILD)/bootloader.bin: $(BUILD)/bootmgr.bin
$(ECHO) "Create $@"
$(Q)$(SHELL) $(BOOT_GEN) $(BUILD)

# Create an empty "float_consts.h" needed by py/mkrules.mk
$(HEADER_BUILD)/float_consts.h: | $(HEADER_BUILD)
touch $@

# Create an empty "qstrdefs.generated.h" needed by py/mkrules.mk
$(HEADER_BUILD)/qstrdefs.generated.h: | $(HEADER_BUILD)
touch $@
Expand Down
1 change: 1 addition & 0 deletions ports/embed/embed.mk
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ CFLAGS += -Wall -Werror -std=c99

# Define the required generated header files.
GENHDR_OUTPUT = $(addprefix $(BUILD)/genhdr/, \
float_consts.h \
moduledefs.h \
mpversion.h \
qstrdefs.generated.h \
Expand Down
4 changes: 3 additions & 1 deletion ports/unix/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,9 @@ endif
CXXFLAGS += $(filter-out -Wmissing-prototypes -Wold-style-definition -std=gnu99,$(CFLAGS) $(CXXFLAGS_MOD))

ifeq ($(MICROPY_FORCE_32BIT),1)
RUN_TESTS_MPY_CROSS_FLAGS = --mpy-cross-flags='-march=x86'
$(info RUN_TESTS_MPY_CROSS_FLAGS=$(RUN_TESTS_MPY_CROSS_FLAGS))
RUN_TESTS_MPY_CROSS_FLAGS ?= --mpy-cross-flags='-march=x86'
$(info RUN_TESTS_MPY_CROSS_FLAGS=$(RUN_TESTS_MPY_CROSS_FLAGS))
endif

ifeq ($(CROSS_COMPILE),arm-linux-gnueabi-)
Expand Down
6 changes: 6 additions & 0 deletions ports/unix/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@
static bool compile_only = false;
static uint emit_opt = MP_EMIT_OPT_NONE;


#if defined(MICROPY_UNIX_COVERAGE) && !defined(NO_QSTR)
#include "genhdr/float_consts.h"
#endif

#if MICROPY_ENABLE_GC
// Heap size of GC heap (if enabled)
// Make it larger on a 64 bit machine, because pointers are larger.
Expand Down Expand Up @@ -613,6 +618,7 @@ MP_NOINLINE int main_(int argc, char **argv) {
MP_DECLARE_CONST_FUN_OBJ_0(extra_cpp_coverage_obj);
mp_store_global(MP_QSTR_extra_coverage, MP_OBJ_FROM_PTR(&extra_coverage_obj));
mp_store_global(MP_QSTR_extra_cpp_coverage, MP_OBJ_FROM_PTR(&extra_cpp_coverage_obj));
mp_store_global(MP_QSTR_one_quarter, (mp_obj_t)MP_CONST_FLOAT_0__25);
}
#endif

Expand Down
43 changes: 43 additions & 0 deletions ports/unix/variants/repr_e/mpconfigvariant.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

// This config exists to test that the MICROPY_OBJ_REPR_E variant
// builds and passes tests. REPR_E uses memory-efficient floating point
// objects encoded directly mp_obj_t (limited exponent range) plus boxed values
// for full float range & precision. Therefore this variant should be built
// using MICROPY_FORCE_32BIT=1

#define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_E)
#define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_FLOAT)

// Set base feature level.
#define MICROPY_CONFIG_ROM_LEVEL (MICROPY_CONFIG_ROM_LEVEL_EXTRA_FEATURES)

// Not compatible with uctypes
#define MICROPY_PY_UCTYPES (0)

// Enable extra Unix features.
#include "../mpconfigvariant_common.h"
8 changes: 8 additions & 0 deletions ports/unix/variants/repr_e/mpconfigvariant.mk
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# build interpreter with "bigints" implemented as "longlong"

# otherwise, small int is essentially 64-bit
MICROPY_FORCE_32BIT := 1

MICROPY_PY_FFI := 0

RUN_TESTS_MPY_CROSS_FLAGS = --mpy-cross-flags='-march=x86 -msmall-int-bits=30'
20 changes: 18 additions & 2 deletions ports/windows/msvc/genhdr.targets
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<Import Project="paths.props" Condition="'$(PyPathsIncluded)' != 'True'"/>

<!--Generate qstrdefs.generated.h and mpversion.h similar to what is done in py/mkrules.mk and py/py.mk-->
<Target Name="GenerateHeaders" DependsOnTargets="MakeVersionHdr;MakeModuleDefs;MakeRootPointers;MakeCompressedData;MakeQstrData">
<Target Name="GenerateHeaders" DependsOnTargets="MakeVersionHdr;MakeModuleDefs;MakeFloatConstants;MakeRootPointers;MakeCompressedData;MakeQstrData">
</Target>

<PropertyGroup>
Expand All @@ -16,6 +16,7 @@
<QstrGen>$(DestDir)qstrdefs.generated.h</QstrGen>
<ModuleDefsCollected>$(DestDir)/moduledefs.collected</ModuleDefsCollected>
<RootPointersCollected>$(DestDir)/root_pointers.collected</RootPointersCollected>
<FloatConstantsCollected>$(DestDir)/float_consts.collected</FloatConstantsCollected>
<CompressedCollected>$(DestDir)/compressed.collected</CompressedCollected>
<PyPython Condition="'$(PyPython)' == ''">$(MICROPY_CPYTHON3)</PyPython>
<PyPython Condition="'$(PyPython)' == ''">python</PyPython>
Expand Down Expand Up @@ -48,7 +49,8 @@ using(var outFile = System.IO.File.CreateText(OutputFile)) {
foreach(var inFile in InputFiles)
foreach(var line in System.IO.File.ReadAllLines(inFile))
if((line.Contains(".c") && line.StartsWith("#line")) || line.Contains("MP_QSTR") ||
line.Contains("MP_REGISTER") || line.Contains("MP_COMPRESSED_ROM_TEXT"))
line.Contains("MP_REGISTER") || line.Contains("MP_COMPRESSED_ROM_TEXT") ||
line.Contains("MP_CONST_FLOAT_"))
outFile.WriteLine( line );
}
]]>
Expand Down Expand Up @@ -122,6 +124,20 @@ using(var outFile = System.IO.File.CreateText(OutputFile)) {
<MSBuild Projects="$(MSBuildThisFileFullPath)" Targets="CopyFileIfDifferent" Properties="SourceFile=$(TmpFile);DestFile=$(DestFile)"/>
</Target>

<Target Name="CollectFloatConstants" DependsOnTargets="MakeQstrDefs" Inputs="$(DestDir)qstr.i.last" Outputs="$(FloatConstantsCollected)">
<Exec Command="$(PyPython) $(PySrcDir)makeqstrdefs.py split float_const $(DestDir)qstr.i.last $(DestDir)float_const _"/>
<Exec Command="$(PyPython) $(PySrcDir)makeqstrdefs.py cat float_const _ $(DestDir)float_const $(FloatConstantsCollected)"/>
</Target>

<Target Name="MakeFloatConstants" DependsOnTargets="CollectFloatConstants" Inputs="$(PySrcDir)make_float_consts.py;$(FloatConstantsCollected)" Outputs="$(DestDir)float_consts.h">
<PropertyGroup>
<DestFile>$(DestDir)float_consts.h</DestFile>
<TmpFile>$(DestFile).tmp</TmpFile>
</PropertyGroup>
<Exec Command="$(PyPython) $(PySrcDir)make_float_consts.py $(FloatConstantsCollected) > $(TmpFile)"/>
<MSBuild Projects="$(MSBuildThisFileFullPath)" Targets="CopyFileIfDifferent" Properties="SourceFile=$(TmpFile);DestFile=$(DestFile)"/>
</Target>

<Target Name="CollectRootPointers" DependsOnTargets="MakeQstrDefs" Inputs="$(DestDir)qstr.i.last" Outputs="$(RootPointersCollected)">
<Exec Command="$(PyPython) $(PySrcDir)makeqstrdefs.py split root_pointer $(DestDir)qstr.i.last $(DestDir)root_pointer _"/>
<Exec Command="$(PyPython) $(PySrcDir)makeqstrdefs.py cat root_pointer _ $(DestDir)root_pointer $(RootPointersCollected)"/>
Expand Down
134 changes: 134 additions & 0 deletions py/make_float_consts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""
This pre-processor parses a single file containing a list of
MP_CONST_FLOAT items.

These are used to generate a header with the required entries.
"""

import argparse
import io
import math
import re
import struct
import sys

from textwrap import dedent

PATTERN = re.compile(r"MP_CONST_FLOAT_[_0-9a-zA-Z]+")


def find_constant_floats(filename):
"""Find any MP_CONST_FLOAT definitions in the provided file.

:param str filename: path to file to check
:return: List[variable_declaration]
"""
with io.open(filename, encoding="utf-8") as c_file_obj:
content = c_file_obj.read()
return set(re.findall(PATTERN, content))


def cast(from_, to, value):
return struct.unpack(to, struct.pack(from_, value))[0]


def removeprefix(s, pfx): # assumes s starts with pfx
return s[len(pfx) :]


repr_e_bias = 0x30080000
repr_e_roll = 3


def roll32_l(val, n):
return ((val << n) | (val >> (32 - n))) & 0xFFFFFFFF


def generate_constant_float_definition(constant_name):
expression = removeprefix(constant_name, "MP_CONST_FLOAT_")
if expression.startswith("__"):
expression = "-" + expression[2:]
expression = expression.replace("__", ".")
value = eval(expression, math.__dict__)
if expression == "inf":
c_value = "INFINITY"
elif expression == "-inf":
c_value = "-INFINITY"
elif expression == "nan":
c_value = "NAN"
elif expression == "-0":
c_value = "-0."
else:
c_value = float(value)

print(f"// {constant_name} = {value}")
double_as_uint64 = cast("d", "Q", value)
repr_d_value = double_as_uint64 + 0x8004000000000000
float_as_uint32 = cast("f", "I", value)
repr_c_value = ((((float_as_uint32) & ~3) | 2) + 0x80800000) & 0xFFFFFFFF
repr_e_value = roll32_l((float_as_uint32 + repr_e_bias) & 0xFFFFFFFF, repr_e_roll)

print(
dedent(f"""\
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B
extern const struct _mp_obj_float_t {constant_name}_obj;
#define {constant_name} MP_ROM_PTR(&{constant_name}_obj)
#if defined(MP_FLOAT_CONSTS_IMPL)
const mp_obj_float_t {constant_name}_obj = {{ {{&mp_type_float}}, (mp_float_t)({c_value}) }};
#endif
#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
#define {constant_name} {{ ((mp_obj_t)((uint64_t){repr_d_value:#x})) }}
#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
#define {constant_name} ((mp_obj_t)((uint64_t){repr_c_value:#x}))
#else // REPR_E""")
)

if repr_e_value & 0x3 == 3:
print(f"#define {constant_name} ((mp_obj_t)((uint64_t){repr_e_value:#x}))")
else:
print(
dedent(f"""\
extern const struct _mp_obj_float_t {constant_name}_obj;
#define {constant_name} MP_ROM_PTR(&{constant_name}_obj)
#if defined(MP_FLOAT_CONSTS_IMPL)
const mp_obj_float_t {constant_name}_obj = {{ {{&mp_type_float}}, (mp_float_t)({c_value}) }};
#endif""")
)

print("""#endif""")
print()


def generate_constant_float_header(constant_floats):
"""Generate header with root pointer entries.

:param List[variable_declaration] constant_floats: root pointer declarations
:return: None
"""

# Print header file for all external modules.
print(
dedent("""\
// Automatically generated by make_constant_floats.py.
#ifndef MICROPY_INCLUDED_FLOAT_CONSTS_H
#define MICROPY_INCLUDED_FLOAT_CONSTS_H
""")
)

for item in constant_floats:
generate_constant_float_definition(item)

print("#endif")


def main():
parser = argparse.ArgumentParser()
parser.add_argument("file", nargs=1, help="file with MP_CONST_FLOAT definitions")
args = parser.parse_args()

constant_floats = find_constant_floats(args.file[0])
generate_constant_float_header(sorted(constant_floats))


if __name__ == "__main__":
main()
20 changes: 18 additions & 2 deletions py/makeqstrdefs.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
# Extract MP_REGISTER_ROOT_POINTER(...) macros.
_MODE_ROOT_POINTER = "root_pointer"

# Extract MP_CONST_FLOAT_ macros.
_MODE_FLOAT_CONST = "float_const"


class PreprocessorError(Exception):
pass
Expand Down Expand Up @@ -103,6 +106,8 @@ def process_file(f):
)
elif args.mode == _MODE_ROOT_POINTER:
re_match = re.compile(r"MP_REGISTER_ROOT_POINTER\(.*?\);")
elif args.mode == _MODE_FLOAT_CONST:
re_match = re.compile(r"MP_CONST_FLOAT_[_a-zA-Z0-9]+")
output = []
last_fname = None
for line in f:
Expand All @@ -122,7 +127,12 @@ def process_file(f):
if args.mode == _MODE_QSTR:
name = match.replace("MP_QSTR_", "")
output.append("Q(" + name + ")")
elif args.mode in (_MODE_COMPRESS, _MODE_MODULE, _MODE_ROOT_POINTER):
elif args.mode in (
_MODE_COMPRESS,
_MODE_MODULE,
_MODE_ROOT_POINTER,
_MODE_FLOAT_CONST,
):
output.append(match)

if last_fname:
Expand Down Expand Up @@ -220,7 +230,13 @@ class Args:
args.output_dir = sys.argv[4]
args.output_file = None if len(sys.argv) == 5 else sys.argv[5] # Unused for command=split

if args.mode not in (_MODE_QSTR, _MODE_COMPRESS, _MODE_MODULE, _MODE_ROOT_POINTER):
if args.mode not in (
_MODE_QSTR,
_MODE_COMPRESS,
_MODE_MODULE,
_MODE_ROOT_POINTER,
_MODE_FLOAT_CONST,
):
print("error: mode %s unrecognised" % sys.argv[2])
sys.exit(2)

Expand Down
Loading
Loading