aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas "Cakeisalie5" Touhey <thomas@touhey.fr>2018-10-23 14:19:07 +0200
committerThomas "Cakeisalie5" Touhey <thomas@touhey.fr>2018-10-23 14:19:07 +0200
commit3ef4a896d944325cd62a66b22dd9bd7ab07937d5 (patch)
tree48c3805568cd5103a1913b669a4428f8e04d20cd
parent313c7fdfb6257db3c847aeab44336b8c57da643b (diff)
Latest changes (a lot).
-rwxr-xr-xMakefile6
-rw-r--r--Pipfile11
-rw-r--r--authors.toml4
-rwxr-xr-xconfigure2
-rw-r--r--configure.bat3
-rw-r--r--copyright.yml19
-rw-r--r--docs/building.en.rst60
-rw-r--r--docs/coding.en.rst3
-rw-r--r--docs/config.en.rst133
-rw-r--r--docs/contributing.en.rst313
-rw-r--r--docs/index.en.rst8
-rw-r--r--docs/licensing.en.rst102
-rw-r--r--docs/preprocessor.en.rst40
-rwxr-xr-xmake2
-rw-r--r--make.bat3
-rw-r--r--modules/all/core-sh/copyright.yml5
-rw-r--r--modules/all/core-sh/docs/index.en.rst4
-rw-r--r--modules/all/core-sh/docs/intrinsics.en.rst46
-rw-r--r--modules/all/core-sh/include/umachine.h2
-rw-r--r--modules/all/core-sh/info.yml7
-rw-r--r--modules/all/core-sh/module.toml60
-rw-r--r--modules/all/core-sh/roles.yml18
-rw-r--r--modules/all/core-sh/src/bswap16.gnu.src (renamed from modules/all/core-sh/src/bswap16.s)0
-rw-r--r--modules/all/core-sh/src/bswap32.gnu.src (renamed from modules/all/core-sh/src/bswap32.s)0
-rw-r--r--modules/all/core-sh/src/smachine/spc.gnu.src (renamed from modules/all/core-sh/src/smachine/spc.s)0
-rw-r--r--modules/all/core-sh/src/smachine/spc.sh.src (renamed from modules/all/core-sh/src/smachine/spc.src)0
-rw-r--r--modules/all/core-sh/src/smachine/ssr.gnu.src (renamed from modules/all/core-sh/src/smachine/ssr.s)0
-rw-r--r--modules/all/core-sh/src/smachine/ssr.sh.src (renamed from modules/all/core-sh/src/smachine/ssr.src)0
-rw-r--r--modules/all/core/copyright.yml10
-rw-r--r--modules/all/core/include/byteswap.h8
-rw-r--r--modules/all/core/include/cdefs.h23
-rw-r--r--modules/all/core/include/stddef.h2
-rw-r--r--modules/all/core/info.yml5
-rw-r--r--modules/all/core/module.toml61
-rw-r--r--modules/all/core/roles.yml17
-rw-r--r--modules/all/ctype/copyright.yml5
-rw-r--r--modules/all/ctype/info.yml5
-rw-r--r--modules/all/ctype/module.toml81
-rw-r--r--modules/all/ctype/roles.yml21
-rw-r--r--modules/all/errno/bits/stdio.h3
-rw-r--r--modules/all/errno/include/errno.h8
-rw-r--r--modules/all/errno/info.yml5
-rw-r--r--modules/all/errno/module.toml25
-rw-r--r--modules/all/errno/roles.yml62
-rw-r--r--modules/all/errno/src/perror.c19
-rw-r--r--modules/all/helloworld/copyright.yml5
-rw-r--r--modules/all/helloworld/info.yml5
-rw-r--r--modules/all/helloworld/module.toml17
-rw-r--r--modules/all/helloworld/roles.yml6
-rw-r--r--modules/all/hosted-sh/copyright.yml5
-rw-r--r--modules/all/hosted-sh/info.yml7
-rw-r--r--modules/all/hosted-sh/module.toml24
-rw-r--r--modules/all/hosted-sh/roles.yml7
-rw-r--r--modules/all/hosted-sh/src/longjmp.gnu.src (renamed from modules/all/hosted-sh/src/longjmp.s)0
-rw-r--r--modules/all/hosted-sh/src/setjmp.gnu.src (renamed from modules/all/hosted-sh/src/setjmp.s)0
-rw-r--r--modules/all/hosted/copyright.yml10
-rw-r--r--modules/all/hosted/include/errno.h14
-rw-r--r--modules/all/hosted/include/inttypes.h183
-rw-r--r--modules/all/hosted/info.yml5
-rw-r--r--modules/all/hosted/module.toml69
-rw-r--r--modules/all/hosted/roles.yml46
-rw-r--r--modules/all/hosted/src/div.c (renamed from modules/all/hosted/src/stdlib/div.c)2
-rw-r--r--modules/all/hosted/src/errno.c45
-rw-r--r--modules/all/hosted/src/locales.c21
-rw-r--r--modules/all/hosted/src/rand.c (renamed from modules/all/hosted/src/stdlib/rand.c)0
-rw-r--r--modules/all/hosted/src/wchar.c (renamed from modules/all/hosted/src/stdlib/wchar.c)0
-rw-r--r--modules/all/iconv-unicode/bits/iconv_proto.h2
-rw-r--r--modules/all/iconv-unicode/bits/iconv_route.h10
-rw-r--r--modules/all/iconv-unicode/copyright.yml5
-rw-r--r--modules/all/iconv-unicode/info.yml5
-rw-r--r--modules/all/iconv-unicode/module.toml24
-rw-r--r--modules/all/iconv-unicode/roles.yml8
-rw-r--r--modules/all/iconv-unicode/src/utf8_to_utf32.c14
-rw-r--r--modules/all/iconv-unicode/src/utf8_to_wchar.c44
-rw-r--r--modules/all/iconv-unicode/src/wchar_to_utf8.c28
-rw-r--r--modules/all/iconv/copyright.yml5
-rw-r--r--modules/all/iconv/include/iconv.h61
-rw-r--r--modules/all/iconv/info.yml5
-rw-r--r--modules/all/iconv/module.toml29
-rw-r--r--modules/all/iconv/roles.yml9
-rw-r--r--modules/all/iconv/src/iconv.c2
-rw-r--r--modules/all/iconv/src/iconv.h9
-rw-r--r--modules/all/iconv/src/open.c64
-rw-r--r--modules/all/iconv/src/routes.c11
-rw-r--r--modules/all/info.yml11
-rw-r--r--modules/all/io/copyright.yml10
-rw-r--r--modules/all/io/docs/printf.en.rst52
-rw-r--r--modules/all/io/include/inttypes.h183
-rw-r--r--modules/all/io/include/printf.h60
-rw-r--r--modules/all/io/include/stdio.h68
-rw-r--r--modules/all/io/info.yml5
-rw-r--r--modules/all/io/module.toml97
-rw-r--r--modules/all/io/roles.yml22
-rw-r--r--modules/all/io/src/mode.c32
-rw-r--r--modules/all/io/src/open.c.draft2
-rw-r--r--modules/all/io/src/printf/default.c139
-rw-r--r--modules/all/io/src/printf/default/char.c24
-rw-r--r--modules/all/io/src/printf/default/cnt.c21
-rw-r--r--modules/all/io/src/printf/default/int.c104
-rw-r--r--modules/all/io/src/printf/default/int.h104
-rw-r--r--modules/all/io/src/printf/default/str.c26
-rw-r--r--modules/all/io/src/printf/default/uint.c106
-rw-r--r--modules/all/io/src/printf/pad.c74
-rw-r--r--modules/all/io/src/printf/printf.h20
-rw-r--r--modules/all/io/src/printf/register.c136
-rw-r--r--modules/all/io/src/printf/sprintf.c29
-rw-r--r--modules/all/io/src/printf/vfprintf.c288
-rw-r--r--modules/all/io/src/read.c21
-rw-r--r--modules/all/io/src/seek.c29
-rw-r--r--modules/all/math/copyright.yml5
-rw-r--r--modules/all/math/info.yml6
-rw-r--r--modules/all/math/module.toml18
-rw-r--r--modules/all/math/roles.yml5
-rw-r--r--modules/all/mem/copyright.yml5
-rw-r--r--modules/all/mem/include/malloc.h26
-rw-r--r--modules/all/mem/info.yml5
-rw-r--r--modules/all/mem/module.toml25
-rw-r--r--modules/all/mem/roles.yml8
-rw-r--r--modules/all/stdcocorico/copyright.yml10
-rw-r--r--modules/all/stdcocorico/info.yml5
-rw-r--r--modules/all/stdcocorico/module.toml18
-rw-r--r--modules/all/stdcocorico/roles.yml4
-rw-r--r--modules/all/string-sh/copyright.yml5
-rw-r--r--modules/all/string-sh/info.yml9
-rw-r--r--modules/all/string-sh/module.toml21
-rw-r--r--modules/all/string-sh/src/memchr.gnu.src (renamed from modules/all/string-sh/src/memchr.s)7
-rw-r--r--modules/all/string/info.yml5
-rw-r--r--modules/all/string/module.toml133
-rw-r--r--modules/all/system.toml5
-rw-r--r--modules/all/time/copyright.yml5
-rw-r--r--modules/all/time/info.yml5
-rw-r--r--modules/all/time/module.toml21
-rw-r--r--modules/all/time/roles.yml2
-rw-r--r--modules/all/time/src/gmtime_r.c1
-rw-r--r--modules/all/time/src/mktime.c4
-rw-r--r--modules/casiowin/copyright.yml5
-rw-r--r--modules/casiowin/core-crt/copyright.yml5
-rw-r--r--modules/casiowin/core-crt/info.yml6
-rw-r--r--modules/casiowin/core-crt/module.toml14
-rw-r--r--modules/casiowin/core-crt/roles.yml4
-rw-r--r--modules/casiowin/core/copyright.yml5
-rw-r--r--modules/casiowin/core/info.yml5
-rw-r--r--modules/casiowin/core/module.toml45
-rw-r--r--modules/casiowin/core/roles.yml17
-rw-r--r--modules/casiowin/core/src/alloc/_syscalls.sx24
-rw-r--r--modules/casiowin/core/src/alloc/syscalls.gnu.src6
-rw-r--r--modules/casiowin/core/src/assert/_syscalls.sx24
-rw-r--r--modules/casiowin/core/src/assert/assert.c8
-rw-r--r--modules/casiowin/core/src/assert/syscalls.gnu.src6
-rw-r--r--modules/casiowin/core/src/core/_syscalls.sx23
-rw-r--r--modules/casiowin/core/src/core/syscalls.gnu.src5
-rw-r--r--modules/casiowin/core/src/dirent/syscalls.gnu.src (renamed from modules/casiowin/core/src/dirent/syscalls.s)2
-rw-r--r--modules/casiowin/core/src/io/syscalls.gnu.src (renamed from modules/casiowin/core/src/io/syscalls.s)2
-rw-r--r--modules/casiowin/core/src/syscall.gnu.inc (renamed from modules/casiowin/fxlib/src/syscall.inc)0
-rw-r--r--modules/casiowin/core/src/syscall.h35
-rw-r--r--modules/casiowin/easy-input/copyright.yml10
-rw-r--r--modules/casiowin/easy-input/info.yml7
-rw-r--r--modules/casiowin/easy-input/module.toml31
-rw-r--r--modules/casiowin/easy-input/roles.yml8
-rw-r--r--modules/casiowin/easy-input/src/syscalls.gnu.src (renamed from modules/casiowin/easy-input/src/_syscalls.s)0
-rw-r--r--modules/casiowin/easy-input/src/syscalls.sh.src (renamed from modules/casiowin/easy-input/src/_syscalls.src)0
-rw-r--r--modules/casiowin/fxlib/copyright.yml5
-rw-r--r--modules/casiowin/fxlib/include/commbios.h3
-rw-r--r--modules/casiowin/fxlib/include/dispbios.h3
-rw-r--r--modules/casiowin/fxlib/include/filebios.h2
-rw-r--r--modules/casiowin/fxlib/include/keybios.h3
-rw-r--r--modules/casiowin/fxlib/include/timer.h3
-rw-r--r--modules/casiowin/fxlib/info.yml6
-rw-r--r--modules/casiowin/fxlib/module.toml114
-rw-r--r--modules/casiowin/fxlib/roles.yml38
-rw-r--r--modules/casiowin/fxlib/src/comm/syscalls.gnu.src (renamed from modules/casiowin/fxlib/src/comm/syscalls.s)2
-rw-r--r--modules/casiowin/fxlib/src/display/syscalls.gnu.src (renamed from modules/casiowin/fxlib/src/display/syscalls.s)2
-rw-r--r--modules/casiowin/fxlib/src/file/syscalls.gnu.src (renamed from modules/casiowin/fxlib/src/file/syscalls.s)2
-rw-r--r--modules/casiowin/fxlib/src/keyboard/syscalls.gnu.src3
-rw-r--r--modules/casiowin/fxlib/src/keyboard/syscalls.s3
-rw-r--r--modules/casiowin/fxlib/src/serial/syscalls.gnu.src (renamed from modules/casiowin/fxlib/src/serial/syscalls.s)2
-rw-r--r--modules/casiowin/fxlib/src/syscall.gnu.inc (renamed from modules/casiowin/io/src/syscall.inc)0
-rw-r--r--modules/casiowin/fxlib/src/timer/syscalls.gnu.src (renamed from modules/casiowin/fxlib/src/timer/syscalls.s)2
-rw-r--r--modules/casiowin/g1a.ld22
-rw-r--r--modules/casiowin/info.yml18
-rw-r--r--modules/casiowin/io/copyright.yml5
-rw-r--r--modules/casiowin/io/info.yml5
-rw-r--r--modules/casiowin/io/module.toml36
-rw-r--r--modules/casiowin/io/roles.yml17
-rw-r--r--modules/casiowin/io/src/open.c20
-rw-r--r--modules/casiowin/io/src/syscall.gnu.inc14
-rw-r--r--modules/casiowin/io/src/syscalls.gnu.src (renamed from modules/casiowin/io/src/syscalls.s)2
-rw-r--r--modules/casiowin/libfxsys/copyright.yml5
-rw-r--r--modules/casiowin/libfxsys/docs/index.en.rst9
-rw-r--r--modules/casiowin/libfxsys/include/app.h31
-rw-r--r--modules/casiowin/libfxsys/include/asm.h60
-rw-r--r--modules/casiowin/libfxsys/include/disp.h31
-rw-r--r--modules/casiowin/libfxsys/include/file.h31
-rw-r--r--modules/casiowin/libfxsys/include/key.h31
-rw-r--r--modules/casiowin/libfxsys/include/keycodes.h31
-rw-r--r--modules/casiowin/libfxsys/include/official.h44
-rw-r--r--modules/casiowin/libfxsys/include/print.h31
-rw-r--r--modules/casiowin/libfxsys/include/rtc.h31
-rw-r--r--modules/casiowin/libfxsys/include/syscall.h31
-rw-r--r--modules/casiowin/libfxsys/info.yml7
-rw-r--r--modules/casiowin/libfxsys/roles.yml13
-rw-r--r--modules/casiowin/monochromelib/copyright.yml8
-rw-r--r--modules/casiowin/monochromelib/info.yml7
-rw-r--r--modules/casiowin/monochromelib/module.toml188
-rw-r--r--modules/casiowin/monochromelib/roles.yml47
-rw-r--r--modules/casiowin/system.toml11
-rw-r--r--modules/compiler/host-gcc-sh/bits/smachine.h43
-rw-r--r--modules/compiler/host-gcc-sh/bits/stdarg.h16
-rw-r--r--modules/compiler/host-gcc-sh/bits/types/exact.h24
-rw-r--r--modules/compiler/host-gcc-sh/bits/types/fast.h57
-rw-r--r--modules/compiler/host-gcc-sh/bits/types/least.h66
-rw-r--r--modules/compiler/host-gcc-sh/bits/types/max.h42
-rw-r--r--modules/compiler/host-gcc-sh/bits/types/ptr.h39
-rw-r--r--modules/compiler/host-gcc-sh/bits/umachine.h224
-rw-r--r--modules/compiler/host-gcc-sh/bits/varargs.h3
-rw-r--r--modules/compiler/host-gcc-sh/copyright.yml5
-rw-r--r--modules/compiler/host-gcc-sh/info.yml9
-rw-r--r--modules/compiler/host-gcc-sh/module.toml21
-rw-r--r--modules/compiler/host-gcc-sh/roles.yml9
-rw-r--r--modules/compiler/host-gcc/bits/stdarg.h5
-rw-r--r--modules/compiler/host-gcc/copyright.yml5
-rw-r--r--modules/compiler/host-gcc/info.yml8
-rw-r--r--modules/compiler/host-gcc/module.toml56
-rw-r--r--modules/compiler/host-gcc/roles.yml9
-rw-r--r--modules/compiler/host-renesas/copyright.yml5
-rw-r--r--modules/compiler/host-renesas/info.yml9
-rw-r--r--modules/compiler/host-renesas/module.toml56
-rw-r--r--modules/compiler/host-renesas/roles.yml3
-rw-r--r--modules/compiler/info.yml10
-rw-r--r--modules/compiler/system.toml6
-rw-r--r--modules/compiler/target-gcc-sh/bits/types/primitive.h61
-rw-r--r--modules/compiler/target-gcc-sh/module.toml17
-rw-r--r--modules/compiler/target-renesas/bits/types/primitive.h (renamed from modules/compiler/target-renesas/bits/primitive.h)0
-rw-r--r--modules/compiler/target-renesas/copyright.yml5
-rw-r--r--modules/compiler/target-renesas/info.yml9
-rw-r--r--modules/compiler/target-renesas/module.toml16
-rw-r--r--modules/compiler/target-renesas/roles.yml3
-rw-r--r--modules/renesas/errno/copyright.yml5
-rw-r--r--modules/renesas/errno/info.yml7
-rw-r--r--modules/renesas/errno/module.toml20
-rw-r--r--modules/renesas/errno/roles.yml6
-rw-r--r--modules/renesas/errno/src/errlist.c2
-rw-r--r--modules/renesas/info.yml9
-rw-r--r--modules/renesas/system.toml7
-rw-r--r--project.toml19
-rw-r--r--project.yml13
-rw-r--r--requirements.txt1
-rwxr-xr-xtools/Internals/__init__.py18
-rwxr-xr-xtools/Internals/arch.py57
-rwxr-xr-xtools/Internals/args.py218
-rwxr-xr-xtools/Internals/build/__init__.py329
-rwxr-xr-xtools/Internals/build/gnu_ar.py105
-rwxr-xr-xtools/Internals/build/gnu_as.py102
-rwxr-xr-xtools/Internals/build/gnu_gcc.py170
-rw-r--r--tools/Internals/build/gnu_ld.py84
-rwxr-xr-xtools/Internals/build/renesas_asmsh.py89
-rwxr-xr-xtools/Internals/build/renesas_optlnk.py79
-rwxr-xr-xtools/Internals/build/renesas_shc.py117
-rwxr-xr-xtools/Internals/build/utils/__init__.py61
-rwxr-xr-xtools/Internals/build/utils/bfd.py150
-rwxr-xr-xtools/Internals/build/utils/formats.py31
-rwxr-xr-xtools/Internals/cache.py55
-rwxr-xr-xtools/Internals/config.py66
-rwxr-xr-xtools/Internals/copyright.py204
-rwxr-xr-xtools/Internals/exceptions.py329
-rwxr-xr-xtools/Internals/gettext.py9
-rwxr-xr-xtools/Internals/headers/__init__.py411
-rw-r--r--tools/Internals/headers/elements.py140
-rwxr-xr-xtools/Internals/headers/eval.py7
-rwxr-xr-xtools/Internals/headers/output.py77
-rwxr-xr-xtools/Internals/headers/parse.py243
-rwxr-xr-xtools/Internals/headers/profile.py74
-rwxr-xr-xtools/Internals/topc.py181
-rw-r--r--tools/Pipfile11
-rw-r--r--tools/Pipfile.lock37
-rwxr-xr-xtools/configure.py286
-rwxr-xr-xtools/make.py379
-rw-r--r--tools/potato.bat2
-rwxr-xr-xtools/potato.sh102
-rwxr-xr-xtools/potato/__init__.py6
-rwxr-xr-xtools/potato/__main__.py130
-rwxr-xr-xtools/potato/_module.py (renamed from tools/Internals/module.py)25
-rwxr-xr-xtools/potato/_project.py (renamed from tools/Internals/project.py)288
-rw-r--r--tools/potato/_utils.py81
-rwxr-xr-xtools/python3.sh30
-rw-r--r--tools/testthings.py11
-rwxr-xr-xtools/updatesource.py95
287 files changed, 4040 insertions, 7098 deletions
diff --git a/Makefile b/Makefile
index ee23a39..cbe73d4 100755
--- a/Makefile
+++ b/Makefile
@@ -1,10 +1,10 @@
#!/usr/bin/make -f
- MK := @PROGNAME='make' tools/python3.sh tools/make.py
- CMDS := $(shell tools/python3.sh tools/make.py listcmds)
+ PT := @tools/potato.sh
+ CMDS := $(shell $(PT) list-commands)
define make-rule
$1:
- $(MK) $1
+ $(PT) $1
endef
$(foreach cmd,$(CMDS),\
$(eval $(call make-rule,$(cmd))))
diff --git a/Pipfile b/Pipfile
new file mode 100644
index 0000000..b9ba84f
--- /dev/null
+++ b/Pipfile
@@ -0,0 +1,11 @@
+[[source]]
+url = "https://pypi.org/simple"
+verify_ssl = true
+name = "pypi"
+
+[packages]
+
+[dev-packages]
+
+[requires]
+python_version = "3.7"
diff --git a/authors.toml b/authors.toml
new file mode 100644
index 0000000..3c50667
--- /dev/null
+++ b/authors.toml
@@ -0,0 +1,4 @@
+[ttouhey]
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+web = "https://thomas.touhey.fr/"
diff --git a/configure b/configure
index 3a6f054..40fb688 100755
--- a/configure
+++ b/configure
@@ -4,5 +4,5 @@ if ! [ x"$curdir" = "$0" ]; then
cd "$curdir"
fi
-PROGNAME='./configure' tools/python3.sh tools/configure.py "$@"
+tools/potato.sh configure "$@"
exit $?
diff --git a/configure.bat b/configure.bat
index b0c6c74..4a63577 100644
--- a/configure.bat
+++ b/configure.bat
@@ -1,3 +1,2 @@
cd %~p0
-set PROGNAME=configure.bat
-py -3 tools/configure.py %*
+tools/potato.bat configure %*
diff --git a/copyright.yml b/copyright.yml
deleted file mode 100644
index feaa23c..0000000
--- a/copyright.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-%YAML 1.2
----
-files:
-- 'modules'
-- 'docs'
-- 'tools/*.py'
-- 'tools/**/*.py'
-- 'tools/Internals/locales/*.yml'
-- 'README.md'
-- 'LICENSE.md'
-- 'copyright.yml'
-- 'configure'
-- 'configure.bat'
-- 'Makefile'
-- 'make'
-- 'make.bat'
-- 'requirements.txt'
-copyright:
-- [2017, 2018, Thomas "Cakeisalie5" Touhey, thomas@touhey.fr]
diff --git a/docs/building.en.rst b/docs/building.en.rst
index c120f4e..7e6180a 100644
--- a/docs/building.en.rst
+++ b/docs/building.en.rst
@@ -7,27 +7,33 @@ you can start building it.
Requirements
------------
-You will need Python 3.x to run the build tool, with the modules described
-in the ``requirements.txt`` file, which you can install using
-``pip3 install -r requirements.txt`` as root/administrator.
+You will need Python 3.x and pipenv to run the build tool, named ``potato``,
+the latest tool being used to install the appropriate modules.
Other dependencies (compilers, assemblers, linkers, packers, ...) are optional,
and should be tipped off by the tools.
-Configuring
------------
+Running the tool
+----------------
+
+Everything goes through the ``potato`` tool, which you can run by using
+the ``tools/potato.sh`` tool under POSIX-compliant systems and
+``tools/potato.bat`` under Microsoft Windows and compatible systems.
+This tool is hidden behind a few scripts to make it easier to the user.
-This project uses the Unix building flow, which means you shall first
-configure with the options that suit your needs, then make (build), then
-install, in three different commands. On Unix-like OSes, this can be achieved
-using the famous ``./configure && make && sudo make install`` bash command;
-but I'll suppose you want to go a little deeper into its options.
+Under Microsoft Windows and compatible systems, you can use the
+``configure.bat`` tool to run the configure command, and the ``make.bat``
+to run other commands.
-The 'real' configure script is in ``tool/configure.py``, though it can be
-accessed under Unix-like OSes through the `configure` bash script and under
-Microsoft Windows' command shell through the ``configure.bat`` script,
-for simplicity. ``-h``/``--help`` prints the help message, listing the options
-and a little help message, ``-v``/``--version`` prints the project version.
+Under POSIX-compliant systems, the ``./configure && make && make install``
+traditional build flow can be used.
+
+For all systems, the commands' options are the same. For simplicity,
+``-h``/``--help`` prints the help message, listing the options and a little
+help message, and ``-v``/``--version`` prints the project version.
+
+Configuring
+-----------
libcarrot is built for a target, which is a combination of the following
elements, separated by dashes:
@@ -65,22 +71,30 @@ Here are some examples:
.. code-block:: bash
# shared libraries for linux, with some more modules
+
./configure --target=x86_64-linux --shared \
--add all/stdcocorico --add all/helloworld
# static libraries for casiowin for use by the Renesas toolchain
+
./configure --target=sh3eb-casiowin --flavour=renesas
+ # same as before but on ms-windows
+
+ configure.bat --target=sh3eb-casiowin --flavour=renesas
+
Building and installing
-----------------------
-Once the project is configured, you can ``make`` under UNIX-like OSes,
-``make.bat`` under Microsoft Windows (using the command shell), or
-``tools/make.py`` on any other system.
+Once the project has been successfully configured, you can make using
+``make [target]`` under POSIX-compliant systems or ``make.bat [target]``
+under Microsoft Windows and compatible.
+
+For building everything, use the ``all`` target (which is the default target),
+and for installing everything, use the ``install`` target.
-There are actually a few other commands you can do with ``make``, such as
-``clean`` to remove generated files (excepted the configuration),
-``mrproper`` or ``distclean`` to remove everything (including the
-configuration), ``re`` to remake everything (expected the configuration).
+Other useful targets are the following:
-To install the library, use ``make install``.
+- ``clean``: remove generated files (except the configuration).
+- ``distclean``: remove everything (including the configuration).
+- ``re``: remake everything (except the configuration).
diff --git a/docs/coding.en.rst b/docs/coding.en.rst
index 790ca1f..ed8a84e 100644
--- a/docs/coding.en.rst
+++ b/docs/coding.en.rst
@@ -5,8 +5,7 @@ This coding style is the one the libcarrot project uses — see
:ref:`contributing` for a more general guide about how to
contribute, or the rest of this guide for how to code in this project.
-A good place to start is `the libcarrot preprocessor guide`
-[the libcarrot preprocessor guide](preprocessor.en.md).
+A good place to start is `the libcarrot preprocessor guide <processor.en.md>`_.
This file is to re-write (TODO), as many things have been rethought
(top comments are now generated, the super-preprocessor has been
diff --git a/docs/config.en.rst b/docs/config.en.rst
index dea3b5a..5f6e8b3 100644
--- a/docs/config.en.rst
+++ b/docs/config.en.rst
@@ -1,74 +1,95 @@
libcarrot configuration format
==============================
-In [the build process](building.en.md), the first step is configuration
-using the `tools/configure.py` utility. This file describes the configuration
+In `the build process <building>`_, the first step is configuration
+using the configure command. This file describes the configuration
format that this utility produces, and that the other utilities will
eventually read.
-The configuration is usually stored in `.config` in the project root.
-It is YAML-encoded, and should have the following properties:
+The configuration is usually stored in ``.config.toml`` in the project root.
+It is TOML-encoded, and is thought to have properties which redefine the
+ones in the project information file, and other properties not in the
+project root.
-- `magic`: should be equal to `potatosdk-1.0`;
-- `locations`: the locations configuration described further;
-- `modules`: the list of selected modules to build and install together;
-- `tools`: the tools configuration described further;
-- `orig`: the original command line of the configure script.
+It has the following properties:
-# Locations configuration structure
-The configuration contains the locations of the key files and directories
-used by the other tools. It contains at least the `main` location, which is
-the location of the project-related data, normally `project.yml` — the
-root directory of the project is deduced from this path, as the folder the
-project-related data file is stored in.
+``magic``
+ Shall be equal to ``potatosdk-1.0``.
-The following properties, if present, override the values in the
-project-related data:
+``locations``
+ The locations (files and folders) to use, among which:
-- `modules`: the modules root directory;
-- `build`: the build directory.
+ ``doc``
+ The documentation root for overall documentation.
+
+ ``modules``
+ The modules root.
+
+ ``build``
+ The build folder to create (if necessary) and use.
+
+ ``project``
+ The project information file.
+
+``modules``
+ (req.) The list of selected modules to build and install together.
+
+``tools``
+ (req.) The tools configuration described further.
+
+``orig``
+ (opt.) The original command line of the configure script.
+
+Tools configuration structure
+-----------------------------
-# Tools configuration structure
The configuration contains the tools that have been selected for building by
-the configure script, and their configuration, in the `tools` property.
+the configure script, and their configuration, in the ``tools`` property.
+
+
+
This property is splitted into two different properties:
-- `ids`: the tools IDs (manufacturer and tool name);
-- `params`: the tools configuration.
+``ids``
+ The tools IDs (manufacturer and tool name).
+
+``params``
+ The tools configuration.
-Each one of these is a dictionary, linking tool types (`cc` for C compilers,
-…) to tool identifiers for `ids` (a two-element
-list containing the manufacturer and tool name as strings) and a
-tool-dependant configuration in `params` (could be a dictionary or anything).
+Each one of these is a dictionary, linking tool types (``cc`` for C compilers,
+…) to tool identifiers for ``ids`` (a two-element list containing the
+manufacturer and tool name as strings) and a tool-dependant configuration
+in ``params`` (could be a dictionary or anything).
-# Full configuration example
An full example configuration is the following:
-```yaml
-%YAML 1.2
----
-magic: potatosdk-1.0
-modules:
-- all/core
-- all/core-sh
-- all/io
-- all/compiler-gcc
-- casiowin/fxlib
-- casiowin/fxlib-core
-- casiowin/fxlib-crt
-tools:
- ids:
- cc: [GNU, GCC]
- asm: [GNU, as]
- pack: [GNU, ar]
- params:
- cc:
- path: /opt/sh3eb-elf/bin/sh3eb-elf-gcc
- flags: [-Wall, -Wextra, -Wno-attributes, -O2, -nostartfiles, -mhitachi]
- asm:
- path: /opt/sh3eb-elf/bin/sh3eb-elf-as
- flags: [--isa=sh3, --big]
- pack:
- path: /opt/sh3eb-elf/bin/sh3eb-elf-ar
-orig: "--target=sh3eb-casiowin"
-```
+.. code-block::
+
+ magic = "potatosdk-1.0"
+ orig = "--target=sh3eb-casiowin"
+
+ modules = ["all/core", "all/core-sh", "all/io",
+ "casiowin/core", "casiowin/core-crt", "casiowin/fxlib", "casiowin/io",
+ "compiler/host-gcc", "compiler/host-gcc-sh", "compiler/target-gcc-sh"]
+
+ [locations]
+ doc = "doc"
+ modules = "modules"
+ build = "build"
+
+ [tools]
+ cc = ["GNU", "GCC"]
+ asm = ["GNU", "as"]
+ pack = ["GNU", "ar"]
+
+ [tools.cc_p]
+ path = "/opt/sh3eb-elf/bin/sh3eb-elf-gcc"
+ flags = ["-Wall", "-Wextra", "-Wno-attributes", "-O2", "-nostartfiles",
+ "-mhitachi"]
+
+ [tools.asm_p]
+ path = "/opt/sh3eb-elf/bin/sh3eb-elf-as"
+ flags = ["--isa=sh3", "--big"]
+
+ [tools.pack_p]
+ path = "/opt/sh3eb-elf/bin/sh3eb-elf-ar"
diff --git a/docs/contributing.en.rst b/docs/contributing.en.rst
index 96e1cbc..a5a4e83 100644
--- a/docs/contributing.en.rst
+++ b/docs/contributing.en.rst
@@ -1,4 +1,5 @@
-:title: Contributing to libcarrot
+Contributing to libcarrot
+=========================
First of all, thanks for reading this! It probably means you think libcarrot
might be worth the effort you are going to put in it, and that rocks! :D
@@ -30,15 +31,16 @@ systems) are located in ``./modules``. They are grouped by systems (folders
representing them). Here's an example ``./modules`` arborescence:
::
- info.yml (global information file)
+ project.toml (global information file)
+ authors.toml (authors for the whole project)
all/
- info.yml (`all` system information file)
+ system.toml (`all` system information file)
core/
(`all/core` module related stuff)
other/
(`all/other` module related stuff)
mysys/
- info.yml (`mysys` system information file)
+ system.toml (`mysys` system information file)
core/
(`mysys/core` module related stuff)
@@ -62,130 +64,172 @@ Modules have the following organization ("opt." means "optional", "req." means
``man/``
(opt.) The manpages corresponding to the module.
-``info.yml``
+``module.toml``
(req.) The module information file.
-``copyright.yml``
- (rec.) The machine-readable copyright information file.
-
-``roles.yml``
- (rec.) The machine-readable roles for your source files.
-
In order not to make a coding style patchwork out of this project, you really
should follow `the project's coding style <coding.en.rst>`_.
-``copyright.yml`` defines the license of each file (see `the libcarrot
-licensing method <licensing.en.md>`_). The other files' roles and structures
-are defined below.
-
Global information file
-----------------------
-The global information file gives information about libcarrot. It is located
-at `modules/info.yml`, and is a YAML-encoded configuration, with the
-following properties:
+The global information file gives information about libcarrot. The default one
+is located at root (``project.toml``), but you can use your own in order to
+define other locations. It has the following properties:
``magic``
- Should be equal to `potatosdk-1.0`.
+ Should be equal to ``potatosdk-1.0``.
+
+``maintainer``
+ The maintainer identifier as defined in the authors file.
``version``
The version details, with the following properties:
-
+
``major``
The major version (as an integer).
-
+
``minor``
The minor version (as an integer).
-
+
``indev``
Whether the current version is in development or not (default: false).
+``locations``
+ The locations (files and folders) to use, among which:
+
+ ``docroot``
+ The documentation root for overall documentation.
+
+ ``modules``
+ The modules root.
+
+ ``build``
+ The build folder to create (if necessary) and use.
+
+ ``authors``
+ The authors file location.
+
+ ``config``
+ The default configuration place to use.
+
An example configuration is the following:
-.. code:: yaml
- %YAML 1.2
- ---
- magic: potatosdk-1.0
- version:
- major: 5
- minor: 11
- indev: true
+.. code:: toml
+
+ magic = "potatosdk-1.0"
+ maintainer = "maintainer-identifier"
+
+ [version]
+ major = 5
+ minor = 11
+ indev = true
+
+ [locations]
+ docroot = "docs"
+ modules = "modules"
+ config = ".config.toml"
+ build = "build"
+
+ [[copyrights]]
+ begin = 1991
+ end = 1996
+ ent = "other-entity-identifier"
+
+Authors file
+------------
+
+Information about the authors are centralized in this file in order not to
+have out-of-date contact information. Every section has the entity identifier
+as their name, e.g. ``some-person`` or ``some-company``, and has the following
+properties:
+
+``name``
+ (req.) The full name of the entity.
+
+``mail``
+ (req.) The e-mail address of the entity.
+
+``web``
+ (opt.) The main website or web page of the entity.
+
+Pay attention to these when choosing an identifier for yourself:
+
+- it must be locally unique.
+- if you ought to change your name at some point, please do not choose an
+ identifier that includes it so that it is easier to change your information
+ later.
System and meta-system information file
---------------------------------------
Every system has a few properties, regrouped in a system information file and
-located at ``modules/<system>/info.yml``. It is a YAML-encoded configuration,
-with the following properties:
+located at ``modules/<system>/system.toml``. It is a TOML-encoded
+configuration, with the following properties:
``magic``
- Should be equal to `potatosdk-1.0`.
+ Should be equal to ``potatosdk-1.0``.
-``description``
+``desc`` (or ``description``)
The platform description.
+``license``
+ The license for the module (either ``free`` or ``proprietary``, default
+ is ``free``). See `the libcarrot licensing method <licensing.en.rst>`_.
+
``abi``
The list of binary interfaces for applications (file formats, calling
conventions, …), with keywords the build tools will understand.
``default``
- The ``{language => modules list}`` dictionary defining the system
- default modules, that will be included if the system is targetted or
- if it is a meta-system and it's imported by the targetted system.
+ The default module list for the system, that will be included if the
+ system is targetted or if it is a meta-system and it's imported by the
+ targetted system.
Modules from meta-systems should not be included directly, please use
- the ``meta`` property described below to import all of the defaults
- from the meta-system.
-
-``import``
- The list of meta-systems to import. Default modules from this other
- platform are included in this one's.
+ the ``requires.sys`` property described below to import all of the
+ defaults from the meta-system.
``requires``
The requirements for this platform to be targetted or imported,
with the following properties:
-
+
``arch``
- The list of architectures the system supports (if not precised,
+ The list of architectures the system supports (if not given,
all architectures are accepted).
+ ``sys``
+ The meta-systems from which to import the default modules.
+
If the list of ABIs is empty (or the ABI property is simply not defined), the
system is considered to be a meta-system. An example configuration is the
following:
-.. code:: yaml
- %YAML 1.2
- ---
- magic: potatosdk-1.0
- description: >-
- That incredible system we should all switch to.
- default:
- - mysys/somepackage
- - mysys/someotherpackage
- import:
- - all
- requires:
- arch:
- - sh3
- - sh4a
+.. code:: toml
+
+ magic = "potatosdk-1.0"
+ desc = "The Mysys OS, which brings incredible features."
+
+ abi = ["elf"]
+ default = ["mysys/core", "mysys/core-crt"]
+
+ [requires]
+ arch = ["x86", "amd64"]
+ sys = ["all", "renesas"]
Module information file
-----------------------
Every module has a set of properties too, regrouped in a module information
-file located at ``modules/<system>/<module>/info.yml``. It is a YAML-encoded
-configuration, with the following properties:
+file located at ``modules/<system>/<module>/module.toml``. It is a
+TOML-encoded configuration, with the following properties:
``magic``
Should be equal to ``potatosdk-1.0``.
-``description``
+``desc`` (or ``description``)
The module description (what features it brings, for which constraints,
etc).
-``deps``
- The module dependencies (preferably excluding language-related
- dependencies.
-
``license``
The license for the module (either ``free`` or ``proprietary``, default
is ``free``). See `the libcarrot licensing method <licensing.en.rst>`_.
@@ -200,63 +244,72 @@ configuration, with the following properties:
``arch``
The subset of architectures the module supports (from the system
ones). If not given, all the system architectures are selected.
-
+
``compiler``
- The list of compilers the module supports, e.g. ``[GNU, GCC]``.
+ The list of compilers the module supports, e.g. ``["GNU", "GCC"]``
+ or ``[["Hitachi", "SHC"], ["Renesas", "SHC"]]``.
+
+ ``modules`` (or ``mod``)
+ The list of modules the module requires (preferably excluding default
+ dependencies imported by the system).
+
+It also defines three file lists:
+
+- ``headers`` for the header files located in the ``include/`` folder;
+- ``bits`` for the header bits located in the ``bits/`` folder;
+- ``source`` for the source files located in the ``src/`` folder.
+
+Each entry has a ``path`` from the ``include/``, ``bits/`` or ``src/`` folder,
+and a ``role`` which will be put on top of the file.
An example configuration is the following:
-.. code:: yaml
- %YAML 1.2
- ---
- magic: potatosdk-1.0
- description: some incredible module bringing the future to your home.
- deps:
- - all/some_general_useful_library
- conflicts:
- - mysystem/some_anonymous_hater
- - all/some_general_module_that_defines_the_same_thing_as_me
- requires:
- arch:
- - sh3
- - sh4a
- compiler:
- - [GNU, GCC]
- - [Renesas, SHC]
-
-Roles files (top comments)
---------------------------
-
-**The top comment of each source/include file is NOT hand-written**,
-it is generated by a script, ``tools/updatesource.py``, which reads the
-copyright and licences from the machine-readable copyright information files
-(see `the libcarrot licensing method <licensing.en.rst>`_), and the short
-description of each file from the roles files ``roles.yml`` present in every
-module root.
-
-A roles file is YAML-encoded, and simply represents an arborescence with
-dictionaries, leading to the description. Here's an example roles file:
-
-.. code:: yaml
- %YAML 1.2
- ---
- bits:
- stdio.h: description for the `bits/stdio.h` file
- stdlib.h: description for the `bits/stdlib.h` file
- include:
- subfolder:
- something.h: description for the `include/subfolder/something.h` file
- other.h: description for the `include/other.h` file
+.. code:: toml
+
+ magic = "potatosdk-1.0"
+ desc = "Some incredible module bringing the future to your home."
+ license = "free"
+ out = "libhome"
+
+ conflicts = ["mysys/some_anonymous_hater",
+ "all/some_general_thing_that_defines_the_same_thing_as_me"]
+
+ [requires]
+ modules = "all/some_general_useful_library"
+ arch = ["sh3", ["sh4a", "big"]]
+ compiler = [["GNU", "GCC"], ["Renesas", "SHC"]]
+ host-compiler = ["GNU", "GCC"]
+
+ [[copyrights]]
+ begin = 1992
+ end = 2012
+ name = "Le Grand Monarque"
+ mail = "monarque@example.org"
+
+ [[header]]
+ path = "future.h"
+ role = "Some future thing."
+
+ [[bits]]
+ path = "libhome.h"
+ role = "Add a function to some library header."
+
+ [[source]]
+ path = "future.c"
+ role = "Future function."
+
+ [[source]]
+ path = "startup_nation.c"
+ role = "Emmanuel Macron would be proud of this one."
C headers and header bits
-------------------------
-libcarrot uses a C superpreprocessor, which role is to:
+libcarrot uses a C superpreprocessor, named “pcpp” for “Potato C PreProcessor”,
+which role is to:
-- find the header files in all of the selected modules (usually ending by
- ``.h``);
-- regroup those headers into one folder, the header output folder
- (usually ``./include`` from the project root);
+- regroup the selected modules' headers into one folder, the header output
+ folder (usually ``./include`` from the project root);
- make the top comment including the authors and licensing information;
- add the appropriate include guards;
- include the appropriate bits at the appropriate places;
@@ -280,13 +333,27 @@ the found ``bits/`` directories in the selected modules).
To know which bits are expected, in what sort of modules they should be
defined and what they are expected to define, the modules using this
-instruction should have a ``BITS.md`` documentation at their root (e.g.
-in ``modules/all/core/``).
+instruction should have some related documentation (e.g. in ``all/core``).
C/ASM source files
-----------------------
-
-Sources are found automatically in the ``src/`` folder, using their extensions
-(``c`` for C source files, and assembler/dialect-specific extensions for
-assembly source files). If you don't want a source file to be found,
-append ``.draft`` to the complete file name (e.g. ``source.c.draft``).
+------------------
+
+Sources are found using the module information files in the ``src/`` folder.
+The build tool will raise an error for source files that are declared but
+not found, and a warning for source files that are found but not declared.
+
+Extensions are the following:
+
+- ``.c``: C source files.
+- ``.h``: C header files.
+- ``.gnu.src``: ASM source files using the GNU syntax, which, for the
+ x86 architecture, is the Intel syntax.
+- ``.gnu.inc``: headers for the previous.
+- ``.nasm.src``: ASM source files using the NASM syntax, which, for the
+ x86 architecture, is the AT&T syntax.
+- ``.nasm.inc``: headers for the previous.
+- ``.sh.src``: ASM source files using the Renesas Asmsh syntax (for SH).
+- ``.sh.inc``: headers for the previous.
+
+If you don't want a source file to be found, you can append ``.draft`` to
+the complete file name (e.g. ``source.c.draft``).
diff --git a/docs/index.en.rst b/docs/index.en.rst
index 251200f..6c72241 100644
--- a/docs/index.en.rst
+++ b/docs/index.en.rst
@@ -34,7 +34,7 @@ function printing "hello world" and what is required to run with it
A module, like any package, has dependencies, conflicts, and requirements.
Among the requirements are the architecture, the compiler, etc.
-Modules only exist at compilation time: once the libcarrot distributed,
+Modules only exist at compilation time: once the libcarrot is distributed,
modules will be transparent, only the set of features they bring will be
available to the user (unless the module defines some preprocessor macro
for the user to use).
@@ -43,9 +43,9 @@ Systems
-------
Modules are grouped by system, for which they are suitable.
-A system generally represents a kernel/OS; for example, Linux with the
-``linux`` system, which regroup the Linux syscalls and the standard libraries
-that are suitable for Linux.
+A system generally represents a kernel/OS, or in general, a way to interact
+with the outside world; an example is Linux with the ``linux`` system,
+which regroups the Linux syscalls and the suitable C interfaces.
Systems have various *default modules* depending on the languages and binary
executable formats you ought to prepare it for.
diff --git a/docs/licensing.en.rst b/docs/licensing.en.rst
index 0566666..12ea55c 100644
--- a/docs/licensing.en.rst
+++ b/docs/licensing.en.rst
@@ -19,50 +19,58 @@ Any proprietary extension should be free'd before being proposed (and merged).
The libcarrot free software license currently is the CeCILL-C license,
written by french people and compliant with french law.
-Copyright files
----------------
-
-The copyright details are given by the ``copyright.yml`` files.
-These files are machine-readable, and used to generate the top comments of
-the source files, and generated text files (headers, ...) — see
-[Contributing](contributing.en.md) for more information about that.
-Each one of them defines a set of rules for the files at the same level
-and beneath, using wildcard patterns (e.g. ``folder/**/*.ext``).
-
-The copyright file shall contain one rule per division ("document").
-Each division shall define the following properties:
-
-- ``files``: the wildcard pattern(s) from the current directory of the
- group of files. If you only define one, you shall use a string, otherwise,
- please use a list of strings.
-- ``copyright``: the people this file belong to, usually the original author
- and the contributors who don't give their rights to the original author.
-
-A ``copyright`` entry consists of the copyright starting year, ending year,
-owner and owner e-mail address. It is defined as a list of either four
-elements, as ``[<start year>, <end year>, <name>, <mail>]`` or, if the ending
-year is the same than the starting year, of three elements, as
-``[<start and end year>, <name>, <mail>]``. The e-mail address is mandatory.
-
-An example ``copyright.yml`` file is the following:
-
-.. code-block:: yaml
-
- %YAML 1.2
- ---
- files: '*'
- copyright:
- - [2017, John "Smithy" Smith, john@smith.ee]
- - [2017, 2018, Robert Dupont, robert.dupont@wanadoo.fr]
- ---
- files: 'src/incredible/*'
- copyright:
- - [2018, Mahatma Gandhi, mahatma@gandi.net]
- ---
- files: 'src/**/parser.c'
- copyright:
- - [2018, Lephenixnoir, lephe@planet-casio.com]
-
-Notice that when trying to guess which rule applies to which file, the
-most precise rule is taken. Also, the license of the file depends on if it
-is in a module or not, and what module it's in.
+License properties
+------------------
+
+Licenses apply at three different levels:
+
+- the trunk level, including the global documentation and the tools.
+- the system or meta-system level.
+- the module level.
+
+The first level always is under the libcarrot free software license, and
+systems and modules can be either under the libcarrot free software license
+or the libcarrot proprietary software license. This can be altered by setting
+the ``license`` property in the corresponding information file to either
+``free`` or ``proprietary``.
+
+By default, the license is applied from the parent level.
+
+Notice that a module within a proprietary system in libcarrot cannot be
+free software, as source distribution couldn't distribute the module context.
+
+Copyright sections
+------------------
+
+The license is defined by the owners of the system or module; by the way,
+if you use that to apply a free software license, that's called copyleft.
+
+These owners are defined through the ``copyrights`` list within information
+files, where each section has the following properties:
+
+``begin``
+ The year when the copyright starts.
+
+``end``
+ The year when the ownership ends.
+
+``ent``
+ The entity identifier as defined in the global authors file.
+
+An example is the following:
+
+.. code-block::
+
+ ...
+
+ license = "free"
+
+ [[copyrights]]
+ begin = 1991
+ end = 1996
+ ent = "some-non-profit-org"
+
+ [[copyrights]]
+ begin = 2004
+ end = 2008
+ ent = "ttouhey"
diff --git a/docs/preprocessor.en.rst b/docs/preprocessor.en.rst
index 13c0ae4..8426283 100644
--- a/docs/preprocessor.en.rst
+++ b/docs/preprocessor.en.rst
@@ -1,5 +1,5 @@
-Using the libcarrot preprocessor
-================================
+Using the potato preprocessor (pcpp)
+====================================
.. quote::
:author: `The C Preprocessor (GNU), 1. Overview <gnucpp_>`_
@@ -16,17 +16,18 @@ of the lines have been removed). It can be multiline if each line which is
part of the macro ends with a backslash ``\``, which makes the preprocessor
ignore the newline.
-The libcarrot uses a special preprocessor that implements everything the
-standard/GNU C preprocessor does, and adds more things that are specific
-to the libcarrot's needs (plus little touches for tolerance).
+The libcarrot uses a special preprocessor called the “potato preprocessor”
+(or “pcpp”) that implements everything the standard/GNU C preprocessor
+does, and adds more things that are specific to the libcarrot's needs
+(plus little touches for tolerance).
-This page describes how to use the libcarrot preprocessor and best practices.
+This page describes how to use *pcpp* and best practices.
Defining macros
---------------
As in standard C, to manage the macros definition, the two basic instructions
-are `#define` and `#undef`. They shall be used like this:
+are ``#define`` and ``#undef``. They shall be used like this:
.. code-block:: c
@@ -36,11 +37,11 @@ are `#define` and `#undef`. They shall be used like this:
or either one or none and one more than one line
#undef NAME
-As the libcarrot preprocessor will try to optimize preprocessor instructions,
-these in libcarrot have two properties:
+As *pcpp* will try to optimize preprocessor instructions, these in libcarrot
+have two properties:
- **internal macros**: these instructions are to use by modules within
- libcarrot itself at compilation time. As libcarrot optimizes expressions
+ libcarrot itself at compilation time. As *pcpp* optimizes expressions
and conditions when possible, you can sort of use these macros in “runtime”;
- **raw macros**: normally, macros allow other macros to be used in their
content. Raw macros disallow this, which means that the content of the
@@ -91,12 +92,11 @@ using the basic instructions given below:
Where ``expr`` represents an expression to evaluate. Expressions evaluated to
0 or equivalent will be interpreted as false, others will be interpreted as
true. If the expression depends on unknown objects or objects of unknown
-values at superprocessing time, the libcarrot preprocessor will not optimize
-the expression.
+values at superprocessing time, *pcpp* will not optimize the expression.
In such expressions, an native expression is added, the ``defined(<name>)``
macro, which returns 1 if the macro is defined and 0 otherwise. For example,
-the following code will print 2:
+the following code will print 3:
.. code-block:: c
@@ -104,24 +104,24 @@ the following code will print 2:
#define MACRO2(_WITH, _ARGUMENTS) ((_WITH) - (_ARGUMENTS))
#define MACRO3 4
#undef MACRO3
-
+
int main(void)
{
int count = 0;
-
+
#if defined(MACRO1)
- count++;
+ count += 1;
#endif
#if defined(MACRO2)
- count++;
+ count += 2;
#endif
#if defined(MACRO3)
- count++;
+ count += 4;
#endif
#if defined(MACRO4)
- count++;
+ count += 8;
#endif
-
+
printf("%d\n", count);
return (0);
}
diff --git a/make b/make
index d8d5181..e7f9650 100755
--- a/make
+++ b/make
@@ -4,5 +4,5 @@ if ! [ x"$curdir" = "$0" ]; then
cd "$curdir"
fi
-PROGNAME='./make' tools/python3.sh tools/make.py "$@"
+tools/potato.sh "$@"
exit $?
diff --git a/make.bat b/make.bat
index 594c729..aa6eaed 100644
--- a/make.bat
+++ b/make.bat
@@ -1,3 +1,2 @@
cd %~p0
-set PROGNAME=make.bat
-py -3 tools/make.py %*
+tools/potato.bat %*
diff --git a/modules/all/core-sh/copyright.yml b/modules/all/core-sh/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/core-sh/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/core-sh/docs/index.en.rst b/modules/all/core-sh/docs/index.en.rst
index 0a41add..e5e1686 100644
--- a/modules/all/core-sh/docs/index.en.rst
+++ b/modules/all/core-sh/docs/index.en.rst
@@ -12,7 +12,7 @@ this are Sega (Sega Saturn, Sega 32X, Dreamcast) and CASIO (calculators such
as the fx-9860G series).
`Read more on the Wikipedia page <SuperH on Wikipedia_>`_
-This module brings the SuperH-specific type and macros to the freestanding libc
-modules.
+This module brings the SuperH-specific type and macros to the freestanding
+libc modules.
.. _SuperH on Wikipedia: https://en.wikipedia.org/wiki/SuperH
diff --git a/modules/all/core-sh/docs/intrinsics.en.rst b/modules/all/core-sh/docs/intrinsics.en.rst
index 6b5856c..b4df895 100644
--- a/modules/all/core-sh/docs/intrinsics.en.rst
+++ b/modules/all/core-sh/docs/intrinsics.en.rst
@@ -93,13 +93,31 @@ These specifies and cancels modulo addressing (??).
void set_circ_y(array, size);
void clr_circ();
+An example given in the manual is the following:
+
+.. code-block:: c
+
+ #include <machine.h>
+
+ __circ __X __fixed input[4] = {0.0r, 0.25r, 0.5r, 0.25r};
+ __Y __fixed output[8];
+
+ void main(void)
+ {
+ int i;
+
+ set_circ_x(input, sizeof(input)); /* Specifies modulo addressing. */
+ for (i = 0; i < 8; i++)
+ output[i] = input[i];
+ clr_circ(); /* Cancels modulo addressing. */
+ }
+
Set the interrupt mask level and jump to subroutine
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-If I am right on the macro signification, then I don't understand why
-it's useful. I thought it was basically there to force the 'store to control
-register' to be in the delayed branch of the 'jump to subroutine', which
-may not be enforced by default by Hitachi's compiler...?
+Clears the RB (Register Bank) so that the privileged register bank is accessed,
+the BL (Interrupt Block Bit) so that interrupts can be processed, and sets
+the imask value in the I0 to I3 bits of the SR, then calls the given function.
.. code-block:: c
@@ -119,6 +137,8 @@ functions:
uint32_t get_spc(void);
void set_spc(uint32_t spc);
+These are not available using Renesas' compiler.
+
Interacting with and using the global base register (GBR)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -159,7 +179,7 @@ cache block corresponding to a memory area.
.. code-block:: c
- void tas(void* addr);
+ void tas(void *addr);
Trap
~~~~
@@ -183,10 +203,10 @@ This instruction performs signed multiplication of two operands.
.. code-block:: c
- uint32_t macw(uint16_t* ptr1, uint16_t* ptr2, int count);
- uint32_t macwl(uint16_t* ptr1, uint16_t* ptr2, int count, uint16_t mask);
- uint32_t macl(uint32_t* ptr1, uint32_t* ptr2, int count);
- uint32_t macll(uint32_t* ptr1, uint32_t* ptr2, int count, uint32_t mask);
+ uint32_t macw(uint16_t *ptr1, uint16_t *ptr2, int count);
+ uint32_t macwl(uint16_t *ptr1, uint16_t *ptr2, int count, uint16_t mask);
+ uint32_t macl(uint32_t *ptr1, uint32_t *ptr2, int count);
+ uint32_t macll(uint32_t *ptr1, uint32_t *ptr2, int count, uint32_t mask);
Prefetch a memory area
~~~~~~~~~~~~~~~~~~~~~~
@@ -195,7 +215,7 @@ This instruction loads data to cache on software prefetching:
.. code-block:: c
- void prefetch(void* addr);
+ void prefetch(void *addr);
Interact with the FPU System Register
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -256,17 +276,17 @@ doing it yourself!
uint16_t swapb(uint16_t data);
uint32_t swapw(uint32_t data);
-There are also equivalents I can't seem to understand…?
+These macros reverse the byte order inside a 2-byte and 4-byte data.
.. code-block:: c
- uint16_t end_cnvw(uint16_t rm);
+ uint16_t end_cvnw(uint16_t data);
uint32_t end_cnvl(uint32_t data);
Double-length Multiply As Signed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-These instructions perform 32-bit mutliplications of two operations, and
+These instructions perform 32-bit multiplications of two operations, and
stores the 64-bit result in the MACH and MACL.
.. code-block:: c
diff --git a/modules/all/core-sh/include/umachine.h b/modules/all/core-sh/include/umachine.h
index 7d8b47b..5f31a77 100644
--- a/modules/all/core-sh/include/umachine.h
+++ b/modules/all/core-sh/include/umachine.h
@@ -52,7 +52,7 @@ _BEGIN_DECLS
/* Generics. */
#if __NDIC_SPC
-#elif !defined(set_spc)
+#elif !defined(set_spc) && !__FREESTANDING
_EXTERN __uint32_t __asm_get_spc OF((void));
_EXTERN void __asm_set_spc OF((__uint32_t __spc));
diff --git a/modules/all/core-sh/info.yml b/modules/all/core-sh/info.yml
deleted file mode 100644
index 394578d..0000000
--- a/modules/all/core-sh/info.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The freestanding libc, SuperH-specific parts.
-license: free
-requires:
- arch: [sh]
diff --git a/modules/all/core-sh/module.toml b/modules/all/core-sh/module.toml
new file mode 100644
index 0000000..7bd3551
--- /dev/null
+++ b/modules/all/core-sh/module.toml
@@ -0,0 +1,60 @@
+magic = "potatosdk-1.0"
+desc = "The freestanding libc environment."
+license = "free"
+
+[requires]
+arch = ["sh"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "builtin.h"
+role = "Built-ins for SHC."
+
+[[headers]]
+path = "fixed.h"
+role = "Fixed-point numbers, Renesas' way."
+
+[[headers]]
+path = "machine.h"
+role = "SuperH intrinsics."
+
+[[headers]]
+path = "smachine.h"
+role = "SuperH intrinsics, privileged mode."
+
+[[headers]]
+path = "umachine.h"
+role = "SuperH intrinsics, user mode."
+
+[[bits]]
+path = "byteswap.h"
+role = "Optimized byteswapping utilities for SuperH."
+
+[[source]]
+path = "bswap16.s"
+role = "Hosted bswap_16 fallback."
+
+[[source]]
+path = "bswap32.s"
+role = "Hosted bswap_32 fallback."
+
+[[source]]
+path = "smachine/spc.src"
+role = "Hosted get_spc and set_spc fallbacks for Asmsh."
+
+[[source]]
+path = "smachine/spc.s"
+role = "Hosted get_spc and set_spc fallbacks for GNU AS."
+
+[[source]]
+path = "smachine/ssr.spc"
+role = "Hosted get_ssr and set_ssr fallbacks for Asmsh."
+
+[[source]]
+path = "smachine/ssr.s"
+role = "Hosted get_ssr and set_ssr fallbacks for GNU AS."
diff --git a/modules/all/core-sh/roles.yml b/modules/all/core-sh/roles.yml
deleted file mode 100644
index e8220aa..0000000
--- a/modules/all/core-sh/roles.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-%YAML 1.2
----
-bits:
- byteswap.h: Optimized byteswapping utilities for SuperH.
-include:
- builtin.h: Built-ins for SHC.
- fixed.h: Fixed-point numbers, Renesas' way.
- machine.h: SuperH intrinsics.
- smachine.h: SuperH intrinsics, privileged mode.
- umachine.h: SuperH intrinsics, user mode.
-src:
- bswap16.s: Hosted bswap_16 fallback.
- bswap32.s: Hosted bswap_32 fallback.
- smachine:
- spc.src: Hosted get_spc and set_spc fallbacks for Asmsh.
- spc.s: Hosted get_spc and set_spc fallbacks for GNU AS.
- ssr.src: Hosted get_ssr and set_ssr fallbacks for Asmsh.
- ssr.s: Hosted get_ssr and set_ssr fallbacks for GNU AS.
diff --git a/modules/all/core-sh/src/bswap16.s b/modules/all/core-sh/src/bswap16.gnu.src
index df49a18..df49a18 100644
--- a/modules/all/core-sh/src/bswap16.s
+++ b/modules/all/core-sh/src/bswap16.gnu.src
diff --git a/modules/all/core-sh/src/bswap32.s b/modules/all/core-sh/src/bswap32.gnu.src
index d5f34c6..d5f34c6 100644
--- a/modules/all/core-sh/src/bswap32.s
+++ b/modules/all/core-sh/src/bswap32.gnu.src
diff --git a/modules/all/core-sh/src/smachine/spc.s b/modules/all/core-sh/src/smachine/spc.gnu.src
index 8e425c2..8e425c2 100644
--- a/modules/all/core-sh/src/smachine/spc.s
+++ b/modules/all/core-sh/src/smachine/spc.gnu.src
diff --git a/modules/all/core-sh/src/smachine/spc.src b/modules/all/core-sh/src/smachine/spc.sh.src
index 9f30e1a..9f30e1a 100644
--- a/modules/all/core-sh/src/smachine/spc.src
+++ b/modules/all/core-sh/src/smachine/spc.sh.src
diff --git a/modules/all/core-sh/src/smachine/ssr.s b/modules/all/core-sh/src/smachine/ssr.gnu.src
index 0267fa9..0267fa9 100644
--- a/modules/all/core-sh/src/smachine/ssr.s
+++ b/modules/all/core-sh/src/smachine/ssr.gnu.src
diff --git a/modules/all/core-sh/src/smachine/ssr.src b/modules/all/core-sh/src/smachine/ssr.sh.src
index ee1c741..ee1c741 100644
--- a/modules/all/core-sh/src/smachine/ssr.src
+++ b/modules/all/core-sh/src/smachine/ssr.sh.src
diff --git a/modules/all/core/copyright.yml b/modules/all/core/copyright.yml
deleted file mode 100644
index 546a0ed..0000000
--- a/modules/all/core/copyright.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
----
-files: 'src/ctype/tab.c'
-copyright:
-- [1991, 2016, "Free Software Foundation, Inc", "info@fsf.org"]
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/core/include/byteswap.h b/modules/all/core/include/byteswap.h
index 62a35ea..3c9966c 100644
--- a/modules/all/core/include/byteswap.h
+++ b/modules/all/core/include/byteswap.h
@@ -32,9 +32,13 @@
#include <stdint.h>
/* Include the architecture-specific header. */
+
#include_bits <byteswap.h>
/* Functions */
+
+#if !__FREESTANDING
+
_BEGIN_DECLS
_EXTERN _PURE __uint16_t bswap_16 _OF((__uint16_t __x)) __THROW;
@@ -43,7 +47,10 @@ _EXTERN _PURE __uint32_t bswap_32 _OF((__uint32_t __x)) __THROW;
_END_DECLS
+#endif
+
/* Replace with the quicker macros. */
+
#ifndef __NO_BYTESWAP
# ifdef __bswap_16
# define bswap_16(_X) __bswap_16(_X)
@@ -54,6 +61,7 @@ _END_DECLS
#endif
/* fxlib compatible macros */
+
#define UtlSwapWord(w) (bswap_16(w))
#define UtlSwapDword(l) (bswap_32(l))
#define UtlSwapInteger(i) (bswap_32(i))
diff --git a/modules/all/core/include/cdefs.h b/modules/all/core/include/cdefs.h
index 7fbb71c..18d822b 100644
--- a/modules/all/core/include/cdefs.h
+++ b/modules/all/core/include/cdefs.h
@@ -73,7 +73,7 @@
# define _PURE /* _PURE: not implemented */
#endif
-/* `_ATLEAST(N)`, `_NOTNULL`: static check for elements in an array.
+/* `_ATLEAST(NM, N)`, `_NOTNULL(NM)`: static check for elements in an array.
* This feature appeared in C99. It basically checks that an array contains
* at least _N elements. It can be used as a cross-compiler way to check that
* a pointer is not NULL.
@@ -89,11 +89,26 @@
# undef _NOTNULL
#endif
#if _USE_C99
-# define _ATLEAST(_N) static (_N)
+# define _ATLEAST(_NAME, _N) _NAME[static (_N)]
#else
-# define _ATLEAST(_N)
+# define _ATLEAST(_NAME, _N) *_NAME
#endif
-#define _NOTNULL _ATLEAST(1)
+#define _NOTNULL(_NAME) _ATLEAST(_NAME, 1)
+
+/* `_ATLEASTA(NM, A, N)`, `_NOTNULL(NM, A)`: equivalents with attributes. */
+
+#ifdef _ATLEASTA
+# undef _ATLEASTA
+#endif
+#ifdef _NOTNULLA
+# undef _NOTNULLA
+#endif
+#if _USE_C99
+# define _ATLEASTA(_NAME, _ATTRS, _N) _ATTRS _NAME[static (_N)]
+#else
+# define _ATLEASTA(_NAME, _ATTRS, _N) *_ATTRS _NAME
+#endif
+#define _NOTNULLA(_NAME, _ATTRS) _ATLEASTA(_NAME, _ATTRS, 1)
/* `_NONNULL`: a function requires a pointer argument not to be NULL.
* A warning shall be issued when a NULL value is passed as an argument that
diff --git a/modules/all/core/include/stddef.h b/modules/all/core/include/stddef.h
index 7099766..352c6e7 100644
--- a/modules/all/core/include/stddef.h
+++ b/modules/all/core/include/stddef.h
@@ -32,7 +32,7 @@
_BEGIN_NAMESPACE_STD
#include_bits <types/primitive.h>
-#if !__INTERNAL
+#if __INTERNAL
# defint schar signed char
# defint uchar unsigned char
# defint sshort signed short
diff --git a/modules/all/core/info.yml b/modules/all/core/info.yml
deleted file mode 100644
index 81edce1..0000000
--- a/modules/all/core/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The freestanding libc environment.
-license: free
diff --git a/modules/all/core/module.toml b/modules/all/core/module.toml
new file mode 100644
index 0000000..c8b1770
--- /dev/null
+++ b/modules/all/core/module.toml
@@ -0,0 +1,61 @@
+magic = "potatosdk-1.0"
+desc = "The freestanding libc environment."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "byteswap.h"
+role = "Byte swapping utilities."
+
+[[headers]]
+path = "cdefs.h"
+role = "Basic C definitions for all other headers."
+
+[[headers]]
+path = "endian.h"
+role = "Endian detection and conversion."
+
+[[headers]]
+path = "features.h"
+role = "C features."
+
+[[headers]]
+path = "float.h"
+role = "Floating constants."
+
+[[headers]]
+path = "iso646.h"
+role = "Floating constants."
+
+[[headers]]
+path = "limits.h"
+role = "English words."
+
+[[headers]]
+path = "stdarg.h"
+role = "Variable argument lists."
+
+[[headers]]
+path = "stdbool.h"
+role = "Booleans."
+
+[[headers]]
+path = "stddef.h"
+role = "Standard definitions."
+
+[[headers]]
+path = "stdint.h"
+role = "Standard integer types."
+
+[[headers]]
+path = "varargs.h"
+role = "Deprecated variable argument lists."
+
+[[bits]]
+path = "version.h"
+role = "libcarrot version definition."
diff --git a/modules/all/core/roles.yml b/modules/all/core/roles.yml
deleted file mode 100644
index 7956e67..0000000
--- a/modules/all/core/roles.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-%YAML 1.2
----
-include:
- byteswap.h: Byte swapping utilities.
- cdefs.h: Basic C definitions for all other headers.
- endian.h: Endian detection and conversion.
- features.h: C features.
- float.h: Floating constants.
- iso646.h: English words.
- limits.h: Integer limits.
- stdarg.h: Variable argument lists.
- stdbool.h: Booleans.
- stddef.h: Standard definitions.
- stdint.h: Standard integer types.
- varargs.h: Old variable argument lists.
-bits:
- version.h: libcarrot version definition.
diff --git a/modules/all/ctype/copyright.yml b/modules/all/ctype/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/ctype/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/ctype/info.yml b/modules/all/ctype/info.yml
deleted file mode 100644
index 1ea5efb..0000000
--- a/modules/all/ctype/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: ASCII character type.
-license: free
diff --git a/modules/all/ctype/module.toml b/modules/all/ctype/module.toml
new file mode 100644
index 0000000..f35d6a4
--- /dev/null
+++ b/modules/all/ctype/module.toml
@@ -0,0 +1,81 @@
+magic = "potatosdk-1.0"
+desc = "ASCII character type."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "ctype.h"
+role = "ASCII character type."
+
+[[source]]
+path = "ctype.h"
+role = "Character type identification internals."
+
+[[source]]
+path = "ascii.c"
+role = "ASCII locale table for character identification."
+
+[[source]]
+path = "isalnum.c"
+role = "Alpha-numeric character identification."
+
+[[source]]
+path = "isalpha.c"
+role = "Alphabetic character identification."
+
+[[source]]
+path = "isascii.c"
+role = "ASCII character identification."
+
+[[source]]
+path = "iscntrl.c"
+role = "Control character identification."
+
+[[source]]
+path = "isdigit.c"
+role = "Digit character identification."
+
+[[source]]
+path = "isgraph.c"
+role = "Graphical character identification."
+
+[[source]]
+path = "islower.c"
+role = "Lowercase alphabetic character identification."
+
+[[source]]
+path = "isprint.c"
+role = "Printable character identification."
+
+[[source]]
+path = "ispunct.c"
+role = "Punctuation character identification."
+
+[[source]]
+path = "isspace.c"
+role = "Space character identification."
+
+[[source]]
+path = "isupper.c"
+role = "Uppercase alphabetic character identification."
+
+[[source]]
+path = "isxdigit.c"
+role = "Hexadecimal digit character identification."
+
+[[source]]
+path = "toascii.c"
+role = "ASCII character truncature."
+
+[[source]]
+path = "tolower.c"
+role = "Uppercase to lowercase character conversion function."
+
+[[source]]
+path = "toupper.c"
+role = "Lowercase to uppercase character conversion function."
diff --git a/modules/all/ctype/roles.yml b/modules/all/ctype/roles.yml
deleted file mode 100644
index b9852cf..0000000
--- a/modules/all/ctype/roles.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-%YAML 1.2
----
-include:
- ctype.h: Character type.
-src:
- ascii.c: ASCII locale table for character identification.
- isalnum.c: Alpha-numeric character identification.
- isalpha.c: Alphabetic character identification.
- isascii.c: ASCII character identification.
- iscntrl.c: Control character identification.
- isdigit.c: Digit character identification.
- isgraph.c: Graphical character identification.
- islower.c: Lowercase alphabetic character identification.
- isprint.c: Printable character identification.
- ispunct.c: Punctuation character identifiation.
- isspace.c: Space character identification.
- isupper.c: Uppercase alphabetic character identification.
- isxdigit.c: Hexadecimal digit character identification.
- toascii.c: ASCII character truncature.
- tolower.c: Uppercase to lowercase character conversion function.
- toupper.c: Lowercase to uppercase character conversion function.
diff --git a/modules/all/errno/bits/stdio.h b/modules/all/errno/bits/stdio.h
new file mode 100644
index 0000000..b9fca2b
--- /dev/null
+++ b/modules/all/errno/bits/stdio.h
@@ -0,0 +1,3 @@
+/* `perror()`: print an error. */
+
+extern void perror _OF((char const *__prefix));
diff --git a/modules/all/errno/include/errno.h b/modules/all/errno/include/errno.h
index aaa1717..5151128 100644
--- a/modules/all/errno/include/errno.h
+++ b/modules/all/errno/include/errno.h
@@ -26,4 +26,12 @@ extern int *__errno_addr _OF((void));
extern char const * const sys_errlist[];
extern int sys_nerr;
+/* The default error string to be used with the `sys_errlist`. */
+
+extern char const *__default_errstring;
+
+/* Error definitions. */
+
+#include_bits <errno.h>
+
_END_NAMESPACE_STD
diff --git a/modules/all/errno/info.yml b/modules/all/errno/info.yml
deleted file mode 100644
index f2f148b..0000000
--- a/modules/all/errno/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: General utilities for error numbers.
-license: free
diff --git a/modules/all/errno/module.toml b/modules/all/errno/module.toml
new file mode 100644
index 0000000..1a70142
--- /dev/null
+++ b/modules/all/errno/module.toml
@@ -0,0 +1,25 @@
+magic = "potatosdk-1.0"
+desc = "General utilities for error numbers."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "errno.h"
+role = "libc error codes."
+
+[[bits]]
+path = "stdio.h"
+role = "perror() declaration for stdio.h"
+
+[[bits]]
+path = "string.h"
+role = "strerror() declarations for string.h"
+
+[[source]]
+path = "perror.c"
+role = "Error message printing."
diff --git a/modules/all/errno/roles.yml b/modules/all/errno/roles.yml
deleted file mode 100644
index 46f8745..0000000
--- a/modules/all/errno/roles.yml
+++ /dev/null
@@ -1,62 +0,0 @@
-%YAML 1.2
----
-include:
- assert.h: Assertions.
- byteswap.h: Byte swapping utilities.
- cdefs.h: C definitions.
- complex.h: Complex utilities.
- ctype.h: Character type.
- dirent.h: Directory listing.
- endian.h: Endian conversion utilities.
- errno.h: libc error codes.
- features.h: C features.
- fenv.h: Floating environment.
- float.h: Floating constants.
- inttypes.h: Things using types from `stdint.h`.
- iso646.h: English words.
- limits.h: Integer limits.
- locale.h: Locales.
- printf.h: printf-related utilities.
- setjmp.h: Non-local jumps.
- signal.h: Signals.
- stdarg.h: Variable argument lists.
- stdatomic.h: Atomic integer types.
- stdbool.h: Booleans.
- stddef.h: Standard definitions.
- stdfix.h: Standard fix integers.
- stdint.h: Standard integer types.
- stdlib.h: Standard library utilities.
- string.h: String utilities.
- strings.h: BSD-compatible string utilities.
- time.h: Time utilities.
- varargs.h: Old variable argument lists.
-src:
- ctype:
- funcs.c: Character utilities.
- tab.c: ASCII locale table for character identification.
- stdio:
- printf:
- default.c: Default printf callbacks.
- fprintf.c: Print formatted in a stream.
- prinf.h: Internal header for printf-related utilities.
- register.c: Manage printf callbacks.
- sprintf.c: String front-end to [v]s[n]printf.
- vfprintf.c: The core of all.
- read.c: Read from a stream.
- seek.c: Seek on a stream.
- stdio.h: Internal header for standard I/O utilities.
- stdout.c: Standard output and error streams definition.
- write.c: Write to a stream.
- stdlib:
- div.c: Division utilities.
- rand.c: Basic random utilities.
- wchar.c: Wide char-related utilities.
- string:
- memchr.c: Look for a character in a memory area.
- memcpy.c: Copy the content of a memory area into another.
- memset.c: Initialize the content of a memory area.
- strchr.c: Look for a character in a string.
- strlen.c: Find out the length of a string.
- byteswap.c: default byte swapping utilities.
- errno.c: errno management.
- locales.c: Localization register.
diff --git a/modules/all/errno/src/perror.c b/modules/all/errno/src/perror.c
new file mode 100644
index 0000000..5e14bbe
--- /dev/null
+++ b/modules/all/errno/src/perror.c
@@ -0,0 +1,19 @@
+#include <stdio.h>
+#include <errno.h>
+
+/* `__default_errstring`: the default error string. */
+
+char const *__default_errstring = "Unknown error";
+
+/* `perror()`: print the current error. */
+
+void perror(char const *prefix)
+{
+ if (prefix && *prefix) {
+ fputs(prefix, stderr);
+ fputs(": ", stderr);
+ }
+
+ fputs(strerror(errno), stderr);
+ fputc('\n', stderr);
+}
diff --git a/modules/all/helloworld/copyright.yml b/modules/all/helloworld/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/helloworld/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/helloworld/info.yml b/modules/all/helloworld/info.yml
deleted file mode 100644
index 346efea..0000000
--- a/modules/all/helloworld/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The "hello, world" module, for demonstration purposes.
-license: free
diff --git a/modules/all/helloworld/module.toml b/modules/all/helloworld/module.toml
new file mode 100644
index 0000000..e03e701
--- /dev/null
+++ b/modules/all/helloworld/module.toml
@@ -0,0 +1,17 @@
+magic = "potatosdk-1.0"
+desc = "The \"hello, world\" module, for demonstration purposes."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "helloworld.h"
+role = "helloworld() function declaration."
+
+[[source]]
+path = "helloworld.c"
+role = "helloworld() function definition."
diff --git a/modules/all/helloworld/roles.yml b/modules/all/helloworld/roles.yml
deleted file mode 100644
index 2a7be6a..0000000
--- a/modules/all/helloworld/roles.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-%YAML 1.2
----
-src:
- helloworld.c: hello world function.
-include:
- helloworld.h: hello world features.
diff --git a/modules/all/hosted-sh/copyright.yml b/modules/all/hosted-sh/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/hosted-sh/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/hosted-sh/info.yml b/modules/all/hosted-sh/info.yml
deleted file mode 100644
index 11f1e4e..0000000
--- a/modules/all/hosted-sh/info.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The core libc, SuperH-specific parts.
-license: free
-requires:
- arch: [sh]
diff --git a/modules/all/hosted-sh/module.toml b/modules/all/hosted-sh/module.toml
new file mode 100644
index 0000000..ed9ad64
--- /dev/null
+++ b/modules/all/hosted-sh/module.toml
@@ -0,0 +1,24 @@
+magic = "potatosdk-1.0"
+desc = "The core libc, SuperH-specific parts."
+license = "free"
+
+[requires]
+arch = ["sh"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "setjmp.h"
+role = "Non-local jump buffer type."
+
+[[source]]
+path = "longjmp.s"
+role = "Non-local jump."
+
+[[source]]
+path = "setjmp.s"
+role = "Non-local jump preparation."
diff --git a/modules/all/hosted-sh/roles.yml b/modules/all/hosted-sh/roles.yml
deleted file mode 100644
index 50f6386..0000000
--- a/modules/all/hosted-sh/roles.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-bits:
- setjmp.h: Non-local jump buffer type.
-src:
- longjmp.s: Non-local jump.
- setjmp.s: Non-local jump preparation.
diff --git a/modules/all/hosted-sh/src/longjmp.s b/modules/all/hosted-sh/src/longjmp.gnu.src
index c57e0b1..c57e0b1 100644
--- a/modules/all/hosted-sh/src/longjmp.s
+++ b/modules/all/hosted-sh/src/longjmp.gnu.src
diff --git a/modules/all/hosted-sh/src/setjmp.s b/modules/all/hosted-sh/src/setjmp.gnu.src
index 88671c7..88671c7 100644
--- a/modules/all/hosted-sh/src/setjmp.s
+++ b/modules/all/hosted-sh/src/setjmp.gnu.src
diff --git a/modules/all/hosted/copyright.yml b/modules/all/hosted/copyright.yml
deleted file mode 100644
index 546a0ed..0000000
--- a/modules/all/hosted/copyright.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
----
-files: 'src/ctype/tab.c'
-copyright:
-- [1991, 2016, "Free Software Foundation, Inc", "info@fsf.org"]
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/hosted/include/errno.h b/modules/all/hosted/include/errno.h
deleted file mode 100644
index e9a86fa..0000000
--- a/modules/all/hosted/include/errno.h
+++ /dev/null
@@ -1,14 +0,0 @@
-#include <cdefs.h>
-_BEGIN_DECLS
-
-/* Global variable management.
- * Because of potential concurrency problems, write access to this variable
- * should be executed using the `__set_errno()` function below. */
-
-_EXTERN volatile int errno;
-
-_EXTERN void __set_errno _OF((int __value));
-
-#include_bits <errno.h>
-
-_END_DECLS
diff --git a/modules/all/hosted/include/inttypes.h b/modules/all/hosted/include/inttypes.h
index a931dfc..1344fed 100644
--- a/modules/all/hosted/include/inttypes.h
+++ b/modules/all/hosted/include/inttypes.h
@@ -48,186 +48,5 @@ _EXTERN __intmax_t imaxabs
_EXTERN imaxdiv_t imaxdiv
_OF((__intmax_t __num, __intmax_t __den)) _THROW;
#endif
-/* ************************************************************************* */
-/* `printf` and `scanf` macros. */
-/* ************************************************************************* */
-/* These macros make use of the C compile-time string concatenation.
- * You shall use them like this: "My int8_t variable is %" PRId8 "!" */
-
-#if _USE_C99 || (_USE_CXX11 && defined(__STDC_FORMAT_MACROS))
-
-/* Decimal notation */
-
-# define PRId8 __PRI8 "d"
-# define PRId16 __PRI16 "d"
-# define PRId32 __PRI32 "d"
-# define PRId64 __PRI64 "d"
-# define PRIdFAST8 __PRIFAST8 "d"
-# define PRIdFAST16 __PRIFAST16 "d"
-# define PRIdFAST32 __PRIFAST32 "d"
-# define PRIdFAST64 __PRIFAST64 "d"
-# define PRIdLEAST8 __PRILEAST8 "d"
-# define PRIdLEAST16 __PRILEAST16 "d"
-# define PRIdLEAST32 __PRILEAST32 "d"
-# define PRIdLEAST64 __PRILEAST64 "d"
-# define PRIdMAX __PRIMAX "d"
-# define PRIdPTR __PRIPTR "d"
-
-# define SCNd8 __PRI8 "d"
-# define SCNd16 __PRI16 "d"
-# define SCNd32 __PRI32 "d"
-# define SCNd64 __PRI64 "d"
-# define SCNdFAST8 __PRIFAST8 "d"
-# define SCNdFAST16 __PRIFAST16 "d"
-# define SCNdFAST32 __PRIFAST32 "d"
-# define SCNdFAST64 __PRIFAST64 "d"
-# define SCNdLEAST8 __PRILEAST8 "d"
-# define SCNdLEAST16 __PRILEAST16 "d"
-# define SCNdLEAST32 __PRILEAST32 "d"
-# define SCNdLEAST64 __PRILEAST64 "d"
-# define SCNdMAX __PRIMAX "d"
-# define SCNdPTR __PRIPTR "d"
-
-# define PRIi8 __PRI8 "i"
-# define PRIi16 __PRI16 "i"
-# define PRIi32 __PRI32 "i"
-# define PRIi64 __PRI64 "i"
-# define PRIiFAST8 __PRIFAST8 "i"
-# define PRIiFAST16 __PRIFAST16 "i"
-# define PRIiFAST32 __PRIFAST32 "i"
-# define PRIiFAST64 __PRIFAST64 "i"
-# define PRIiLEAST8 __PRILEAST8 "i"
-# define PRIiLEAST16 __PRILEAST16 "i"
-# define PRIiLEAST32 __PRILEAST32 "i"
-# define PRIiLEAST64 __PRILEAST64 "i"
-# define PRIiMAX __PRIMAX "i"
-# define PRIiPTR __PRIPTR "i"
-
-# define SCNi8 __PRI8 "i"
-# define SCNi16 __PRI16 "i"
-# define SCNi32 __PRI32 "i"
-# define SCNi64 __PRI64 "i"
-# define SCNiFAST8 __PRIFAST8 "i"
-# define SCNiFAST16 __PRIFAST16 "i"
-# define SCNiFAST32 __PRIFAST32 "i"
-# define SCNiFAST64 __PRIFAST64 "i"
-# define SCNiLEAST8 __PRILEAST8 "i"
-# define SCNiLEAST16 __PRILEAST16 "i"
-# define SCNiLEAST32 __PRILEAST32 "i"
-# define SCNiLEAST64 __PRILEAST64 "i"
-# define SCNiMAX __PRIMAX "i"
-# define SCNiPTR __PRIPTR "i"
-
-/* Octal notation */
-
-# define PRIo8 __PRI8 "o"
-# define PRIo16 __PRI16 "o"
-# define PRIo32 __PRI32 "o"
-# define PRIo64 __PRI64 "o"
-# define PRIoFAST8 __PRIFAST8 "o"
-# define PRIoFAST16 __PRIFAST16 "o"
-# define PRIoFAST32 __PRIFAST32 "o"
-# define PRIoFAST64 __PRIFAST64 "o"
-# define PRIoLEAST8 __PRILEAST8 "o"
-# define PRIoLEAST16 __PRILEAST16 "o"
-# define PRIoLEAST32 __PRILEAST32 "o"
-# define PRIoLEAST64 __PRILEAST64 "o"
-# define PRIoMAX __PRIMAX "o"
-# define PRIoPTR __PRIPTR "o"
-# define SCNo8 __PRI8 "o"
-# define SCNo16 __PRI16 "o"
-# define SCNo32 __PRI32 "o"
-# define SCNo64 __PRI64 "o"
-# define SCNoFAST8 __PRIFAST8 "o"
-# define SCNoFAST16 __PRIFAST16 "o"
-# define SCNoFAST32 __PRIFAST32 "o"
-# define SCNoFAST64 __PRIFAST64 "o"
-# define SCNoLEAST8 __PRILEAST8 "o"
-# define SCNoLEAST16 __PRILEAST16 "o"
-# define SCNoLEAST32 __PRILEAST32 "o"
-# define SCNoLEAST64 __PRILEAST64 "o"
-# define SCNoMAX __PRIMAX "o"
-# define SCNoPTR __PRIPTR "o"
-
-/* Unsigned notation */
-
-# define PRIu8 __PRI8 "u"
-# define PRIu16 __PRI16 "u"
-# define PRIu32 __PRI32 "u"
-# define PRIu64 __PRI64 "u"
-# define PRIuFAST8 __PRIFAST8 "u"
-# define PRIuFAST16 __PRIFAST16 "u"
-# define PRIuFAST32 __PRIFAST32 "u"
-# define PRIuFAST64 __PRIFAST64 "u"
-# define PRIuLEAST8 __PRILEAST8 "u"
-# define PRIuLEAST16 __PRILEAST16 "u"
-# define PRIuLEAST32 __PRILEAST32 "u"
-# define PRIuLEAST64 __PRILEAST64 "u"
-# define PRIuMAX __PRIMAX "u"
-# define PRIuPTR __PRIPTR "u"
-
-# define SCNu8 __PRI8 "u"
-# define SCNu16 __PRI16 "u"
-# define SCNu32 __PRI32 "u"
-# define SCNu64 __PRI64 "u"
-# define SCNuFAST8 __PRIFAST8 "u"
-# define SCNuFAST16 __PRIFAST16 "u"
-# define SCNuFAST32 __PRIFAST32 "u"
-# define SCNuFAST64 __PRIFAST64 "u"
-# define SCNuLEAST8 __PRILEAST8 "u"
-# define SCNuLEAST16 __PRILEAST16 "u"
-# define SCNuLEAST32 __PRILEAST32 "u"
-# define SCNuLEAST64 __PRILEAST64 "u"
-# define SCNuMAX __PRIMAX "u"
-# define SCNuPTR __PRIPTR "u"
-
-/* Lowercase hexadecimal notation */
-
-# define PRIx8 __PRI8 "x"
-# define PRIx16 __PRI16 "x"
-# define PRIx32 __PRI32 "x"
-# define PRIx64 __PRI64 "x"
-# define PRIxFAST8 __PRIFAST8 "x"
-# define PRIxFAST16 __PRIFAST16 "x"
-# define PRIxFAST32 __PRIFAST32 "x"
-# define PRIxFAST64 __PRIFAST64 "x"
-# define PRIxLEAST8 __PRILEAST8 "x"
-# define PRIxLEAST16 __PRILEAST16 "x"
-# define PRIxLEAST32 __PRILEAST32 "x"
-# define PRIxLEAST64 __PRILEAST64 "x"
-# define PRIxMAX __PRIMAX "x"
-# define PRIxPTR __PRIPTR "x"
-
-# define SCNx8 __PRI8 "x"
-# define SCNx16 __PRI16 "x"
-# define SCNx32 __PRI32 "x"
-# define SCNx64 __PRI64 "x"
-# define SCNxFAST8 __PRIFAST8 "x"
-# define SCNxFAST16 __PRIFAST16 "x"
-# define SCNxFAST32 __PRIFAST32 "x"
-# define SCNxFAST64 __PRIFAST64 "x"
-# define SCNxLEAST8 __PRILEAST8 "x"
-# define SCNxLEAST16 __PRILEAST16 "x"
-# define SCNxLEAST32 __PRILEAST32 "x"
-# define SCNxLEAST64 __PRILEAST64 "x"
-# define SCNxMAX __PRIMAX "x"
-# define SCNxPTR __PRIPTR "x"
-
-/* Uppercase hexadecimal notation */
-
-# define PRIX8 __PRI8 "X"
-# define PRIX16 __PRI16 "X"
-# define PRIX32 __PRI32 "X"
-# define PRIX64 __PRI64 "X"
-# define PRIXFAST8 __PRIFAST8 "X"
-# define PRIXFAST16 __PRIFAST16 "X"
-# define PRIXFAST32 __PRIFAST32 "X"
-# define PRIXFAST64 __PRIFAST64 "X"
-# define PRIXLEAST8 __PRILEAST8 "X"
-# define PRIXLEAST16 __PRILEAST16 "X"
-# define PRIXLEAST32 __PRILEAST32 "X"
-# define PRIXLEAST64 __PRILEAST64 "X"
-# define PRIXMAX __PRIMAX "X"
-# define PRIXPTR __PRIPTR "X"
-#endif
+#include_bits <inttypes.h>
diff --git a/modules/all/hosted/info.yml b/modules/all/hosted/info.yml
deleted file mode 100644
index 6b8def8..0000000
--- a/modules/all/hosted/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The base hosted libc environment.
-license: free
diff --git a/modules/all/hosted/module.toml b/modules/all/hosted/module.toml
new file mode 100644
index 0000000..7543a44
--- /dev/null
+++ b/modules/all/hosted/module.toml
@@ -0,0 +1,69 @@
+magic = "potatosdk-1.0"
+desc = "The base hosted libc environment."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "assert.h"
+role = "Assertions"
+
+[[headers]]
+path = "complex.h"
+role = "Complex utilities."
+
+[[headers]]
+path = "fenv.h"
+role = "Floating-point environment."
+
+[[headers]]
+path = "inttypes.h"
+role = "Utilities using types from `stdint.h`."
+
+[[headers]]
+path = "locale.h"
+role = "Locales."
+
+[[headers]]
+path = "setjmp.h"
+role = "Non-local jumps."
+
+[[headers]]
+path = "signal.h"
+role = "Signals."
+
+[[headers]]
+path = "stdatomic.h"
+role = "Atomic integer types."
+
+[[headers]]
+path = "stdfix.h"
+role = "Standard fix integers."
+
+[[headers]]
+path = "stdlib.h"
+role = "Standard library utilities."
+
+[[source]]
+path = "byteswap.c"
+role = "Default byte swapping utilities."
+
+[[source]]
+path = "locales.c"
+role = "Localization register."
+
+[[source]]
+path = "div.c"
+role = "Division utilities."
+
+[[source]]
+path = "rand.c"
+role = "Pseudo-random utilities."
+
+[[source]]
+path = "wchar.c"
+role = "Wide char related utilities."
diff --git a/modules/all/hosted/roles.yml b/modules/all/hosted/roles.yml
deleted file mode 100644
index 28ee578..0000000
--- a/modules/all/hosted/roles.yml
+++ /dev/null
@@ -1,46 +0,0 @@
-%YAML 1.2
----
-include:
- assert.h: Assertions.
- complex.h: Complex utilities.
- dirent.h: Directory listing.
- errno.h: libc error codes.
- fenv.h: Floating environment.
- inttypes.h: Things using types from `stdint.h`.
- locale.h: Locales.
- printf.h: printf-related utilities.
- setjmp.h: Non-local jumps.
- signal.h: Signals.
- stdatomic.h: Atomic integer types.
- stdfix.h: Standard fix integers.
- stdlib.h: Standard library utilities.
- string.h: String utilities.
- strings.h: BSD-compatible string utilities.
- time.h: Time utilities.
-src:
- stdio:
- printf:
- default.c: Default printf callbacks.
- fprintf.c: Print formatted in a stream.
- prinf.h: Internal header for printf-related utilities.
- register.c: Manage printf callbacks.
- sprintf.c: String front-end to [v]s[n]printf.
- vfprintf.c: The core of all.
- read.c: Read from a stream.
- seek.c: Seek on a stream.
- stdio.h: Internal header for standard I/O utilities.
- stdout.c: Standard output and error streams definition.
- write.c: Write to a stream.
- stdlib:
- div.c: Division utilities.
- rand.c: Basic random utilities.
- wchar.c: Wide char-related utilities.
- string:
- memchr.c: Look for a character in a memory area.
- memcpy.c: Copy the content of a memory area into another.
- memset.c: Initialize the content of a memory area.
- strchr.c: Look for a character in a string.
- strlen.c: Find out the length of a string.
- byteswap.c: default byte swapping utilities.
- errno.c: errno management.
- locales.c: Localization register.
diff --git a/modules/all/hosted/src/stdlib/div.c b/modules/all/hosted/src/div.c
index 8ef426d..7c160c0 100644
--- a/modules/all/hosted/src/stdlib/div.c
+++ b/modules/all/hosted/src/div.c
@@ -67,6 +67,7 @@ ldiv_t ldiv(long num, long den)
}
#if _USE_C99
+
/**
* lldiv:
* Divide and get remainder, long long version.
@@ -84,4 +85,5 @@ lldiv_t lldiv(long long num, long long den)
dv.rem = num % den;
return (dv);
}
+
#endif
diff --git a/modules/all/hosted/src/errno.c b/modules/all/hosted/src/errno.c
deleted file mode 100644
index ee7c4ac..0000000
--- a/modules/all/hosted/src/errno.c
+++ /dev/null
@@ -1,45 +0,0 @@
-/* ****************************************************************************
- * errno.c -- errno management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'all/core' module in libcarrot, an experimental
- * modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <errno.h>
-
-/**
- * __set_errno:
- * Set the errno global.
- *
- * TODO: use a mutex to access it to prevent concurrency-related problems?
- *
- * @arg value the value.
- */
-
-void __set_errno(int value)
-{
- errno = value;
-}
diff --git a/modules/all/hosted/src/locales.c b/modules/all/hosted/src/locales.c
index a3d8dac..d223485 100644
--- a/modules/all/hosted/src/locales.c
+++ b/modules/all/hosted/src/locales.c
@@ -32,9 +32,10 @@
#include <limits.h>
#include <string.h>
-/* ************************************************************************* */
-/* Built-in locales and registry */
-/* ************************************************************************* */
+/* ---
+ * Built-in locales and registry.
+ * --- */
+
/* Default 'C' locale, defined in the C standard. */
static const struct lconv c_locale = {
@@ -52,9 +53,11 @@ static const struct lconv *current_locales[5] = {
&c_locale, /* LC_NUMERIC */
&c_locale /* LC_TIME */
};
-/* ************************************************************************* */
-/* Main functions */
-/* ************************************************************************* */
+
+/* ---
+ * Main functions.
+ * --- */
+
/**
* setlocale:
* Set the current locale.
@@ -103,12 +106,14 @@ struct lconv *localeconv(void)
const struct lconv *num = current_locales[LC_NUMERIC - 1];
const struct lconv *mon = current_locales[LC_MONETARY - 1];
- /* nonmonetary things */
+ /* Nonmonetary things */
+
locale.decimal_point = num->decimal_point;
locale.thousands_sep = num->thousands_sep;
locale.grouping = num->grouping;
- /* monetary things */
+ /* Monetary things */
+
locale.mon_decimal_point = mon->mon_decimal_point;
locale.mon_thousands_sep = mon->mon_thousands_sep;
locale.mon_grouping = mon->mon_grouping;
diff --git a/modules/all/hosted/src/stdlib/rand.c b/modules/all/hosted/src/rand.c
index 3cb7355..3cb7355 100644
--- a/modules/all/hosted/src/stdlib/rand.c
+++ b/modules/all/hosted/src/rand.c
diff --git a/modules/all/hosted/src/stdlib/wchar.c b/modules/all/hosted/src/wchar.c
index 44fe4e4..44fe4e4 100644
--- a/modules/all/hosted/src/stdlib/wchar.c
+++ b/modules/all/hosted/src/wchar.c
diff --git a/modules/all/iconv-unicode/bits/iconv_proto.h b/modules/all/iconv-unicode/bits/iconv_proto.h
index 0ef5730..70d7a66 100644
--- a/modules/all/iconv-unicode/bits/iconv_proto.h
+++ b/modules/all/iconv-unicode/bits/iconv_proto.h
@@ -1,6 +1,6 @@
/* UTF-8 <> wide char */
-ICONV_PROTO(__iconv_utf8_to_wchar)
+ICONV_PROTP(__iconv_utf8_to_wchar, __iconv_prepare_utf8_to_wchar)
ICONV_PROTO(__iconv_wchar_to_utf8)
/* UTF-32 <> UTF-8 */
diff --git a/modules/all/iconv-unicode/bits/iconv_route.h b/modules/all/iconv-unicode/bits/iconv_route.h
index 312507b..ba6bc71 100644
--- a/modules/all/iconv-unicode/bits/iconv_route.h
+++ b/modules/all/iconv-unicode/bits/iconv_route.h
@@ -1,6 +1,12 @@
-/* UTF-8 <> wide char */
+/* Conversions between UTF-8 and wide char. */
-ICONV_ROUTE("utf8", "wchar_t", __iconv_utf8_to_wchar)
+struct __iconv_utf8_to_wchar_cookie {
+
+};
+
+ICONV_ROUTP("utf8", "wchar_t",
+ __iconv_utf8_to_wchar, __iconv_prepare_utf8_to_wchar,
+ sizeof(__iconv_utf8_to_wchar_cookie))
ICONV_ROUTE("wchar_t", "utf8", __iconv_wchar_to_utf8)
/* UTF-32 <> UTF-8 */
diff --git a/modules/all/iconv-unicode/copyright.yml b/modules/all/iconv-unicode/copyright.yml
deleted file mode 100644
index 36f270f..0000000
--- a/modules/all/iconv-unicode/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/iconv-unicode/info.yml b/modules/all/iconv-unicode/info.yml
deleted file mode 100644
index aa7df5e..0000000
--- a/modules/all/iconv-unicode/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Unicode encodings for the generic character conversion interface.
-license: free
diff --git a/modules/all/iconv-unicode/module.toml b/modules/all/iconv-unicode/module.toml
new file mode 100644
index 0000000..ed12bce
--- /dev/null
+++ b/modules/all/iconv-unicode/module.toml
@@ -0,0 +1,24 @@
+magic = "potatosdk-1.0"
+desc = "Unicode encodings for the generic character conversion interface."
+license = "free"
+
+[[copyrights]]
+begin = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "iconv_proto.h"
+role = "Prototypes for the Unicode encodings for the iconv interface."
+
+[[bits]]
+path = "iconv_route.h"
+role = "Routes for the Unicode encodings for the iconv interface."
+
+[[source]]
+path = "utf8_to_wchar.c"
+role = "UTF-8 to wide chars."
+
+[[source]]
+path = "wchar_to_utf8.c"
+role = "Wide chars to UTF-8."
diff --git a/modules/all/iconv-unicode/roles.yml b/modules/all/iconv-unicode/roles.yml
deleted file mode 100644
index d7d7ad5..0000000
--- a/modules/all/iconv-unicode/roles.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-%YAML 1.2
----
-bits:
- iconv_proto.h: Prototypes for the Unicode encodings for the iconv interface.
- iconv_route.h: Routes for the Unicode encodings for the iconv interface.
-src:
- utf8_to_wchar.c: "UTF-8 to wide chars."
- wchar_to_utf8.c: "Wide chars to UTF-8."
diff --git a/modules/all/iconv-unicode/src/utf8_to_utf32.c b/modules/all/iconv-unicode/src/utf8_to_utf32.c
index 7efb752..d8ccf25 100644
--- a/modules/all/iconv-unicode/src/utf8_to_utf32.c
+++ b/modules/all/iconv-unicode/src/utf8_to_utf32.c
@@ -10,11 +10,11 @@
int left, proc = 1, byte; \
uint32_t val; \
\
- __I_HASIN(step, 1) \
- __I_CHECK(step, sizeof(val)) \
+ __I_HASIN(1) \
+ __I_CHECK(sizeof(val)) \
\
- in = __I_IN(step); \
- left = __I_INSIZE(step); \
+ in = __I_IN; \
+ left = __I_INSIZE; \
byte = *in; \
\
/* Check if it's special. */ \
@@ -67,10 +67,10 @@
\
/* Return the buffer. */ \
\
- __I_RETURN(step, proc, HTOF(val), sizeof(val)) \
+ __I_RETURN(proc, HTOF(val), sizeof(val)) \
}
-int __iconv_utf8_to_utf32be(struct __iconv_step *step)
+__I_FUNC(__iconv_utf8_to_utf32be)
__iconv_utf8_to_utf32(htobe32)
-int __iconv_utf8_to_utf32le(struct __iconv_step *step)
+__I_FUNC(__iconv_utf8_to_utf32le)
__iconv_utf8_to_utf32(htole32)
diff --git a/modules/all/iconv-unicode/src/utf8_to_wchar.c b/modules/all/iconv-unicode/src/utf8_to_wchar.c
index 4290f6a..9e42af8 100644
--- a/modules/all/iconv-unicode/src/utf8_to_wchar.c
+++ b/modules/all/iconv-unicode/src/utf8_to_wchar.c
@@ -29,29 +29,35 @@
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
#include "../iconv.h"
-#define set_utf8_cookie(c_count, c_ini) { \
+#define set_count_val(c_count, c_ini) { \
count = (c_count); \
val = (c_ini); }
-/**
- * __iconv_utf8_to_wchar:
- * Convert one UTF-8 sequence to a wchar_t.
- *
- * @arg step the step data.
- * @return the error code (0 if ok).
- */
+/* `__iconv_prepare_utf8_to_wchar()`: prepare a UTF-8 sequence to wchar_t
+ * conversion. */
+
+__I_PREP(__iconv_prepare_utf8_to_wchar)
+{
+ char const *flag;
+
+ while ((flag = __I_NEXT_FLAG)) {
+ __I_NOCHAR
+ }
+}
+
+/* `__iconv_utf8_to_wchar()`: convert one UTF-8 sequence to a wchar_t. */
-int __iconv_utf8_to_wchar(struct __iconv_step *step)
+__I_FUNC(__iconv_utf8_to_wchar)
{
const unsigned char *in;
int left, proc = 1, byte;
wchar_t val;
- __I_HASIN(step, 1)
- __I_CHECK(step, sizeof(wchar_t))
+ __I_HASIN(1)
+ __I_CHECK(sizeof(wchar_t))
- in = __I_IN(step);
- left = __I_INSIZE(step);
+ in = __I_IN;
+ left = __I_INSIZE;
byte = *in;
/* Check if it's special. */
@@ -64,15 +70,15 @@ int __iconv_utf8_to_wchar(struct __iconv_step *step)
/* Make the cookie. */
if (~byte & 0x20)
- set_utf8_cookie(1, byte & 0x1F)
+ set_count_val(1, byte & 0x1F)
else if (~byte & 0x10)
- set_utf8_cookie(2, byte & 0x0F)
+ set_count_val(2, byte & 0x0F)
else if (~byte & 0x08)
- set_utf8_cookie(3, byte & 0x07)
+ set_count_val(3, byte & 0x07)
else if (~byte & 0x04)
- set_utf8_cookie(4, byte & 0x03)
+ set_count_val(4, byte & 0x03)
else if (~byte & 0x02)
- set_utf8_cookie(5, byte & 0x01)
+ set_count_val(5, byte & 0x01)
else {
/* error: not a valid starting byte */
return (I_EILSEQ);
@@ -99,5 +105,5 @@ int __iconv_utf8_to_wchar(struct __iconv_step *step)
/* Return the buffer. */
- __I_RETURN(step, proc, &val, sizeof(wchar_t))
+ __I_RETURN(proc, &val, sizeof(wchar_t))
}
diff --git a/modules/all/iconv-unicode/src/wchar_to_utf8.c b/modules/all/iconv-unicode/src/wchar_to_utf8.c
index 5da6726..4225b05 100644
--- a/modules/all/iconv-unicode/src/wchar_to_utf8.c
+++ b/modules/all/iconv-unicode/src/wchar_to_utf8.c
@@ -30,45 +30,39 @@
* ************************************************************************* */
#include "../iconv.h"
-/**
- * __iconv_wchar_to_utf8:
- * Convert a wchar_t to a UTF-8 sequence.
- *
- * @arg step the step data.
- * @return the error code (0 if ok).
- */
+/* `__iconv_wchar_to_utf8()`: convert a wchar_t to a UTF-8 sequence. */
-int __iconv_wchar_to_utf8(struct __iconv_step *step)
+__I_FUNC(__iconv_wchar_to_utf8)
{
wchar_t val;
unsigned char seq[6];
int length;
- __I_HASIN(step, sizeof(wchar_t))
- val = *(wchar_t)__I_IN(step);
+ __I_HASIN(sizeof(wchar_t))
+ val = *(wchar_t *)__I_IN;
/* Make the buffer. */
if (val <= 0x7F) {
- __I_CHECK(step, 1)
+ __I_CHECK(1)
seq[0] = (unsigned char)val & 0x7F;
length = 1;
} else if (val <= 0x7FF) {
- __I_CHECK(step, 2)
+ __I_CHECK(2)
seq[0] = 0xC0 | (unsigned char)(val >> 6);
seq[1] = 0x80 | (unsigned char)(val & 0x3F);
length = 2;
} else if (val <= 0xFFFF) {
- __I_CHECK(step, 3)
+ __I_CHECK(3)
seq[0] = 0xE0 | (unsigned char)(val >> 12);
seq[1] = 0x80 | (unsigned char)((val >> 6) & 0x3F);
seq[2] = 0x80 | (unsigned char)(val & 0x3F);
length = 3;
} else if (val <= 0x1FFFFF) {
- __I_CHECK(step, 4)
+ __I_CHECK(4)
seq[0] = 0xF0 | (unsigned char)(val >> 18);
seq[1] = 0x80 | (unsigned char)((val >> 12) & 0x3F);
@@ -76,7 +70,7 @@ int __iconv_wchar_to_utf8(struct __iconv_step *step)
seq[3] = 0x80 | (unsigned char)(val & 0x3F);
length = 4;
} else if (val <= 0x3FFFFFF) {
- __I_CHECK(step, 5)
+ __I_CHECK(5)
seq[0] = 0xF8 | (unsigned char)(val >> 24);
seq[1] = 0x80 | (unsigned char)((val >> 18) & 0x3F);
@@ -85,7 +79,7 @@ int __iconv_wchar_to_utf8(struct __iconv_step *step)
seq[4] = 0x80 | (unsigned char)(val & 0x3F);
length = 5;
} else if (val <= 0x7FFFFFFF) {
- __I_CHECK(step, 6)
+ __I_CHECK(6)
seq[0] = 0xF8 | (unsigned char)(val >> 30);
seq[1] = 0x80 | (unsigned char)((val >> 24) & 0x3F);
@@ -99,5 +93,5 @@ int __iconv_wchar_to_utf8(struct __iconv_step *step)
/* Return the buffer. */
- __I_RETURN(step, sizeof(wchar_t), seq, length)
+ __I_RETURN(sizeof(wchar_t), seq, length)
}
diff --git a/modules/all/iconv/copyright.yml b/modules/all/iconv/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/iconv/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/iconv/include/iconv.h b/modules/all/iconv/include/iconv.h
index 1cc9840..8424f45 100644
--- a/modules/all/iconv/include/iconv.h
+++ b/modules/all/iconv/include/iconv.h
@@ -37,20 +37,30 @@
* `iconv_t` is the conversion descriptor. */
#if __INTERNAL
+# include <string.h>
+# define __I_FLAG_BUFSIZE 32
/* The conversion works while using steps.
* A step corresponds to the decoding of a character sequence. */
+struct __iconv_prep;
struct __iconv_step;
+typedef int __iconv_prep_func _OF((struct __iconv_step *__data));
typedef int __iconv_step_func _OF((struct __iconv_step *__step));
struct __iconv_step {
- struct __iconv_step *next;
- __iconv_step_func *next_func;
+ struct __iconv_step *__IS_next;
+ __iconv_step_func *__IS_next_func;
- char *in, *out;
- int inleft, outleft;
+ char *__IS_in;
+ char *__IS_out;
+ int __IS_inleft;
+ int __IS_outleft;
+
+ char *__IS_flagoff;
+ char __IS_flagbuf[__I_FLAG_BUFSIZE];
+ void *__IS_cookie;
};
/* iconv internal errors:
@@ -73,6 +83,24 @@ struct __iconv_step {
# define I_EBADF 4
# endif
+/* Define the function. */
+
+# define __I_PREP(_NAME) \
+ extern int _NAME _OF((struct __iconv_prep *__I_prep));
+# define __I_FUNC(_NAME) \
+ extern int _NAME _OF((struct __iconv_step *__I_step))
+
+/* Get the next flag from a function. */
+
+_EXTERN char const *__iconv_next_flag
+ _OF((struct __iconv_prep *__data));
+
+# define __I_NEXT_FLAG __iconv_next_flag(__I_prep)
+# define __I_IS_TRANSLIT(_FLAG) \
+ (!strcmp((_FLAG), "TRANSLIT"))
+# define __I_IS_IGNORE(_FLAG) \
+ (!strcmp((_FLAG), "IGNORE"))
+
/* Define the type and the macro to return an output buffer from a
* conversion function.
* `__I_TYPE`: type of the conversion thingy.
@@ -86,21 +114,19 @@ struct __iconv_step {
* `__I_HASIN`: check if has at least _SIZE bytes in the input buffer. */
# define __I_TYPE __iconv_t
-# define __I_IN(_STEP) ((const void*)(_STEP)->in)
-# define __I_INSIZE(_STEP) ((_STEP)->inleft)
+# define __I_IN ((const void *)__I_step->__IS_in)
+# define __I_INSIZE (__I_step->__IS_inleft)
-# define __I_CHECK(_STEP, _SIZE) \
+# define __I_CHECK(_SIZE) \
{ \
- __iconv_step *__I_step = (_STEP); \
int __I_sz = (_SIZE); \
\
if (__I_step->outleft < __I_sz) \
return (I_E2BIG); \
}
-# define __I_RETURN(_STEP, _PROC, _OUT, _SIZE) \
+# define __I_RETURN(_PROC, _OUT, _SIZE) \
{ \
- __iconv_step *__I_step = (_STEP); \
int __I_sz = (_SIZE); \
int __I_proc = (_PROC); \
char *__I_out = (_OUT); \
@@ -112,6 +138,7 @@ struct __iconv_step {
__I_step->next->inleft = __I_sz; \
__I_step->next->out = __I_step->out; \
__I_step->next->outleft = __I_step->outleft; \
+ __I_step->next->flags = __I_step->flags; \
return ((*__I_step->next_func)(__I_step->next)); \
} else { \
if (__I_sz > __I_step->outleft) \
@@ -121,9 +148,8 @@ struct __iconv_step {
return (0); \
}
-# define __I_HASIN(_STEP, _SIZE) \
+# define __I_HASIN(_SIZE) \
{ \
- __iconv_step *__Ih_step = (_STEP); \
int __Ih_sz = (_SIZE); \
\
if (!__Ih_step->inleft) \
@@ -132,6 +158,17 @@ struct __iconv_step {
return (I_EINVAL);
}
+/* Make the prototypes using the `iconv_proto.h` bits.
+ * Such bits shall use the `ICONV_PROTO(FUNC_NAME)` macro. */
+
+# define ICONV_PROTO(_NAME) \
+ ICONV_FUNC(_NAME);
+# define ICONV_PROTP(_NAME, _PREP) \
+ ICONV_FUNC(_NAME); \
+ ICONV_PREP(_NAME);
+
+#include_bits <iconv_proto.h>
+
#else
# define __I_TYPE const void
#endif
diff --git a/modules/all/iconv/info.yml b/modules/all/iconv/info.yml
deleted file mode 100644
index 1a1170d..0000000
--- a/modules/all/iconv/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The generic character conversion interface.
-license: free
diff --git a/modules/all/iconv/module.toml b/modules/all/iconv/module.toml
new file mode 100644
index 0000000..f0a9d6b
--- /dev/null
+++ b/modules/all/iconv/module.toml
@@ -0,0 +1,29 @@
+magic = "potatosdk-1.0"
+desc = "The generic character conversion interface."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "iconv.h"
+role = "Generic character conversion interface."
+
+[[source]]
+path = "iconv.c"
+role = "Main conversion function."
+
+[[source]]
+path = "iconv.h"
+role = "iconv internals."
+
+[[source]]
+path = "open.c"
+role = "Open and close an iconv descriptor."
+
+[[source]]
+path = "routes.c"
+role = "Encoding routes."
diff --git a/modules/all/iconv/roles.yml b/modules/all/iconv/roles.yml
deleted file mode 100644
index bef2d65..0000000
--- a/modules/all/iconv/roles.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-include:
- iconv.h: Generic Conversion Interface.
-src:
- iconv.c: Main conversion function.
- iconv.h: iconv internals.
- open.c: Open and close an iconv descriptor.
- routes.c: Encoding routes.
diff --git a/modules/all/iconv/src/iconv.c b/modules/all/iconv/src/iconv.c
index 5b870fc..6cf8ccb 100644
--- a/modules/all/iconv/src/iconv.c
+++ b/modules/all/iconv/src/iconv.c
@@ -51,12 +51,14 @@ size_t iconv(iconv_t cd, char **inbuf, size_t *inleft,
size_t ret = 0; int err;
/* Check the route. */
+
if (!r || r->magic != I_MAGIC) {
__set_errno(I_EBADF);
return ((size_t)-1);
}
/* Prepare the step. */
+
step.next = NULL;
step.next_func = NULL;
step.in = *inbuf;
diff --git a/modules/all/iconv/src/iconv.h b/modules/all/iconv/src/iconv.h
index 565fae8..4d4e66c 100644
--- a/modules/all/iconv/src/iconv.h
+++ b/modules/all/iconv/src/iconv.h
@@ -24,12 +24,19 @@
# define I_MAGIC 0x1256347F
-/* Conversion routes types and occurrences. */
+/* Conversion routes types and occurrences.
+ * `in`: the name of the input encoding.
+ * `out`: the name of the output encoding.
+ * `func`: the conversion step function.
+ * `prep`: the step preparation function.
+ * `magic`: the magic. */
struct iconv_route {
const char *in;
const char *out;
__iconv_step_func *func;
+ __iconv_step_prep *prep;
+ size_t csize;
unsigned long magic;
};
diff --git a/modules/all/iconv/src/open.c b/modules/all/iconv/src/open.c
index e7ca3b0..ce44b77 100644
--- a/modules/all/iconv/src/open.c
+++ b/modules/all/iconv/src/open.c
@@ -42,12 +42,72 @@
iconv_t iconv_open(char const *tocode, char const *fromcode)
{
const struct iconv_route *r = &__iconvs[0];
+ unsigned int flags = 0;
+ size_t fromsize;
+ size_t tosize;
+
+ fromsize = strlen(fromcode);
+ tosize = strlen(tocode);
+
+ /* Flags management in `tocode`.
+ * All flags start with `//` and go to the end of the string.
+ * Supported flags are the following:
+ *
+ * "TRANSLIT" (__I_FLAG_TRANSLIT).
+ * "IGNORE" (__I_FLAG_IGNORE). */
+
+ {
+ size_t lookfrom = tosize - 1;
+
+ while (1) {
+ char const *flag;
+ char const *flagsl;
+ size_t flagoff;
+ size_t flagsize;
+
+ flagsl = memrchr(tocode, '/', lookfrom);
+ if (!flagsl)
+ break;
+
+ flagoff = (size_t)(flagsl - tocode);
+ if (!flagoff)
+ break;
+
+ if (tocode[flagoff - 1] != '/') {
+ if (flagoff == 1)
+ break;
+
+ lookfrom = flagoff - 2;
+ continue;
+ }
+
+ flag = &tocode[flagoff + 1];
+ flagsize = tosize - (flagoff + 1);
+ tosize = flagoff - 1;
+ lookfrom = tosize - 1;
+
+ switch (flagsize) {
+ case 6:
+ if (!memcmp(flag, "IGNORE", 6))
+ flags |= __I_FLAG_IGNORE;
+ break;
+ case 8:
+ if (!memcmp(flag, "TRANSLIT", 8))
+ flags |= __I_FLAG_TRANSLIT;
+ break;
+ }
+ }
+ }
+
+ /* Main lookup. */
while (1) {
if (!r->in)
return ((iconv_t)-1);
- if (strcmp(fromcode, r->in) || strcmp(tocode, r->out))
- continue;
+ if (memcmp(fromcode, r->in, fromsize) || r->in[fromsize])
+ return ((iconv_t)-1);
+ if (memcmp(tocode, r->out, tosize) || r->out[tosize])
+ return ((iconv_t)-1);
break;
}
diff --git a/modules/all/iconv/src/routes.c b/modules/all/iconv/src/routes.c
index 0b8ce1f..8f2ad13 100644
--- a/modules/all/iconv/src/routes.c
+++ b/modules/all/iconv/src/routes.c
@@ -29,18 +29,13 @@
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
#include "iconv.h"
-#define ICONV_PROTO(_NAME) \
- extern int _NAME _OF((struct __iconv_step *__step));
#define ICONV_ROUTE(_FROM, _TO, _FUNC) \
- {_FROM, _TO, &_FUNC, I_MAGIC},
+ {_FROM, _TO, &_FUNC, NULL, 0, I_MAGIC},
+#define ICONV_ROUTP(_FROM, _TO, _FUNC, _PREP, _CSIZ) \
+ {_FROM, _TO, &_FUNC, &_PREP, _CSIZ, I_MAGIC},
#define ICONV_END \
{NULL, NULL, NULL, 0}
-/* Make the prototypes using the `iconv_proto.h` bits.
- * Such bits shall use the `ICONV_PROTO(FUNC_NAME)` macro. */
-
-#include_bits <iconv_proto.h>
-
/* Make the routes using the `iconv_routes.h` bits.
* Such bits shall use the `ICONV_ROUTE(FROM, TO, FUNC_NAME)` macro. */
diff --git a/modules/all/info.yml b/modules/all/info.yml
deleted file mode 100644
index 6a04789..0000000
--- a/modules/all/info.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: >-
- Meta-system for modules that are suitable for all systems.
-default:
-- all/core
-- all/core-sh
-- all/iconv
-import:
-- compiler
diff --git a/modules/all/io/copyright.yml b/modules/all/io/copyright.yml
deleted file mode 100644
index 546a0ed..0000000
--- a/modules/all/io/copyright.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
----
-files: 'src/ctype/tab.c'
-copyright:
-- [1991, 2016, "Free Software Foundation, Inc", "info@fsf.org"]
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/io/docs/printf.en.rst b/modules/all/io/docs/printf.en.rst
new file mode 100644
index 0000000..368ef4b
--- /dev/null
+++ b/modules/all/io/docs/printf.en.rst
@@ -0,0 +1,52 @@
+Using printf
+============
+
+In C, the ``printf()`` family of functions, where the term itself means
+“print formatted”, are functions that produce output according to a format.
+The prototype of any member of the ``printf()`` family of functions
+is the following:
+
+.. code:: c
+
+ int <output>printf(<output arguments>, char const *format, ...);
+
+ #include <stdarg.h>
+
+ int v<output>printf(<output arguments>, char const *format, va_list ap);
+
+The functions take what is necessary to output the result, the format and
+a variable argument list which is read accordingly to what the format
+indicates. The variable argument list is either under the exploitable
+``va_list`` format if the function name is prefixed by ``v``, or under the
+usable way otherwise.
+
+Output types
+------------
+
+As written above, there are several ``printf()`` functions according to where
+the function should output its result. The default functions are the following:
+
+- ``printf()`` and ``vprintf()``: output in the standard output
+ stream (``stdout``).
+- ``fprintf()`` and ``vfprintf()``: output in the given standard stream.
+- ``dprintf()`` and ``vdprintf()``: output in the given file descriptor.
+- ``sprintf()`` and ``vsprintf()``: output in the given string.
+- ``snprintf()`` and ``vsnprintf()``: output within the first N characters
+ of the given string.
+- ``asprintf()`` and ``vasprintf()``: output in an allocated string.
+
+Their prototypes are the following:
+
+.. code:: c
+
+ int printf(char const *format, ...);
+ int fprintf(FILE *stream, char const *format, ...);
+ int dprintf(int fd, char const *format, ...);
+ int sprintf(char *str, char const *format, ...);
+ int snprintf(char *str, size_t size, char const *format, ...);
+ int asprintf(char **strp, char const *format, ...);
+
+Format string
+-------------
+
+
diff --git a/modules/all/io/include/inttypes.h b/modules/all/io/include/inttypes.h
new file mode 100644
index 0000000..8b885f7
--- /dev/null
+++ b/modules/all/io/include/inttypes.h
@@ -0,0 +1,183 @@
+/* ************************************************************************* */
+/* `printf` and `scanf` macros. */
+/* ************************************************************************* */
+/* These macros make use of the C compile-time string concatenation.
+ * You shall use them like this: "My int8_t variable is %" PRId8 "!" */
+
+#if _USE_C99 || (_USE_CXX11 && defined(__STDC_FORMAT_MACROS))
+
+/* Decimal notation */
+
+# define PRId8 __PRI8 "d"
+# define PRId16 __PRI16 "d"
+# define PRId32 __PRI32 "d"
+# define PRId64 __PRI64 "d"
+# define PRIdFAST8 __PRIFAST8 "d"
+# define PRIdFAST16 __PRIFAST16 "d"
+# define PRIdFAST32 __PRIFAST32 "d"
+# define PRIdFAST64 __PRIFAST64 "d"
+# define PRIdLEAST8 __PRILEAST8 "d"
+# define PRIdLEAST16 __PRILEAST16 "d"
+# define PRIdLEAST32 __PRILEAST32 "d"
+# define PRIdLEAST64 __PRILEAST64 "d"
+# define PRIdMAX __PRIMAX "d"
+# define PRIdPTR __PRIPTR "d"
+
+# define SCNd8 __PRI8 "d"
+# define SCNd16 __PRI16 "d"
+# define SCNd32 __PRI32 "d"
+# define SCNd64 __PRI64 "d"
+# define SCNdFAST8 __PRIFAST8 "d"
+# define SCNdFAST16 __PRIFAST16 "d"
+# define SCNdFAST32 __PRIFAST32 "d"
+# define SCNdFAST64 __PRIFAST64 "d"
+# define SCNdLEAST8 __PRILEAST8 "d"
+# define SCNdLEAST16 __PRILEAST16 "d"
+# define SCNdLEAST32 __PRILEAST32 "d"
+# define SCNdLEAST64 __PRILEAST64 "d"
+# define SCNdMAX __PRIMAX "d"
+# define SCNdPTR __PRIPTR "d"
+
+# define PRIi8 __PRI8 "i"
+# define PRIi16 __PRI16 "i"
+# define PRIi32 __PRI32 "i"
+# define PRIi64 __PRI64 "i"
+# define PRIiFAST8 __PRIFAST8 "i"
+# define PRIiFAST16 __PRIFAST16 "i"
+# define PRIiFAST32 __PRIFAST32 "i"
+# define PRIiFAST64 __PRIFAST64 "i"
+# define PRIiLEAST8 __PRILEAST8 "i"
+# define PRIiLEAST16 __PRILEAST16 "i"
+# define PRIiLEAST32 __PRILEAST32 "i"
+# define PRIiLEAST64 __PRILEAST64 "i"
+# define PRIiMAX __PRIMAX "i"
+# define PRIiPTR __PRIPTR "i"
+
+# define SCNi8 __PRI8 "i"
+# define SCNi16 __PRI16 "i"
+# define SCNi32 __PRI32 "i"
+# define SCNi64 __PRI64 "i"
+# define SCNiFAST8 __PRIFAST8 "i"
+# define SCNiFAST16 __PRIFAST16 "i"
+# define SCNiFAST32 __PRIFAST32 "i"
+# define SCNiFAST64 __PRIFAST64 "i"
+# define SCNiLEAST8 __PRILEAST8 "i"
+# define SCNiLEAST16 __PRILEAST16 "i"
+# define SCNiLEAST32 __PRILEAST32 "i"
+# define SCNiLEAST64 __PRILEAST64 "i"
+# define SCNiMAX __PRIMAX "i"
+# define SCNiPTR __PRIPTR "i"
+
+/* Octal notation */
+
+# define PRIo8 __PRI8 "o"
+# define PRIo16 __PRI16 "o"
+# define PRIo32 __PRI32 "o"
+# define PRIo64 __PRI64 "o"
+# define PRIoFAST8 __PRIFAST8 "o"
+# define PRIoFAST16 __PRIFAST16 "o"
+# define PRIoFAST32 __PRIFAST32 "o"
+# define PRIoFAST64 __PRIFAST64 "o"
+# define PRIoLEAST8 __PRILEAST8 "o"
+# define PRIoLEAST16 __PRILEAST16 "o"
+# define PRIoLEAST32 __PRILEAST32 "o"
+# define PRIoLEAST64 __PRILEAST64 "o"
+# define PRIoMAX __PRIMAX "o"
+# define PRIoPTR __PRIPTR "o"
+
+# define SCNo8 __PRI8 "o"
+# define SCNo16 __PRI16 "o"
+# define SCNo32 __PRI32 "o"
+# define SCNo64 __PRI64 "o"
+# define SCNoFAST8 __PRIFAST8 "o"
+# define SCNoFAST16 __PRIFAST16 "o"
+# define SCNoFAST32 __PRIFAST32 "o"
+# define SCNoFAST64 __PRIFAST64 "o"
+# define SCNoLEAST8 __PRILEAST8 "o"
+# define SCNoLEAST16 __PRILEAST16 "o"
+# define SCNoLEAST32 __PRILEAST32 "o"
+# define SCNoLEAST64 __PRILEAST64 "o"
+# define SCNoMAX __PRIMAX "o"
+# define SCNoPTR __PRIPTR "o"
+
+/* Unsigned notation */
+
+# define PRIu8 __PRI8 "u"
+# define PRIu16 __PRI16 "u"
+# define PRIu32 __PRI32 "u"
+# define PRIu64 __PRI64 "u"
+# define PRIuFAST8 __PRIFAST8 "u"
+# define PRIuFAST16 __PRIFAST16 "u"
+# define PRIuFAST32 __PRIFAST32 "u"
+# define PRIuFAST64 __PRIFAST64 "u"
+# define PRIuLEAST8 __PRILEAST8 "u"
+# define PRIuLEAST16 __PRILEAST16 "u"
+# define PRIuLEAST32 __PRILEAST32 "u"
+# define PRIuLEAST64 __PRILEAST64 "u"
+# define PRIuMAX __PRIMAX "u"
+# define PRIuPTR __PRIPTR "u"
+
+# define SCNu8 __PRI8 "u"
+# define SCNu16 __PRI16 "u"
+# define SCNu32 __PRI32 "u"
+# define SCNu64 __PRI64 "u"
+# define SCNuFAST8 __PRIFAST8 "u"
+# define SCNuFAST16 __PRIFAST16 "u"
+# define SCNuFAST32 __PRIFAST32 "u"
+# define SCNuFAST64 __PRIFAST64 "u"
+# define SCNuLEAST8 __PRILEAST8 "u"
+# define SCNuLEAST16 __PRILEAST16 "u"
+# define SCNuLEAST32 __PRILEAST32 "u"
+# define SCNuLEAST64 __PRILEAST64 "u"
+# define SCNuMAX __PRIMAX "u"
+# define SCNuPTR __PRIPTR "u"
+
+/* Lowercase hexadecimal notation */
+
+# define PRIx8 __PRI8 "x"
+# define PRIx16 __PRI16 "x"
+# define PRIx32 __PRI32 "x"
+# define PRIx64 __PRI64 "x"
+# define PRIxFAST8 __PRIFAST8 "x"
+# define PRIxFAST16 __PRIFAST16 "x"
+# define PRIxFAST32 __PRIFAST32 "x"
+# define PRIxFAST64 __PRIFAST64 "x"
+# define PRIxLEAST8 __PRILEAST8 "x"
+# define PRIxLEAST16 __PRILEAST16 "x"
+# define PRIxLEAST32 __PRILEAST32 "x"
+# define PRIxLEAST64 __PRILEAST64 "x"
+# define PRIxMAX __PRIMAX "x"
+# define PRIxPTR __PRIPTR "x"
+
+# define SCNx8 __PRI8 "x"
+# define SCNx16 __PRI16 "x"
+# define SCNx32 __PRI32 "x"
+# define SCNx64 __PRI64 "x"
+# define SCNxFAST8 __PRIFAST8 "x"
+# define SCNxFAST16 __PRIFAST16 "x"
+# define SCNxFAST32 __PRIFAST32 "x"
+# define SCNxFAST64 __PRIFAST64 "x"
+# define SCNxLEAST8 __PRILEAST8 "x"
+# define SCNxLEAST16 __PRILEAST16 "x"
+# define SCNxLEAST32 __PRILEAST32 "x"
+# define SCNxLEAST64 __PRILEAST64 "x"
+# define SCNxMAX __PRIMAX "x"
+# define SCNxPTR __PRIPTR "x"
+
+/* Uppercase hexadecimal notation */
+
+# define PRIX8 __PRI8 "X"
+# define PRIX16 __PRI16 "X"
+# define PRIX32 __PRI32 "X"
+# define PRIX64 __PRI64 "X"
+# define PRIXFAST8 __PRIFAST8 "X"
+# define PRIXFAST16 __PRIFAST16 "X"
+# define PRIXFAST32 __PRIFAST32 "X"
+# define PRIXFAST64 __PRIFAST64 "X"
+# define PRIXLEAST8 __PRILEAST8 "X"
+# define PRIXLEAST16 __PRILEAST16 "X"
+# define PRIXLEAST32 __PRILEAST32 "X"
+# define PRIXLEAST64 __PRILEAST64 "X"
+# define PRIXMAX __PRIMAX "X"
+# define PRIXPTR __PRIPTR "X"
+#endif
diff --git a/modules/all/io/include/printf.h b/modules/all/io/include/printf.h
index 178a404..4ce40fb 100644
--- a/modules/all/io/include/printf.h
+++ b/modules/all/io/include/printf.h
@@ -74,42 +74,58 @@ _EXTERN _NONNULL(2, __fmt) int vfprintf
_OF((FILE *__stream, const char __fmt[_NOTNULL], va_list __ap)) _THROW;
_END_NAMESPACE_STD
-/* ************************************************************************* */
-/* Descriptors management */
-/* ************************************************************************* */
+
+/* ---
+ * Descriptors management.
+ * --- */
+
/* Flags. */
+#define printf_flag_width 0x01ff /* All width flags combined. */
+
#define printf_flag_char 0x0001 /* 'hh' type modifier */
#define printf_flag_short 0x0002 /* 'h' type modifier */
-#define printf_flag_long 0x0004 /* 'l' type modifier */
-#define printf_flag_llong 0x0008 /* 'L', 'll' or 'q' type modifier */
+#define printf_flag_long 0x0004 /* 'l' or 'w' type modifier */
+#define printf_flag_llong 0x0008 /* 'L', 'll' type modifier */
#define printf_flag_size 0x0010 /* 'z' type modifier */
#define printf_flag_imax 0x0020 /* 'j' type modifier */
-#define printf_flag_ptr 0x0040 /* 't' type modifier */
-
-#define printf_flag_alt 0x0100 /* '#' flag */
-#define printf_flag_space 0x0200 /* ' ' flag */
-#define printf_flag_left 0x0400 /* '-' flag */
-#define printf_flag_sign 0x0800 /* '+' flag */
-#define printf_flag_grp 0x1000 /* "'" flag */
-
-/* Descriptor information. */
+#define printf_flag_ptr 0x0040 /* 'I' or 't' type modifier */
+#define printf_flag_i32 0x0080 /* 'I32' type modifier */
+#define printf_flag_i64 0x0100 /* 'I64' or 'q' type modifier */
+
+#define printf_flag_alt 0x0400 /* # flag */
+#define printf_flag_space 0x0800 /* " " flag */
+#define printf_flag_left 0x1000 /* - flag */
+#define printf_flag_sign 0x2000 /* + flag */
+#define printf_flag_grp 0x4000 /* ' flag */
+
+/* Descriptor information.
+ * `flags`: the length flags among those above.
+ * `spec`: the original character (e.g. `s` for `%.10s`).
+ * `prec`: precision, -1 if none specified.
+ * `width`: minimum field width, 0 if none specified.
+ * `pad`: character used for padding the output, '0' or ' '. */
typedef struct printf_info {
unsigned int flags;
- int spec; /* original character */
- int prec; /* precision, -1 if none specified */
- int width; /* minimum field width, 0 if none specified */
- int pad; /* character used for padding the output, '0' or ' ' */
+ int spec;
+ int prec;
+ int width;
+ int pad;
} printf_t;
/* Descriptor callback type. */
-typedef int printf_callback_t _OF((FILE*, printf_t*, va_list));
-/* ************************************************************************* */
-/* Interact with printf callbacks */
-/* ************************************************************************* */
+typedef int printf_arg_t
+ _OF((void *, printf_t const *, va_list));
+typedef int printf_spec_t
+ _OF((FILE *, printf_t const *, void const *));
+
+/* ---
+ * Interact with printf callbacks.
+ * --- */
+
/* Get a callback corresponding to a specifier. */
_EXTERN _NONNULL(2, __func) int find_printf_function
diff --git a/modules/all/io/include/stdio.h b/modules/all/io/include/stdio.h
index ab428b9..0a6da64 100644
--- a/modules/all/io/include/stdio.h
+++ b/modules/all/io/include/stdio.h
@@ -40,21 +40,21 @@ typedef struct _IO_FILE FILE;
/* Standard input and output. */
-_EXTERN FILE* stdout;
-_EXTERN FILE* stderr;
+_EXTERN FILE *stdout;
+_EXTERN FILE *stderr;
/* Basic standard I/O.
* We ought to open, close a stream, read and write from it,
* and move within it. */
_EXTERN _NONNULL(1, __path) _NONNULL(2, __cmode) _PURE FILE* fopen
- _OF((const char __path[_NOTNULL], const char __mode[_NOTNULL])) _THROW;
+ _OF((char const _NOTNULL(__path), char const _NOTNULL(__mode))) _THROW;
_EXTERN int fclose
_OF((FILE *__stream)) _THROW;
_EXTERN _NONNULL(1, __ptr) _WUR size_t fread
_OF((void *__ptr, size_t __size, size_t __nmemb, FILE *__stream)) _THROW;
_EXTERN _NONNULL(1, __ptr) _WUR size_t fwrite
- _OF((const void *__ptr, size_t __size, size_t __nmemb,
+ _OF((void const *__ptr, size_t __size, size_t __nmemb,
FILE *__stream)) _THROW;
#define SEEK_SET 0 /* from beginning */
@@ -87,13 +87,13 @@ _EXTERN void setvbuf
* internal interface. */
typedef long cookie_read_function_t
- _OF((void*, char*, size_t));
+ _OF((void *, char *, size_t));
typedef long cookie_write_function_t
- _OF((void*, const char*, size_t));
+ _OF((void *, char const *, size_t));
typedef int cookie_seek_function_t
- _OF((void*, long*, int));
+ _OF((void *, long *, int));
typedef int cookie_close_function_t
- _OF((void*));
+ _OF((void *));
typedef struct {
cookie_read_function_t *read;
@@ -102,8 +102,8 @@ typedef struct {
cookie_close_function_t *close;
} cookie_io_functions_t;
-_EXTERN FILE* fopencookie
- _OF((void* __cookie, const char* __mode, cookie_io_functions_t __funcs));
+_EXTERN FILE *fopencookie
+ _OF((void *__cookie, char const *__mode, cookie_io_functions_t __funcs));
_END_DECLS
_END_NAMESPACE_STD
@@ -124,7 +124,7 @@ _END_NAMESPACE_STD
# define __IO_MODE_KWCOOKIE_VBUFSIZE 128
typedef struct {
- const char* raw;
+ char const *raw;
char kbuf[__IO_MODE_KWCOOKIE_KBUFSIZE];
char vbuf[__IO_MODE_KWCOOKIE_VBUFSIZE];
} _IO_MODE_KEYWORD_COOKIE;
@@ -135,12 +135,12 @@ typedef struct {
* appropriately, and non-zero if there was an error or an end. */
typedef struct {
- const char *key;
- const char *val;
+ char const *key;
+ char const *val;
} _IO_MODE_KEYWORD;
_EXTERN int __get_open_keyword
- _OF((_IO_MODE_KEYWORD_COOKIE* __cookie, _IO_MODE_KEYWORD* kw));
+ _OF((_IO_MODE_KEYWORD_COOKIE *__cookie, _IO_MODE_KEYWORD *kw));
/* FILE opening flags:
* `_IO_OPEN_FLAG_ALLOC`: the FILE was allocated;
@@ -172,11 +172,11 @@ typedef unsigned int _IO_MODE_FLAGS;
typedef struct {
_IO_MODE_FLAGS flags;
- _IO_MODE_KEYWORD_COOKIE* kwcookie;
+ _IO_MODE_KEYWORD_COOKIE *kwcookie;
} _IO_MODE;
-_EXTERN int _decode_open_mode
- _OF((const char* __raw, _IO_MODE* __mode));
+_EXTERN int __decode_open_mode
+ _OF((char const _NOTNULL(__raw), _IO_MODE _NOTNULL(__mode)));
#endif
/* Internal API to opening a FILE stream, intended for other modules.
@@ -187,34 +187,28 @@ _EXTERN int _decode_open_mode
* Please do not fill the `__file_functions_t` yourself, use `__FILEFUNCS`
* for compatibility. */
-typedef size_t __file_offset_t; /* FIXME: 64-bits */
+typedef off64_t __file_offset_t; /* FIXME: 64-bits */
-typedef size_t __file_read_t
- _OF((void* __cookie, void* __buf, size_t __size));
-typedef size_t __file_write_t
- _OF((void* __cookie, const void* __buf, size_t __size));
+typedef int __file_read_t
+ _OF((void *__cookie, void *__buf, size_t *__size));
+typedef int __file_write_t
+ _OF((void *__cookie, void const *__buf, size_t *__size));
typedef int __file_seek_t
- _OF((void* __cookie, __file_offset_t* __offset, int __whence));
+ _OF((void *__cookie, __file_offset_t *__offset, int __whence));
typedef int __file_close_t
- _OF((void* __cookie));
-
-/* Please don't fill this structure directly, see below. */
+ _OF((void *__cookie));
typedef struct {
- __file_read_t* read;
- __file_write_t* write;
- __file_seek_t* seek;
- __file_close_t* close;
+ __file_read_t *read;
+ __file_write_t *write;
+ __file_seek_t *seek;
+ __file_close_t *close;
} __file_functions_t;
-/* Prefer using this macro directly, in case the order of the
- * function pointers change. */
-
-# define __FILEFUNCS(_RD, _WR, _SK, _CL) \
- {_RD, _WR, _SK, _CL}
+/* Internal function to make a FILE stream. */
-_EXTERN FILE* __make_file
- _OF((const __file_functions_t* functions, int __buffering_mode,
+_EXTERN FILE *__make_file
+ _OF((__file_functions_t const *functions, int __buffering_mode,
size_t __cookie_size));
#endif
diff --git a/modules/all/io/info.yml b/modules/all/io/info.yml
deleted file mode 100644
index 41a0f1d..0000000
--- a/modules/all/io/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Standard I/O libraries.
-license: free
diff --git a/modules/all/io/module.toml b/modules/all/io/module.toml
new file mode 100644
index 0000000..ad029e3
--- /dev/null
+++ b/modules/all/io/module.toml
@@ -0,0 +1,97 @@
+magic = "potatosdk-1.0"
+desc = "Standard I/O libraries."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "dirent.h"
+role = "Directory listing."
+
+[[headers]]
+path = "inttypes.h"
+role = "printf descriptors for C99 integer types."
+
+[[headers]]
+path = "printf.h"
+role = "printf-related utilities."
+
+[[headers]]
+path = "stdio.h"
+role = "Standard I/O utilities."
+
+[[headers]]
+path = "stdio_ext.h"
+role = "Extended standard I/O utilities."
+
+[[source]]
+path = "printf/printf.h"
+role = "printf internals."
+
+[[source]]
+path = "printf/fprintf.c"
+role = "Print formatted in a stream."
+
+[[source]]
+path = "printf/sprintf.c"
+role = "String front-end to [v]s[n]printf."
+
+[[source]]
+path = "printf/vfprintf.c"
+role = "printf core."
+
+[[source]]
+path = "printf/register.c"
+role = "Manage printf callbacks."
+
+[[source]]
+path = "printf/pad.c"
+role = "Padding displaying."
+
+[[source]]
+path = "printf/default/int.h"
+role = "Integer printing internals."
+
+[[source]]
+path = "printf/default/int.c"
+role = "Signed integer printing."
+
+[[source]]
+path = "printf/default/uint.c"
+role = "Unsigned integer printing."
+
+[[source]]
+path = "printf/default/char.c"
+role = "Character printing."
+
+[[source]]
+path = "printf/default/str.c"
+role = "String printing."
+
+[[source]]
+path = "read.c"
+role = "Read from a stream."
+
+[[source]]
+path = "seek.c"
+role = "Seek on a stream."
+
+[[source]]
+path = "stdio.h"
+role = "Internal header for standard I/O utilities."
+
+[[source]]
+path = "stdout.c"
+role = "Standard output and error streams definition."
+
+[[source]]
+path = "write.c"
+role = "Write to a stream."
+
+[[source]]
+path = "open.c"
+role = "Open a stream."
diff --git a/modules/all/io/roles.yml b/modules/all/io/roles.yml
deleted file mode 100644
index 34e766c..0000000
--- a/modules/all/io/roles.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-%YAML 1.2
----
-include:
- dirent.h: Directory listing.
- errno.h: libc error codes.
- printf.h: printf-related utilities.
- stdio.h: Standard I/O.
- stdio_ext.h: Extended standard I/O utilities.
-src:
- printf:
- default.c: Default printf callbacks.
- fprintf.c: Print formatted in a stream.
- prinf.h: Internal header for printf-related utilities.
- register.c: Manage printf callbacks.
- sprintf.c: String front-end to [v]s[n]printf.
- vfprintf.c: The core of all.
- read.c: Read from a stream.
- seek.c: Seek on a stream.
- stdio.h: Internal header for standard I/O utilities.
- stdout.c: Standard output and error streams definition.
- write.c: Write to a stream.
- open.c: Open a stream.
diff --git a/modules/all/io/src/mode.c b/modules/all/io/src/mode.c
index ad80318..2d0b5c8 100644
--- a/modules/all/io/src/mode.c
+++ b/modules/all/io/src/mode.c
@@ -6,9 +6,9 @@
*/
int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
- _IO_MODE_KEYWORD* kw)
+ _IO_MODE_KEYWORD *kw)
{
- const char *raw, *comma, *val;
+ char const *raw, *comma, *val;
size_t kwlen, vlen;
raw = cookie->raw;
@@ -17,6 +17,7 @@ int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
/* Pass the first comma and the spacing characters after it.
* This plays the role of our global and keyword `ltrim()`. */
+
for (++raw; isspace(*raw); ++raw);
/* Get the next comma and initial value length.
@@ -26,6 +27,7 @@ int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
* for the function to return early.
* After this update, the `comma` pointer will be used for locating the
* end of string. */
+
comma = strchrnul(raw, ',');
cookie->raw = comma;
@@ -36,15 +38,18 @@ int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
/* Get the separator between keyword and value.
* If there is no separator, then the current element is keyword-only. */
+
val = memchr(raw, '=', kwlen);
if (!val) {
/* Copy the keyword to the keyword buffer. */
+
if (kwlen > _IO_MODE_KWCOOKIE_KBUFSIZE - 1)
kwlen = _IO_MODE_KWCOOKIE_KBUFSIZE - 1;
memcpy(cookie->kbuf, raw, kwlen);
cookie->kbuf[kwlen] = 0;
/* Fill the user structure and return. */
+
kw->key = cookie->kbuf;
kw->val = NULL;
return (0);
@@ -55,26 +60,31 @@ int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
*
* `val == raw`: there is no keyword;
* `++val == &raw[kwlen - 1]`: there is no value. */
+
if (val == raw || ++val == &raw[kwlen - 1])
return (-1);
/* Correct the keyword and value length accordingly. */
+
vlen = kwlen - (size_t)(val - raw + 1);
kwlen = kwlen - vlen - 1;
/* Check for spaces in the keyword, from the equals.
* No need to check if the keyword is empty afterwards, we have
* checked this before. No need to do the `ltrim()` either. */
+
for (; kwlen && isspace(raw[kwlen - 1]); kwlen--);
/* Check for spaces in the value, from the equals.
* No need to check if the value is empty afterwards, we have
* checked this before. No need to do the `rtrim()` either. */
+
for (; isspace(*val); val++, vlen--);
/* Copy the keyword and value to our final buffers.
* Make a substring if the entire keyword/value doesn't fit in the buffer,
* it's probably okay. */
+
if (kwlen > _IO_MODE_KWCOOKIE_KBUFSIZE - 1)
kwlen = _IO_MODE_KWCOOKIE_KBUFSIZE - 1;
memcpy(cookie->kbuf, raw, kwlen);
@@ -86,6 +96,7 @@ int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
cookie->vbuf[vlen] = 0;
/* Fill the user structure and return. */
+
kw->key = cookie->kbuf;
kw->val = cookie->vbuf;
return (0);
@@ -96,9 +107,9 @@ int __get_open_keyword(_IO_MODE_KEYWORD_COOKIE *cookie,
* Get some flags in the keyword.
*/
-_LOCAL void _get_flags(const char **praw, _IO_MODE_FLAGS *pflags)
+_LOCAL void _get_flags(char const **rawp, _IO_MODE_FLAGS *flagsp)
{
- const char *raw = *praw;
+ char const *raw = *rawp;
_IO_MODE_FLAGS flags = 0;
for (;; ++raw) switch (*raw) {
@@ -118,27 +129,28 @@ _LOCAL void _get_flags(const char **praw, _IO_MODE_FLAGS *pflags)
flags |= _IO_OPEN_FLAG_EXISTS;
break;
case 't':
- /* Text mode, enabled by default (?) */
+ /* Text mode, enabled by default. */
break;
default:
goto end;
}
end:
- *praw = raw;
- *pflags |= flags;
+ *rawp = raw;
+ *flagsp |= flags;
}
/**
- * _decode_open_mode:
+ * __decode_open_mode:
* Decode the open mode.
*/
-_EXTERN int _decode_open_mode(const char* raw, _IO_MODE* mode)
+_EXTERN int __decode_open_mode(char const *raw, _IO_MODE *mode)
{
_IO_MODE_FLAGS flags;
/* Decode the main open mode. */
+
switch (*raw++) {
case 'r':
flags |= _IO_OPEN_FLAG_READ;
@@ -185,10 +197,12 @@ _EXTERN int _decode_open_mode(const char* raw, _IO_MODE* mode)
}
/* Pass the last spaces to prepare for the keyword decoding. */
+
while (isspace(*raw))
*raw++;
/* Set the properties and go. */
+
mode->flags = flags;
mode->kwcookie->raw = raw;
return (0);
diff --git a/modules/all/io/src/open.c.draft b/modules/all/io/src/open.c.draft
index 1f2b06c..a323e8e 100644
--- a/modules/all/io/src/open.c.draft
+++ b/modules/all/io/src/open.c.draft
@@ -18,7 +18,7 @@ FILE *fopen(const char *path, const char *smode)
int ret;
mode.kwcookie = &cookie;
- if (_decode_openmode(smode, &mode))
+ if (__decode_openmode(smode, &mode))
return (NULL);
/* TODO: allocate the `FILE`, open the resource (internal callback?) */
diff --git a/modules/all/io/src/printf/default.c b/modules/all/io/src/printf/default.c
deleted file mode 100644
index 35d18ee..0000000
--- a/modules/all/io/src/printf/default.c
+++ /dev/null
@@ -1,139 +0,0 @@
-/* ****************************************************************************
- * printf/default.c -- Default printf callbacks.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'all/io' module in libcarrot, an experimental
- * modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include "printf.h"
-#include <string.h>
-
-/* ************************************************************************* */
-/* Utilities */
-/* ************************************************************************* */
-/**
- * put_pad:
- * Put some spaces.
- *
- * @arg stream the stream to write to.
- * @arg count number of spaces to put.
- * @return the number of output characters.
- */
-
-static int put_pad(FILE *stream, size_t count)
-{
- char sp[128]; memset(sp, ' ', 128);
- for (; count > 128; count -= 128)
- if (!fwrite(sp, 128, 1, stream)) return (-1);
- if (count)
- if (!fwrite(sp, count, 1, stream)) return (-1);
-
- return (count);
-}
-
-/**
- * put_padding:
- * Put a string with the padding.
- *
- * @arg stream the stream to write to.
- * @arg info the information.
- * @arg buf the buffer to put.
- * @arg size the buffer size.
- * @return the number of written bytes.
- */
-
-static int put_padding(FILE *stream, printf_t *info,
- const char *buf, size_t size)
-{
- int n = 0, ntemp;
-
- /* left alignment */
- if (info->width && ~info->flags & printf_flag_left && n < info->width) {
- ntemp = put_pad(stream, info->width - size);
- if (ntemp < 0) return (-1);
- n += ntemp;
- }
-
- /* put */
- if (!fwrite(buf, size, 1, stream)) return (-1);
- n += (int)size;
-
- /* right alignment */
- if (info->width && info->flags & printf_flag_left && n < info->width) {
- ntemp = put_pad(stream, info->width - size);
- if (ntemp < 0) return (-1);
- n += ntemp;
- }
-
- /* everything went well! */
- return (n);
-}
-/* ************************************************************************* */
-/* Formatting functions */
-/* ************************************************************************* */
-/**
- * printf_default_s:
- * Print a string.
- *
- * TODO: wide string?
- *
- * @arg stream the stream to write to.
- * @arg info the format information.
- * @arg ap the arguments pointer.
- * @return the number of written bytes.
- */
-
-int printf_default_s(FILE *stream, printf_t *info, va_list ap)
-{
- /* get the string and length */
- const char *s = va_arg(ap, char*);
- size_t n = info->prec >= 0 ? strnlen(s, info->prec) : strlen(s);
-
- /* put it and leave */
- return (put_padding(stream, info, s, n));
-}
-
-/**
- * printf_default_c:
- * Print a character.
- *
- * TODO: wide character?
- *
- * @arg stream the stream to write to.
- * @arg info the format information.
- * @arg ap the arguments pointer.
- * @return the number of written bytes.
- */
-
-int printf_default_c(FILE *stream, printf_t *info, va_list ap)
-{
- /* get the character */
- char character = va_arg(ap, int) & 0x7F;
-
- /* put it and leave */
- int n = character != 0;
- return (put_padding(stream, info, &character, n));
-}
diff --git a/modules/all/io/src/printf/default/char.c b/modules/all/io/src/printf/default/char.c
new file mode 100644
index 0000000..712758c
--- /dev/null
+++ b/modules/all/io/src/printf/default/char.c
@@ -0,0 +1,24 @@
+#include "../printf.h"
+
+/* `__printf_arg_c()`: get a character.
+ * TODO: wide character? */
+
+int __printf_arg_c(void *vchar, printf_t const *info, va_list ap)
+{
+ char *c = (void *)vchar;
+
+ *c = va_arg(ap, int) & 0x7f;
+ return (0);
+}
+
+/* `__printf_spec_c()`: print a character.
+ * TODO: wide character? */
+
+int __printf_spec_c(FILE *stream, printf_t const *info, void const *vchar)
+{
+ char c = *(char *)vchar;
+
+ /* Put the character and leave. */
+
+ return (__printf_pad(stream, info, NULL, 0, &c, c != 0));
+}
diff --git a/modules/all/io/src/printf/default/cnt.c b/modules/all/io/src/printf/default/cnt.c
new file mode 100644
index 0000000..29f1d57
--- /dev/null
+++ b/modules/all/io/src/printf/default/cnt.c
@@ -0,0 +1,21 @@
+#include "../printf.h"
+
+/* `__printf_arg_n()`: get an unsigned integer. */
+
+int __printf_arg_n(void *vptr, printf_t const *info, va_list ap)
+{
+ int **ptr = (void *)vptr;
+
+ *ptr = va_arg(ap, int *);
+
+ return (0);
+}
+
+/* `__printf_spec_u()`: print an unsigned integer. */
+
+int __printf_spec_u(FILE *stream, printf_t const *oinfo, void const *vuint)
+{
+ /* TODO: get the current count */
+
+ return (0);
+}
diff --git a/modules/all/io/src/printf/default/int.c b/modules/all/io/src/printf/default/int.c
new file mode 100644
index 0000000..3d5863f
--- /dev/null
+++ b/modules/all/io/src/printf/default/int.c
@@ -0,0 +1,104 @@
+#include "int.h"
+
+/* `__printf_arg_d()`: get a signed integer. */
+
+int __printf_arg_d(void *vint, printf_t const *info, va_list ap)
+{
+ _int *i = (void *)vint;
+
+ if (!(info->flags & printf_flag_width)) {
+ i.type = I_INT;
+ i.val.val_int = va_arg(ap, int);
+ } else if (info->flags & printf_flag_char) {
+ i.type = I_INT;
+ i.val.val_int = va_arg(ap, int) &
+ ((1 << __INT_WIDTH - 1) | __SCHAR_MAX);
+ } else if (info->flags & printf_flag_short) {
+ i.type = I_INT;
+ i.val.val_int = va_arg(ap, int) &
+ ((1 << __INT_WIDTH - 1) | __SHRT_MAX)
+ } else if (info->flags & printf_flag_long) {
+ i.type = I_LONG;
+ i.val.val_long = va_arg(ap, long);
+ } else if (info->flags & printf_flag_llong) {
+ i.type = I_LLONG;
+ i.val.val_llong = va_arg(ap, long long);
+ } else if (info->flags & (printf_flag_size | printf_flag_ptr)) {
+ i.type = I_PTR;
+ i.val.val_ptr = va_arg(ap, intptr_t);
+ } else if (info->flags & printf_flag_imax) {
+ i.type = I_MAX;
+ i.val.val_max = va_arg(ap, intmax_t);
+ } else if (info->flags & printf_flag_i32) {
+ i.type = I_32;
+ i.val.val_32 = va_arg(ap, int32_t);
+ } else if (info->flags & printf_flag_i64) {
+ i.type = I_64;
+ i.val.val_64 = va_arg(ap, int64_t);
+ }
+
+ return (1);
+}
+
+/* `__printf_spec_d()`: print a signed integer. */
+
+int __printf_spec_d(FILE *stream, printf_t const *info, void const *vint)
+{
+ char buf[30], *p = &buf[29];
+ char const *prepend = NULL;
+ _int const *i = (void *)vint;
+
+ switch (i->type) {
+ case I_INT:
+ {
+ int value = i->val.val_int;
+
+ FILLBUF_D(value, __INT_MAX)
+ break;
+ }
+ case I_LONG:
+ {
+ long value = i->val.val_long;
+
+ FILLBUF_D(value, __LONG_MAX)
+ break;
+ }
+ case I_LLONG:
+ {
+ llong value = i->val.val_llong;
+
+ FILLBUF_D(value, __LLONG_MAX)
+ break;
+ }
+ case I_PTR:
+ {
+ intptr_t value = i->val.val_ptr;
+
+ FILLBUF_D(value, __INTPTR_MAX)
+ break;
+ }
+ case I_MAX:
+ {
+ intmax_t value = i->val.val_max;
+
+ FILLBUF_D(value, __INTMAX_MAX)
+ break;
+ }
+ case I_32:
+ {
+ int32_t value = i->val.val_32;
+
+ FILLBUF_D(value, __INT32_MAX)
+ break;
+ }
+ case I_64:
+ {
+ int64_t value = i->val.val_64;
+
+ FILLBUF_D(value, __INT64_MAX)
+ }
+ }
+
+ return (__printf_pad(stream, info,
+ prepend, 1, buf, (size_t)(buf + 1 - p)));
+}
diff --git a/modules/all/io/src/printf/default/int.h b/modules/all/io/src/printf/default/int.h
new file mode 100644
index 0000000..d7208a0
--- /dev/null
+++ b/modules/all/io/src/printf/default/int.h
@@ -0,0 +1,104 @@
+#include "../printf.h"
+
+/* Main macros for type-independent algorithms. */
+
+#define FILLBUF_BASE(VAR, MAX, CHARS, BASE) \
+ do { \
+ *p-- = CHARS[VAR % BASE]; \
+ VAR /= BASE; \
+ } while (VAR);
+
+#define FILLBUF_U(VAR, MAX) \
+ if (info.spec == 'p' && !VAR) { \
+ *p-- = ')'; \
+ *p-- = 'l'; \
+ *p-- = 'i'; \
+ *p-- = 'n'; \
+ *p-- = '('; \
+ info.pad = ' '; \
+ } else { \
+ if (!VAR) { \
+ } else if (info.spec == 'x') { \
+ base = 16; \
+ \
+ if (info.flags & printf_flag_alt) { \
+ prepend = "0x"; \
+ psize = 2; \
+ } \
+ } else if (info.spec == 'X') { \
+ base = 16; \
+ bchars = "0123456789ABCDEF"; \
+ \
+ if (info.flags & printf_flag_alt) { \
+ prepend = "0X"; \
+ psize = 2; \
+ } \
+ } else if (info.spec == 'o') { \
+ base = 8; \
+ \
+ if (info.flags & printf_flag_alt) { \
+ prepend = "0"; \
+ psize = 1; \
+ } \
+ } \
+ \
+ FILLBUF_BASE(VAR, MAX, bchars, base) \
+ }
+
+#define FILLBUF_D(VAR, MAX) \
+ if (VAR < 0) { \
+ prepend = "-"; \
+ VAR = -VAR; \
+ } else if (info->flags & printf_flag_sign) \
+ prepend = "+"; \
+ else if (info->flags & printf_flag_space) \
+ prepend = " "; \
+ \
+ FILLBUF_BASE(VAR, MAX, "0123456789", 10) \
+ \
+ if (prepend && info->pad != '0') { \
+ *p-- = *prepend; \
+ prepend = NULL; \
+ }
+
+/* ---
+ * Types.
+ * --- */
+
+#define I_INT 1
+#define I_LONG 2
+#define I_LLONG 3
+#define I_PTR 4
+#define I_MAX 5
+#define I_32 6
+#define I_64 7
+
+union _intval {
+ int val_int;
+ long val_long;
+ llong val_llong;
+ intptr_t val_ptr;
+ intmax_t val_max;
+ int32_t val_32;
+ int64_t val_64;
+};
+
+struct _int {
+ int type;
+ _intval val;
+};
+
+union _uintval {
+ uint val_int;
+ ulong val_long;
+ ullong val_llong;
+ uintptr_t val_ptr;
+ uintmax_t val_max;
+ uint32_t val_32;
+ uint64_t val_64;
+};
+
+struct _uint {
+ int type;
+ _uintval val;
+};
diff --git a/modules/all/io/src/printf/default/str.c b/modules/all/io/src/printf/default/str.c
new file mode 100644
index 0000000..171b8ac
--- /dev/null
+++ b/modules/all/io/src/printf/default/str.c
@@ -0,0 +1,26 @@
+#include "../printf.h"
+
+/* `__printf_arg_s()`: get a string.
+ * TODO: wide string? */
+
+int __printf_arg_s(void *vstr, printf_t const *info, va_list ap)
+{
+ char const **s = (void *)vstr;
+
+ *s = va_arg(ap, char const *);
+ return (0);
+}
+
+/* `__printf_spec_s()`: print a string.
+ * TODO: wide string? */
+
+int __printf_spec_s(FILE *stream, printf_t const *info, void const *vstr)
+{
+ char const *s = *(char const **)vstr;
+ size_t n;
+
+ /* Get the string and length, and print it. */
+
+ n = info->prec >= 0 ? strnlen(s, info->prec) : strlen(s);
+ return (__printf_pad(stream, info, NULL, 0, s, n));
+}
diff --git a/modules/all/io/src/printf/default/uint.c b/modules/all/io/src/printf/default/uint.c
new file mode 100644
index 0000000..a954b78
--- /dev/null
+++ b/modules/all/io/src/printf/default/uint.c
@@ -0,0 +1,106 @@
+#include "int.h"
+
+/* `__printf_arg_u()`: get an unsigned integer. */
+
+int __printf_arg_u(void *vuint, printf_t const *info, va_list ap)
+{
+ _uint *u = (void *)vuint;
+
+ if (!(info->flags & printf_flag_width)) {
+ u.type = I_INT;
+ u.val.val_int = va_arg(ap, unsigned int);
+ } else if (info->flags & printf_flag_char) {
+ u.type = I_INT;
+ u.val.val_int = va_arg(ap, unsigned int) & __UCHAR_MAX;
+ } else if (info->flags & printf_flag_short) {
+ u.type = I_INT;
+ u.val.val_int = va_arg(ap, unsigned short) & __SHRT_MAX;
+ } else if (info->flags & printf_flag_long) {
+ u.type = I_LONG;
+ u.val.val_long = va_arg(ap, unsigned long);
+ } else if (info->flags & printf_flag_llong) {
+ u.type = I_LLONG;
+ u.val.val_llong = va_arg(ap, unsigned long long);
+ } else if (info->flags & (printf_flag_size | printf_flag_ptr)) {
+ u.type = I_PTR;
+ u.val.val_ptr = va_arg(ap, uintptr_t);
+ } else if (info->value & printf_flag_imax) {
+ u.type = I_MAX;
+ u.val.val_max = va_arg(ap, uintmax_t);
+ } else if (info->value & printf_flag_i32) {
+ u.type = I_32;
+ u.val.val_32 = va_arg(ap, uint32_t);
+ } else if (info->value & printf_flag_i64) {
+ u.type = I_64;
+ u.val.val_64 = va_arg(ap, uint64_t);
+ }
+
+ return (0);
+}
+
+/* `__printf_spec_u()`: print an unsigned integer. */
+
+int __printf_spec_u(FILE *stream, printf_t const *oinfo, void const *vuint)
+{
+ char buf[30], *p = &buf[29];
+ int base = 10;
+ char const *bchars = "0123456789abcdef";
+ printf_t info;
+ _uint *u = (void *)vuint;
+
+ memcpy(&info, oinfo, sizeof(info));
+
+ switch (u->type) {
+ case I_INT:
+ {
+ uint value = u->val.val_int;
+
+ FILLBUF_U(value, __UINT_MAX)
+ break;
+ }
+ case I_LONG:
+ {
+ ulong value = u->val.val_long;
+
+ FILLBUF_U(value, __ULONG_MAX)
+ break;
+ }
+ case I_LLONG:
+ {
+ ullong value = u->val.val_llong;
+
+ FILLBUF_U(value, __ULLONG_MAX)
+ break;
+ }
+ case I_PTR:
+ {
+ uintptr_t value = u->val.val_ptr;
+
+ FILLBUF_U(value, __UINTPTR_MAX)
+ break;
+ }
+ case I_MAX:
+ {
+ uintmax_t value = u->val.val_max;
+
+ FILLBUF_U(value, __UINTMAX_MAX)
+ break;
+ }
+ case I_32:
+ {
+ uint32_t value = u->val.val_32;
+
+ FILLBUF_U(value, __UINT32_MAX)
+ break;
+ }
+ case I_64:
+ {
+ uint64_t value = u->val.val_64;
+
+ FILLBUF_U(value, __UINT64_MAX)
+ }
+ }
+
+ return (__printf_pad(stream, &info,
+ prepend, psize, buf, (size_t)(buf + 1 - p)));
+}
diff --git a/modules/all/io/src/printf/pad.c b/modules/all/io/src/printf/pad.c
new file mode 100644
index 0000000..c086918
--- /dev/null
+++ b/modules/all/io/src/printf/pad.c
@@ -0,0 +1,74 @@
+#include "printf.h"
+#include <string.h>
+
+/* `put_pad()`: put some padding characters.
+ * `pad` is the character to put `count` times in `stream`. */
+
+static int put_pad(FILE *stream, int pad, size_t count)
+{
+ char sp[128];
+
+ memset(sp, ' ', 128);
+
+ for (; count > 128; count -= 128)
+ if (!fwrite(sp, 128, 1, stream))
+ return (-1);
+
+ if (count)
+ if (!fwrite(sp, count, 1, stream))
+ return (-1);
+
+ return (count);
+}
+
+/* `__printf_pad()`: put a string with padding.
+ * `buf` (of size `size`) is the buffer to put with padding and alignment
+ * defined in `info` to `stream`.
+ *
+ * `prepend` is the character to prepend while taking it into account
+ * for width and alignment. It is there to manage the `-00000045` case. */
+
+int __printf_pad(FILE *stream, printf_t const *info,
+ char const *prepend, size_t psize, char const *buf, size_t size)
+{
+ int n = 0, ntemp;
+ int width = info->width;
+
+ /* Character to prepend. */
+
+ if (prepend) {
+ fwrite(prepend, 1, psize, stream);
+
+ if (width >= psize)
+ width -= psize;
+ else
+ width = 0;
+ }
+
+ /* Left alignment. */
+
+ if (width && ~info->flags & printf_flag_left && n < width) {
+ if ((ntemp = put_pad(stream, info->pad, width - size)) < 0)
+ return (-1);
+
+ n += ntemp;
+ }
+
+ /* Put the content. */
+
+ if (!fwrite(buf, size, 1, stream))
+ return (-1);
+
+ n += (int)size;
+
+ /* Right alignment. */
+
+ if (width && info->flags & printf_flag_left && n < width) {
+ if ((ntemp = put_pad(stream, info->pad, info->width - size)) < 0)
+ return (-1);
+
+ n += ntemp;
+ }
+
+ return (n);
+}
diff --git a/modules/all/io/src/printf/printf.h b/modules/all/io/src/printf/printf.h
index 5113fe5..bdf3428 100644
--- a/modules/all/io/src/printf/printf.h
+++ b/modules/all/io/src/printf/printf.h
@@ -1,10 +1,16 @@
-#ifndef _LOCAL_PRINTF_H
-# define _LOCAL_PRINTF_H
-# include "../stdio.h"
+#include "../stdio.h"
-# define __PRINTF_FUNC(_X) printf_callback_t printf_default_ ## _X;
+_EXTERN int __printf_pad
+ _OF((FILE *__stream, printf_t const *__info,
+ char const *__prepend, size_t __prepend_size,
+ char const *__buf, size_t __size));
-__PRINTF_FUNC(s)
-__PRINTF_FUNC(c)
+_EXTERN printf_arg_t __printf_arg_s;
+_EXTERN printf_arg_t __printf_arg_c;
+_EXTERN printf_arg_t __printf_arg_d;
+_EXTERN printf_arg_t __printf_arg_u;
-#endif /* _LOCAL_STDIO_H */
+_EXTERN printf_spec_t __printf_spec_s;
+_EXTERN printf_spec_t __printf_spec_c;
+_EXTERN printf_spec_t __printf_spec_d;
+_EXTERN printf_spec_t __printf_spec_u;
diff --git a/modules/all/io/src/printf/register.c b/modules/all/io/src/printf/register.c
index f4fe1a7..a16261d 100644
--- a/modules/all/io/src/printf/register.c
+++ b/modules/all/io/src/printf/register.c
@@ -32,9 +32,10 @@
#include <string.h>
#include <ctype.h>
-/* ************************************************************************* */
-/* `printf` register */
-/* ************************************************************************* */
+/* ---
+ * 'printf' register.
+ * --- */
+
/* The `printf` register keeps track of which specifier goes to where. */
struct printf_entry {
@@ -44,82 +45,78 @@ struct printf_entry {
/* The register is here. (number of letters) * 2, for upper and lower case. */
static struct printf_entry printf_register[52];
-/* ************************************************************************* */
-/* Default callbacks */
-/* ************************************************************************* */
-/**
- * printf_default_percent:
- * Print a percent '%' character.
- *
- * @arg stream the stream to write to.
- * @arg info the format information.
- * @arg ap the arguments pointer.
- * @return the number of written bytes.
- */
+
+/* ---
+ * Default callbacks.
+ * --- */
+
+/* `printf_default_percent()`: print a percent '%' character. */
static int printf_default_percent(FILE *stream, printf_t *info, va_list ap)
{
char percent = '%';
- (void)info; (void)ap;
- if (!fwrite(&percent, 1, 1, stream)) return (-1);
+ (void)info;
+ (void)ap;
+
+ if (!fwrite(&percent, 1, 1, stream))
+ return (-1);
+
return (1);
}
-/* ************************************************************************* */
-/* Interact with the registers */
-/* ************************************************************************* */
-/**
- * reset_printf_functions:
- * Reset the printf functions.
- */
+
+/* ---
+ * Interact with the registers.
+ * --- */
+
+/* `reset_printf_functions()`: reset the printf functions. */
void reset_printf_functions(void)
{
- /* set NULLs */
- memset(printf_register, 0, 52 * sizeof(struct printf_entry));
+ int i;
+
+ /* Set NULLs. */
+
+ for (i = 0; i < 52; i++)
+ printf_register[i].callback = NULL;
+
+ /* Integer related callbacks. */
-#if 0
- /* integer related callbacks */
register_printf_function('d', printf_default_d);
- register_printf_function('i', printf_default_i);
+ register_printf_function('i', printf_default_d);
register_printf_function('u', printf_default_u);
- register_printf_function('x', printf_default_x);
- register_printf_function('X', printf_default_X);
- register_printf_function('o', printf_default_o);
- register_printf_function('p', printf_default_p);
-
- /* floating-point related callbacks */
- register_printf_function('F', printf_default_f);
- register_printf_function('f', printf_default_f);
- register_printf_function('E', printf_default_e);
- register_printf_function('e', printf_default_e);
- register_printf_function('A', printf_default_a);
- register_printf_function('a', printf_default_a);
- register_printf_function('G', printf_default_g);
- register_printf_function('g', printf_default_g);
-
- /* Hitachi fixed-point related callbacks */
- register_printf_function('r', printf_default_r); /* __fixed */
- register_printf_function('a', printf_default_a); /* __accum */
- register_printf_function('P', printf_default_p); /* __circ */
+ register_printf_function('x', printf_default_u);
+ register_printf_function('X', printf_default_u);
+ register_printf_function('o', printf_default_u);
+ register_printf_function('p', printf_default_u);
+
+#if 0
+ /* Floating-point related callbacks. */
+
+ register_printf_function('F', __printf_default_f);
+ register_printf_function('f', __printf_default_f);
+ register_printf_function('E', __printf_default_e);
+ register_printf_function('e', __printf_default_e);
+ register_printf_function('A', __printf_default_a);
+ register_printf_function('a', __printf_default_a);
+ register_printf_function('G', __printf_default_g);
+ register_printf_function('g', __printf_default_g);
+
+ /* Hitachi fixed-point related callbacks. */
+
+ register_printf_function('r', __printf_default_r); /* __fixed */
+ register_printf_function('a', __printf_default_a); /* __accum */
+ register_printf_function('P', __printf_default_p); /* __circ */
#endif
- /* string/character-related callbacks */
+ /* String/character-related callbacks. */
+
register_printf_function('s', printf_default_s);
register_printf_function('c', printf_default_c);
}
-/**
- * find_printf_function:
- * Find a printf function.
- *
- * In order to later support additional specifications using registering,
- * we should use a tab or something like this?
- *
- * @arg spec the specifier.
- * @arg func the double pointer to the function.
- * @return -1 if an error occured, 0 otherwise.
- */
+/* `find_printf_function()`: find a printf function using a specifier.
+ * Returns -1 if an error occured, or 0. */
int find_printf_function(int spec, printf_callback_t **func)
{
@@ -128,29 +125,26 @@ int find_printf_function(int spec, printf_callback_t **func)
else {
int lwrspec = tolower(spec), lwr = islower(spec) ? 26 : 0;
- /* check that it is a character */
+ /* Check that it is a character. */
+
if (likely(lwrspec != spec || lwr))
*func = printf_register[lwrspec - 'a' + (26 - lwr)].callback;
- else return (-1);
+ else
+ return (-1);
}
return (0);
}
-/**
- * register_printf_function:
- * Register a printf function.
- *
- * @arg spec the specifier.
- * @arg func the callback.
- * @return 0 on success, -1 on failure.
- */
+/* `register_printf_function()`: register a printf function tied to the
+ * specifier `spec`. */
int register_printf_function(int spec, printf_callback_t *func)
{
int lwrspec = tolower(spec), lwr = islower(spec) ? 26 : 0;
- /* check it's a character */
+ /* Check it's a character. */
+
if (likely(lwrspec != spec || lwr)) {
printf_register[lwrspec - 'a' + (26 - lwr)].callback = func;
return (0);
diff --git a/modules/all/io/src/printf/sprintf.c b/modules/all/io/src/printf/sprintf.c
index ae5dc85..549aeb2 100644
--- a/modules/all/io/src/printf/sprintf.c
+++ b/modules/all/io/src/printf/sprintf.c
@@ -31,10 +31,12 @@
#include "printf.h"
#include <string.h>
-/* ************************************************************************* */
-/* Stream callbacks */
-/* ************************************************************************* */
-/* The cookie structure */
+/* ---
+ * Stream callbacks.
+ * --- */
+
+/* The cookie structure. */
+
typedef struct {
char *buf;
size_t left;
@@ -66,9 +68,11 @@ static long swrite(scookie_t *cookie, const char *buffer, size_t sz)
/* pretend everything went well */
return (sz);
}
-/* ************************************************************************* */
-/* Using variable argument length */
-/* ************************************************************************* */
+
+/* ---
+ * Using variable argument length.
+ * --- */
+
/**
* vsprintf:
* Print formatted in a buffer using a variable argument list.
@@ -113,15 +117,18 @@ int vsnprintf(char *str, size_t size, const char *fmt, va_list ap)
(cookie_seek_function_t*)NULL,
(cookie_close_function_t*)NULL, 0};
- if (!size) return (0);
+ if (!size)
+ return (0);
stream.cookie = &cookie;
cookie.buf = str;
cookie.left = size - 1;
return (vfprintf(&stream, fmt, ap));
}
-/* ************************************************************************* */
-/* Easy functions */
-/* ************************************************************************* */
+
+/* ---
+ * Easy functions.
+ * --- */
+
/**
* sprintf:
* Print formatted in a buffer (string).
diff --git a/modules/all/io/src/printf/vfprintf.c b/modules/all/io/src/printf/vfprintf.c
index 2648c9a..4485f14 100644
--- a/modules/all/io/src/printf/vfprintf.c
+++ b/modules/all/io/src/printf/vfprintf.c
@@ -33,162 +33,276 @@
#include <string.h>
#include <ctype.h>
-/* ************************************************************************* */
-/* Utilities */
-/* ************************************************************************* */
-/**
- * get_num:
- * Get a number from the string.
- *
- * @arg ps double pointer on the format.
- * @return the number.
- */
+/* ---
+ * Utilities.
+ * --- */
+
+/* `get_num()`: get a number from the string `*sp`.
+ * Uses a double pointer `sp` on the string to make it go forward. */
-static int get_num(const char **ps)
+static int get_num(char const **sp)
{
- int i = 0; const char *s = *ps;
+ int i = 0;
+ const char *s = *sp;
while (isdigit(*s))
- i = i * 10 + *s++ - '0';
- *ps = s;
+ i = i * 10 + (*s++ - '0');
+
+ *sp = s;
return (i);
}
-/**
- * get_format:
- * Get the format.
- *
- * @arg p double pointer on the format.
- * @arg info the information.
- * @arg ap the arguments pointer.
- * @return number of read characters.
- */
+/* `get_format()`: decode the format from somewhere in the string.
+ * Fills the information structure `info`.
+ * Uses a double pointer `sp` on the string to make it go forward. */
-static int get_format(const char **ps, printf_t *info, va_list ap)
+static int get_format(char const **sp, printf_t *info, va_list ap)
{
const char *s; int i;
- int still_info;
int n;
- /* initialize info */
+ /* Initialize the information. */
+
info->flags = 0;
info->prec = -1;
info->width = 0;
info->pad = ' ';
- s = *ps; still_info = 1;
- for (; still_info; s++) switch (*s) {
- /* flags */
- case '-': info->flags |= printf_flag_left; break;
- case '+': info->flags |= printf_flag_sign; break;
- case ' ': info->flags |= printf_flag_space; break;
- case '#': info->flags |= printf_flag_alt; break;
- case '0': info->pad = '0'; break;
+ s = *sp;
+ while (1) switch (*s) {
+ /* Flags first! */
+
+ case '-':
+ if (info->flags & printf_flag_left)
+ goto found_spec;
+
+ info->flags |= printf_flag_left;
+ break;
+ case '+':
+ if (info->flags & printf_flag_sign)
+ goto found_spec;
+
+ info->flags |= printf_flag_sign;
+ break;
+ case ' ':
+ if (info->flags & printf_flag_space)
+ goto found_spec;
+
+ info->flags |= printf_flag_space;
+ break;
+ case '#':
+ if (info->flags & printf_flag_alt)
+ goto found_spec;
+
+ info->flags |= printf_flag_alt;
+ break;
+ case '0':
+ if (info->pad == '0')
+ goto found_spec;
+
+ info->pad = '0';
+ break;
+ case '\'':
+ if (info->flags & printf_flag_grp)
+ goto found_spec;
+
+ info->flags |= printf_flag_grp;
+ break;
+
+ /* Width. */
- /* width */
case '*':
+ if (info->width > 0)
+ goto found_spec;
+
i = va_arg(ap, int);
if (i < 0) {
info->flags |= printf_flag_left;
i = -i;
}
+
info->width = i;
break;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
+ if (info->width > 0)
+ goto found_spec;
+
info->width = get_num(&s);
- s--; /* compensate */
+ s--; /* Compensate for the upcoming `*++s`. */
break;
- /* precision */
- case '.': s++; switch (*s) {
- case '*': info->prec = va_arg(ap, int); break;
+ /* Precision. */
+
+ case '.':
+ if (info->prec >= 0)
+ goto found_spec;
+
+ switch (*++s) {
+ case '*':
+ info->prec = va_arg(ap, int);
+ break;
+
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
i = get_num(&s);
info->prec = abs(i);
- s--; /* compensate */
+ s--; /* Compensate for the upcoming `*++s`. */
break;
- default: return (-1);
- } break;
- /* length */
+ default:
+ return (-1);
+ }
+
+ break;
+
+ /* Length. */
+
case 'h':
+ if (info->flags & (printf_flag_width & ~printf_flag_short))
+ goto found_spec;
+
info->flags |= printf_flag_short
| ((info->flags & printf_flag_short) << 1);
break;
- case 'l':
+ case 'l': case 'w':
+ if (info->flags & (printf_flag_width & ~printf_flag_long))
+ goto found_spec;
+
info->flags |= printf_flag_long
| ((info->flags & printf_flag_long) >> 1);
break;
- case 'L': case 'q':
- info->flags |= printf_flag_llong; break;
- case 'z': info->flags |= printf_flag_ptr; break;
- case 'j': info->flags |= printf_flag_imax; break;
- case 't': info->flags |= printf_flag_ptr; break;
+ case 'L':
+ if (info->flags & printf_flag_width)
+ goto found_spec;
+
+ info->flags |= printf_flag_llong;
+ break;
+ case 'q':
+ if (info->flags & printf_flag_width)
+ goto found_spec;
+
+ info->flags |= printf_flag_i64;
+ break;
+ case 'z':
+ if (info->flags & printf_flag_width)
+ goto found_spec;
- default: /* TODO: check if is a letter? */
- still_info = 0; break;
+ info->flags |= printf_flag_ptr;
+ break;
+ case 'j':
+ if (info->flags & printf_flag_width)
+ goto found_spec;
+
+ info->flags |= printf_flag_imax;
+ break;
+ case 'I':
+ if (info->flags & printf_flag_width)
+ goto found_spec;
+
+ /* Check for 'I32'. */
+
+ if (s[1] == '3' && s[2] == '2') {
+ info->flags |= printf_flag_i32;
+ s += 2;
+ break;
+ }
+
+ /* Check for 'I64'. */
+
+ if (s[1] == '6' && s[2] == '4') {
+ info->flags |= printf_flag_i64;
+ s += 2;
+ break;
+ }
+
+ info->flags |= printf_flag_ptr;
+ break;
+ case 't':
+ if (info->flags & printf_flag_width)
+ goto found_spec;
+
+ info->flags |= printf_flag_ptr;
+ break;
+
+ default:
+ /* Double break time! */
+
+ goto found_spec;
}
- /* and get the type */
+found_spec:
+ /* And get the specifier. */
+
info->spec = *s++;
- /* everything went well :) */
- n = (int)(s - *ps);
- *ps = s;
+ /* Everything went well :) */
+
+ n = (int)(s - *sp);
+ *sp = s;
return (n);
}
-/* ************************************************************************* */
-/* Main function */
-/* ************************************************************************* */
-/**
- * vfprintf:
- * Main print formatted function.
- *
- * @arg stream the stream to print to.
- * @arg fmt the format string.
- * @arg ap the variable argument list (argument pointer).
- * @return if everything is okay.
- */
-int vfprintf(FILE *stream, const char *fmt, va_list ap)
+/* ---
+ * Main function.
+ * --- */
+
+/* `vfprintf()`: print formatted in a `stream`.
+ * This function is the core of all print formatted functions.
+ * It takes the variable argument list `ap` as the user input source. */
+
+int vfprintf(FILE *stream, char const *fmt, va_list ap)
{
int n = 0, ntemp;
size_t l; const char *f;
printf_t info;
printf_callback_t *cb;
+ int search_offset = 0;
while (*fmt) {
- /* pass litteral text */
- f = strchr(fmt, '%');
- if (!f) {
- l = strlen(fmt);
- if (!fwrite(fmt, l, 1, stream)) return (-1);
- n += l;
- break;
- }
+ /* Copy literal text. */
+
+ f = strchrnul(&fmt[search_offset], '%');
+ search_offset = 0;
- /* don't forget to copy it */
l = (size_t)(f - fmt);
- if (l && !fwrite(fmt, l, 1, stream)) return (-1);
+ if (l && !fwrite(fmt, l, 1, stream))
+ return (-1);
+
n += l;
- /* get the format */
- fmt++; ntemp = get_format(&fmt, &info, ap);
- if (ntemp < 0) return (-1);
+ /* Stop here if we have not found a percent. */
+
+ if (*f != '%')
+ break;
+
+ /* Get the format. */
+
+ fmt++;
+ if ((ntemp = get_format(&fmt, &info, ap)) < 0
+ || find_printf_function(info.spec, &cb)) {
+ /* If we didn't manage to decode the format, or the specifier
+ * is unknown to us, we just tell the beginning of the loop
+ * that we ought to copy at least the first character in the
+ * format. */
+
+ search_offset = 1;
+ continue;
+ }
+
n += ntemp;
- /* lookup for a callback using that specifier */
- if (find_printf_function(info.spec, &cb))
+ /* Call this callback.
+ * This is not put into the previous condition as the callback
+ * might've written to the stream before failing. */
+
+ if ((ntemp = (*cb)(stream, &info, ap)) < 0)
return (-1);
- /* call this callback */
- ntemp = (*cb)(stream, &info, ap);
- if (ntemp < 0) return (-1);
n += ntemp;
}
- /* well, looks like everything went well */
+ /* Well, it looks like everything went well! */
+
return (n);
}
diff --git a/modules/all/io/src/read.c b/modules/all/io/src/read.c
index 3d1d4e0..53d5c17 100644
--- a/modules/all/io/src/read.c
+++ b/modules/all/io/src/read.c
@@ -30,16 +30,7 @@
* ************************************************************************* */
#include "stdio.h"
-/**
- * fread:
- * Read from a FILE stream.
- *
- * @arg ptr the reception buffer.
- * @arg size the size of an element.
- * @arg nmemb the number of elements to receive.
- * @arg stream the stream.
- * @return the number of received elements.
- */
+/* `fread()`: read from the `stream`. */
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
@@ -49,16 +40,18 @@ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
/* Check if we can read. */
- rd = stream->funcs.read;
- if (!rd) return (0);
+ if (!(rd = stream->funcs.read))
+ return (0);
cookie = stream->funcs.read;
/* Read */
rd = (*stream->read)(stream->cookie, ptr, size * nmemb);
- if (rd < 0) return (0);
+ if (rd < 0)
+ return (0);
+
+ /* Update offset and return. */
- /* update offset and return */
stream->offset += rd;
return (rd / size);
}
diff --git a/modules/all/io/src/seek.c b/modules/all/io/src/seek.c
index 66c513c..04dceaf 100644
--- a/modules/all/io/src/seek.c
+++ b/modules/all/io/src/seek.c
@@ -30,40 +30,25 @@
* ************************************************************************* */
#include "stdio.h"
-/**
- * fseek:
- * Seek on a FILE stream.
- *
- * @arg stream the stream.
- * @arg offset the offset to seek.
- * @arg whence the whence.
- * @return 0 for a success, -1 for an error.
- */
+/* `fseek()`: seek on `stream`.
+ * `whence` indicates to what the offset corresponds, either `SEEK_SET` (for
+ * an offset from the beginning of the file), `SEEK_CUR` (from the current
+ * file position) or `SEEK_END` (from the end of the file). */
int fseek(FILE *stream, long offset, int whence)
{
- /* check if we can seek */
- if (!stream->seek) return (-1);
-
- /* seek */
+ if (!stream->seek)
+ return (-1);
if ((*stream->seek)(stream->cookie, &offset, whence) < 0)
return (-1);
- /* update offset and return */
stream->offset = offset;
return (0);
}
-/**
- * ftell:
- * Get the current offset in a FILE stream.
- *
- * @arg stream the stream.
- * @return the offset.
- */
+/* `ftell()`: get the current offset from the beginning of the file. */
long ftell(FILE *stream)
{
- /* return the offset */
return (stream->offset);
}
diff --git a/modules/all/math/copyright.yml b/modules/all/math/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/math/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/math/info.yml b/modules/all/math/info.yml
deleted file mode 100644
index 908af55..0000000
--- a/modules/all/math/info.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Mathematical utilities for the libc.
-license: free
-out: libm
diff --git a/modules/all/math/module.toml b/modules/all/math/module.toml
new file mode 100644
index 0000000..9d792e1
--- /dev/null
+++ b/modules/all/math/module.toml
@@ -0,0 +1,18 @@
+magic = "potatosdk-1.0"
+desc = "Mathematical utilities for the C library."
+license = "free"
+out = "libm"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "math.h"
+role = "Mathematical functions."
+
+[[headers]]
+path = "mathf.h"
+role = "Mathematical functions on floats."
diff --git a/modules/all/math/roles.yml b/modules/all/math/roles.yml
deleted file mode 100644
index 8bade51..0000000
--- a/modules/all/math/roles.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-include:
- math.h: Math functions.
- mathf.h: Math functions for floats.
diff --git a/modules/all/mem/copyright.yml b/modules/all/mem/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/mem/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/mem/include/malloc.h b/modules/all/mem/include/malloc.h
index 5214e46..e82c6f0 100644
--- a/modules/all/mem/include/malloc.h
+++ b/modules/all/mem/include/malloc.h
@@ -33,10 +33,12 @@
_BEGIN_DECLS
_BEGIN_NAMESPACE_STD
-/* ************************************************************************* */
-/* Memory allocation functions */
-/* ************************************************************************* */
-/* Allocate memory */
+/* ---
+ * Public memory allocation functions.
+ * --- */
+
+/* Allocate memory. */
+
_EXTERN _MALLOC _WUR void* malloc
_OF((size_t __size)) _THROW;
_EXTERN _MALLOC _WUR void* calloc
@@ -45,18 +47,22 @@ _EXTERN _MALLOC _WUR void* calloc
_EXTERN _MALLOC void* memalign
_OF((size_t __alignment, size_t __size)) _THROW;
-/* Re-allocate memory */
+/* Re-allocate memory. */
+
_EXTERN _WUR void* realloc
_OF((void *__ptr, size_t __size)) _THROW;
-/* Free memory */
+/* Free memory. */
+
_EXTERN void free
_OF((void *__ptr)) _THROW;
-/* ************************************************************************* */
-/* Hooks */
-/* ************************************************************************* */
-/* Reproduces the glibc behaviour. See `man __malloc_hook`. */
+/* ---
+ * Hooks.
+ * --- */
+
+/* Reproduces the (deprecated) glibc behaviour. See `man __malloc_hook` on any
+ * GNU system or equivalent. */
typedef void* __malloc_hook_t _OF((size_t __size, const void* __caller));
typedef void* __realloc_hook_t _OF((void* __ptr, size_t __size,
diff --git a/modules/all/mem/info.yml b/modules/all/mem/info.yml
deleted file mode 100644
index 8c90e25..0000000
--- a/modules/all/mem/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Standard memory management.
-license: free
diff --git a/modules/all/mem/module.toml b/modules/all/mem/module.toml
new file mode 100644
index 0000000..de156c6
--- /dev/null
+++ b/modules/all/mem/module.toml
@@ -0,0 +1,25 @@
+magic = "potatosdk-1.0"
+desc = "Standard memory management."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "alloca.h"
+role = "Static memory allocation."
+
+[[headers]]
+path = "malloc.h"
+role = "Dynamic memory allocation."
+
+[[source]]
+path = "malloc.c"
+role = "Dynamic memory allocation."
+
+[[source]]
+path = "init.c"
+role = "Initialize dynamic memory allocation."
diff --git a/modules/all/mem/roles.yml b/modules/all/mem/roles.yml
deleted file mode 100644
index c6884c4..0000000
--- a/modules/all/mem/roles.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-%YAML 1.2
----
-include:
- alloca.h: static memory allocation.
- malloc.h: dynamic memory allocation.
-src:
- malloc.c: dynamic memory allocation.
- init.c: initialize dynamic memory allocation.
diff --git a/modules/all/stdcocorico/copyright.yml b/modules/all/stdcocorico/copyright.yml
deleted file mode 100644
index 5f2f4b6..0000000
--- a/modules/all/stdcocorico/copyright.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
----
-files: 'include/stdcocorico.h'
-copyright:
-- [2014, Simon "Gee" Giraudot, contact@ptilouk.net]
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/stdcocorico/info.yml b/modules/all/stdcocorico/info.yml
deleted file mode 100644
index beecbfb..0000000
--- a/modules/all/stdcocorico/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Implementation of `stdcocorico.h`.
-license: free
diff --git a/modules/all/stdcocorico/module.toml b/modules/all/stdcocorico/module.toml
new file mode 100644
index 0000000..766d25d
--- /dev/null
+++ b/modules/all/stdcocorico/module.toml
@@ -0,0 +1,18 @@
+magic = "potatosdk-1.0"
+desc = "Implementation of `stdcocorico.h`."
+license = "free"
+
+[[copyrights]]
+begin = 2014
+name = "Simon \"Gee\" Giraudot"
+mail = "contact@ptilouk.net"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "stdcocorico.h"
+role = "Cocorico! Code in french."
diff --git a/modules/all/stdcocorico/roles.yml b/modules/all/stdcocorico/roles.yml
deleted file mode 100644
index b4f9860..0000000
--- a/modules/all/stdcocorico/roles.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-%YAML 1.2
----
-include:
- stdcocorico.h: Cocorico! Code in french.
diff --git a/modules/all/string-sh/copyright.yml b/modules/all/string-sh/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/string-sh/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/string-sh/info.yml b/modules/all/string-sh/info.yml
deleted file mode 100644
index 30f7240..0000000
--- a/modules/all/string-sh/info.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Optimized string functions for the SuperH platform.
-license: free
-depends:
-- all/string
-requires:
- arch: [sh]
diff --git a/modules/all/string-sh/module.toml b/modules/all/string-sh/module.toml
new file mode 100644
index 0000000..59a5bd6
--- /dev/null
+++ b/modules/all/string-sh/module.toml
@@ -0,0 +1,21 @@
+magic = "potatosdk-1.0"
+desc = "Optimized string functions for the SuperH platform."
+license = "free"
+depends = "all/string"
+
+[requires]
+arch = ["sh"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "string.h"
+role = "Tell the string module about the optimized versions."
+
+[[source]]
+path = "memchr.s"
+role = "Optimized memchr version."
diff --git a/modules/all/string-sh/src/memchr.s b/modules/all/string-sh/src/memchr.gnu.src
index 6c13469..d3b9a65 100644
--- a/modules/all/string-sh/src/memchr.s
+++ b/modules/all/string-sh/src/memchr.gnu.src
@@ -7,6 +7,7 @@
_memchr:
/* Construct a register made of four times the requested bytes. */
+
mov r5, r1
shll8 r5
or r1, r5
@@ -16,25 +17,30 @@ _memchr:
loop:
/* Test whether size limit (as multiple of 4) is reached. */
+
mov #4, r0
cmp/hs r0, r6
bf analyze_four
/* Test the incoming four bytes. */
+
mov.l @r4+, r3
cmp/str r1, r3
bt found
/* Loop and reduce size count. */
+
bra loop
add #-4, r6
found:
/* Prepare the byte-level analysis of the four bytes that matched. */
+
add #-4, r4
analyze_four:
/* Analyze at most four bytes, stop if r6 reaches 0. */
+
tst r6, r6
bt end_not_found
@@ -66,6 +72,7 @@ end_not_found:
end_found:
/* Return the current pointer and revert the last post-increment. */
+
mov r4, r0
rts
add #-1, r0
diff --git a/modules/all/string/info.yml b/modules/all/string/info.yml
deleted file mode 100644
index 6dea9af..0000000
--- a/modules/all/string/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Bytes manipulating functions.
-license: free
diff --git a/modules/all/string/module.toml b/modules/all/string/module.toml
new file mode 100644
index 0000000..efb36ca
--- /dev/null
+++ b/modules/all/string/module.toml
@@ -0,0 +1,133 @@
+magic = "potatosdk-1.0"
+desc = "Bytes manipulating functions."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "string.h"
+role = "Standard bytes manipulating functions."
+
+[[headers]]
+path = "strings.h"
+role = "BSD-compatible bytes manipulating functions."
+
+[[source]]
+path = "bsd/bcmp.c"
+role = ""
+
+[[source]]
+path = "bsd/bcopy.c"
+role = ""
+
+[[source]]
+path = "bsd/bzero.c"
+role = ""
+
+[[source]]
+path = "bsd/ffs.c"
+role = ""
+
+[[source]]
+path = "bsd/index.c"
+role = ""
+
+[[source]]
+path = "bsd/rindex.c"
+role = ""
+
+[[source]]
+path = "bsd/strcasecmp.c"
+role = ""
+
+[[source]]
+path = "bsd/strlcat.c"
+role = ""
+
+[[source]]
+path = "bsd/strncasecmp.c"
+role = ""
+
+[[source]]
+path = "memccpy.c"
+role = ""
+
+[[source]]
+path = "memchr.c"
+role = ""
+
+[[source]]
+path = "memcmp.c"
+role = ""
+
+[[source]]
+path = "memcpy.c"
+role = ""
+
+[[source]]
+path = "memmove.c"
+role = ""
+
+[[source]]
+path = "memset.c"
+role = ""
+
+[[source]]
+path = "strcat.c"
+role = ""
+
+[[source]]
+path = "strchr.c"
+role = ""
+
+[[source]]
+path = "strcmp.c"
+role = ""
+
+[[source]]
+path = "strcpy.c"
+role = ""
+
+[[source]]
+path = "strcspn.c"
+role = ""
+
+[[source]]
+path = "strlen.c"
+role = ""
+
+[[source]]
+path = "strncat.c"
+role = ""
+
+[[source]]
+path = "strncmp.c"
+role = ""
+
+[[source]]
+path = "strncpy.c"
+role = ""
+
+[[source]]
+path = "strnlen.c"
+role = ""
+
+[[source]]
+path = "strpbrk.c"
+role = ""
+
+[[source]]
+path = "strrchr.c"
+role = ""
+
+[[source]]
+path = "strspn.c"
+role = ""
+
+[[source]]
+path = "strstr.c"
+role = ""
diff --git a/modules/all/system.toml b/modules/all/system.toml
new file mode 100644
index 0000000..b4bbf9c
--- /dev/null
+++ b/modules/all/system.toml
@@ -0,0 +1,5 @@
+magic = "potatosdk-1.0"
+desc = "Meta-system for modules that are suitable for all systems."
+
+default = ["all/core", "all/core-sh", "all/iconv"]
+import = ["compiler"]
diff --git a/modules/all/time/copyright.yml b/modules/all/time/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/all/time/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/all/time/info.yml b/modules/all/time/info.yml
deleted file mode 100644
index 51e02b8..0000000
--- a/modules/all/time/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Time-related operations.
-license: free
diff --git a/modules/all/time/module.toml b/modules/all/time/module.toml
new file mode 100644
index 0000000..b3b6bf6
--- /dev/null
+++ b/modules/all/time/module.toml
@@ -0,0 +1,21 @@
+magic = "potatosdk-1.0"
+desc = "Time-related operations."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "time.h"
+role = "Time-related functions."
+
+[[source]]
+path = "gmtime_r.c"
+role = "Get the GMT time."
+
+[[source]]
+path = "mktime.c"
+role = "Build a UNIX timestamp out of a broken-down time."
diff --git a/modules/all/time/roles.yml b/modules/all/time/roles.yml
deleted file mode 100644
index b97ec83..0000000
--- a/modules/all/time/roles.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-%YAML 1.2
----
diff --git a/modules/all/time/src/gmtime_r.c b/modules/all/time/src/gmtime_r.c
index 5cf05f6..8b53e98 100644
--- a/modules/all/time/src/gmtime_r.c
+++ b/modules/all/time/src/gmtime_r.c
@@ -10,6 +10,7 @@ _EXTERN struct tm* gmtime_r(const time_t* _RESTRICT timer,
int y4;
/* Calculate the year from the 4-year offset. */
+
y4 = ts / secs_in_4years;
timep->year = 70 + 4 * ts / secs_in_4years;
ts -= y4 * secs_in_4years;
diff --git a/modules/all/time/src/mktime.c b/modules/all/time/src/mktime.c
index 6be9df5..3c059b8 100644
--- a/modules/all/time/src/mktime.c
+++ b/modules/all/time/src/mktime.c
@@ -21,22 +21,26 @@ _EXTERN _WUR time_t mktime(struct tm *timep)
time_t secs;
/* Overflow isn't managed. */
+
year = timep->year;
if (year < 1970)
return (0);
/* Put years. */
+
year -= 1970;
leaps = (year + 1) / 4; /* not counting the current year */
is_leap = is_leap1900(year);
secs = year * secs_in_year + leaps * secs_in_day;
/* Put month. */
+
secs += secs_through_month[timep->mon - 1];
if (is_leap && timep->mon > 2 /* february */)
t += secs_in_day;
/* Put other stuff. */
+
secs += secs_in_day * timep->yday;
secs += secs_in_hour * timep->hour;
secs += secs_in_minute * timep->min;
diff --git a/modules/casiowin/copyright.yml b/modules/casiowin/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/casiowin/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/core-crt/copyright.yml b/modules/casiowin/core-crt/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/casiowin/core-crt/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/core-crt/info.yml b/modules/casiowin/core-crt/info.yml
deleted file mode 100644
index 6b540af..0000000
--- a/modules/casiowin/core-crt/info.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The CASIOWIN startup files.
-license: free
-out: crt
diff --git a/modules/casiowin/core-crt/module.toml b/modules/casiowin/core-crt/module.toml
new file mode 100644
index 0000000..363c0ab
--- /dev/null
+++ b/modules/casiowin/core-crt/module.toml
@@ -0,0 +1,14 @@
+magic = "potatosdk-1.0"
+desc = "The CASIOWIN startup files."
+license = "free"
+out = "crt"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[source]]
+path = "crt0.c"
+role = "Main C runtime initialization."
diff --git a/modules/casiowin/core-crt/roles.yml b/modules/casiowin/core-crt/roles.yml
deleted file mode 100644
index c8a6d06..0000000
--- a/modules/casiowin/core-crt/roles.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-%YAML 1.2
----
-src:
- crt0.c: Main C runtime initialization.
diff --git a/modules/casiowin/core/copyright.yml b/modules/casiowin/core/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/casiowin/core/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/core/info.yml b/modules/casiowin/core/info.yml
deleted file mode 100644
index 9813d0e..0000000
--- a/modules/casiowin/core/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The CASIOWIN libc bits.
-license: free
diff --git a/modules/casiowin/core/module.toml b/modules/casiowin/core/module.toml
new file mode 100644
index 0000000..3a3a9e9
--- /dev/null
+++ b/modules/casiowin/core/module.toml
@@ -0,0 +1,45 @@
+magic = "potatosdk-1.0"
+desc = "The CASIOWIN C library bits."
+license = "free"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "time.h"
+role = "Standard time header internals."
+
+[[source]]
+path = "alloc/syscalls.s"
+role = ""
+
+[[source]]
+path = "assert/assert.c"
+role = "Make an assertion failed pop-up."
+
+[[source]]
+path = "assert/syscalls.s"
+role = "Assertion-related syscalls."
+
+[[source]]
+path = "core/syscalls.s"
+role = "Syscalls for the C runtime initialization."
+
+[[source]]
+path = "dirent/dirent.h"
+role = "dirent internals."
+
+[[source]]
+path = "dirent/error.c"
+role = "Standard error number from file-specific error."
+
+[[source]]
+path = "dirent/open.c"
+role = "Open a directory stream."
+
+[[source]]
+path = "syscall.inc"
+role = "Syscall macro."
diff --git a/modules/casiowin/core/roles.yml b/modules/casiowin/core/roles.yml
deleted file mode 100644
index 7cad08a..0000000
--- a/modules/casiowin/core/roles.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-%YAML 1.2
----
-bits:
- time.h: Standard time header internals.
-src:
- alloc:
- _syscalls.sx: Memory allocation related syscalls.
- assert:
- assert.c: Make an assertion failed pop-up.
- _syscalls.sx: Assertion-related syscalls.
- core:
- _syscalls.sx: Syscalls for the C runtime initialization.
- syscall.h: Syscall macro.
- dirent:
- dirent.h: dirent internals.
- error.c: Standard error number from file-specific error.
- open.c: Open a directory stream.
diff --git a/modules/casiowin/core/src/alloc/_syscalls.sx b/modules/casiowin/core/src/alloc/_syscalls.sx
deleted file mode 100644
index 78c4c4e..0000000
--- a/modules/casiowin/core/src/alloc/_syscalls.sx
+++ /dev/null
@@ -1,24 +0,0 @@
-/* ****************************************************************************
- * alloc/_syscalls.sx -- memory allocation related syscalls.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of libcarrot.
- * libcarrot is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 3.0 of the License,
- * or (at your option) any later version.
- *
- * libcarrot is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with the libcarrot; if not, see <http://www.gnu.org/licenses/>.
- * ************************************************************************* */
-#include <fxlib/syscall.h>
-
-__SYSCALL(0xACC, _free)
-__SYSCALL(0xACD, _malloc)
-__SYSCALL(0xE6B, _calloc)
-__SYSCALL(0xE6D, _realloc)
diff --git a/modules/casiowin/core/src/alloc/syscalls.gnu.src b/modules/casiowin/core/src/alloc/syscalls.gnu.src
new file mode 100644
index 0000000..ad700a0
--- /dev/null
+++ b/modules/casiowin/core/src/alloc/syscalls.gnu.src
@@ -0,0 +1,6 @@
+.include "../syscall.gnu.inc"
+
+syscall 0xACC _free
+syscall 0xACD _malloc
+syscall 0xE6B _calloc
+syscall 0xE6D _realloc
diff --git a/modules/casiowin/core/src/assert/_syscalls.sx b/modules/casiowin/core/src/assert/_syscalls.sx
deleted file mode 100644
index 9ff34d1..0000000
--- a/modules/casiowin/core/src/assert/_syscalls.sx
+++ /dev/null
@@ -1,24 +0,0 @@
-/* ****************************************************************************
- * assert/_syscalls.sx -- assert-related syscalls.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of libcarrot.
- * libcarrot is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 3.0 of the License,
- * or (at your option) any later version.
- *
- * libcarrot is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with the libcarrot; if not, see <http://www.gnu.org/licenses/>.
- * ************************************************************************* */
-#include "../syscall.h"
-
-__SYSCALL(0x02A, ___assert_putdisp)
-__SYSCALL(0x807, ___assert_locate)
-__SYSCALL(0x808, ___assert_Print)
-__SYSCALL(0x8FE, ___assert_PopUpWin)
diff --git a/modules/casiowin/core/src/assert/assert.c b/modules/casiowin/core/src/assert/assert.c
index 6e3929b..85fc694 100644
--- a/modules/casiowin/core/src/assert/assert.c
+++ b/modules/casiowin/core/src/assert/assert.c
@@ -75,13 +75,13 @@ void __assert_fail(const char *expr, const char *file,
__assert_PopUpWin(4);
__assert_locate(3, 2);
- __assert_Print((unsigned char*)f);
+ __assert_Print((unsigned char const *)f);
__assert_locate(3, 3);
- __assert_Print((unsigned char*)"Assertion failed:");
+ __assert_Print((unsigned char const *)"Assertion failed:");
__assert_locate(4, 4);
- __assert_Print((unsigned char*)expr);
+ __assert_Print((unsigned char const *)expr);
__assert_locate(5, 3);
- __assert_Print((unsigned char*)"Exiting now.");
+ __assert_Print((unsigned char const *)"Exiting now.");
__assert_putdisp();
/* Exit. */
diff --git a/modules/casiowin/core/src/assert/syscalls.gnu.src b/modules/casiowin/core/src/assert/syscalls.gnu.src
new file mode 100644
index 0000000..40355ad
--- /dev/null
+++ b/modules/casiowin/core/src/assert/syscalls.gnu.src
@@ -0,0 +1,6 @@
+.include "../syscall.gnu.inc"
+
+syscall 0x02A ___assert_putdisp
+syscall 0x807 ___assert_locate
+syscall 0x808 ___assert_Print
+syscall 0x8FE ___assert_PopUpWin
diff --git a/modules/casiowin/core/src/core/_syscalls.sx b/modules/casiowin/core/src/core/_syscalls.sx
deleted file mode 100644
index 0245115..0000000
--- a/modules/casiowin/core/src/core/_syscalls.sx
+++ /dev/null
@@ -1,23 +0,0 @@
-/* ****************************************************************************
- * core/_syscalls.sx -- syscalls for the C runtime initialization.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of libcarrot.
- * libcarrot is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 3.0 of the License,
- * or (at your option) any later version.
- *
- * libcarrot is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with the libcarrot; if not, see <http://www.gnu.org/licenses/>.
- * ************************************************************************* */
-#include "../syscall.h"
-
-__SYSCALL(0x013, ___GLibAddinAplExecutionCheck)
-__SYSCALL(0x3FA, ___Hmem_SetMMU)
-__SYSCALL(0x494, ___SetQuitHandler)
diff --git a/modules/casiowin/core/src/core/syscalls.gnu.src b/modules/casiowin/core/src/core/syscalls.gnu.src
new file mode 100644
index 0000000..38bf708
--- /dev/null
+++ b/modules/casiowin/core/src/core/syscalls.gnu.src
@@ -0,0 +1,5 @@
+.include "../syscall.gnu.inc"
+
+syscall 0x013 ___GLibAddinAplExecutionCheck
+syscall 0x3FA ___Hmem_SetMMU
+syscall 0x494 ___SetQuitHandler
diff --git a/modules/casiowin/core/src/dirent/syscalls.s b/modules/casiowin/core/src/dirent/syscalls.gnu.src
index f0dd37b..8a03438 100644
--- a/modules/casiowin/core/src/dirent/syscalls.s
+++ b/modules/casiowin/core/src/dirent/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x43B ___dirent_findfirst
syscall 0x43C ___dirent_findnext
diff --git a/modules/casiowin/core/src/io/syscalls.s b/modules/casiowin/core/src/io/syscalls.gnu.src
index a90c737..31ce813 100644
--- a/modules/casiowin/core/src/io/syscalls.s
+++ b/modules/casiowin/core/src/io/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x42C ___bfile_openfile
syscall 0x42D ___bfile_closefile
diff --git a/modules/casiowin/fxlib/src/syscall.inc b/modules/casiowin/core/src/syscall.gnu.inc
index 26fddd3..26fddd3 100644
--- a/modules/casiowin/fxlib/src/syscall.inc
+++ b/modules/casiowin/core/src/syscall.gnu.inc
diff --git a/modules/casiowin/core/src/syscall.h b/modules/casiowin/core/src/syscall.h
deleted file mode 100644
index 6b9d67f..0000000
--- a/modules/casiowin/core/src/syscall.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/* ****************************************************************************
- * syscall.h -- syscall macro.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of libcarrot.
- * libcarrot is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation; either version 3.0 of the License,
- * or (at your option) any later version.
- *
- * libcarrot is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with the libcarrot; if not, see <http://www.gnu.org/licenses/>.
- * ************************************************************************* */
-#ifndef _LOCAL_SYSCALL_H
-# define _LOCAL_SYSCALL_H 1
-
-/* Make a syscall. */
-
-# define __SYSCALL(_X, _NAME) \
-.section .text; .global _NAME; \
-.type _NAME, @function; \
-.align 2; _NAME: \
- mov.l 1f, r2; \
- mov.l 2f, r0; \
- jmp @r2; \
- nop; \
-1: .long 0x80010070; \
-2: .long _X
-
-#endif /* _LOCAL_SYSCALL_H */
diff --git a/modules/casiowin/easy-input/copyright.yml b/modules/casiowin/easy-input/copyright.yml
deleted file mode 100644
index 296cb53..0000000
--- a/modules/casiowin/easy-input/copyright.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-%YAML 1.2
----
-files: 'src/*'
-copyright:
-- [2015, 2016, Louis "Dark Storm" Gatin, l.gatin@neuf.fr]
-- [2016, 2018, Thomas Touhey, thomas@touhey.fr]
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/easy-input/info.yml b/modules/casiowin/easy-input/info.yml
deleted file mode 100644
index 7860cb0..0000000
--- a/modules/casiowin/easy-input/info.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Easy input dialogs.
-license: free
-requires:
- deps: ['casiowin/fxlib']
diff --git a/modules/casiowin/easy-input/module.toml b/modules/casiowin/easy-input/module.toml
new file mode 100644
index 0000000..d8828bd
--- /dev/null
+++ b/modules/casiowin/easy-input/module.toml
@@ -0,0 +1,31 @@
+magic = "potatosdk-1.0"
+desc = "Easy input dialogs."
+license = "free"
+
+[[copyrights]]
+begin = 2015
+end = 2016
+name = "Louis Gatin"
+mail = "l.gatin@neuf.fr"
+
+[[copyrights]]
+begin = 2016
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "EasyInput.h"
+role = "Easy Input utilities."
+
+[[source]]
+path = "main.c"
+role = "Easy Input main file."
+
+[[source]]
+path = "syscalls.src"
+role = "Easy Input syscalls for Renesas Asmsh."
+
+[[source]]
+path = "syscalls.s"
+role = "Easy Input syscalls for GNU AS."
diff --git a/modules/casiowin/easy-input/roles.yml b/modules/casiowin/easy-input/roles.yml
deleted file mode 100644
index a3fb26d..0000000
--- a/modules/casiowin/easy-input/roles.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-%YAML 1.2
----
-include:
- EasyInput.h: Easy input.
-src:
- main.c: the easy input main file.
- _syscalls.src: Easy Input syscalls for the Renesas SHC.
- _syscalls.sx: Easy Input syscalls for GCC.
diff --git a/modules/casiowin/easy-input/src/_syscalls.s b/modules/casiowin/easy-input/src/syscalls.gnu.src
index e875d1e..e875d1e 100644
--- a/modules/casiowin/easy-input/src/_syscalls.s
+++ b/modules/casiowin/easy-input/src/syscalls.gnu.src
diff --git a/modules/casiowin/easy-input/src/_syscalls.src b/modules/casiowin/easy-input/src/syscalls.sh.src
index 597566a..597566a 100644
--- a/modules/casiowin/easy-input/src/_syscalls.src
+++ b/modules/casiowin/easy-input/src/syscalls.sh.src
diff --git a/modules/casiowin/fxlib/copyright.yml b/modules/casiowin/fxlib/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/casiowin/fxlib/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/fxlib/include/commbios.h b/modules/casiowin/fxlib/include/commbios.h
index aa249f4..9ec021e 100644
--- a/modules/casiowin/fxlib/include/commbios.h
+++ b/modules/casiowin/fxlib/include/commbios.h
@@ -28,8 +28,9 @@
* The fact that you are presently reading this means you have had knowledge of
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
-#include <fxlib/cdefs.h>
+#include <cdefs.h>
#if _USE_FXLIB_UNOFFICIAL
+
_BEGIN_NAMESPACE_FXLIB
_BEGIN_DECLS
diff --git a/modules/casiowin/fxlib/include/dispbios.h b/modules/casiowin/fxlib/include/dispbios.h
index 1067f3e..a240e48 100644
--- a/modules/casiowin/fxlib/include/dispbios.h
+++ b/modules/casiowin/fxlib/include/dispbios.h
@@ -28,7 +28,8 @@
* The fact that you are presently reading this means you have had knowledge of
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
-#include <fxlib/cdefs.h>
+#include <cdefs.h>
+
_BEGIN_NAMESPACE_FXLIB
/* These macros can be used by the applications:
diff --git a/modules/casiowin/fxlib/include/filebios.h b/modules/casiowin/fxlib/include/filebios.h
index 646b22c..42beb09 100644
--- a/modules/casiowin/fxlib/include/filebios.h
+++ b/modules/casiowin/fxlib/include/filebios.h
@@ -28,7 +28,7 @@
* The fact that you are presently reading this means you have had knowledge of
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
-#include <fxlib/cdefs.h>
+#include <cdefs.h>
_BEGIN_NAMESPACE_FXLIB
diff --git a/modules/casiowin/fxlib/include/keybios.h b/modules/casiowin/fxlib/include/keybios.h
index a85f7bb..6aadfea 100644
--- a/modules/casiowin/fxlib/include/keybios.h
+++ b/modules/casiowin/fxlib/include/keybios.h
@@ -28,7 +28,8 @@
* The fact that you are presently reading this means you have had knowledge of
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
-#include <fxlib/cdefs.h>
+#include <cdefs.h>
+
_BEGIN_NAMESPACE_FXLIB
/* The FX library distinguishes two type of keys:
diff --git a/modules/casiowin/fxlib/include/timer.h b/modules/casiowin/fxlib/include/timer.h
index 2b0af06..8e106f6 100644
--- a/modules/casiowin/fxlib/include/timer.h
+++ b/modules/casiowin/fxlib/include/timer.h
@@ -28,7 +28,8 @@
* The fact that you are presently reading this means you have had knowledge of
* the CeCILL-C license and that you accept its terms.
* ************************************************************************* */
-#include <fxlib/cdefs.h>
+#include <cdefs.h>
+
_BEGIN_NAMESPACE_FXLIB
/* The FX library defines five virtual timers that you can use to make
diff --git a/modules/casiowin/fxlib/info.yml b/modules/casiowin/fxlib/info.yml
deleted file mode 100644
index 4465f4c..0000000
--- a/modules/casiowin/fxlib/info.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The FX library (port).
-license: free
-out: libfx
diff --git a/modules/casiowin/fxlib/module.toml b/modules/casiowin/fxlib/module.toml
new file mode 100644
index 0000000..bdf0164
--- /dev/null
+++ b/modules/casiowin/fxlib/module.toml
@@ -0,0 +1,114 @@
+magic = "potatosdk-1.0"
+desc = "The FX library (port)."
+license = "free"
+out = "libfx"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "fxlib.h"
+role = "Library for interacting with CASIO's fx calculators."
+
+[[headers]]
+path = "commbios.h"
+role = "Definitions for the fxlib communication aspects."
+
+[[headers]]
+path = "dispbios.h"
+role = "Definitions for the fxlib display aspects."
+
+[[headers]]
+path = "filebios.h"
+role = "Definitions for the fxlib file management aspects."
+
+[[headers]]
+path = "keybios.h"
+role = "Definitions for the fxlib keyboard management aspects."
+
+[[headers]]
+path = "timer.h"
+role = "Definitions for the fxlib timer management aspects."
+
+[[bits]]
+path = "fxlib/app.h"
+role = "fxlib's app management."
+
+[[bits]]
+path = "fxlib/battery.h"
+role = "fxlib's battery management."
+
+[[bits]]
+path = "fxlib/bcd.h"
+role = "fxlib's BCD numbers management."
+
+[[bits]]
+path = "fxlib/clock.h"
+role = "fxlib's clock management."
+
+[[bits]]
+path = "fxlib/comm.h"
+role = "fxlib's communication management."
+
+[[bits]]
+path = "fxlib/display.h"
+role = "fxlib's display management."
+
+[[bits]]
+path = "fxlib/file.h"
+role = "fxlib's file management."
+
+[[bits]]
+path = "fxlib/keyboard.h"
+role = "fxlib's keyboard management."
+
+[[bits]]
+path = "fxlib/serial.h"
+role = "fxlib's serial port management."
+
+[[bits]]
+path = "fxlib/timer.h"
+role = "fxlib's timer management."
+
+[[bits]]
+path = "cdefs.h"
+role = "Add fxlib C definitions."
+
+[[source]]
+path = "comm/comm.s"
+role = "General communication-related syscalls."
+
+[[source]]
+path = "comm/serial.s"
+role = "Serial communication-related syscalls."
+
+[[source]]
+path = "display/syscalls.s"
+role = "Display-related syscalls."
+
+[[source]]
+path = "file/sdk.c"
+role = "File-related functions."
+
+[[source]]
+path = "file/syscalls.s"
+role = "File-related syscalls."
+
+[[source]]
+path = "keyboard/syscalls.s"
+role = "Main keyboard syscalls."
+
+[[source]]
+path = "timer/sdk.c"
+role = "fxlib-compatible timer functions."
+
+[[source]]
+path = "timer/syscalls.s"
+role = "Timer-related syscalls."
+
+[[source]]
+path = "syscall.inc"
+role = "Syscall macro for GNU AS."
diff --git a/modules/casiowin/fxlib/roles.yml b/modules/casiowin/fxlib/roles.yml
deleted file mode 100644
index 478f4ca..0000000
--- a/modules/casiowin/fxlib/roles.yml
+++ /dev/null
@@ -1,38 +0,0 @@
-%YAML 1.2
----
-include:
- fxlib:
- app.h: fxlib's app management.
- battery.h: fxlib's battery management.
- bcd.h: fxlib's BCD numbers management.
- clock.h: fxlib's clock management.
- comm.h: fxlib's communication management.
- display.h: fxlib's display management.
- file.h: fxlib's file management.
- keyboard.h: fxlib's keyboard management.
- serial.h: fxlib's serial management.
- syscall.h: fxlib's syscall definition for ASM-C.
- timer.h: fxlib's timer management.
- commbios.h: fxlib's communication definitions.
- dispbios.h: fxlib's display definitions.
- filebios.h: fxlib's file definitions.
- fxlib.h: library for interacting with CASIO's fx calculators.
- keybios.h: fxlib's keyboard definitions.
- timer.h: fxlib's timer definitions.
-bits:
- cdefs.h: fxlib-specific C definitions.
-src:
- comm:
- comm.s: General communication-related syscalls.
- serial.s: Serial communication-related syscalls.
- display:
- syscalls.s: Display-related syscalls.
- file:
- sdk.c: File related functions.
- syscalls.s: File related syscalls.
- keyboard:
- syscalls.s: Main keyboard syscalls.
- timer:
- sdk.c: fxlib-compatible timer functions.
- syscalls.s: Timer-related syscalls.
- syscall.h: Syscall macro for ASM-C files.
diff --git a/modules/casiowin/fxlib/src/comm/syscalls.s b/modules/casiowin/fxlib/src/comm/syscalls.gnu.src
index 586a2f9..40f1163 100644
--- a/modules/casiowin/fxlib/src/comm/syscalls.s
+++ b/modules/casiowin/fxlib/src/comm/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x28D _Comm_Open
syscall 0x28E _Comm_Close
diff --git a/modules/casiowin/fxlib/src/display/syscalls.s b/modules/casiowin/fxlib/src/display/syscalls.gnu.src
index cb8b6e5..6c88939 100644
--- a/modules/casiowin/fxlib/src/display/syscalls.s
+++ b/modules/casiowin/fxlib/src/display/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x01C _Bdisp_WriteGraph_VRAM
syscall 0x01D _Bdisp_WriteGraph_DD
diff --git a/modules/casiowin/fxlib/src/file/syscalls.s b/modules/casiowin/fxlib/src/file/syscalls.gnu.src
index 2c7e744..0647a77 100644
--- a/modules/casiowin/fxlib/src/file/syscalls.s
+++ b/modules/casiowin/fxlib/src/file/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x429 _Bfile_identify_device_OS
syscall 0x42C _Bfile_OpenFile_OS
diff --git a/modules/casiowin/fxlib/src/keyboard/syscalls.gnu.src b/modules/casiowin/fxlib/src/keyboard/syscalls.gnu.src
new file mode 100644
index 0000000..bdad829
--- /dev/null
+++ b/modules/casiowin/fxlib/src/keyboard/syscalls.gnu.src
@@ -0,0 +1,3 @@
+.include "../syscall.gnu.inc"
+
+syscall 0x90F _GetKey
diff --git a/modules/casiowin/fxlib/src/keyboard/syscalls.s b/modules/casiowin/fxlib/src/keyboard/syscalls.s
deleted file mode 100644
index 80d54f1..0000000
--- a/modules/casiowin/fxlib/src/keyboard/syscalls.s
+++ /dev/null
@@ -1,3 +0,0 @@
-.include "../syscall.inc"
-
-syscall 0x90F _GetKey
diff --git a/modules/casiowin/fxlib/src/serial/syscalls.s b/modules/casiowin/fxlib/src/serial/syscalls.gnu.src
index 55d350c..3e593c7 100644
--- a/modules/casiowin/fxlib/src/serial/syscalls.s
+++ b/modules/casiowin/fxlib/src/serial/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x409 _Serial_ResetAndDisable
syscall 0x40A _Serial_GetInterruptHandler
diff --git a/modules/casiowin/io/src/syscall.inc b/modules/casiowin/fxlib/src/syscall.gnu.inc
index 26fddd3..26fddd3 100644
--- a/modules/casiowin/io/src/syscall.inc
+++ b/modules/casiowin/fxlib/src/syscall.gnu.inc
diff --git a/modules/casiowin/fxlib/src/timer/syscalls.s b/modules/casiowin/fxlib/src/timer/syscalls.gnu.src
index 708e9f4..ce5f479 100644
--- a/modules/casiowin/fxlib/src/timer/syscalls.s
+++ b/modules/casiowin/fxlib/src/timer/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "../syscall.inc"
+.include "../syscall.gnu.inc"
syscall 0x118 _Timer_Install
syscall 0x119 _Timer_Deinstall
diff --git a/modules/casiowin/g1a.ld b/modules/casiowin/g1a.ld
index e56dc1a..010a571 100644
--- a/modules/casiowin/g1a.ld
+++ b/modules/casiowin/g1a.ld
@@ -25,10 +25,11 @@ MEMORY {
}
SECTIONS {
-/* ************************************************************************* */
-/* ROM sections: binary code and read-only data */
-/* ************************************************************************* */
-/* Initialization code, constructors, text. */
+ /* ---
+ * ROM sections: binary code and read-only data.
+ * --- */
+
+ /* Initialization code, constructors, text. */
.text : {
/* Initialization code. */
@@ -55,12 +56,13 @@ SECTIONS {
_romdata = ALIGN(4) ;
} > rom
-/* ************************************************************************* */
-/* RAM sections: BSS and read/write data */
-/* ************************************************************************* */
-/* The BSS section is meant to be stripped off the ELF file to reduce binary
- * size, and initialize with zeroes in the initialization routine;
- * therefore its location is undefined. */
+ /* ---
+ * RAM sections: BSS and read/write data.
+ * --- */
+
+ /* The BSS section is meant to be stripped off the ELF file to reduce binary
+ * size, and initialize with zeroes in the initialization routine;
+ * therefore its location is undefined. */
.bss : {
/* BSS */
diff --git a/modules/casiowin/info.yml b/modules/casiowin/info.yml
deleted file mode 100644
index 549bfbe..0000000
--- a/modules/casiowin/info.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: >-
- The OS on CASIO's fx-9860G series calculators, from 2005 to nowadays'
- monochrome calculators.
-abi:
-- g1a
-default:
-- casiowin/core
-- casiowin/core-crt
-import:
-- all
-- renesas
-requires:
- arch:
- - [sh3, big]
- - [sh4a, big]
diff --git a/modules/casiowin/io/copyright.yml b/modules/casiowin/io/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/casiowin/io/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/io/info.yml b/modules/casiowin/io/info.yml
deleted file mode 100644
index 9d4cbdf..0000000
--- a/modules/casiowin/io/info.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: CASIOWIN standard I/O
-license: free
diff --git a/modules/casiowin/io/module.toml b/modules/casiowin/io/module.toml
new file mode 100644
index 0000000..f044d5d
--- /dev/null
+++ b/modules/casiowin/io/module.toml
@@ -0,0 +1,36 @@
+magic = "potatosdk-1.0"
+desc = "CASIOWIN standard I/O."
+license = "free"
+
+[requires]
+modules = ["all/io"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[source]]
+path = "io.h"
+role = "Bfile I/O internals."
+
+[[source]]
+path = "open.c"
+role = "Open a Bfile stream."
+
+[[source]]
+path = "read.c"
+role = "Read from a Bfile stream."
+
+[[source]]
+path = "write.c"
+role = "Write to a Bfile stream."
+
+[[source]]
+path = "syscall.inc"
+role = "Syscall macro for GNU AS."
+
+[[source]]
+path = "syscalls.s"
+role = "I/O-related syscalls for GNU AS."
diff --git a/modules/casiowin/io/roles.yml b/modules/casiowin/io/roles.yml
deleted file mode 100644
index 7cad08a..0000000
--- a/modules/casiowin/io/roles.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-%YAML 1.2
----
-bits:
- time.h: Standard time header internals.
-src:
- alloc:
- _syscalls.sx: Memory allocation related syscalls.
- assert:
- assert.c: Make an assertion failed pop-up.
- _syscalls.sx: Assertion-related syscalls.
- core:
- _syscalls.sx: Syscalls for the C runtime initialization.
- syscall.h: Syscall macro.
- dirent:
- dirent.h: dirent internals.
- error.c: Standard error number from file-specific error.
- open.c: Open a directory stream.
diff --git a/modules/casiowin/io/src/open.c b/modules/casiowin/io/src/open.c
index 9d36a60..ef26bbf 100644
--- a/modules/casiowin/io/src/open.c
+++ b/modules/casiowin/io/src/open.c
@@ -1,15 +1,16 @@
#include "io.h"
-_EXTERN cookie_io_functions_t __bfile_funcs = {
- (cookie_read_function_t*)&__bfile_read,
- (cookie_write_function_t*)&__bfile_write,
- (cookie_seek_function_t*)&__bfile_seek,
- (cookie_close_function_t*)&__bfile_close
+_EXTERN __file_functions_t __bfile_funcs = {
+ (__file_read_t *)&__bfile_read,
+ (__file_write_t *)&__bfile_write,
+ (__file_seek_t *)&__bfile_seek,
+ (__file_close_t *)&__bfile_close
};
-_EXTERN int __bfile_fopen(FILE** stream, char const *filename,
+_EXTERN int __bfile_fopen(FILE **stream, char const *filename,
struct _IO_MODE* mode)
{
+ FILE *stream;
uint16_t path[2] = {0};
struct _Bfile_cookie *cookie;
int handle, err, omode = 0;
@@ -22,15 +23,16 @@ _EXTERN int __bfile_fopen(FILE** stream, char const *filename,
omode |= __openmode_read;
if (mode->flags & _IO_OPEN_FLAG_WRITE)
omode |= __openmode_write;
+
handle = __bfile_openfile(path, omode);
if (handle < 0)
return (__errno_from_fileerr(handle));
/* Make the stream. */
- if ((err = __carrot_open(stream, sizeof(_Bfile_Cookie), mode,
- &__bfile_funcs)))
- return (err);
+ if (!(stream = __make_file(&__bfile_funcs, _IOFBF, sizeof(_Bfile_Cookie))))
+ return (-1);
+
cookie = (*stream)->cookie;
cookie->handle = handle;
diff --git a/modules/casiowin/io/src/syscall.gnu.inc b/modules/casiowin/io/src/syscall.gnu.inc
new file mode 100644
index 0000000..26fddd3
--- /dev/null
+++ b/modules/casiowin/io/src/syscall.gnu.inc
@@ -0,0 +1,14 @@
+.macro syscall CODE NAME
+.section text
+.align 2
+.global \NAME
+.type \NAME , @function
+
+\NAME :
+ mov.l 1f, r2
+ mov.l 2f, r0
+ jmp @r2
+ nop
+1: .long 0x80010070
+2: .long \CODE
+.endm
diff --git a/modules/casiowin/io/src/syscalls.s b/modules/casiowin/io/src/syscalls.gnu.src
index 633885a..70e480e 100644
--- a/modules/casiowin/io/src/syscalls.s
+++ b/modules/casiowin/io/src/syscalls.gnu.src
@@ -1,4 +1,4 @@
-.include "syscall.inc"
+.include "syscall.gnu.inc"
syscall 0x42C ___bfile_openfile
syscall 0x42D ___bfile_closefile
diff --git a/modules/casiowin/libfxsys/copyright.yml b/modules/casiowin/libfxsys/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/casiowin/libfxsys/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/libfxsys/docs/index.en.rst b/modules/casiowin/libfxsys/docs/index.en.rst
deleted file mode 100644
index 0a5fda0..0000000
--- a/modules/casiowin/libfxsys/docs/index.en.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-Compatibility layer with Andreas Bertheussen's fxlib
-====================================================
-
-While making his own utilities on Linux, Andreas Bertheussen also made a
-little libc with some headers more or less equivalents to the fxlib's ones.
-This module brings compatibility with the very few add-ins using this library.
-
-You can find the original library here:
-https://sourceforge.net/p/fxsdk/code/HEAD/tree/libfxsys/trunk/
diff --git a/modules/casiowin/libfxsys/include/app.h b/modules/casiowin/libfxsys/include/app.h
deleted file mode 100644
index 1d2a7ed..0000000
--- a/modules/casiowin/libfxsys/include/app.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * app.h -- libfxsys' app management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <fxlib/app.h>
diff --git a/modules/casiowin/libfxsys/include/asm.h b/modules/casiowin/libfxsys/include/asm.h
deleted file mode 100644
index 9132180..0000000
--- a/modules/casiowin/libfxsys/include/asm.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/* ****************************************************************************
- * asm.h -- libfxsys' assembly utilities.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-/* Make the syscall entry */
-
-# define ENTRY(_NAME) \
-.section .text; \
-.global _NAME; \
-.type _NAME, @function; \
-.align 2; \
-_NAME:
-
-/* Make the bare syscall, using the `sc_addr` symbol. */
-
-# define SYSCALL_BARE(_NAME, _X) \
-ENTRY(_NAME) \
- mov.l sc_addr, r2; \
- mov.l 1f, r0; \
- jmp @r2; \
- nop; \
-1: .long _X
-
-/* Define the local `sc_addr` local symbol, which is where the syscall table
- * address is. */
-
-# define SYSCALL_ADDRESS \
-sc_addr: .long 0x80010070
-
-/* Define a syscall, defining and using the `sc_addr` local symbol. */
-
-# define SYSCALL(_NAME, _X) \
-SYSCALL_BARE(_NAME, _X); \
-SYSCALL_ADDRESS
diff --git a/modules/casiowin/libfxsys/include/disp.h b/modules/casiowin/libfxsys/include/disp.h
deleted file mode 100644
index b52906b..0000000
--- a/modules/casiowin/libfxsys/include/disp.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * disp.h -- libfxsys' display management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <fx/display.h>
diff --git a/modules/casiowin/libfxsys/include/file.h b/modules/casiowin/libfxsys/include/file.h
deleted file mode 100644
index d469bb6..0000000
--- a/modules/casiowin/libfxsys/include/file.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * file.h -- libfxsys' file management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <fx/file.h>
diff --git a/modules/casiowin/libfxsys/include/key.h b/modules/casiowin/libfxsys/include/key.h
deleted file mode 100644
index f1abd24..0000000
--- a/modules/casiowin/libfxsys/include/key.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * key.h -- libfxsys' keyboard management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <fx/keyboard.h>
diff --git a/modules/casiowin/libfxsys/include/keycodes.h b/modules/casiowin/libfxsys/include/keycodes.h
deleted file mode 100644
index a1797f7..0000000
--- a/modules/casiowin/libfxsys/include/keycodes.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * keycodes.h -- libfxsys' keyboard definitions.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <keybios.h>
diff --git a/modules/casiowin/libfxsys/include/official.h b/modules/casiowin/libfxsys/include/official.h
deleted file mode 100644
index 3ab807e..0000000
--- a/modules/casiowin/libfxsys/include/official.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/* ****************************************************************************
- * official.h -- libfxsys' official calls.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-/* Technically, this macro is supposed to tell the headers we include not
- * to define any non-official system call/interaction, but you know...
- * why care? */
-
-# define ONLY_OFFICIAL_CALLS /* no value? */
-# define _USE_FXLIB_UNOFFICIAL 0
-
-/* And here are the includes, using the compatibility layer. */
-
-# include <stdlib.h>
-# include <disp.h>
-# include <key.h>
-# include <print.h>
-# include <file.h>
diff --git a/modules/casiowin/libfxsys/include/print.h b/modules/casiowin/libfxsys/include/print.h
deleted file mode 100644
index 646d9f8..0000000
--- a/modules/casiowin/libfxsys/include/print.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * print.h -- libfxsys' character display management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <fx/display.h>
diff --git a/modules/casiowin/libfxsys/include/rtc.h b/modules/casiowin/libfxsys/include/rtc.h
deleted file mode 100644
index 4bd3d36..0000000
--- a/modules/casiowin/libfxsys/include/rtc.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * rtc.h -- libfxsys' clock management.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <fx/clock.h>
diff --git a/modules/casiowin/libfxsys/include/syscall.h b/modules/casiowin/libfxsys/include/syscall.h
deleted file mode 100644
index 3df9641..0000000
--- a/modules/casiowin/libfxsys/include/syscall.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* ****************************************************************************
- * syscall.h -- libfxsys' assembly utilities.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'casiowin/libfxsys' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#include <asm.h>
diff --git a/modules/casiowin/libfxsys/info.yml b/modules/casiowin/libfxsys/info.yml
deleted file mode 100644
index fcbaa30..0000000
--- a/modules/casiowin/libfxsys/info.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: fx-9860G libfxsys port.
-license: free
-out: libfxsys
-deps: ['casiowin/fxlib']
diff --git a/modules/casiowin/libfxsys/roles.yml b/modules/casiowin/libfxsys/roles.yml
deleted file mode 100644
index ba5a4b8..0000000
--- a/modules/casiowin/libfxsys/roles.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-%YAML 1.2
----
-include:
- app.h: libfxsys' app management.
- asm.h: libfxsys' assembly utilities.
- disp.h: libfxsys' display management.
- file.h: libfxsys' file management.
- key.h: libfxsys' keyboard management.
- keycodes.h: libfxsys' keyboard definitions.
- official.h: libfxsys' official calls.
- print.h: libfxsys' character display management.
- rtc.h: libfxsys' clock management.
- syscall.h: libfxsys' assembly utilities.
diff --git a/modules/casiowin/monochromelib/copyright.yml b/modules/casiowin/monochromelib/copyright.yml
deleted file mode 100644
index f022178..0000000
--- a/modules/casiowin/monochromelib/copyright.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-%YAML 1.2
----
-files:
-- 'src/*'
-- 'include/*'
-copyright:
-- [2011, Pierre Le Gall, legallpierre89@gmail.com]
-- [2016, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/casiowin/monochromelib/info.yml b/modules/casiowin/monochromelib/info.yml
deleted file mode 100644
index 6dad0d5..0000000
--- a/modules/casiowin/monochromelib/info.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Graphics library for the fx-9860G.
-license: free
-out: libmonochrome
-deps: ['casiowin/fxlib']
diff --git a/modules/casiowin/monochromelib/module.toml b/modules/casiowin/monochromelib/module.toml
new file mode 100644
index 0000000..dec6245
--- /dev/null
+++ b/modules/casiowin/monochromelib/module.toml
@@ -0,0 +1,188 @@
+magic = "potatosdk-1.0"
+desc = "Graphics library for the fx-9860G."
+license = "free"
+out = "libmonochrome"
+deps = ["casiowin/fxlib"]
+
+[[copyrights]]
+begin = 2011
+name = "Pierre Le Gall"
+mail = "legallpierre89@gmail.com"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[headers]]
+path = "monochrome.h"
+role = "MonochromeLib's main header."
+
+[[headers]]
+path = "MonochromeLib.h"
+role = "MonochromeLib's main header alias."
+
+[[source]]
+path = "bmp_8_and.c"
+role = "Display a 8x8 BMP, using ANDs."
+
+[[source]]
+path = "bmp_8_and_cl.c"
+role = "Display a 8x8 BMP, using ANDs and clipping."
+
+[[source]]
+path = "bmp_8_or.c"
+role = "Display a 8x8 BMP, using ORs."
+
+[[source]]
+path = "bmp_8_or_cl.c"
+role = "Display a 8x8 BMP, using ORs and clipping."
+
+[[source]]
+path = "bmp_8_xor.c"
+role = "Display a 8x8 BMP, using XORs."
+
+[[source]]
+path = "bmp_8_xor_cl.c"
+role = "Display a 8x8 BMP, using XORs and clipping."
+
+[[source]]
+path = "bmp_16_and.c"
+role = "Display a 16x16 BMP, using ANDs."
+
+[[source]]
+path = "bmp_16_and_cl.c"
+role = "Display a 16x16 BMP, using ANDs and clipping."
+
+[[source]]
+path = "bmp_16_or.c"
+role = "Display a 16x16 BMP, using ORs."
+
+[[source]]
+path = "bmp_16_or_cl.c"
+role = "Display a 16x16 BMP, using ORs and clipping."
+
+[[source]]
+path = "bmp_16_xor.c"
+role = "Display a 16x16 BMP, using XORs."
+
+[[source]]
+path = "bmp_16_xor_cl.c"
+role = "Display a 16x16 BMP, using XORs and clipping."
+
+[[source]]
+path = "bmp_and.c"
+role = "Display a BMP, using ANDs."
+
+[[source]]
+path = "bmp_and_cl.c"
+role = "Display a BMP, using ANDs and clipping."
+
+[[source]]
+path = "bmp_or.c"
+role = "Display a BMP, using ORs."
+
+[[source]]
+path = "bmp_or_cl.c"
+role = "Display a BMP, using ORs and clipping."
+
+[[source]]
+path = "bmp_xor.c"
+role = "Display a BMP, using XORs."
+
+[[source]]
+path = "bmp_xor_cl.c"
+role = "Display a BMP, using XORs and clipping."
+
+[[source]]
+path = "circle.c"
+role = "Draw a circle."
+
+[[source]]
+path = "clear_screen.c"
+role = "Clear the screen."
+
+[[source]]
+path = "clear_vram.c"
+role = "Clear the VRAM."
+
+[[source]]
+path = "display_vram.c"
+role = "Update the screen content."
+
+[[source]]
+path = "ellipse.c"
+role = "Draw an ellipse."
+
+[[source]]
+path = "ellipse_in_rect.c"
+role = "Draw an ellipse in a rectangle."
+
+[[source]]
+path = "filled_circle.c"
+role = "Draw a filled circle."
+
+[[source]]
+path = "filled_ellipse.c"
+role = "Draw a filled ellipse."
+
+[[source]]
+path = "filled_ellipse_in_rect.c"
+role = "Draw a filled ellipse in a rectangle."
+
+[[source]]
+path = "filled_polygon.c"
+role = "Draw a filled polygon."
+
+[[source]]
+path = "get_contrast.c"
+role = "Get the screen contrast."
+
+[[source]]
+path = "horizontal_line.c"
+role = "Draw a horizontal line."
+
+[[source]]
+path = "horizontal_scroll.c"
+role = "Scroll the screen horizontally."
+
+[[source]]
+path = "line.c"
+role = "Draw a line."
+
+[[source]]
+path = "pixel.c"
+role = "Draw a pixel."
+
+[[source]]
+path = "pixel_test.c"
+role = "Get a pixel's value."
+
+[[source]]
+path = "point.c"
+role = "Draw a dot."
+
+[[source]]
+path = "polygon.c"
+role = "Draw a polygon."
+
+[[source]]
+path = "rectangle.c"
+role = "Draw a rectangle."
+
+[[source]]
+path = "set_contrast.c"
+role = "Set the screen contrast."
+
+[[source]]
+path = "vertical_line.c"
+role = "Draw a vertical line."
+
+[[source]]
+path = "vertical_scroll.c"
+role = "Draw a vertical scroll."
+
+[[source]]
+path = "vram_adress.c"
+role = "Get the VRAM address."
diff --git a/modules/casiowin/monochromelib/roles.yml b/modules/casiowin/monochromelib/roles.yml
deleted file mode 100644
index 2940ea3..0000000
--- a/modules/casiowin/monochromelib/roles.yml
+++ /dev/null
@@ -1,47 +0,0 @@
-%YAML 1.2
----
-include:
- monochrome.h: MonochromeLib's main header.
- MonochromeLib.h: MonochromeLib's main header alias.
-src:
- bmp_8_and.c: Display a 8x8 BMP, using ANDs.
- bmp_8_and_cl.c: Display a 8x8 BMP, using ANDs and clipping.
- bmp_8_or.c: Display a 8x8 BMP, using ORs.
- bmp_8_or_cl.c: Display a 8x8 BMP, using ORs and clipping.
- bmp_8_xor.c: Display a 8x8 BMP, using XORs.
- bmp_8_xor_cl.c: Display a 8x8 BMP, using XORs and clipping.
- bmp_16_and.c: Display a 16x16 BMP, using ANDs.
- bmp_16_and_cl.c: Display a 16x16 BMP, using ANDs and clipping.
- bmp_16_or.c: Display a 16x16 BMP, using ORs.
- bmp_16_or_cl.c: Display a 16x16 BMP, using ORs and clipping.
- bmp_16_xor.c: Display a 16x16 BMP, using XORs.
- bmp_16_xor_cl.c: Display a 16x16 BMP, using XORs and clipping.
- bmp_and.c: Display a BMP, using ANDs.
- bmp_and_cl.c: Display a BMP, using ANDs and clipping.
- bmp_or.c: Display a BMP, using ORs.
- bmp_or_cl.c: Display a BMP, using ORs and clipping.
- bmp_xor.c: Display a BMP, using XORs.
- bmp_xor_cl.c: Display a BMP, using XORs and clipping.
- circle.c: Draw a circle.
- clear_screen.c: Clear the screen.
- clear_vram.c: Clear the VRAM.
- display_vram.c: Update the screen content.
- ellipse.c: Draw an ellipse.
- ellipse_in_rect.c: Draw an ellipse in a rectangle.
- filled_circle.c: Draw a filled circle.
- filled_ellipse.c: Draw a filled ellipse.
- filled_ellipse_in_rect.c: Draw a filled ellipse in a rectangle.
- filled_polygon.c: Draw a filled polygon.
- get_contrast.c: Get the screen contrast.
- horizontal_line.c: Draw a horizontal line.
- horizontal_scroll.c: Scroll the screen horizontally.
- line.c: Draw a line.
- pixel.c: Draw a pixel.
- pixel_test.c: Get a pixel's value.
- point.c: Draw a dot.
- polygon.c: Draw a polygon.
- rectangle.c: Draw a rectangle.
- set_contrast.c: Set the screen contrast.
- vertical_line.c: Draw a vertical line.
- vertical_scroll.c: Draw a vertical scroll.
- vram_adress.c: Get the VRAM address.
diff --git a/modules/casiowin/system.toml b/modules/casiowin/system.toml
new file mode 100644
index 0000000..1c21121
--- /dev/null
+++ b/modules/casiowin/system.toml
@@ -0,0 +1,11 @@
+magic = "potatosdk-1.0"
+desc = """
+The OS on CASIO's fx-9860G series calculators, from 2005 to nowadays'
+monochrome calculators. """
+
+abi = ["g1a"]
+default = ["casiowin/core", "casiowin/core-crt"]
+
+[requires]
+arch = [["sh3", "big"], ["sh4a", "big"]]
+sys = ["all", "renesas"]
diff --git a/modules/compiler/host-gcc-sh/bits/smachine.h b/modules/compiler/host-gcc-sh/bits/smachine.h
index 74b794b..52a93a7 100644
--- a/modules/compiler/host-gcc-sh/bits/smachine.h
+++ b/modules/compiler/host-gcc-sh/bits/smachine.h
@@ -2,9 +2,9 @@
#if __NDIC_CR
#elif __GNUC_ASM
-static inline __uint32_t __get_sr(void) {
- __uint32_t __ret; asm("stc sr, %0" : "=r"(__ret)); return (__ret); }
-static inline void __set_sr(__uint32_t __sr) {
+static inline uint32_t __get_sr(void) {
+ uint32_t __ret; asm("stc sr, %0" : "=r"(__ret)); return (__ret); }
+static inline void __set_sr(uint32_t __sr) {
asm("ldc %0, sr" :: "r"(__sr)); }
# define set_cr(_CR) __set_sr(_CR)
@@ -18,9 +18,9 @@ static inline void __set_sr(__uint32_t __sr) {
#if __NDIC_SSR
#elif __GNUC_ASM
-static inline __uint32_t __get_ssr(void) {
- __uint32_t __ret; asm("stc ssr, %0" :: "=r"(__ret)); return (__ret); }
-static inline void __set_ssr(__uint32_t __ssr) {
+static inline uint32_t __get_ssr(void) {
+ uint32_t __ret; asm("stc ssr, %0" :: "=r"(__ret)); return (__ret); }
+static inline void __set_ssr(uint32_t __ssr) {
asm("ldc %0, ssr" :: "r"(__ssr)); }
# define set_ssr(_SSR) __set_ssr(_SSR)
@@ -33,10 +33,15 @@ static inline void __set_ssr(__uint32_t __ssr) {
#if __NDIC_CR
#elif __GNUC_ASM
-# define set_imask(_IMASK) \
- set_cr((get_cr() & ~0xF0) | (((_IMASK) & 0x0F) << 4))
-# define get_imask() \
- ((get_cr() >> 4) & 0x0F)
+static inline uint32_t __get_imask(void) {
+ uint32_t __ret; asm("stc sr, %0" : "=r"(__ret));
+ return ((__ret >> 4) & 0x0F); }
+static inline void __set_imask(uint32_t __imask) {
+ uint32_t __sr; asm("stc sr, %0" : "=r"(__sr));
+ asm("ldc %0, sr" :: "r"((__sr & ~0xF0) | ((__imask & 0x0F) << 4))); }
+
+# define set_imask(_IMASK) __set_imask(_IMASK)
+# define get_imask() __get_imask()
#endif
/* Vector base register management.
@@ -45,9 +50,9 @@ static inline void __set_ssr(__uint32_t __ssr) {
#if __NDIC_VBR
#elif __GNUC_ASM
-_LOCAL _INLINE __uint32_t __get_vbr(void) {
- __uint32_t __vbr; __asm("ldc.l vbr, %0":"=r"(__vbr):); return (__vbr); }
-_LOCAL _INLINE void __set_vbr(__uint32_t __vbr) {
+_LOCAL _INLINE uint32_t __get_vbr(void) {
+ uint32_t __vbr; __asm("ldc.l vbr, %0":"=r"(__vbr):); return (__vbr); }
+_LOCAL _INLINE void __set_vbr(uint32_t __vbr) {
__asm("stc.l %0, vbr"::"r"(__vbr)); }
# define set_vbr(_VBR) __set_vbr(_VBR)
@@ -72,8 +77,9 @@ _LOCAL _INLINE void __set_vbr(__uint32_t __vbr) {
#if __NDIC_CIRC
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE void __clr_circ(void) {
- set_cr(get_cr() & ~0xC00); }
+static inline void __clr_circ(void) {
+ uint32_t __sr; asm("stc sr, %0" : "=r"(__sr));
+ asm("ldc %0, sr" :: "r"(__sr & ~0xC00); }
# define set_circ_x(_ARRAY, _SIZE) ((void)0)
# define set_circ_y(_ARRAY, _SIZE) ((void)0)
@@ -84,6 +90,9 @@ _LOCAL _ASM_INLINE void __clr_circ(void) {
#if __NDIC_SRJSR
#elif __GNUC_ASM
-# define sr_jsr(_FUNC, _IMASK) __asm("jsr %1\r\n" "stc.l %0" \
- :: "r"((get_cr() & ~0xF0) | ((_IMASK) << 4)), "r"(_FUNC))
+static inline uint32_t __sr_jsr_get_sr(void) {
+ uint32_t __ret; asm("stc sr, %0" : "=r"(__ret)); return (__ret); }
+
+# define sr_jsr(_FUNC, _IMASK) __asm("jsr %1\r\n" "stc sr, %0" \
+ :: "r"((__sr_jsr_get_sr() & 0xCFFFFF0F) | ((_IMASK) << 4)), "r"(_FUNC))
#endif
diff --git a/modules/compiler/host-gcc-sh/bits/stdarg.h b/modules/compiler/host-gcc-sh/bits/stdarg.h
deleted file mode 100644
index 0091e72..0000000
--- a/modules/compiler/host-gcc-sh/bits/stdarg.h
+++ /dev/null
@@ -1,16 +0,0 @@
-/* GCC provides built-ins to make the variable argument list implementation
- * easier. */
-
-#if __GNUC_PREREQ(1, 0)
-typedef __builtin_va_list va_list;
-
-/* Open and close a variable argument list. */
-# define va_start(_AP, _PARAM) __builtin_va_start(_AP, _PARAM)
-# define va_end(_AP) __builtin_va_end(_AP)
-
-/* Obtain an argument from the variable argument list. */
-# define va_arg(_AP, _TYPE) __builtin_va_arg(_AP, _TYPE)
-
-/* Copy a variable argument list. */
-# define va_copy(_D, _S) __builtin_va_copy(_D, _S)
-#endif
diff --git a/modules/compiler/host-gcc-sh/bits/types/exact.h b/modules/compiler/host-gcc-sh/bits/types/exact.h
deleted file mode 100644
index 6db1f0a..0000000
--- a/modules/compiler/host-gcc-sh/bits/types/exact.h
+++ /dev/null
@@ -1,24 +0,0 @@
-#define_raw __int8_t __INT8_TYPE__
-#define_raw __uint8_t __UINT8_TYPE__
-#define_raw __int16_t __INT16_TYPE__
-#define_raw __uint16_t __UINT16_TYPE__
-#define_raw __int32_t __INT32_TYPE__
-#define_raw __uint32_t __UINT32_TYPE__
-
-#define __INT8_MIN __INT8_C(-128)
-#define __INT8_MAX __INT8_C(+127)
-#define __UINT8_MIN __UINT8_C( 0)
-#define __UINT8_MAX __UINT8_C( 255)
-#define __PRI8 "hh"
-
-#define __INT16_MIN __INT16_C(-32768)
-#define __INT16_MAX __INT16_C(+32767)
-#define __UINT16_MIN __UINT16_C( 0)
-#define __UINT16_MAX __UINT16_C( 65535)
-#define __PRI16 "h"
-
-#define __INT32_MIN __INT32_C(-2147483648)
-#define __INT32_MAX __INT32_C(+2147483647)
-#define __UINT32_MIN __UINT32_C(0)
-#define __UINT32_MAX __UINT32_C( 4294967295)
-#define __PRI32 ""
diff --git a/modules/compiler/host-gcc-sh/bits/types/fast.h b/modules/compiler/host-gcc-sh/bits/types/fast.h
deleted file mode 100644
index 1389381..0000000
--- a/modules/compiler/host-gcc-sh/bits/types/fast.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* ****************************************************************************
- * types/fast.h -- Fastest-width integer types for GCC.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'all/compiler-gcc' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#define __int_fast8_t __int32_t
-#define __uint_fast8_t __uint32_t
-#define __int_fast16_t __int32_t
-#define __uint_fast16_t __uint32_t
-#define __int_fast32_t __int32_t
-#define __uint_fast32_t __uint32_t
-
-#define __INT_FAST8_WIDTH __INT32_WIDTH
-#define __INT_FAST8_MIN __INT32_MIN
-#define __INT_FAST8_MAX __INT32_MAX
-#define __UINT_FAST8_MIN __UINT32_MIN
-#define __UINT_FAST8_MAX __UINT32_MAX
-#define __PRIFAST8 __PRI32
-
-#define __INT_FAST16_WIDTH __INT32_WIDTH
-#define __INT_FAST16_MIN __INT32_MIN
-#define __INT_FAST16_MAX __INT32_MAX
-#define __UINT_FAST16_MIN __UINT32_MIN
-#define __UINT_FAST16_MAX __UINT32_MAX
-#define __PRIFAST16 __PRI32
-
-#define __INT_FAST32_WIDTH __INT32_WIDTH
-#define __INT_FAST32_MIN __INT32_MIN
-#define __INT_FAST32_MAX __INT32_MAX
-#define __UINT_FAST32_MIN __UINT32_MIN
-#define __UINT_FAST32_MAX __UINT32_MAX
-#define __PRIFAST32 __PRI32
diff --git a/modules/compiler/host-gcc-sh/bits/types/least.h b/modules/compiler/host-gcc-sh/bits/types/least.h
deleted file mode 100644
index 9b51314..0000000
--- a/modules/compiler/host-gcc-sh/bits/types/least.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/* ****************************************************************************
- * types/least.h -- Least-width integer types for GCC.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'all/compiler-gcc' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#define __int_least8_t __int8_t
-#define __uint_least8_t __uint8_t
-#define __int_least16_t __int16_t
-#define __uint_least16_t __uint16_t
-#define __int_least32_t __int32_t
-#define __uint_least32_t __uint32_t
-
-#define __INT_LEAST8_WIDTH __INT8_WIDTH
-#define __INT_LEAST8_MIN __INT8_MIN
-#define __INT_LEAST8_MAX __INT8_MAX
-#define __UINT_LEAST8_MIN __UINT8_MIN
-#define __UINT_LEAST8_MAX __UINT8_MAX
-#define __PRILEAST8 __PRI8
-
-#define __INT8_C(_X) _X
-#define __UINT8_C(_X) _X ## U
-
-#define __INT_LEAST16_WIDTH __INT16_WIDTH
-#define __INT_LEAST16_MIN __INT16_MIN
-#define __INT_LEAST16_MAX __INT16_MAX
-#define __UINT_LEAST16_MIN __UINT16_MIN
-#define __UINT_LEAST16_MAX __UINT16_MAX
-#define __PRILEAST16 __PRI16
-
-#define __INT16_C(_X) _X
-#define __UINT16_C(_X) _X ## U
-
-#define __INT_LEAST32_WIDTH __INT32_WIDTH
-#define __INT_LEAST32_MIN __INT32_MIN
-#define __INT_LEAST32_MAX __INT32_MAX
-#define __UINT_LEAST32_MIN __UINT32_MIN
-#define __UINT_LEAST32_MAX __UINT32_MAX
-#define __PRILEAST32 __PRI32
-
-#define __INT32_C(_X) _X ## L
-#define __UINT32_C(_X) _X ## UL
diff --git a/modules/compiler/host-gcc-sh/bits/types/max.h b/modules/compiler/host-gcc-sh/bits/types/max.h
deleted file mode 100644
index aa24224..0000000
--- a/modules/compiler/host-gcc-sh/bits/types/max.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* ****************************************************************************
- * types/max.h -- Maximum width integer types for GCC.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'all/compiler-gcc' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#define __intmax_t __int32_t
-#define __uintmax_t __uint32_t
-
-#define __INTMAX_WIDTH __INT32_WIDTH
-#define __INTMAX_MIN __INT32_MIN
-#define __INTMAX_MAX __INT32_MAX
-#define __UINTMAX_MIN __UINT32_MIN
-#define __UINTMAX_MAX __UINT32_MAX
-#define __PRIMAX __PRI32
-
-#define __INTMAX_C(_X) _X ## L
-#define __UINTMAX_C(_X) _X ## UL
diff --git a/modules/compiler/host-gcc-sh/bits/types/ptr.h b/modules/compiler/host-gcc-sh/bits/types/ptr.h
deleted file mode 100644
index 571015a..0000000
--- a/modules/compiler/host-gcc-sh/bits/types/ptr.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* ****************************************************************************
- * types/ptr.h -- Pointer type in GCC.
- * Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
- *
- * This file is part of the 'all/compiler-gcc' module in libcarrot, an
- * experimental modular libc project.
- *
- * This file is governed by the CeCILL-C license under French law and abiding
- * by the rules of distribution of free software. You can use, modify and or
- * redistribute it under the terms of the CeCILL-C license as circulated by
- * CEA, CNRS and INRIA at the following URL: http://www.cecill.info
- *
- * As a counterpart to the access to the source code and rights to copy, modify
- * and redistribute granted by the license, users are provided only with a
- * limited warranty and the software's author, the holder of the economic
- * rights, and the successive licensors have only limited liability.
- *
- * In this respect, the user's attention is drawn to the risks associated with
- * loading, using, modifying and/or developing and reproducing the software by
- * the user in light of its specific status of free software, that may mean
- * that it is complicated to manipulate, and that also therefore means that it
- * is reserved for developers and experienced professionals having in-depth
- * computer knowledge. Users are therefore encouraged to load and test the
- * software's suitability as regards their requirements in conditions enabling
- * the security of their systems and/or data to be ensured and, more generally,
- * to use and operate it in the same conditions as regards security.
- *
- * The fact that you are presently reading this means you have had knowledge of
- * the CeCILL-C license and that you accept its terms.
- * ************************************************************************* */
-#define __intptr_t __int32_t
-#define __uintptr_t __uint32_t
-
-#define __INTPTR_WIDTH __INT32_WIDTH
-#define __INTPTR_MIN __INT32_MIN
-#define __INTPTR_MAX __INT32_MAX
-#define __UINTPTR_MIN __UINT32_MIN
-#define __UINTPTR_MAX __UINT32_MAX
-#define __PRIPTR __PRI32
diff --git a/modules/compiler/host-gcc-sh/bits/umachine.h b/modules/compiler/host-gcc-sh/bits/umachine.h
index d6fecff..3372077 100644
--- a/modules/compiler/host-gcc-sh/bits/umachine.h
+++ b/modules/compiler/host-gcc-sh/bits/umachine.h
@@ -3,9 +3,9 @@
#if __NDIC_SPC
#elif __GNUC_ASM
-_LOCAL _INLINE __uint32_t __get_spc(void) {
- __uint32_t __ret; __asm("ldc.l spc, %0" :: "=r"(__ret)); return (__ret); }
-_LOCAL _INLINE void __set_spc(__uint32_t __spc) {
+_LOCAL _INLINE uint32_t __get_spc(void) {
+ uint32_t __ret; __asm("ldc.l spc, %0" :: "=r"(__ret)); return (__ret); }
+_LOCAL _INLINE void __set_spc(uint32_t __spc) {
__asm("stc %0, sr" :: "r"(__spc)); }
# define set_spc(_SPC) __set_spc(_SPC)
@@ -15,9 +15,9 @@ _LOCAL _INLINE void __set_spc(__uint32_t __spc) {
/* GBR interaction. */
#if __GNUC_ASM
-_LOCAL _ASM_INLINE __uint32_t __get_gbr(void) {
- __uint32_t __gbr; __asm("ldc.l gbr, %0":"=r"(__gbr):); return (__gbr); }
-_LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
+_LOCAL _ASM_INLINE uint32_t __get_gbr(void) {
+ uint32_t __gbr; __asm("ldc.l gbr, %0":"=r"(__gbr):); return (__gbr); }
+_LOCAL _ASM_INLINE void __set_gbr(uint32_t __gbr) {
__asm("stc.l %0, gbr"::"r"(__gbr)); }
# define set_gbr(_BASE) __set_gbr(_BASE)
@@ -28,17 +28,17 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
#if __NDIC_GBR_RW
#elif __GNUC_ASM
-# define gbr_read_byte(_OFF) ({__asm_inline \
+# define gbr_read_byte(_OFF) ({_ASM_INLINE \
uint8_t __fn__(void) { \
uint8_t __ret; __asm("mov.b @(%1, gbr), %0":"=r"(__ret):"I"(_OFF)); \
return (__ret); } __fn__; })()
-# define gbr_read_word(_OFF) ({__asm_inline \
+# define gbr_read_word(_OFF) ({_ASM_INLINE \
uint16_t __fn__(void) { \
uint16_t __ret; __asm("mov.w @(%1, gbr), %0":"=r"(__ret):"I"(_OFF)); \
return (__ret); } __fn__; })()
-# define gbr_read_long(_OFF) ({__asm_inline \
- __uint32_t __fn__(void) { \
- __uint32_t __ret; __asm("mov.l @(%1, gbr), %0":"=r"(__ret):"I"(_OFF)); \
+# define gbr_read_long(_OFF) ({_ASM_INLINE \
+ uint32_t __fn__(void) { \
+ uint32_t __ret; __asm("mov.l @(%1, gbr), %0":"=r"(__ret):"I"(_OFF)); \
return (__ret); } __fn__; })()
# define gbr_write_byte(_OFF, _DATA) \
@@ -80,48 +80,48 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
* this interface, so this will not work with it. */
#if __NDIC_TRAPA
-#elif __GNUC_ASM && defined(__count_va_args)
-# define __make_trapa_svc_1(_CODE, _R0) ({__asm_inline \
+#elif __GNUC_ASM
+# define __make_trapa_svc_1(_CODE, _R0) ({_ASM_INLINE \
int __fn__(void) { \
register int __ret asm ("r0") = (_R0); \
\
__asm("trapa %0" :: "i"(_CODE)); \
return (__ret); } \
__fn__; })
-# define __make_trapa_svc_2(_CODE, _R0, _R4) ({__asm_inline \
+# define __make_trapa_svc_2(_CODE, _R0, _R4) ({_ASM_INLINE \
int __fn__(void) { \
- register int __ret asm ("r0") = (_R0); \
- register int __arg4 asm ("r4") = (_R4); \
+ register int __ret asm ("r0") = (_R0), \
+ __arg4 asm ("r4") = (_R4); \
\
__asm("trapa %0" :: "i"(_CODE)); \
return (__ret); } \
__fn__; })
-# define __make_trapa_svc_3(_CODE, _R0, _R4, _R5) ({__asm_inline \
+# define __make_trapa_svc_3(_CODE, _R0, _R4, _R5) ({_ASM_INLINE \
int __fn__(void) { \
- register int __ret asm ("r0") = (_R0); \
- register int __arg4 asm ("r4") = (_R4); \
- register int __arg5 asm ("r5") = (_R5); \
+ register int __ret asm ("r0") = (_R0), \
+ __arg4 asm ("r4") = (_R4), \
+ __arg5 asm ("r5") = (_R5); \
\
__asm("trapa %0" :: "i"(_CODE)); \
return (__ret); } \
__fn__; })
-# define __make_trapa_svc_4(_CODE, _R0, _R4, _R5, _R6) ({__asm_inline \
+# define __make_trapa_svc_4(_CODE, _R0, _R4, _R5, _R6) ({_ASM_INLINE \
int __fn__(void) { \
- register int __ret asm ("r0") = (_R0); \
- register int __arg4 asm ("r4") = (_R4); \
- register int __arg5 asm ("r5") = (_R5); \
- register int __arg6 asm ("r6") = (_R6); \
+ register int __ret asm ("r0") = (_R0), \
+ __arg4 asm ("r4") = (_R4), \
+ __arg5 asm ("r5") = (_R5), \
+ __arg6 asm ("r6") = (_R6); \
\
__asm("trapa %0" :: "i"(_CODE)); \
return (__ret); } \
__fn__; })
-# define __make_trapa_svc_5(_CODE, _R0, _R4, _R5, _R6, _R7) ({__asm_inline \
+# define __make_trapa_svc_5(_CODE, _R0, _R4, _R5, _R6, _R7) ({_ASM_INLINE \
int __fn__(void) { \
- register int __ret asm ("r0") = (_R0); \
- register int __arg4 asm ("r4") = (_R4); \
- register int __arg5 asm ("r5") = (_R5); \
- register int __arg6 asm ("r6") = (_R6); \
- register int __arg7 asm ("r7") = (_R7); \
+ register int __ret asm ("r0") = (_R0), \
+ __arg4 asm ("r4") = (_R4), \
+ __arg5 asm ("r5") = (_R5), \
+ __arg6 asm ("r6") = (_R6), \
+ __arg7 asm ("r7") = (_R7); \
\
__asm("trapa %0" :: "i"(_CODE)); \
return (__ret); } \
@@ -142,10 +142,36 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
# define __make_trapa_svc_12(...) \
_Pragma("GCC error \"trapa_svc takes up to six arguments only\"")
+/* Count the number of arguments.
+ * Taken from here: https://stackoverflow.com/a/2124385 */
+
+# define __trapa_svc_narg(...) \
+ __trapa_svc_narg_(__VA_ARGS__,__trapa_svc_narg_rseq_n())
+# define __trapa_svc_narg_(...) \
+ __trapa_svc_narg_n(__VA_ARGS__)
+# define __trapa_svc_narg_n( \
+ _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
+ _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
+ _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
+ _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
+ _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
+ _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
+ _61,_62,_63,N,...) N
+# define __trapa_svc_narg_rseq_n() \
+ 63,62,61,60, \
+ 59,58,57,56,55,54,53,52,51,50, \
+ 49,48,47,46,45,44,43,42,41,40, \
+ 39,38,37,36,35,34,33,32,31,30, \
+ 29,28,27,26,25,24,23,22,21,20, \
+ 19,18,17,16,15,14,13,12,11,10, \
+ 9,8,7,6,5,4,3,2,1,0
+
+/* Main macro. */
+
# define trapa_svc(_CODE, _R0, ...) \
__trapa_svc_(_CODE, _R0, ##__VA_ARGS__)
# define __trapa_svc_(_CODE, ...) \
- __concat(__make_trapa_svc_, __count_va_args(__VA_ARGS__))\
+ __concat(__make_trapa_svc_, __trapa_svc_narg(__VA_ARGS__))\
(_CODE, __VA_ARGS__)()
#endif
@@ -154,9 +180,9 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
#if __NDIC_MAC
#elif __GNUC_ASM
-# define macw(_PTR1, _PTR2, _COUNT) ({__asm_inline \
- __uint32_t __fn__(uint16_t *__p1, uint16_t *__p2) { \
- __uint32_t __macl, __mach, __mul; \
+# define macw(_PTR1, _PTR2, _COUNT) ({_ASM_INLINE \
+ uint32_t __fn__(uint16_t *__p1, uint16_t *__p2) { \
+ uint32_t __macl, __mach, __mul; \
__asm("sts macl, %0\r\n" "sts mach, %1":"=r"(__macl), "=r"(__mach)); \
__asm("clrmac"); \
int __count; for (__count = 0; __count < (_COUNT); __count++) \
@@ -165,9 +191,9 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
__asm("lds %0, macl"::"r"(__macl)); \
__asm("lds %0, mach"::"r"(__mach)); \
return (__mul); } __fn__; })(_PTR1, _PTR2)
-# define macwl(_PTR1, _PTR2, _COUNT, _MASK) ({__asm_inline \
- __uint32_t __fn__(uint16_t *__p1, uint16_t *__p1, uint16_t __mask) { \
- __uint32_t __macl, __mach, __mul; \
+# define macwl(_PTR1, _PTR2, _COUNT, _MASK) ({_ASM_INLINE \
+ uint32_t __fn__(uint16_t *__p1, uint16_t *__p1, uint16_t __mask) { \
+ uint32_t __macl, __mach, __mul; \
__asm("sts macl, %0\r\n" "sts mach, %1":"=r"(__macl), "=r"(__mach)); \
__asm("clrmac"); \
int __count; for (__count = 0; __count < (_COUNT); __count++) \
@@ -178,9 +204,9 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
__asm("lds %0, mach"::"r"(__mach)); \
return (__mul); } __fn__; })(_PTR1, _PTR2, _MASK)
-# define macl(_PTR1, _PTR2, _COUNT) ({__asm_inline \
- __uint32_t __fn__(__uint32_t *__p1, __uint32_t *__p2) { \
- __uint32_t __macl, __mach, __mul; \
+# define macl(_PTR1, _PTR2, _COUNT) ({_ASM_INLINE \
+ uint32_t __fn__(uint32_t *__p1, uint32_t *__p2) { \
+ uint32_t __macl, __mach, __mul; \
__asm("sts macl, %0\r\n" "sts mach, %1":"=r"(__macl), "=r"(__mach)); \
__asm("clrmac"); \
int __count; for (__count = 0; __count < (_COUNT); __count++) \
@@ -189,9 +215,9 @@ _LOCAL _ASM_INLINE void __set_gbr(__uint32_t __gbr) {
__asm("lds %0, macl"::"r"(__macl)); \
__asm("lds %0, mach"::"r"(__mach)); \
return (__mul); } __fn__; })(_PTR1, _PTR2)
-# define macll(_PTR1, _PTR2, _COUNT, _MASK) ({__asm_inline \
- __uint32_t __fn__(__uint32_t *__p1, __uint32_t *__p1, __uint32_t __mask) { \
- __uint32_t __macl, __mach, __mul; \
+# define macll(_PTR1, _PTR2, _COUNT, _MASK) ({_ASM_INLINE \
+ uint32_t __fn__(uint32_t *__p1, uint32_t *__p1, uint32_t __mask) { \
+ uint32_t __macl, __mach, __mul; \
__asm("sts macl, %0\r\n" "sts mach, %1":"=r"(__macl), "=r"(__mach)); \
__asm("clrmac"); \
int __count; for (__count = 0; __count < (_COUNT); __count++) \
@@ -218,10 +244,10 @@ _LOCAL _ASM_INLINE void __prefetch(void *addr) {
#if __NDIC_FPUSCR
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE void __set_fpscr(__uint32_t __cr) {
+_LOCAL _ASM_INLINE void __set_fpscr(uint32_t __cr) {
__asm("lds %0, FPSCR"::"r"(__cr)); }
-_LOCAL _ASM_INLINE __uint32_t __get_fpscr(void) {
- __uint32_t __fpscr; __asm("sts FPSCR, %0":"=r"(__fpscr):);
+_LOCAL _ASM_INLINE uint32_t __get_fpscr(void) {
+ uint32_t __fpscr; __asm("sts FPSCR, %0":"=r"(__fpscr):);
return (__fpscr); }
# define set_fpscr(_CR) __set_fpscr(_CR)
@@ -433,21 +459,23 @@ _LOCAL _ASM_INLINE void __mtrx4mulsub(float __mat1[4][4], float __mat2[4][4],
#if __NDIC_SWAP
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __uint16_t __swapb(__uint16_t __data) {
- __uint16_t __res; __asm("swap.b %1, %0":"=r"(__res):"r"(__data));
+_LOCAL _ASM_INLINE uint16_t __swapb(uint16_t __data) {
+ uint16_t __res; __asm("swap.b %1, %0":"=r"(__res):"r"(__data));
return (__res); }
-_LOCAL _ASM_INLINE __uint32_t __swapw(__uint32_t __data) {
- __uint32_t __res; __asm("swap.w %1, %0":"=r"(__res):"r"(__data));
+_LOCAL _ASM_INLINE uint32_t __swapw(uint32_t __data) {
+ uint32_t __res; __asm("swap.w %1, %0":"=r"(__res):"r"(__data));
return (__res); }
+_LOCAL uint32_t __end_cvnl(uint32_t __data) {
+ __asm("swap.b %0, %0\r\n" "swap.w %0, %0\r\n" "swap.b %0, %0"
+ : "=r"(__data));
+ return (__data); }
-# define swapb(_WORD) __swapb(_WORD)
-# define swapw(_LONG) __swapw(_LONG)
-#endif
-
-/* Here are some other macros that seem to use the last ones...? */
+# define swapb(_WORD) __swapb(_WORD)
+# define swapw(_LONG) __swapw(_LONG)
-#define end_cnvw(_RM) swapb(_RM)
-#define end_cnvl(_DATA) swapw(_DATA) /* XXX: _builtin_end_cnvl(data)? */
+# define end_cnvw(_DATA) __swapw(_DATA)
+# define end_cnvl(_DATA) __end_cvnl(_DATA)
+#endif
/* Double-length Multiply as Signed.
* Performs 32-bit multiplication of two operands, and stores the 64-bit
@@ -455,24 +483,24 @@ _LOCAL _ASM_INLINE __uint32_t __swapw(__uint32_t __data) {
#if __NDIC_DMUL
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __uint32_t __dmulu_h(__uint32_t __data1,
- __uint32_t __data2) {
- __uint32_t __result; __asm("dmulu.l %1, %2\r\n" "lds.l MACH, %0"
+_LOCAL _ASM_INLINE uint32_t __dmulu_h(uint32_t __data1,
+ uint32_t __data2) {
+ uint32_t __result; __asm("dmulu.l %1, %2\r\n" "lds.l MACH, %0"
:"=r"(__result) :"r"(__data1), "r"(__data2));
return (__result); }
-_LOCAL _ASM_INLINE __uint32_t __dmulu_l(__uint32_t __data1,
- __uint32_t __data2) {
- __uint32_t __result; __asm("dmulu.l %1, %2\r\n" "lds.l MACL, %0"
+_LOCAL _ASM_INLINE uint32_t __dmulu_l(uint32_t __data1,
+ uint32_t __data2) {
+ uint32_t __result; __asm("dmulu.l %1, %2\r\n" "lds.l MACL, %0"
:"=r"(__result) :"r"(__data1), "r"(__data2));
return (__result); }
-_LOCAL _ASM_INLINE __int32_t __dmuls_h(__int32_t __data1,
- __int32_t __data2) {
- __int32_t __result; __asm("dmuls.l %1, %2\r\n" "lds.l MACH, %0"
+_LOCAL _ASM_INLINE int32_t __dmuls_h(int32_t __data1,
+ int32_t __data2) {
+ int32_t __result; __asm("dmuls.l %1, %2\r\n" "lds.l MACH, %0"
:"=r"(__result) :"r"(__data1), "r"(__data2));
return (__result); }
-_LOCAL _ASM_INLINE __int32_t __dmuls_l(__int32_t __data1,
- __int32_t __data2) {
- __int32_t __result; __asm("dmuls.l %1, %2\r\n" "lds.l MACL, %0"
+_LOCAL _ASM_INLINE int32_t __dmuls_l(int32_t __data1,
+ int32_t __data2) {
+ int32_t __result; __asm("dmuls.l %1, %2\r\n" "lds.l MACL, %0"
:"=r"(__result) :"r"(__data1), "r"(__data2));
return (__result); }
@@ -488,7 +516,7 @@ _LOCAL _ASM_INLINE __int32_t __dmuls_l(__int32_t __data1,
#if __NDIC_FSC
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE void __fsca(__int32_t __angle, float *__sinv,
+_LOCAL _ASM_INLINE void __fsca(int32_t __angle, float *__sinv,
float *__cosv) {
__asm("lds %0, fpul\r\n"
"fsca fpul, dr0\r\n"
@@ -547,14 +575,14 @@ _LOCAL _ASM_INLINE __fixed __pdmsb_la(long __accum __data) {
# define pdmsb_lf(_DATA) __pdmsb_lf(_DATA)
# define pdmsb_la(_DATA) __pdmsb_la(_DATA)
-# define psha_lf(_DATA, _COUNT) ({__asm_inline \
+# define psha_lf(_DATA, _COUNT) ({_ASM_INLINE \
int __fn__(long __fixed __data) { \
__asm("movs.l @%0, x1\r\n" \
"psha %1, x1\r\n" \
"movs.l x1, @%0\r\n" \
:: "r"(&__data), "i"(_COUNT)); \
return (__data); }})(_DATA)
-# define psha_la(_DATA, _COUNT) ({__asm_inline \
+# define psha_la(_DATA, _COUNT) ({_ASM_INLINE \
int __fn__(long __accum __data) { \
__asm("movs.l @%0, a1 \r\n" \
"movs.l @-%0, a1g\r\n" \
@@ -648,7 +676,7 @@ _LOCAL _ASM_INLINE void __set_dsr(uint32_t __dsr) {
#if __NDIC_T
#elif __GNUC_ASM
_LOCAL _ASM_INLINE int __movt(void) {
- __uint32_t __result; __asm("movt %0":"=r"(__result):);
+ uint32_t __result; __asm("movt %0":"=r"(__result):);
return (__result); }
# define movt() __movt()
@@ -661,28 +689,28 @@ _LOCAL _ASM_INLINE int __movt(void) {
#if __NDIC_CARRY
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __uint32_t __xtrct(__uint32_t __upper,
- __uint32_t __lower) {
+_LOCAL _ASM_INLINE uint32_t __xtrct(uint32_t __upper,
+ uint32_t __lower) {
__asm("xtrct %1, %0"
: "+r"(__lower) : "r"(__upper));
return (__lower); }
-_LOCAL _ASM_INLINE __int32_t __addc(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int32_t __addc(int32_t __data1, int32_t __data2) {
__asm("addc %1, %0"
: "+r"(__data2) : "r"(__data1));
return (__data2); }
-_LOCAL _ASM_INLINE __int32_t __addv(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int32_t __addv(int32_t __data1, int32_t __data2) {
__asm("addv %1, %0"
: "+r"(__data2) : "r"(__data1));
return (__data2); }
-_LOCAL _ASM_INLINE __int32_t __subc(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int32_t __subc(int32_t __data1, int32_t __data2) {
__asm("subc %1, %0"
: "+r"(__data2) : "r"(__data1));
return (__data2); }
-_LOCAL _ASM_INLINE __int32_t __subv(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int32_t __subv(int32_t __data1, int32_t __data2) {
__asm("subv %1, %0"
: "+r"(__data2) : "r"(__data1));
return (__data2); }
-_LOCAL _ASM_INLINE __int32_t __negc(__int32_t __data) {
+_LOCAL _ASM_INLINE int32_t __negc(int32_t __data) {
__asm("negc %0, %0" : "+r"(__data));
return (__data); }
@@ -693,16 +721,16 @@ _LOCAL _ASM_INLINE __int32_t __negc(__int32_t __data) {
# define subv(_DATA1, _DATA2) __subv(_DATA1, _DATA2)
# define negc(_DATA) __negc(_DATA)
-_LOCAL _ASM_INLINE int __ovf_addc(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int __ovf_addc(int32_t __data1, int32_t __data2) {
__asm("addc %0, %1" :: "r"(__data1), "r"(__data2));
return (movt()); }
-_LOCAL _ASM_INLINE int __ovf_addv(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int __ovf_addv(int32_t __data1, int32_t __data2) {
__asm("addv %0, %1" :: "r"(__data1), "r"(__data2));
return (movt()); }
-_LOCAL _ASM_INLINE int __unf_subc(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int __unf_subc(int32_t __data1, int32_t __data2) {
__asm("subc %0, %1" :: "r"(__data1), "r"(__data2));
return (movt()); }
-_LOCAL _ASM_INLINE int __unf_subv(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int __unf_subv(int32_t __data1, int32_t __data2) {
__asm("subv %0, %1" :: "r"(__data1), "r"(__data2));
return (movt()); }
@@ -717,11 +745,11 @@ _LOCAL _ASM_INLINE int __unf_subv(__int32_t __data1, __int32_t __data2) {
#if __NDIC_DIV
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __uint32_t __div1(__uint32_t __data1, __uint32_t __data2) {
+_LOCAL _ASM_INLINE uint32_t __div1(uint32_t __data1, uint32_t __data2) {
__asm("div1 %1, %0"
: "+r"(__data2) : "r"(__data1));
return (__data2); }
-_LOCAL _ASM_INLINE __int32_t __div0s(__int32_t __data1, __int32_t __data2) {
+_LOCAL _ASM_INLINE int32_t __div0s(int32_t __data1, int32_t __data2) {
__asm("div0s %0, %1"
:: "r"(__data1), "r"(__data2));
return (movt()); }
@@ -736,16 +764,16 @@ _LOCAL _ASM_INLINE __int32_t __div0s(__int32_t __data1, __int32_t __data2) {
#if __NDIC_ROT
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __uint32_t __rotl(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __rotl(uint32_t __data) {
__asm("rotl %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __uint32_t __rotr(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __rotr(uint32_t __data) {
__asm("rotr %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __uint32_t __rotcl(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __rotcl(uint32_t __data) {
__asm("rotcl %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __uint32_t __rotcr(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __rotcr(uint32_t __data) {
__asm("rotcr %0" : "+r"(__data));
return (__data); }
@@ -760,13 +788,13 @@ _LOCAL _ASM_INLINE __uint32_t __rotcr(__uint32_t __data) {
#if __NDIC_SHIFT
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __uint32_t __shll(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __shll(uint32_t __data) {
__asm("shll %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __uint32_t __shlr(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __shlr(uint32_t __data) {
__asm("shlr %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __uint32_t __shar(__uint32_t __data) {
+_LOCAL _ASM_INLINE uint32_t __shar(uint32_t __data) {
__asm("shar %0" : "+r"(__data));
return (__data); }
@@ -782,16 +810,16 @@ _LOCAL _ASM_INLINE __uint32_t __shar(__uint32_t __data) {
#if __NDIC_CLIP
#elif __GNUC_ASM
-_LOCAL _ASM_INLINE __int32_t __clipsb(__int32_t __data) {
+_LOCAL _ASM_INLINE int32_t __clipsb(int32_t __data) {
__asm("clips.b %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __int32_t __clipsw(__int32_t __data) {
+_LOCAL _ASM_INLINE int32_t __clipsw(int32_t __data) {
__asm("clips.w %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __int32_t __clipub(__int32_t __data) {
+_LOCAL _ASM_INLINE int32_t __clipub(int32_t __data) {
__asm("clipu.b %0" : "+r"(__data));
return (__data); }
-_LOCAL _ASM_INLINE __int32_t __clipuw(__int32_t __data) {
+_LOCAL _ASM_INLINE int32_t __clipuw(int32_t __data) {
__asm("clipu.w %0" : "+r"(__data));
return (__data); }
diff --git a/modules/compiler/host-gcc-sh/bits/varargs.h b/modules/compiler/host-gcc-sh/bits/varargs.h
deleted file mode 100644
index ef6f9ed..0000000
--- a/modules/compiler/host-gcc-sh/bits/varargs.h
+++ /dev/null
@@ -1,3 +0,0 @@
-/* GCC has abandoned this header. */
-
-#error "GCC no longer implements <varargs.h>, please use <stdarg.h>."
diff --git a/modules/compiler/host-gcc-sh/copyright.yml b/modules/compiler/host-gcc-sh/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/compiler/host-gcc-sh/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/compiler/host-gcc-sh/info.yml b/modules/compiler/host-gcc-sh/info.yml
deleted file mode 100644
index 59827c6..0000000
--- a/modules/compiler/host-gcc-sh/info.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Host compiler bits for GCC for the SuperH architecture.
-license: free
-requires:
- host-compiler:
- - ['GNU', 'GCC']
- arch: [sh]
diff --git a/modules/compiler/host-gcc-sh/module.toml b/modules/compiler/host-gcc-sh/module.toml
new file mode 100644
index 0000000..e0d4a1a
--- /dev/null
+++ b/modules/compiler/host-gcc-sh/module.toml
@@ -0,0 +1,21 @@
+magic = "potatosdk-1.0"
+desc = "Host compiler bits for GCC for the SuperH architecture."
+license = "free"
+
+[requires]
+host-compiler = ["GNU", "GCC"]
+arch = ["sh"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "smachine.h"
+role = "Privileged SuperH intrinsics."
+
+[[bits]]
+path = "umachine.h"
+role = "Usermode SuperH intrinsics."
diff --git a/modules/compiler/host-gcc-sh/roles.yml b/modules/compiler/host-gcc-sh/roles.yml
deleted file mode 100644
index 5451182..0000000
--- a/modules/compiler/host-gcc-sh/roles.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-bits:
- types:
- exact.h: exact-width compiler types.
- fast.h: fast-width compiler types.
- least.h: least-width compiler types.
- max.h: maximum-width compiler types.
- ptr.h: pointer compiler types.
diff --git a/modules/compiler/host-gcc/bits/stdarg.h b/modules/compiler/host-gcc/bits/stdarg.h
index 0091e72..90f9873 100644
--- a/modules/compiler/host-gcc/bits/stdarg.h
+++ b/modules/compiler/host-gcc/bits/stdarg.h
@@ -5,12 +5,15 @@
typedef __builtin_va_list va_list;
/* Open and close a variable argument list. */
+
# define va_start(_AP, _PARAM) __builtin_va_start(_AP, _PARAM)
# define va_end(_AP) __builtin_va_end(_AP)
/* Obtain an argument from the variable argument list. */
+
# define va_arg(_AP, _TYPE) __builtin_va_arg(_AP, _TYPE)
/* Copy a variable argument list. */
-# define va_copy(_D, _S) __builtin_va_copy(_D, _S)
+
+# define __va_copy(_D, _S) __builtin_va_copy(_D, _S)
#endif
diff --git a/modules/compiler/host-gcc/copyright.yml b/modules/compiler/host-gcc/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/compiler/host-gcc/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/compiler/host-gcc/info.yml b/modules/compiler/host-gcc/info.yml
deleted file mode 100644
index 2247150..0000000
--- a/modules/compiler/host-gcc/info.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Host compiler bits for GCC.
-license: free
-requires:
- host-compiler:
- - ['GNU', 'GCC']
diff --git a/modules/compiler/host-gcc/module.toml b/modules/compiler/host-gcc/module.toml
new file mode 100644
index 0000000..73eaf4a
--- /dev/null
+++ b/modules/compiler/host-gcc/module.toml
@@ -0,0 +1,56 @@
+magic = "potatosdk-1.0"
+desc = "Host compiler bits for GCC."
+license = "free"
+
+[requires]
+host-compiler = ["GNU", "GCC"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "types/exact.h"
+role = "Exact-width compiler types."
+
+[[bits]]
+path = "types/fast.h"
+role = "Fast-width compiler types."
+
+[[bits]]
+path = "types/least.h"
+role = "Least-width compiler types."
+
+[[bits]]
+path = "types/max.h"
+role = "Maximum-width compiler types."
+
+[[bits]]
+path = "types/ptr.h"
+role = "Pointer compiler types."
+
+[[bits]]
+path = "alloca.h"
+role = "Static memory allocation."
+
+[[bits]]
+path = "attrs.h"
+role = "Compiler attributes."
+
+[[bits]]
+path = "compiler.h"
+role = "Compiler definition."
+
+[[bits]]
+path = "endian.h"
+role = "Endianness definition."
+
+[[bits]]
+path = "stdarg.h"
+role = "Variadic arguments management."
+
+[[bits]]
+path = "varargs.h"
+role = "Old-style variadic arguments management."
diff --git a/modules/compiler/host-gcc/roles.yml b/modules/compiler/host-gcc/roles.yml
deleted file mode 100644
index 5451182..0000000
--- a/modules/compiler/host-gcc/roles.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-bits:
- types:
- exact.h: exact-width compiler types.
- fast.h: fast-width compiler types.
- least.h: least-width compiler types.
- max.h: maximum-width compiler types.
- ptr.h: pointer compiler types.
diff --git a/modules/compiler/host-renesas/copyright.yml b/modules/compiler/host-renesas/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/compiler/host-renesas/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/compiler/host-renesas/info.yml b/modules/compiler/host-renesas/info.yml
deleted file mode 100644
index 8113c4b..0000000
--- a/modules/compiler/host-renesas/info.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Host compiler bits for SHC.
-license: free
-requires:
- host-compiler:
- - ['Hitachi', 'SHC']
- - ['Renesas', 'SHC']
diff --git a/modules/compiler/host-renesas/module.toml b/modules/compiler/host-renesas/module.toml
new file mode 100644
index 0000000..400933e
--- /dev/null
+++ b/modules/compiler/host-renesas/module.toml
@@ -0,0 +1,56 @@
+magic = "potatosdk-1.0"
+desc = "Host compiler bits for Renesas' SHC."
+license = "free"
+
+[requires]
+host-compiler = [["Hitachi", "SHC"], ["Renesas", "SHC"]]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "types/exact.h"
+role = "Exact-width compiler types."
+
+[[bits]]
+path = "types/fast.h"
+role = "Fast-width compiler types."
+
+[[bits]]
+path = "types/float.h"
+role = "Floating-point compiler types."
+
+[[bits]]
+path = "types/least.h"
+role = "Least-width compiler types."
+
+[[bits]]
+path = "types/max.h"
+role = "Maximum-width compiler types."
+
+[[bits]]
+path = "types/ptr.h"
+role = "Pointer compiler types."
+
+[[bits]]
+path = "compiler.h"
+role = "Compiler definition."
+
+[[bits]]
+path = "endian.h"
+role = "Endianness definition."
+
+[[bits]]
+path = "stdarg.h"
+role = "Variadic arguments management."
+
+[[bits]]
+path = "smachine.h"
+role = "Privileged SuperH intrinsics."
+
+[[bits]]
+path = "umachine.h"
+role = "Usermode SuperH intrinsics."
diff --git a/modules/compiler/host-renesas/roles.yml b/modules/compiler/host-renesas/roles.yml
deleted file mode 100644
index f143f99..0000000
--- a/modules/compiler/host-renesas/roles.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-%YAML 1.2
----
-
diff --git a/modules/compiler/info.yml b/modules/compiler/info.yml
deleted file mode 100644
index 6dfaa3f..0000000
--- a/modules/compiler/info.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: >-
- Meta-system for modules that are compiler-dependant.
-default:
-- compiler/host-gcc
-- compiler/host-renesas
-- compiler/target-gcc-sh
-- compiler/target-renesas
diff --git a/modules/compiler/system.toml b/modules/compiler/system.toml
new file mode 100644
index 0000000..0a3a8db
--- /dev/null
+++ b/modules/compiler/system.toml
@@ -0,0 +1,6 @@
+magic = "potatosdk-1.0"
+desc = "Meta-system for modules that are compiler-dependant."
+
+default = ["compiler/host-gcc", "compiler/host-gcc-sh",
+ "compiler/target-gcc-sh", "compiler/host-renesas",
+ "compiler/target-renesas"]
diff --git a/modules/compiler/target-gcc-sh/bits/types/primitive.h b/modules/compiler/target-gcc-sh/bits/types/primitive.h
new file mode 100644
index 0000000..9579094
--- /dev/null
+++ b/modules/compiler/target-gcc-sh/bits/types/primitive.h
@@ -0,0 +1,61 @@
+/* Char type. */
+
+#define char int8_t
+#define schar int8_t
+#define uchar uint8_t
+
+#define __CHAR_WIDTH ( 8)
+#define __CHAR_MIN (-128)
+#define __CHAR_MAX (+127)
+#define __UCHAR_MIN ( 0)
+#define __UCHAR_MAX ( 255)
+
+#if defined(__CHAR_UNSIGNED)
+# define __CHAR_IS_SIGNED 0
+#else
+# define __CHAR_IS_SIGNED 1
+#endif
+
+/* Short type. */
+
+#define short __int16_t
+#define ushort __uint16_t
+
+#define __SHRT_WIDTH ( 16)
+#define __SHRT_MIN (-32768)
+#define __SHRT_MAX (+32767)
+#define __USHRT_MIN ( 0)
+#define __USHRT_MAX ( 65535)
+
+/* Int type. */
+
+#define int __int32_t
+#define uint __uint32_t
+
+#define __INT_WIDTH ( 32)
+#define __INT_MIN (-2147483648)
+#define __INT_MAX (+2147483647)
+#define __UINT_MIN ( 0)
+#define __UINT_MAX ( 4294967295)
+
+/* Long type. */
+
+#define long __int32_t
+#define ulong __uint32_t
+
+#define __LONG_WIDTH ( 32)
+#define __LONG_MIN (-2147483648)
+#define __LONG_MAX (+2147483647)
+#define __ULONG_MIN ( 0)
+#define __ULONG_MAX ( 4294967295)
+
+/* Long long type. */
+
+#define llong __int64_t
+#define ullong __uint64_t
+
+#define __LLONG_WIDTH ( 64)
+#define __LLONG_MIN (-9223372036854775808)
+#define __LLONG_MAX (+9223372036854775807)
+#define __ULLONG_MIN ( 0)
+#define __ULLONG_MAX ( 18446744073709551615)
diff --git a/modules/compiler/target-gcc-sh/module.toml b/modules/compiler/target-gcc-sh/module.toml
new file mode 100644
index 0000000..f9ba915
--- /dev/null
+++ b/modules/compiler/target-gcc-sh/module.toml
@@ -0,0 +1,17 @@
+magic = "potatosdk-1.0"
+desc = "Target compiler bits for GCC."
+license = "free"
+
+[requires]
+compiler = [["Hitachi", "SHC"], ["Renesas", "SHC"]]
+arch = ["sh"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "types/primitive.h"
+role = "Primitive types."
diff --git a/modules/compiler/target-renesas/bits/primitive.h b/modules/compiler/target-renesas/bits/types/primitive.h
index e1b3410..e1b3410 100644
--- a/modules/compiler/target-renesas/bits/primitive.h
+++ b/modules/compiler/target-renesas/bits/types/primitive.h
diff --git a/modules/compiler/target-renesas/copyright.yml b/modules/compiler/target-renesas/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/compiler/target-renesas/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/compiler/target-renesas/info.yml b/modules/compiler/target-renesas/info.yml
deleted file mode 100644
index 2e47754..0000000
--- a/modules/compiler/target-renesas/info.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: Target compiler bits for SHC.
-license: free
-requires:
- compiler:
- - ['Hitachi', 'SHC']
- - ['Renesas', 'SHC']
diff --git a/modules/compiler/target-renesas/module.toml b/modules/compiler/target-renesas/module.toml
new file mode 100644
index 0000000..57c3962
--- /dev/null
+++ b/modules/compiler/target-renesas/module.toml
@@ -0,0 +1,16 @@
+magic = "potatosdk-1.0"
+desc = "Target compiler bits for SHC."
+license = "free"
+
+[requires]
+compiler = [["Hitachi", "SHC"], ["Renesas", "SHC"]]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "types/primitive.h"
+role = "Primitive types."
diff --git a/modules/compiler/target-renesas/roles.yml b/modules/compiler/target-renesas/roles.yml
deleted file mode 100644
index f143f99..0000000
--- a/modules/compiler/target-renesas/roles.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-%YAML 1.2
----
-
diff --git a/modules/renesas/errno/copyright.yml b/modules/renesas/errno/copyright.yml
deleted file mode 100644
index ce52c6a..0000000
--- a/modules/renesas/errno/copyright.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-%YAML 1.2
----
-files: '*'
-copyright:
-- [2017, 2018, Thomas Touhey, thomas@touhey.fr]
diff --git a/modules/renesas/errno/info.yml b/modules/renesas/errno/info.yml
deleted file mode 100644
index 2028021..0000000
--- a/modules/renesas/errno/info.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: The Renesas style of error numbers.
-license: free
-requires:
- deps: ['all/errno']
diff --git a/modules/renesas/errno/module.toml b/modules/renesas/errno/module.toml
new file mode 100644
index 0000000..b75b9d9
--- /dev/null
+++ b/modules/renesas/errno/module.toml
@@ -0,0 +1,20 @@
+magic = "potatosdk-1.0"
+desc = "The Renesas style of error numbers."
+license = "free"
+
+[requires]
+deps = ["all/errno"]
+
+[[copyrights]]
+begin = 2017
+end = 2018
+name = "Thomas Touhey"
+mail = "thomas@touhey.fr"
+
+[[bits]]
+path = "errno.h"
+role = "Renesas' error codes."
+
+[[source]]
+path = "errlist.c"
+role = "Renesas' error descriptions."
diff --git a/modules/renesas/errno/roles.yml b/modules/renesas/errno/roles.yml
deleted file mode 100644
index a5c0814..0000000
--- a/modules/renesas/errno/roles.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-%YAML 1.2
----
-bits:
- errno.h: Renesas' error codes.
-src:
- errlist.c: Renesas' error descriptions.
diff --git a/modules/renesas/errno/src/errlist.c b/modules/renesas/errno/src/errlist.c
index a8feb5b..edd0cf1 100644
--- a/modules/renesas/errno/src/errlist.c
+++ b/modules/renesas/errno/src/errlist.c
@@ -3,7 +3,7 @@
#define R5(E) E, E, E, E, E
#define R8(E) R5(E), E, E, E
-#define R9(E) R8(E), E
+#define R9(E) R5(E), E, E, E, E
#define R10(E) R5(E), R5(E)
#define R50(E) R10(E), R10(E), R10(E), R10(E), R10(E)
#define R90(E) R50(E), R10(E), R10(E), R10(E), R10(E)
diff --git a/modules/renesas/info.yml b/modules/renesas/info.yml
deleted file mode 100644
index 2d39bda..0000000
--- a/modules/renesas/info.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-description: >-
- Meta-system for modules representing bits of Renesas' generated C libraries.
-default:
-- renesas/errno
-import:
-- all
diff --git a/modules/renesas/system.toml b/modules/renesas/system.toml
new file mode 100644
index 0000000..01428c0
--- /dev/null
+++ b/modules/renesas/system.toml
@@ -0,0 +1,7 @@
+magic = "potatosdk-1.0"
+desc = """
+Meta-system for modules representing bits of Renesas' generated C
+libraries. """
+
+default = ["renesas/errno"]
+import = ["all"]
diff --git a/project.toml b/project.toml
new file mode 100644
index 0000000..e0931ba
--- /dev/null
+++ b/project.toml
@@ -0,0 +1,19 @@
+magic = "potatosdk-1.0"
+maintainer = "ttouhey"
+
+[version]
+major = 0
+minor = 1
+indev = true
+
+[locations]
+docroot = "docs"
+modules = "modules"
+build = "build"
+authors = "authors.toml"
+config = ".config.toml"
+
+[[copyrights]]
+begin = 2017
+end = 2018
+ent = "ttouhey"
diff --git a/project.yml b/project.yml
deleted file mode 100644
index 5ac1482..0000000
--- a/project.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-%YAML 1.2
----
-magic: potatosdk-1.0
-maintainer: [Thomas "Cakeisalie5" Touhey, thomas@touhey.fr]
-version:
- major: 0
- minor: 1
- indev: true
-locations:
- docroot: docs
- modules: modules
- config: .config.yml
- build: build
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index 5500f00..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1 +0,0 @@
-PyYAML
diff --git a/tools/Internals/__init__.py b/tools/Internals/__init__.py
deleted file mode 100755
index da93167..0000000
--- a/tools/Internals/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/usr/bin/env python3
-import sys
-
-from .exceptions import *
-from .args import *
-from .copyright import *
-from .gettext import *
-
-from .arch import *
-from .project import *
-from .config import *
-from .topc import *
-from .cache import *
-from .headers import *
-
-import Internals.build as tools
-
-# End of file.
diff --git a/tools/Internals/arch.py b/tools/Internals/arch.py
deleted file mode 100755
index 2aee0f4..0000000
--- a/tools/Internals/arch.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/env python3
-
-__all__ = ["get_arch_detail"]
-
-# The architecture detail.
-
-_arch_detail = {
- # Intel's x86 (8080).
-
- 'x86': ('x86', 'i386', 'little'),
- 'i286': ('x86', 'i286', 'little'),
- 'i386': ('x86', 'i386', 'little'),
- 'i486': ('x86', 'i486', 'little'),
- 'i586': ('x86', 'i586', 'little'),
- 'i686': ('x86', 'i686', 'little'),
- 'i786': ('x86', 'i786', 'little'),
-
- # Intel's x86_64 (64-bit version of the x86).
-
- 'x86_64': ('x86_64', None, 'little'),
-
- # Hitachi's SuperH, J-Core.
-
- 'sh': ('sh', None, None),
- 'sh1': ('sh', 'sh1', None),
- 'sh2': ('sh', 'sh2', None),
- 'sh2eb': ('sh', 'sh2', 'big'),
- 'sh2le': ('sh', 'sh2', 'little'),
- 'sh2a': ('sh', 'sh2a', None),
- 'sh2e': ('sh', 'sh2e', None),
- 'sh3': ('sh', 'sh3', None),
- 'sh3eb': ('sh', 'sh3', 'big'),
- 'sh3le': ('sh', 'sh3', 'little'),
- 'sh3e': ('sh', 'sh3e', None),
- 'sh3ele': ('sh', 'sh3e', 'little'),
- 'sh4': ('sh', 'sh4', None),
- 'sh4eb': ('sh', 'sh4', 'big'),
- 'sh4le': ('sh', 'sh4', 'little'),
- 'sh4a': ('sh', 'sh4', None),
-}
-
-_flavours = {
-
-}
-
-def get_arch_detail(arch):
- """ Return the (family, arch, endianness) tuple. """
-
- try: det = _arch_detail[arch]
- except: return None
-
- # XXX: Temporary?
- if not det[1]:
- det = (det[0], det[0], det[2])
- return det
-
-# End of file.
diff --git a/tools/Internals/args.py b/tools/Internals/args.py
deleted file mode 100755
index 7be8ad8..0000000
--- a/tools/Internals/args.py
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env python3
-""" argparse extensions for the libcarrot utilities. """
-
-import os as _os
-import sys as _sys
-import argparse as _argparse
-import platform as _platform
-import re as _re
-from .gettext import gettext
-
-_ = gettext
-
-__all__ = ['CarrotArgumentParser']
-
-class _CarrotHelpFormatter(_argparse.HelpFormatter):
- """ Custom argument parser help message formatter to eliminate some of
- the problems I had with the default one (linked to metavars). """
-
- def __init__(self, *args, **kwargs):
- kwargs['max_help_position'] = 78
- kwargs['width'] = 79
- super(_CarrotHelpFormatter, self).__init__(*args, **kwargs)
-
- def _format_usage(self, usage, actions, groups, prefix):
- if prefix is None:
- prefix = _("Syntax:") + " "
-
- # if usage is specified, use that
- if usage is not None:
- usage = usage % dict(prog=self._prog)
-
- # if no optionals or positionals are available, usage is just prog
- elif usage is None and not actions:
- usage = '%(prog)s' % dict(prog=self._prog)
-
- # if optionals and positionals are available, calculate usage
- elif usage is None:
- prog = '%(prog)s' % dict(prog=self._prog)
-
- # split optionals from positionals
- optionals = []
- positionals = []
- for action in actions:
- if action.option_strings:
- optionals.append(action)
- else:
- positionals.append(action)
-
- # build full usage string
- format = self._format_actions_usage
- action_usage = format(optionals + positionals, groups)
- usage = ' '.join([s for s in [prog, action_usage] if s])
-
- # wrap the usage parts if it's too long
- text_width = self._width - self._current_indent
- if len(prefix) + len(usage) > text_width:
-
- # break usage into wrappable parts
- part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
- opt_usage = format(optionals, groups)
- pos_usage = format(positionals, groups)
- opt_parts = _re.findall(part_regexp, opt_usage)
- pos_parts = _re.findall(part_regexp, pos_usage)
- assert ' '.join(opt_parts) == opt_usage
- assert ' '.join(pos_parts) == pos_usage
-
- # helper for wrapping lines
- def get_lines(parts, indent, prefix=None):
- lines = []
- line = []
- if prefix is not None:
- line_len = len(prefix) - 1
- else:
- line_len = len(indent) - 1
- for part in parts:
- if line_len + 1 + len(part) > text_width and line:
- lines.append(indent + ' '.join(line))
- line = []
- line_len = len(indent) - 1
- line.append(part)
- line_len += len(part) + 1
- if line:
- lines.append(indent + ' '.join(line))
- if prefix is not None:
- lines[0] = lines[0][len(indent):]
- return lines
-
- # if prog is short, follow it with optionals or positionals
- if len(prefix) + len(prog) <= 0.75 * text_width:
- indent = ' ' * (len(prefix) + len(prog) + 1)
- if opt_parts:
- lines = get_lines([prog] + opt_parts, indent, prefix)
- lines.extend(get_lines(pos_parts, indent))
- elif pos_parts:
- lines = get_lines([prog] + pos_parts, indent, prefix)
- else:
- lines = [prog]
-
- # if prog is long, put it on its own line
- else:
- indent = ' ' * len(prefix)
- parts = opt_parts + pos_parts
- lines = get_lines(parts, indent)
- if len(lines) > 1:
- lines = []
- lines.extend(get_lines(opt_parts, indent))
- lines.extend(get_lines(pos_parts, indent))
- lines = [prog] + lines
-
- # join lines into usage
- usage = '\n'.join(lines)
-
- # prefix with 'usage:'
- return '%s%s\n\n' % (prefix, usage)
-
- def _format_action_invocation(self, action):
- """ Format the left part of the optional arguments description.
- Pretty much copied from the official source code, except
- that when we have a metavar, we'll only put the metavar on
- the last element. """
-
- if not action.option_strings:
- default = self._get_default_metavar_for_positional(action)
- metavar, = self._metavar_formatter(action, default)(1)
- return metavar
-
- parts = []
-
- # If the optional doesn't have a value, format is:
- # -s, --long
- # Otherwise, it is:
- # -s, --long ARGS
- # (instead of the default one, `-s ARGS, --long ARGS`)
-
- parts.extend(action.option_strings)
- if action.nargs != 0:
- default = self._get_default_metavar_for_optional(action)
- args_string = self._format_args(action, default)
-
- parts[-1] += ' %s'%args_string
-
- return ', '.join(parts)
-
-class CarrotArgumentGroup(_argparse._ArgumentGroup):
- """ Custom class for managing libcarrot argument groups. """
-
- def add_argument(self, *names, **kwargs):
- """ Add an argument. """
-
- public_names = []
- hidden_names = []
- for name in names:
- if name.startswith('/'):
- hidden_names.append('-' + name[1:])
- else:
- public_names.append(name)
-
- if public_names:
- super(CarrotArgumentGroup, self).add_argument(*public_names,
- **kwargs)
- if hidden_names:
- kwargs['help'] = _argparse.SUPPRESS
- super(CarrotArgumentGroup, self).add_argument(*hidden_names,
- **kwargs)
-
-class CarrotArgumentParser(_argparse.ArgumentParser):
- """ Custom class for libcarrot argument parsing. """
-
- def __init__(self, prog=None, description=None, usage=None):
- """ Initialize the argument parser object. """
-
- # Get the prefix chars.
- prefix_chars = '-'
- if _platform.system == "Windows":
- prefix_chars += '/'
-
- # Get the program name.
- if prog == None:
- try: prog = _os.environ['PROGNAME']
- except: prog = _os.path.basename(_sys.argv[0])
-
- super(CarrotArgumentParser, self).__init__(prog=prog, usage=usage,
- description=description, prefix_chars=prefix_chars,
- formatter_class=_CarrotHelpFormatter, add_help=False)
-
- self._action_groups = []
- self._positionals = \
- self.add_argument_group(_("Positional arguments"))
- self._optionals = \
- self.add_argument_group(_("Optional arguments"))
- self.add_argument('-h', '/?', '--help', dest='carrot_help',
- action='help', help=_("show this help message and exit"))
-
- def add_argument(self, *names, **kwargs):
- """ Add an argument. """
-
- public_names = []
- hidden_names = []
- for name in names:
- if name.startswith('/'):
- hidden_names.append('-' + name[1:])
- else:
- public_names.append(name)
-
- if public_names:
- super(CarrotArgumentParser, self).add_argument(*public_names,
- **kwargs)
- if hidden_names:
- kwargs['help'] = _argparse.SUPPRESS
- super(CarrotArgumentParser, self).add_argument(*hidden_names,
- **kwargs)
-
- def add_argument_group(self, *args, **kwargs):
- group = CarrotArgumentGroup(self, *args, **kwargs)
- self._action_groups.append(group)
- return group
-
-# End of file.
diff --git a/tools/Internals/build/__init__.py b/tools/Internals/build/__init__.py
deleted file mode 100755
index 7921baf..0000000
--- a/tools/Internals/build/__init__.py
+++ /dev/null
@@ -1,329 +0,0 @@
-#!/usr/bin/env python3
-""" This is the main build tool directory/interface.
- See `docs/tools/build-tools.en.md` for more details.
-"""
-
-import os, sys, functools as ft
-from subprocess import call
-
-from ..exceptions import *
-
-# ---
-# Get and list the tools.
-# ---
-
-from .gnu_gcc import *
-from .gnu_as import *
-from .gnu_ar import *
-#from .renesas_shc import *
-#from .renesas_asmsh import *
-#from .renesas_optlnk import *
-
-_tools = {
- ('GNU', 'GCC'): GNU_GCC,
- ('GNU', 'as'): GNU_AS,
- ('GNU', 'ar'): GNU_AR,
-# ('LLVM', 'Clang'): LLVM_Clang,
-# ('Renesas', 'SHC'): Renesas_SHC,
-# ('Hitachi', 'SHC'): Renesas_SHC,
-# ('Renesas', 'Asmsh'): Renesas_Asmsh,
-# ('Hitachi', 'Asmsh'): Renesas_Asmsh,
-# ('Renesas', 'Optlnk'): Renesas_OptLnk,
-# ('Hitachi', 'Optlnk'): Renesas_OptLnk,
-# ('Intel', 'ICC'): Intel_ICC,
-# ('IBM', 'XL C'): IBM_XLC,
-# ('IBM', 'XL C/C++'): IBM_XLC,
-# ('SDCC', 'SDCC'): SDCC_SDCC,
-# ('Borland', 'Turbo C'): Borland_TurboC,
-# ('Borland', 'Turbo C++'): Borland_TurboCpp,
-# ('Bellard', 'TCC'): Bellard_TCC,
-# ('Lifeboat', 'Lattice C'): SAS_C,
-# ('SAS', 'SAS/C'): SAS_C,
-# ('Bell Labs', '0c'): Plan9_CC, -- little-endian MIPS 3000 family
-# ('Bell Labs', 'vc'): Plan9_CC, -- big-endian MIPS 3000 family
-# ('Bell Labs', '1c'): Plan9_CC, -- Motorola MC68000
-# ('Bell Labs', '2c'): Plan9_CC, -- Motorola MC68020
-# ('Bell Labs', '5c'): Plan9_CC, -- little-endian ARM
-# ('Bell Labs', '6c'): Plan9_CC, -- AMD64 and compatibles
-# ('Bell Labs', '7c'): Plan9_CC, -- Digital Alpha APX
-# ('Bell Labs', '8c'): Plan9_CC, -- Intel i386, i486, Pentium, etc.
-# ('Bell Labs', '9c'): Plan9_CC, -- 64-bit PowerPC
-# ('Bell Labs', 'kc'): Plan9_CC, -- Sun (now Oracle) SPARC
-# ('Bell Labs', 'qc'): Plan9_CC, -- PowerPC
-}
-
-# ---
-# Find the utilities.
-# ---
-
-def _find_cc(arch, endian, system, flavour, standard):
- """ Find a C compiler. """
-
- for cc in _tools:
- try: gp = _tools[cc]['conf_cc']
- except: continue
- try: cp = gp(arch, endian, system, flavour, standard)
- except ToolNotFoundException:
- continue
-
- return (cc, cp)
-
- Raise(NoCCompilerException)
-
-def _find_cxx(arch, endian, system, flavour, standard):
- """ Find a C++ compiler. """
-
- for cxx in _tools:
- try: gp = _tools[cxx]['conf_cxx']
- except: continue
- try: cxxp = gp(arch, endian, system, flavour, standard)
- except ToolNotFoundException:
- continue
-
- return (cxx, cxxp)
-
- Raise(NoCppCompilerException)
-
-def _find_asm(arch, endian, system, flavour, syntax):
- """ Find an assembler. """
-
- for asm in _tools:
- try: gp = _tools[asm]['conf_asm']
- except: continue
- try: asmp = gp(arch, endian, system, flavour, syntax)
- except ToolNotFoundException:
- continue
-
- return (asm, asmp)
-
- Raise(NoAssemblerException)
-
-def _find_pack(arch, endian, system, flavour):
- """ Find a packer. """
-
- for pack in _tools:
- try: gp = _tools[pack]['conf_pack']
- except: continue
- try: packp = gp(arch, endian, system, flavour)
- except ToolNotFoundException:
- continue
-
- return (pack, packp)
-
- Raise(NoPackerException)
-
-def _find_link(arch, endian, system, flavour, abi):
- """ Find a dynamic library generator. """
-
- for link in _tools:
- try: gp = _tools[link]['conf_link']
- except: continue
- try: linkp = gp(arch, endian, system, flavour, abi)
- except ToolNotFoundException:
- continue
-
- return (link, linkp)
-
- Raise(NoLinkException)
-
-def _find_bin(arch, endian, system, flavour, abi):
- """ Find a binary executable generator. """
-
- for bing in _tools:
- try: gp = _tools[bing]['conf_bin']
- except: continue
- try: binp = gp(arch, endian, system, flavour, abi)
- except ToolNotFoundException:
- continue
-
- return (bing, binp)
-
- Raise(NoBinException)
-
-# ---
-# Iterate on operations.
-# ---
-
-def get_build_operations(build_dir, modules):
- """ Iterate on the operations to do. """
-
- __cxx_ext = ['cpp', 'CPP', 'cc', 'CC', 'cp', 'CP', 'cxx', 'CXX',
- 'c++', 'C++']
-
- for name, module in map(lambda x: (x, modules[x]), sorted(modules)):
- namepts = name.split('/')
- modbdir = os.path.join(build_dir, *namepts)
-
- for source in module.getfiles('src', ['c']):
- srcpath = module.getpath('src', source)
- objpath = os.path.join(modbdir, '{}.o'.format(source))
-
- try: objmtime = os.path.getmtime(objpath)
- except: objmtime = -1
- try: srcmtime = os.path.getmtime(srcpath)
- except: srcmtime = 0
-
- # TODO: headers dependencies.
-
- if objmtime < srcmtime:
- yield ('cc', module, source)
-
- for source in module.getfiles('src', __cxx_ext):
- srcpath = module.getpath('src', source)
- objpath = os.path.join(modbdir, '{}.o'.format(source))
-
- try: objmtime = os.path.getmtime(objpath)
- except: objmtime = -1
- try: srcmtime = os.path.getmtime(srcpath)
- except: srcmtime = 0
-
- # TODO: headers dependencies.
-
- if objmtime < srcmtime:
- yield ('cxx', module, source)
-
- for source in module.getfiles('src', 's'):
- srcpath = module.getpath('src', source)
- objpath = os.path.join(modbdir, '{}.o'.format(source))
-
- try: objmtime = os.path.getmtime(objpath)
- except: objmtime = -1
- try: srcmtime = os.path.getmtime(srcpath)
- except: srcmtime = 0
-
- # TODO: headers dependencies.
-
- if objmtime < srcmtime:
- yield ('asm', module, source)
-
- # TODO: linking operation
-
-# ---
-# Interact with the tools before using them.
-# ---
-
-# The tools.
-_current_tools = {}
-__compiler = '(none)'
-
-def find(languages, arch, endian, system, abi, flavour):
- """ Find tools. """
-
- ids, params = {}, {}
-
- ids['cc'], params['cc'] = \
- _find_cc(arch, endian, system, flavour, 'c89')
-# ids['cxx'], params['cxx'] = \
-# _find_cxx(arch, endian, system, flavour, 'c++98')
- ids['asm'], params['asm'] = \
- _find_asm(arch, endian, system, flavour, 'gnu')
- ids['pack'], params['pack'] = \
- _find_pack(arch, endian, system, flavour)
-# ids['link'], params['link'] = \
-# _find_link(arch, endian, system, flavour, abi)
-# ids['bin'], params['bin'] = \
-# _find_bin(arch, endian, system, flavour, abi)
-
- return {'ids': ids, 'params': params}
-
-def setup(data):
- """ Setup the tools. """
-
- global _current_tools, __compiler
-
- ids = data['ids']
- params = data['params']
-
- # Get the C compiler.
- if 'cc' in ids:
- cc, cp = ids['cc'], params['cc']
- _current_tools['cc'] = \
- ft.partial(_tools[cc]['cc'], cp)
- __compiler = ids['cc']
-
- # Get the C++ compiler.
- if 'cxx' in ids:
- cxx, cxxp = ids['cxx'], params['cxx']
- _current_tools['cxx'] = \
- ft.partial(_tools[cxx]['cxx'], cxxp)
-
- # Get the assembler.
- if 'asm' in ids:
- asm, asmp = ids['asm'], params['asm']
- _current_tools['asm'] = \
- ft.partial(_tools[asm]['asm'], asmp)
-
- # Get the packer.
- if 'pack' in ids:
- pack, packp = ids['pack'], params['pack']
- _current_tools['pack'] = \
- ft.partial(_tools[pack]['pack'], packp)
-
- # Get the linker.
- if 'link' in ids:
- link, linkp = ids['link'], params['link']
- _current_tools['link'] = \
- ft.partial(_tools[link]['link'], linkp)
-
- # Get the binary executable generator.
- if 'bin' in ids:
- bing, binp = ids['bin'], params['bin']
- _current_tools['bin'] = \
- ft.partial(_tools[bing]['bin'], binp)
-
-def get(key):
- """ Get an information. """
-
- cpp_ext = ['cpp', 'CPP', 'cc', 'CC', 'cp', 'CP', 'cxx', 'CXX',
- 'c++', 'C++']
-
- return {
- # Compiler ID
- 'compiler': __compiler,
-
- # Extensions
- 'obj_ext': 'o',
- 'lib_ext': 'a',
- 'cc_ext': ['c', 'CC'],
- 'cxx_ext': cpp_ext,
- 'cpp_ext': cpp_ext,
- 'asm_ext': ['s', 'S'],
- }[key]
-
-# ---
-# Build things.
-# ---
-
-def cc(obj, src, incdirs=[], std='c89'):
- """ Make an object out of a C source file. """
-
- if not 'cc' in _current_tools:
- print("No C compiler has been setup!")
- Raise(SilentException)
- return _current_tools['cc'](obj, src, incdirs, std)
-
-def cxx(obj, src, incdirs=[], std='c++98'):
- """ Make an object out of a C++ source file. """
-
- if not 'cxx' in _current_tools:
- print("No C++ compiler has been setup!")
- Raise(SilentException)
- return _current_tools['cxx'](obj, src, indirs, std)
-
-def asm(obj, src):
- """ Make an object out of an assembly source file. """
-
- if not 'asm' in _current_tools:
- print("No assembler has been setup!")
- Raise(SilentException)
- return _current_tools['asm'](obj, src)
-
-def pack(lib, objs):
- """ Pack objects in a library. """
-
- if not 'pack' in _current_tools:
- print("No packer has been setup!")
- Raise(SilentException)
- return _current_tools['pack'](lib, objs)
-
-# End of file.
diff --git a/tools/Internals/build/gnu_ar.py b/tools/Internals/build/gnu_ar.py
deleted file mode 100755
index c296a94..0000000
--- a/tools/Internals/build/gnu_ar.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the GNU archive manager, part of GNU binutils,
- to the libcarrot build tools.
-
- When configured for a non-native target, as for all GNU Binutils elements,
- GCC will install the binary as `<bfd target>-ar`, so we're looking for
- something like `<arch>-<os or format>-ar`, e.g. `sh3eb-elf-ar` for
- system-independent assembler for the SuperH Core 3, big endian version,
- generating ELF object files or executables.
-
- If there is no appropriate non-native target, the native assembler might
- just be usable. We just have to check the BFD target in GNU ar's help
- message (non-translated version).
-"""
-
-import os
-import tempfile
-from subprocess import call, check_output
-from .utils import *
-
-__all__ = ["GNU_AR"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def __get_ar_targets(path):
- """ Get the supported targets (flavours) out of the ar binary path. """
-
- # Make the help command with the default locale, get the output.
- env = os.environ.copy()
- try: del env['LANG']
- except KeyError: pass
- out = check_output([path, '--help'], env=env).decode()
-
- # Get the targets from the appropriate lines.
- targets = set()
- for line in out.splitlines():
- if not line.startswith("ar: supported targets: "):
- continue
- targets = targets.union(line[23:].split())
-
- # Return the found targets.
- return list(targets)
-
-def _configure(arch, endian, system, flavour):
- """ Get the params. """
-
- # Prepare the BFD targets.
- bfd = prepare_bfd(arch, endian, system, flavour)
- art = prepare_ar(arch, endian, system, flavour)
-
- # Get the utility
- path = None
- for gar in getgnu('ar', bfd):
- target_list = __get_ar_targets(gar)
-
- for target in target_list:
- if not check_ar(art, target):
- continue
-
- path = gar
- break
-
- if path: break
-
- if not path:
- Raise(ToolNotFoundException)
-
- return {'path': path}
-
-# ---
-# Usage.
-# ---
-
-def _pack(params, lib, objs):
- """ Pack using the GNU archiver. """
-
- # Set up the MRI script.
- tmp_fd, tmp_path = tempfile.mkstemp(suffix='.mri')
- tmp = os.fdopen(tmp_fd, mode='w')
- print('CREATE %s'%lib, file=tmp)
- for obj in objs:
- print('ADDMOD %s'%obj, file=tmp)
- print('SAVE', 'END', sep='\n', file=tmp)
- tmp.close()
-
- # Set up the command line.
- commandline = [params['path'], '-M']
-
- # Make the call.
- ret = call(commandline, stdin=open(tmp_path))
- os.remove(tmp_path)
- return ret
-
-# ---
-# Main utility descriptor.
-# ---
-
-GNU_AR = {
- 'conf_pack': _configure,
- 'pack': _pack
-}
-
-# End of file.
diff --git a/tools/Internals/build/gnu_as.py b/tools/Internals/build/gnu_as.py
deleted file mode 100755
index 265616f..0000000
--- a/tools/Internals/build/gnu_as.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the GNU assembler, part of GNU binutils,
- to the libcarrot build tools.
-
- When configured for a non-native target, as for all GNU Binutils elements,
- GCC will install the binary as `<bfd target>-as`, so we're looking for
- something like `<arch>-<os or format>-as`, e.g. `sh3eb-elf-as` for
- system-independent assembler for the SuperH Core 3, big endian version,
- generating ELF object files or executables.
-
- If there is no appropriate non-native target, the native assembler might
- just be usable. We just have to check the BFD target in GNU as' version
- message (non-translated version).
-"""
-
-import os
-from subprocess import call, check_output
-from .utils import *
-
-__all__ = ["GNU_AS"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def __get_as_bfd(path):
- """ Get the BFD target out of the `as` binary path. """
-
- # Make the version command with the default locale, get the output.
- env = os.environ.copy()
- try: del env['LANG']
- except KeyError: pass
- out = check_output([path, '--version'], env=env).decode()
-
- # Get the BFD target, which is on the last line, e.g.
- # This assembler was configured for a target of `sh3eb-elf'.
- return out.splitlines()[-1].split('`')[1].split("'")[0]
-
-def __iter_as(arch):
- """ Iterate through all of the `as` occurrences among the system. """
-
- for elt in getgnu('as', bfd):
- yield elt
-
-def _configure(arch, endian, system, flavour, syntax):
- """ Get the assembler parameters. """
-
- # Check the object format.
- # TODO: some configurations of AS produce other formats such as PE...?
- if syntax != 'gnu':
- raise ToolNotFound
-
- # Get the BFD object.
- bfd = prepare_bfd(arch, endian, system, flavour)
-
- # Get the utility.
- path = None
- for gas in getgnu('as', bfd):
- found_target = __get_as_bfd(gas)
-
- if not check_bfd(bfd, found_target):
- continue
-
- path = gas
- break
- if not path:
- Raise(ToolNotFoundException)
-
- # Get the flags.
- flags = []
- if arch[-3:] == 'dsp':
- flags.append('-dsp')
- arch = arch[:-3]
- flags += ['--isa=' + arch, '--big']
-
- return {'path': path, 'flags': flags}
-
-# ---
-# Usage.
-# ---
-
-def _asm(params, obj, src):
- """ Assemble using the GNU assembler. """
-
- # Set up the command line.
- commandline = [params['path']]
- commandline += ['-c', '-o', obj, src]
- commandline += params['flags']
-
- # Make the call.
- return call(commandline)
-
-# ---
-# Main utility descriptor.
-# ---
-
-GNU_AS = {
- 'conf_asm': _configure,
- 'asm': _asm
-}
-
-# End of file.
diff --git a/tools/Internals/build/gnu_gcc.py b/tools/Internals/build/gnu_gcc.py
deleted file mode 100755
index 10db87e..0000000
--- a/tools/Internals/build/gnu_gcc.py
+++ /dev/null
@@ -1,170 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the GNU Compiler Collection, more precisely
- the C/C++ compiler, to the libcarrot build tools.
-
- When configured for a non-native target, GCC will install its binary as
- `<bfd target>-gcc` in the host binary directory, so we're looking for
- something like `<arch>-<os or format>-gcc`, e.g. `sh3eb-elf-gcc` for
- system-independent gcc for the SuperH Core 3, big endian version,
- generating ELF object files or executables.
-
- If there is no appropriate non-native target, the native compiler might
- just be usable. We just have to check the BFD target using
- GCC's `-dumpmachine` option.
-"""
-
-import os
-from subprocess import call, check_output, DEVNULL
-from tempfile import mkstemp
-from .utils import *
-
-__all__ = ["GNU_GCC"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def __get_gcc_bfd(path):
- """ Get the BFD target out of the gcc binary path. """
-
- # Make the dump command with the default locale, get the output.
- env = os.environ.copy()
- try: del env['LANG']
- except KeyError: pass
- out = check_output([path, '-dumpmachine'], env=env).decode()
-
- return out.strip()
-
-def __testcc(typ, path, flags=[],
- text='int main(void) { return (0); }'):
- """ Try to compile, see if it works. """
-
- if typ == "cc":
- source_suffix = '.c'
- gcc_lang = 'c'
- elif typ == "cxx":
- source_suffix = '.cpp'
- gcc_lang = 'c++'
-
- sfd, sf = mkstemp(suffix=source_suffix, text=text)
- os.close(sfd)
-
- ofd, of = mkstemp(suffix='.o')
- os.close(ofd)
-
- cl = [path, '-x', gcc_lang, '-c', '-o', of, sf] \
- + flags + ['-nostdlib', '-ffreestanding']
- if call(cl, shell=False, stdout=DEVNULL, stderr=DEVNULL):
- worked = False
- else:
- worked = True
-
- try: os.remove(of)
- except: pass
- try: os.remove(sf)
- except: pass
-
- return worked
-
-def __teststd(typ, path, standard):
- ''' Test if GCC supports those standards using the `-std` option. '''
-
- return __testcc(typ, path, ['-std={}'.format(standard)])
-
-def _configure(typ, arch, endian, system, flavour, standard):
- """ Get the GNU Compiler Collection respecting some
- pre-defined constraints. """
-
- # Prepare the minimum compilation flags.
- cflags = []
- if arch[:2] == 'sh':
- cflags += ['-mhitachi', '-fomit-frame-pointer']
- cflags.append('-mb' if endian == 'big' else '-ml')
- if arch[-3:] == 'dsp':
- cflags.append('-Wa,-dsp')
- arch = arch[:-3]
- cflags += ['-m%s'%arch[2:], '-m' + 'bl'[endian == 'little']]
- else:
- # FIXME: is it like this for everything? raise exception here?
- cflags.append('-march=%s'%arch)
-
- # Get the BFD object.
- bfd = prepare_bfd(arch, endian, system, flavour)
-
- # Get the utility.
- path = None
- for gcc in getgnu('gcc', bfd):
- found_target = __get_gcc_bfd(gcc)
- if not check_bfd(bfd, found_target):
- continue
- if not __testcc(typ, gcc, cflags):
- continue
- if not __teststd(typ, gcc, standard):
- continue
-
- path = gcc
- break
- if not path:
- Raise(ToolNotFoundException)
-
- # TODO: check the standard.
- cflags += ['-std={}'.format(standard)]
-
- # Get the rest of the compilation flags.
- # TODO: use `-ffreestanding` (implies `-fno-builtin`?)
- cflags += ['-Wall', '-Wextra', '-Wno-attributes',
- '-O2', '-nostartfiles', '-fno-builtin-function']
-
- return {'path': path, 'flags': cflags}
-
-def _configure_cc(arch, endian, system, flavour, standard):
- return _configure('cc', arch, endian, system, flavour, standard)
-
-def _configure_cxx(arch, endian, system, flavour, standard):
- return _configure('cxx', arch, endian, system, flavour, standard)
-
-# ---
-# Use the parameters.
-# ---
-
-def _makeenv(incdirs):
- incpath = os.pathsep.join(incdirs)
- env = os.environ.copy()
- env['CPATH'] = incpath
- env['C_INCLUDE_PATH'] = incpath
- env['CPLUS_INCLUDE_PATH'] = incpath
- return env
-
-def _cc(params, obj, src, incdirs, std):
- ''' Compile a C file. '''
-
- # Set up the command line.
- commandline = [params['path'], '-x', 'c', '-std=' + std, '-pedantic']
- commandline += ['-c', '-o', obj, src]
- commandline += params['flags']
-
- # Make the call.
- return call(commandline, env=_makeenv(incdirs))
-
-def _cxx(params, obj, src, incdirs, std):
- # Set up the command line.
- commandline = [params['path'], '-x', 'c++', '-std=' + std, '-pedantic']
- commandline += ['-c', '-o', obj, src]
- commandline += params['flags']
-
- # Make the call.
- return call(commandline, env=_makeenv(incdirs))
-
-# ---
-# Main utility descriptor.
-# ---
-
-GNU_GCC = {
- 'conf_cc': _configure_cc,
- 'conf_cxx': _configure_cxx,
-
- 'cc': _cc,
- 'cxx': _cxx,
-}
-
-# End of file.
diff --git a/tools/Internals/build/gnu_ld.py b/tools/Internals/build/gnu_ld.py
deleted file mode 100644
index 4e05d5c..0000000
--- a/tools/Internals/build/gnu_ld.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the GNU linker, part of GNU binutils,
- to the libcarrot build tools.
-
- When configured for a non-native target, as for all GNU Binutils elements,
- GCC will install the binary as `<bfd target>-ld`, so we're looking for
- something like `<arch>-<os or format>-ld`, e.g. `sh3eb-elf-ld` for
- system-independent assembler for the SuperH Core 3, big endian version,
- generating ELF object files or executables.
-
- If there is no appropriate non-native target, the native assembler might
- just be usable. We just have to check the BFD target in GNU ld's version
- message (non-translated version).
-"""
-
-import os
-from subprocess import call, check_output
-
-__all__ = ["GNU_LD"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def __get_ld_bfd(path):
- """ Get the BFD target out of the `ld` binary path. """
-
- # Make the version command with the default locale, get the output.
- env = os.environ.copy()
- try: del env['LANG']
- except KeyError: pass
- out = check_output([path, '--help'], env=env).decode()
-
- # Get the targets from the appropriate lines.
- targets = set()
- for line in out.splitlines():
- if not line.startswith("ld: supported targets: "):
- continue
- targets = targets.union(line[23:].split())
-
- # Return the found targets.
- return list(targets)
-
-def _configure(arch, endian, system, flavour):
- """ Get the params. """
-
- # Prepare the BFD targets.
- bfd = prepare_bfd(arch, endian, system, flavour)
- art = prepare_ar(arch, endian, system, flavour)
-
- # Get the utility.
- path = None
- for gld in getgnu('ld', bfd):
- target_list = __get_ld_targets(gld)
-
- for target in target_list:
- if not check_ar(art, target):
- continue
-
- path = gld
- break
-
- if path: break
-
- if not path:
- Raise(ToolNotFoundException)
-
- return {'path': path}
-
-# ---
-# Usage.
-# ---
-
-# TODO
-
-# ---
-# Main utility descriptor.
-# ---
-
-GNU_LD = {
- 'conf_link': _configure
-}
-
-# End of file.
diff --git a/tools/Internals/build/renesas_asmsh.py b/tools/Internals/build/renesas_asmsh.py
deleted file mode 100755
index af68c09..0000000
--- a/tools/Internals/build/renesas_asmsh.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the Renesas SuperH proprietary Assembler to
- the libcarrot build tools.
-
- You can find more information about this assembler in the toolchain manual:
- https://bible.planet-casio.com/renesas/rej10b0152_sh.pdf
-"""
-
-import os, tempfile
-from subprocess import call
-from .utils import *
-
-__all__ = ["Renesas_Asmsh"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def _configure(arch, endian, obj_format, std):
- ''' Get the parameters. '''
-
- if arch[:2] != 'sh':
- raise UnsupportedArchException(arch)
-
- # Get the tool.
- try: asmsh = next(getutil(['asmsh']))
- except StopIteration: Raise(ToolNotFoundException)
-
- CPU = arch.upper()
- flags = ['-cpu=%s'%arch, '-endian={}'.format(endian),
- '-round=zero', '-denormalize=off', '-literal=pool,branch,jump,return',
- '-chgincpath', '-errorpath']
- if arch[-3:] == 'dsp':
- flags.append('-dspc')
-
- return {'path': asmsh, 'CPU': CPU, 'flags': flags}
-
-# ---
-# Usage.
-# ---
-
-def _asm(self, obj, src, incdirs):
- ''' Assemble a source assembly file. '''
-
- # `asmsh.exe` doesn't support double extensions such as `.src.obj`,
- # so let's make a simple `.obj` file, and rename it.
- d = os.path.join(os.path.dirname(obj), '')
- tmpobj = obj[len(d):]
- tmpobj = '.'.join([tmpobj.split('.')[0], 'obj'])
- tmpobj = os.path.join(d, tmpobj)
-
- # Make the temporary thing with all of the subcommands.
- tmpinfo = tempfile.mkstemp()
- tmp = os.fdopen(tmpinfo[0], mode='w')
- print(src, 'object="%s"'%tmpobj,
- '-nologo', '-nodebug', '-nolist', *params['flags'],
- sep=os.linesep, file=tmp)
- tmp.close()
-
- # Edit the environment.
- env = os.environ.copy()
- env['SHCPU'] = params['CPU']
- env['SHC_LIB'] = os.path.dirname(params['path'])
- env['SHC_INC'] = os.pathsep.join(incdirs)
- env['SHC_TMP'] = tempfile.gettempdir()
-
- # Make the command line.
- commandline = [self.util['asmsh']]
- commandline += ['-subcommand=' + tmpinfo[1]]
-
- # Open the subprocess
- ret = call(commandline, env=env)
- os.remove(tmpinfo[1])
- if ret: return ret
-
- # Rename the final file, and return.
- os.rename(tmpobj, obj)
- return ret
-
-# ---
-# Main utility descriptor.
-# ---
-
-Renesas_Asmsh = {
- 'conf_asm': _configure,
- 'asm': _asm
-}
-
-# End of file.
diff --git a/tools/Internals/build/renesas_optlnk.py b/tools/Internals/build/renesas_optlnk.py
deleted file mode 100755
index 27245a2..0000000
--- a/tools/Internals/build/renesas_optlnk.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the Renesas SuperH proprietary Optimizing Linker
- (and archiver) to the libcarrot build tools.
-
- You can find more information about this tool in the toolchain manual:
- https://bible.planet-casio.com/renesas/rej10b0152_sh.pdf
-
- [FIXME]
- It occurred in some early tests that Optlnk doesn't accept files with
- same names. Still, Simon Lothar on Casiopeia gave me some commands for
- adding modules in HLIB libraries:
-
- > http://www.casiopeia.net/forum/viewtopic.php?f=25&t=1804
-
- Still, it probably won't solve the "duplicate module" issue...
- we should probably randomize the names a little, crop and add a random
- suffix to the names, or else?
-"""
-
-import os, tempfile
-from subprocess import call
-from .utils import *
-
-__all__ = ["Renesas_OptLnk"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def _configure(arch, endian, lib_format, obj_format):
- ''' Get the parameters. '''
-
- # Check the format.
- if lib_format != 'HLIB' or obj_format != 'ELF':
- Raise(ToolNotFoundException)
-
- # Check the path.
- try: optlnk = next(getutil(['optlnk']))
- except: Raise(ToolNotFoundException)
-
- # Return the parameters.
- return {'path': optlnk}
-
-# ---
-# Usage.
-# ---
-
-def _pack(params, lib, objs):
- ''' Pack the object files into an archive. '''
-
- # Make the temporary thing with all of the subcommands.
- tmpinfo = tempfile.mkstemp(suffix='.sub')
- tmp = os.fdopen(tmpinfo[0], mode='w')
- print('noprelink', 'nomessage', 'nologo', sep='\n', file=tmp)
- print('form library=s', 'output "%s"'%lib, sep='\n', file=tmp)
- for obj in objs:
- print('input="%s"'%obj, file=tmp)
- print('exit', file=tmp)
- tmp.close()
-
- # Make the command line.
- commandline = [params['path']]
- commandline += ['-subcommand=' + tmpinfo[1]]
-
- # Open the subprocess
- ret = call(commandline)
- os.remove(tmpinfo[1])
- return ret
-
-# ---
-# Main utility descriptor.
-# ---
-
-Renesas_OptLnk = {
- 'conf_pack': _configure,
- 'pack': _pack
-}
-
-# End of file.
diff --git a/tools/Internals/build/renesas_shc.py b/tools/Internals/build/renesas_shc.py
deleted file mode 100755
index 223802a..0000000
--- a/tools/Internals/build/renesas_shc.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/env python3
-""" These functions bring the Renesas SuperH C/C++ proprietary compiler to
- the libcarrot build tools.
-
- This compiler is bundled with some other binary utilities in the
- CASIO fx-9860G SDK, and only supports the oldest C and C++ standards.
-
- You can find more information about this compiler in the toolchain manual:
- https://bible.planet-casio.com/renesas/rej10b0152_sh.pdf
-"""
-
-import os
-from subprocess import call as _call
-from .utils import *
-
-__all__ = ["Renesas_SHC"]
-
-# ---
-# Discovery, configuration.
-# ---
-
-def _configure(typ, arch, endian, objfmt, std):
- """ Get the parameters. """
-
- # Check the architecture, the output format, and the standards.
- if arch[:2] != 'sh' or objfmt != 'elf' or \
- (typ == "cc" and std != ['c89']) or (typ == "cxx" and std != ['c++98']):
- Raise(ToolNotFoundException)
-
- # Get the tool path.
- try: shc = next(getutil(['shc']))
- except StopIteration: Raise(ToolNotFoundException)
-
- # Get the flags.
- CPU = arch.upper()
- flags = ['-cpu=%s'%arch, '-endian={}'.format(endian), '-size',
- '-gbr=auto', '-noinline']
- if arch[-3:] == 'dsp':
- flags.append('-dspc')
-
- return {'path': shc, 'CPU': CPU, 'flags': flags}
-
-def _configure_cc(args):
- return _configure('c', *args)
-def _configure_cxx(args):
- return _configure('cxx', *args)
-
-# ---
-# Usage.
-# ---
-
-def _cc(params, obj, src, incdirs, std):
- """ Compile a C source file into an object file. """
-
- # Make the temporary thing with all of the subcommands.
- tmpinfo = tempfile.mkstemp()
- tmp = os.fdopen(tmpinfo[0], mode='w')
- print(src, '-object="%s"'%obj, '-lang=c',
- '-nodebug', '-nologo', '-chgincpath', '-errorpath', *params['flags'],
- sep=os.linesep, file=tmp)
- tmp.close()
-
- # Edit the environment.
- env = os.environ.copy()
- env['SHCPU'] = params['CPU']
- env['SHC_LIB'] = os.path.dirname(params['path'])
- env['SHC_INC'] = os.pathsep.join(incdirs)
- env['SHC_TMP'] = tempfile.gettempdir()
-
- # Make the command line.
- commandline = [params['path']]
- commandline += ['-subcommand=' + tmpinfo[1]]
-
- # Open the subprocess
- ret = call(commandline, env=env)
- os.remove(tmpinfo[1])
- if ret: return ret
-
-def _cxx(self, obj, src, incdirs=[]):
- """ Compile a C++ file. """
-
- # Make the temporary thing with all of the subcommands.
- tmpinfo = tempfile.mkstemp()
- tmp = os.fdopen(tmpinfo[0], mode='w')
- print(src, '-object="%s"'%obj, '-lang=cpp', *params['flags'],
- sep=os.linesep, file=tmp)
- tmp.close()
-
- # Edit the environment.
- env = os.environ.copy()
- env['SHCPU'] = params['CPU']
- env['SHC_LIB'] = os.path.dirname(params['path'])
- env['SHC_INC'] = os.pathsep.join(incdirs)
- env['SHC_TMP'] = tempfile.gettempdir()
-
- # Make the command line.
- commandline = [params['path']]
- commandline += ['-subcommand=' + tmpinfo[1]]
-
- # Open the subprocess
- ret = call(commandline, env=env)
- os.remove(tmpinfo[1])
- return ret
-
-# ---
-# Main utility descriptor.
-# ---
-
-Renesas_SHC = {
- 'conf_cc': _configure_cc,
- 'conf_cxx': _configure_cxx,
-
- 'cc': _cc,
- 'cxx': _cxx
-}
-
-# End of file.
diff --git a/tools/Internals/build/utils/__init__.py b/tools/Internals/build/utils/__init__.py
deleted file mode 100755
index 7197546..0000000
--- a/tools/Internals/build/utils/__init__.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env python3
-""" Utilities for the build tools.
-"""
-
-import os, platform
-from .bfd import *
-from ...exceptions import *
-
-# ---
-# Path management.
-# ---
-
-__path = os.environ['PATH'].split(os.pathsep) if 'PATH' in os.environ else []
-
-def add_tooldir(tooldir):
- global __path
- if tooldir:
- __path.append(tooldir)
-
-# ---
-# Tool searching functions.
-# ---
-
-def _getutil(match_func):
- """ Generic tool searching function. """
-
- for udir in __path:
- for tool in os.listdir(udir):
- path = tool
- if path[-4:] == ".exe" and platform.system() == "Windows":
- path = path[:-4]
- if path[-4:] == ".elf" and platform.system() == "Linux":
- path = path[:-4]
- if not match_func(tool):
- continue
- yield os.path.join(udir, path)
-
-def getutil(tools):
- """ General tool searching function. """
-
- mt = lambda x: x in tools
- for x in _getutil(mt):
- yield x
-
-def getgnu(tool, tg):
- """ GNU tool searching function. """
-
- nl = len(tool)
- def mt(x):
- if x == tool:
- return True
- if x[-nl-1:] != "-" + tool:
- return False
- if check_bfd(tg, x[:-nl-1]):
- return True
- return False
-
- for x in _getutil(mt):
- yield x
-
-# End of file.
diff --git a/tools/Internals/build/utils/bfd.py b/tools/Internals/build/utils/bfd.py
deleted file mode 100755
index ddb623f..0000000
--- a/tools/Internals/build/utils/bfd.py
+++ /dev/null
@@ -1,150 +0,0 @@
-#!/usr/bin/env python3
-""" BFD are at the core of the portability of the GNU toolchain.
- "Binary Format Description" serves as a backronym for it.
- Basically, the BFD layer (represented by libbfd) is the abstraction
- to 'real' file formats that the GNU toolchain uses.
-
- BFD targets usually have the following information:
- - Instruction Set Architecture (ISA), referred as "architecture" here;
- - Endianness, in the cases where the architecture is bi-endian;
- - System (ABI) for which the utilities build;
- - Flavour, representing the formats used by the configuration.
-
- The GNU toolchain (usually GCC and GNU binutils) binaries are either
- presented as native binaries (`gcc`) or as cross-compiling utilities,
- with the BFD target as a prefix (e.g. `sh3eb-elf-gcc`).
-
- This file contains a set of functions that will make a list of
- BFD targets for a given configuration, and check if a given BFD target
- corresponds to the configuration using the previously generated list.
-"""
-
-import itertools as _itertools
-from ...exceptions import *
-from ...arch import get_arch_detail
-
-# ---
-# Reference.
-# ---
-
-# Known BFD Instruction Set Architectures (ISA).
-#
-# The correspondances make BFD architecture names correspond to a
-# (family, model, endianness) tuple.
-# If the endianness is `None`, it means it is unknown/supports both little
-# and big endian.
-
-_bfd_archs = {
- # Generic families.
-# 'big': (None, None, 'big'),
-# 'little': (None, None, 'little'),
-
- # Intel x86_64 (8080).
- 'x86': ('x86', 'i386', 'little'),
- 'i386': ('x86', 'i386', 'little'),
- 'i486': ('x86', 'i486', 'little'),
- 'i586': ('x86', 'i586', 'little'),
- 'i686': ('x86', 'i686', 'little'),
- 'i786': ('x86', 'i787', 'little'),
-
- # Intel x86_64.
- 'x86_64': ('x86_64', None, 'little'),
-
- # Hitachi SuperH.
- 'sh': ('sh', None, None),
- 'sh1': ('sh', 'sh1', None),
- 'sh2': ('sh', 'sh2', None),
- 'sh2a': ('sh', 'sh2a', None),
- 'sh2e': ('sh', 'sh2e', None),
- 'sh2eb': ('sh', 'sh2', 'big'),
- 'sh2le': ('sh', 'sh2', 'little'),
- 'sh3': ('sh', 'sh3', None),
- 'sh3eb': ('sh', 'sh3', 'big'),
- 'sh3le': ('sh', 'sh3', 'little'),
- 'sh3e': ('sh', 'sh3e', None),
- 'sh3ele': ('sh', 'sh3e', 'little'),
- 'sh4': ('sh', 'sh4', None),
- 'sh4a': ('sh', 'sh4a', None),
- 'sh4eb': ('sh', 'sh4e', 'big'),
- 'sh4le': ('sh', 'sh4e', 'little'),
-}
-
-_bfd_sys = {
- 'linux': ('linux',),
- 'w32': ('win32',),
- 'w64': ('win64',),
-
- 'elf': ('casiowin',),
-}
-
-# Flavours are basically the binary formats the compiler/archive manager
-# can output. There are a few, plus aliases.
-
-_flavours = {
- 'elf': ('elf32', None),
- 'elf32': ('elf32', None),
- 'elf64': ('elf64', None),
- 'gnu': ('elf32', 'linux'),
- 'mingw32': ('coff', 'win32'),
- 'a.out': ('a.out', None),
- 'coff': ('coff', None),
-
-# 'plugin', 'srec', 'symbolsrec', 'verilog', 'tekhex', 'binary', 'ihex'
-}
-
-# ---
-# Prepare and check BFD targets.
-# ---
-
-def prepare_bfd(arch, endian, system, flavour):
- """ Make a list of BFDs that could correspond to the
- given configuration. """
-
- fam, arch, _ = get_arch_detail(arch)
-
- # Make the arch table.
- al = []
- for an, (af, _, ae) in _bfd_archs.items():
- if af != fam:
- continue
- al.append(an)
-
- # Make the system table.
- sl = []
- for sn, sr in _bfd_sys.items():
- if not system in sr:
- continue
- sl.append(sn)
-
- # Combine the two.
- targets = []
- for arch, system in _itertools.product(al, sl):
- targets.extend(('{}-{}'.format(arch, system),))
-
- return targets
-
-def check_bfd(bfds, raw):
- """ Check if the BFD target is in the given BFDs. """
-
- return raw in bfds
-
-# ---
-# Prepare and check AR targets.
-# ---
-
-def prepare_ar(arch, endian, system, flavour):
- """ Make a list of GNU ar targets that could correspond to the given
- configuration. """
-
- fam, arch, _ = get_arch_detail(arch)
- if flavour == "elf":
- flavour = "elf32"
- res = ['{}-{}'.format(flavour, fam)]
- return res
-
-def check_ar(targets, raw):
- """ Check if the AR target is in the given targets. """
-
- return raw in targets
-
-# End of file.
diff --git a/tools/Internals/build/utils/formats.py b/tools/Internals/build/utils/formats.py
deleted file mode 100755
index 3162f18..0000000
--- a/tools/Internals/build/utils/formats.py
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env python3
-""" The list of known formats the tools can use/produce, and their extensions.
- This file should probably be re-worked on some day.
-"""
-
-# This file contains the list of formats these tools can use/produce,
-# with their extensions.
-
-# ---
-# Archive formats.
-# ---
-
-__archive_formats = {
- # Proprietary lib format used by Hitachi's tools.
- 'hlib': ['rlib', 'lib'],
-
- # Unix formats.
- 'coff': ['a'],
- 'a.out': ['a']
-}
-
-# ---
-# Object formats.
-# ---
-
-__object_formats = {
- 'pe': ['obj'],
- 'elf': ['o', 'obj', 'robj'],
-}
-
-# End of file.
diff --git a/tools/Internals/cache.py b/tools/Internals/cache.py
deleted file mode 100755
index 18e4f6f..0000000
--- a/tools/Internals/cache.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python3
-""" Simple cache management for the library.
-"""
-
-import os as _os
-import copy as _copy
-import yaml as _yaml
-
-class CacheManager:
- """ The cache manager. """
-
- __default_cache_path = _os.path.join(_os.path.dirname(__file__),
- '..', '..', '.cache.yml')
-
- def __init__(self, path=__default_cache_path):
- """ Load the cache. """
-
- try: data = _yaml.load(open(path).read())
- except FileNotFoundError: data = {}
- if data == None: data = {}
-
- self.__path = path
- self.__categories = {}
- for key in data:
- if type(data[key]) != dict:
- continue
- self.__categories[key] = data[key]
-
- def get(self, name, default={}):
- """ Get a specific cache out of the overall cache folder. """
-
- if not name in self.__categories:
- return default
- return _copy.deepcopy(self.__categories[name])
-
- def set(self, name, cache):
- """ Set the cache. """
-
- if type(cache) != dict:
- raise Exception("[INT] Cache setting argument should be a dict")
- self.__categories[name] = _copy.deepcopy(cache)
-
- def save(self):
- """ Save the cache. """
-
- with open(self.__path, 'w') as out:
- print(_yaml.dump(self.__categories,
- version=(1, 2), width=60), file=out, end='')
-
- def __del__(self):
- """ Don't forget to save it. """
-
- self.save()
-
-# End of file.
diff --git a/tools/Internals/config.py b/tools/Internals/config.py
deleted file mode 100755
index 8752b11..0000000
--- a/tools/Internals/config.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python3
-""" The user configuration management object.
-
- The format of this configuration is described in `docs/config.en.md`.
-"""
-
-import yaml
-
-__all__ = ["UserConfig"]
-
-class UserConfig:
- """ The user configuration class.
- Extracts data from the file, and offer utilities to interact
- with its elements easily. """
-
- def __init__(self, path = None, orig = None):
- """ Initialize the class.
- `path` is the user configuration file path. """
-
- self.path = path
- self.orig = orig
-
- def load(self):
- """ Gather the information from the configuration,
- and deduce properties out of it. """
-
- # Load the configuration.
- try:
- raw = yaml.load(open(self.path))
- except (NotADirectoryError, FileNotFoundError):
- Raise(ConfigNotFoundException(self.path))
-
- # Check the magic.
- if 'magic' in raw and raw['magic'] != 'potatosdk-1.0':
- Raise(ConfigNotFoundException(path))
-
- # Modules.
- self.modules = []
- if 'modules' in raw:
- self.modules = raw['modules']
-
- # Tools.
- self.tools = {}
- if 'tools' in raw:
- self.tools = raw['tools']
-
- def write(self):
- """ Write the configuration as a YAML file. """
-
- config = {
- 'magic': 'potatosdk-1.0',
- 'paths': {
- 'source': self.source,
- 'cache': self.cache,
- 'build': self.build,
- },
- 'tools': self.tools,
- 'modules': modules,
- 'orig': self.orig
- }
-
- with open(self.path, "w") as out:
- print(yaml.dump(config, version=(1, 2), width=60),
- file=out, end='')
-
-# End of file.
diff --git a/tools/Internals/copyright.py b/tools/Internals/copyright.py
deleted file mode 100755
index b7f9285..0000000
--- a/tools/Internals/copyright.py
+++ /dev/null
@@ -1,204 +0,0 @@
-#!/usr/bin/env python3
-""" Get the copyright rules from a root, and get the copyright rules on a file.
- Based on the `copyright.yml` files -- see `FORMAT.md` for its description.
-"""
-
-import os as _os
-import re as _re
-import fnmatch as _fnmatch
-import datetime as _datetime
-import yaml as _yaml
-
-from .exceptions import *
-
-__all__ = ["get_copyright_rules", "get_copyright", "merge_copyrights"]
-
-__default_maintainer = ((2016, _datetime.date.today().year),
- 'Thomas "Cakeisalie5" Touhey', 'thomas@touhey.fr')
-
-# ---
-# Gather the copyright rules from the filesystem.
-# ---
-
-def get_copyright_rules(root):
- """ Get the copyright rules from a root. """
-
- root = _os.path.join(root, '')
- rules = {}
-
- # Copyright file thing.
- for rt, _, _ in _os.walk(root):
- # Ignore file.
- try:
- with open(_os.path.join(rt, '.gitignore')) as f:
- rulz = []
- for line in f.readlines():
- # Get what's before the comment.
- line = _re.sub('([^\\\\](\\\\\\\\)*)#.*$', '\\1', line)
- line = _re.sub('\\\\(.*)', '\\1', line)
- line = line.strip()
-
- if line: rulz.append(line)
-
- for l in rulz:
- if l[0] == '/':
- nm = l[1:].split('/')
- bases = [_os.path.join(rt, *nm)]
- else:
- nm = l.split('/')
- bases = [_os.path.join(rt, *nm),
- _os.path.join(rt, '**', *nm)]
-
- for base in bases:
- rules[base] = '===IGNORED==='
- except FileNotFoundError:
- pass
-
- # Copyright file.
- try:
- with open(_os.path.join(rt, 'copyright.yml')) as f:
- d_rules = _yaml.load_all(f.read())
-
- # Read each rule.
- for rule in d_rules:
- ml = rule['files']
- if type(ml) != list:
- ml = [ml]
-
- l = rule['license'] if 'license' in rule else 'LGPL-3'
- authors = []
- if 'copyright' in rule:
- for author in rule['copyright']:
- if len(author) == 3:
- authors.append(((author[0], author[0]),
- author[1], author[2]))
- else:
- authors.append(((author[0], author[1]),
- author[2], author[3]))
- if not authors:
- authors.append(__default_maintainer)
-
- for m in ml:
- spl = m.split('/')
- m = _os.path.join(rt, *spl)
- rules[m] = {'authors': authors, 'license': l}
- except FileNotFoundError:
- pass
-
- return rules
-
-# ---
-# Get a file's copyright from the copyright rules obtained before.
-# ---
-
-def __match(rule, path):
- """ Check if a path matches a rule. """
-
- # Check if the full path is matched.
- if _fnmatch.fnmatch(path, rule):
- return True
-
- # Check if one of the parent directories is matched.
- while True:
- dirname, filename = _os.path.split(path)
- if not dirname: break
- if _fnmatch.fnmatch(dirname, rule):
- return True
- path = dirname
-
- # Nothing is matched. Exit!
- return False
-
-def get_copyright(rules, path):
- """ Get a path's copyright using a set of rules. """
-
- if not _os.path.isfile(path):
- raise NotAFileException
- if _os.path.basename(path) == 'copyright.yml':
- raise IgnoredFileException
-
- match = None
-
- for rule in rules:
- # Check if the rule matches the path.
- if not __match(rule, path):
- continue
-
- # Check if it is the first thing.
- if not match:
- match = rule
- continue
-
- # If the current rule is more precise, take it instead.
- # TODO: of course that length rule is stupid and doesn't take into
- # account things such as "arch/**/info.yml is more precise than
- # arch/mysystem/mymodule/*", but it's a quick hack.
- if len(rule) > len(match):
- match = rule
-
- if not match:
- raise NoCopyrightException
- rule = rules[match]
- if rule == '===IGNORED===':
- raise IgnoredFileException
- return (rule['authors'], rule['license'])
-
-# ---
-# Merge file copyrights.
-# ---
-
-def __merge_copyright_dates(dates, dont_be_precise=True):
- """ Merge copyright dates.
- If `dont_be_precise` is False, [(2013, 2014), (2015, 2016)] will
- be left as is (otherwise, is turned as [(2013, 2016)]). """
-
- dates = sorted(dates, key=lambda x:x[0])
-
- fn = [dates[0]]
- for start, end in dates[1:]:
- last_start, last_end = fn[-1]
-
- if dont_be_precise: start -= 1
- if start <= last_end and end >= last_end:
- fn[-1] = (last_start, end)
- else:
- fn.append((start, end))
- return fn
-
-def merge_copyrights(first, second, *others):
- """ Merge copyright tuples returned by `get_copyright()`. """
-
- # Check if there is more than two arguments.
- if others:
- first = merge_copyrights(first, second)
- for other in others:
- first = merge_copyrights(first, other)
- return first
-
- f_authors, f_license = first['authors'], first['license']
- s_authors, s_license = second['authors'], second['license']
-
- # Check that the licenses are compatible.
- # TODO: for now, it's stupid.
- if f_license != s_license:
- raise IncompatibleLicensesException(f_license, s_license)
-
- # Get the authors and all of their copyright dates.
- authors = {}
- for (start, end), name, mail in f_authors + s_authors:
- if not (name, mail) in authors:
- authors[name, mail] = []
- authors[name, mail].append((start, end))
-
- # Sort dates.
- for author in authors:
- authors[author] = __merge_copyright_dates(authors[author])
-
- copyrights = []
- for (name, mail), dates in authors.items():
- for start, end in dates:
- copyrights.append(((start, end), name, mail))
-
- return {'authors': copyrights, 'license': f_license}
-
-# End of file.
diff --git a/tools/Internals/exceptions.py b/tools/Internals/exceptions.py
deleted file mode 100755
index a3476fe..0000000
--- a/tools/Internals/exceptions.py
+++ /dev/null
@@ -1,329 +0,0 @@
-#!/usr/bin/env python3
-""" Exceptions that can occur in the libcarrot custom build tools.
- To manage them correctly, you should use the `do_main()` function.
-"""
-
-import sys as _sys
-from .gettext import gettext
-_ = gettext
-
-#*****************************************************************************#
-# Main definitions #
-#*****************************************************************************#
-# Base classes.
-# - `PotatoException` is the main exception class, which stops the program
-# as soon as it is raised.
-# - `PotatoWarning` is the main warning class, which just prints a message
-# when it is raised.
-
-class PotatoException(Exception):
- ''' The base class for PotatoSDK exceptions. '''
-
- ret = 1
- ags = ()
- msg = None
-
- def __init__(self, *args):
- if self.msg == None:
- message = "Internal exception '%s'"%type(self).__name__
- else:
- try: args = self.prepare(args)
- except: pass
-
- kw = dict(zip(self.ags, args))
- message = self.msg.format(**kw)
-
- super(PotatoException, self).__init__(message)
-
-class PotatoWarning(Exception):
- ''' The base class for PotatoSDK warnings. '''
-
- def __init__(self, *args):
- kw = dict(zip(self.ags, args))
- super(PotatoWarning, self).__init__(self.msg.format(**kw))
-
-# Function to raise one of these.
-
-def Raise(exc):
- ''' Raise either a local exception or warning. '''
- try:
- raise exc
- except PotatoWarning as e:
- print(_("Warning:"), str(e), file=_sys.stderr)
-
-# Main function wrapper.
-
-def do_main(main_func):
- ''' The main function wrapper. '''
- try:
- main_func()
- exit(0)
- except SilentException:
- exit(1)
- except PotatoException as e:
- print(_("Error:"), str(e), file=_sys.stderr)
- exit(e.ret)
-#*****************************************************************************#
-# Internal exceptions #
-#*****************************************************************************#
-class ToolNotFoundException(PotatoException):
- """ (internal) A tool was not found! """
-
- ret = 2
-
-class UnknownBFDTargetException(PotatoException):
- """ (internal) A complete BFD architecture could not be worked out. """
-
- ret = 2
-#*****************************************************************************#
-# 'Public' exceptions #
-#*****************************************************************************#
-class SilentException(PotatoException):
- """ The silent exception, for exiting silently (usually because the
- error messages have already been put, eventually by sub-commands. """
-
- def __init__(self):
- super(SilentException, self).__init__("")
-
-# ---
-# Check that the user configuration options are supported.
-# ---
-
-class MissingSystemInTargetException(PotatoException):
- """ The user didn't give the system in the target. """
-
- ret = 2
- ags = ()
- msg = _("Missing system in the target string.")
-
-class RedundantEndiannessException(PotatoException):
- """ The user shouldn't give the endianness again. """
-
- ret = 2
- ags = ()
- msg = _("This architecture does not have a configurable endianness.")
-
-class MissingEndiannessException(PotatoException):
- """ The user should give the endianness again. """
-
- ret = 2
- ags = ()
- msg = _("Missing endianness in the target string.")
-
-class UnsupportedLanguageException(PotatoException):
- """ One of the given languages were unsupported. """
-
- ret = 2
- ags = ('lang',)
- msg = _("Language '{lang}' is unsupported.")
-
-class MissingConfigurationException(PotatoException):
- """ The user didn't configure! """
-
- ret = 2
- msg = _("Please configure beforehand.")
-
-# ---
-# An information file was updated after the user configuration,
-# which means the user should reconfigure!
-# ---
-
-class UpdatedModuleException(PotatoException):
- """ The configuration of a module has been updated since the
- last user configuration. """
-
- ret = 2
- ags = ('mod',)
- msg = _("Module '{mod}' has been modified since last configuration. " \
- "Please reconfigure.")
-
-class UpdatedSystemException(PotatoException):
- """ The configuration of a system has been updated since the
- last user configuration. """
-
- ret = 2
- ags = ('sys',)
- msg = _("System {sys} has been modified since last configuration. " \
- "Please reconfigure.")
-
-class UpdatedGlobalException(PotatoException):
- """ The global configuration has been updated since the
- last user configuration. """
-
- ret = 2
- msg = _("Global structure has been modified since last configuration. " \
- "Please reconfigure.")
-
-# ---
-# Dependency problems.
-# ---
-
-class UnresolvedDependencyException(PotatoException):
- """ A module dependency could not be resolved. """
-
- ret = 2
- ags = ('dep', 'mods')
- msg = _("Dependency '{dep}' from '{mods}' does not exist or could " \
- "not be loaded!")
-
- def prepare(self, dep, mods):
- return (dep, "', '".join(mods))
-
-# ---
-# Command exceptions for utilities.
-# ---
-
-class InvalidCommandException(PotatoException):
- """ The given command was unknown. """
-
- ret = 2
- ags = ('cmd',)
- msg = _("Unknown command '{cmd}'.")
-
-# ---
-# Unsupported architectures or compilers.
-# ---
-
-class UnsupportedArchForSystemException(PotatoException):
- """ A system doesn't support an architecture. """
-
- ags = ('arch', 'end', 'sys',)
- msg = _("System '{sys}' does not support the '{arch}' ({end} endian) " \
- "architecture!")
-
-class UnsupportedArchForModuleException(PotatoWarning):
- """ A module doesn't support an architecture. """
-
- ags = ('mod', 'arch')
- msg = _("Module '{mod}' does not support the '{arch}' architecture!")
-
-class UnsupportedCompilerForModuleException(PotatoWarning):
- """ A module doesn't support a compiler. """
-
- ags = ('mod', 'comp', 'comp_author')
- msg = _("Module '{mod}' doesn't support the '{comp}' compiler from " \
- "'{comp_author}'!")
-
-# ---
-# Could not load global, a system, a module, or the configuration.
-# ---
-
-class GlobalNotFoundException(PotatoException):
- """ The global source directory was invalid. """
-
- ret = 2
- ags = ('global',)
- msg = _("Source folder '{global}' was not found or is invalid!")
-
-class SystemNotFoundException(PotatoException):
- """ The given system was unsupported. """
-
- ret = 2
- ags = ('sys',)
- msg = _("'{sys}' system was not found or is invalid!")
-
-class MetaSystemException(PotatoException):
- """ The given system was a meta system and should be used
- as a target system. """
-
- ret = 2
- ags = ('sys',)
- msg = _("'{sys}' system is a meta-system and should not be used directly!")
-
-class ABINotFound(PotatoException):
- """ The given system did not support the given ABI. """
-
- ret = 2
- ags = ('sys', 'abi')
- msg = _("No such ABI '{abi}' for system '{sys}'!")
-
-class ModuleNotFoundException(PotatoException):
- """ A module was not found! """
-
- ret = 2
- ags = ('mod',)
- msg = _("Module '{mod}' was not found or is invalid!")
-
-class ConfigNotFoundException(PotatoException):
- """ The user configuration was not found! """
-
- ret = 2
- ags = ('path',)
- msg = _("User configuration was not found or is invalid at '{path}'!")
-
-# ---
-# Utilities could not be found.
-# ---
-
-class NoCCompilerException(PotatoException):
- """ No appropriate C compiler was found. """
-
- ret = 2
- msg = _("No appropriate C compiler was found!")
-
-class NoCppCompilerException(PotatoException):
- """ No appropriate C++ compiler was found. """
-
- ret = 2
- msg = _("No appropriate C++ compiler was found!")
-
-class NoCAssemblerException(PotatoException):
- """ No appropriate ASM-C compiler was found. """
-
- ret = 2
- msg = _("No appropriate ASM-C compiler was found!")
-
-class NoAssemblerException(PotatoException):
- """ No appropriate assembler was found. """
-
- ret = 2
- msg = _("No appropriate assembler was found!")
-
-class NoPackerException(PotatoException):
- """ No appropriate packer was found. """
-
- ret = 2
- msg = _("No appropriate packer was found!")
-
-# ---
-# Copyright definition problems.
-# ---
-
-class NoCopyrightException(PotatoException):
- """ No copyright was found for this file. """
-
- ret = 2
- msg = _("No copyright was found for this file.")
-
-class NotAFileException(PotatoException):
- """ Expected a regular file. """
-
- ret = 2
- msg = _("A regular file was expected.")
-
-class IgnoredFileException(PotatoException):
- """ This file should be ignored. """
-
- ret = 2
- msg = _("This file should be ignored.")
-
-class FileNotFoundException(PotatoException):
- """ A file doesn't exist! """
-
- ret = 2
- ags = ('path',)
- msg = _("'{path}': the file doesn't exist!")
-
-# ---
-# Super-preprocessor exceptions.
-# ---
-
-class DuplicateHeaderException(PotatoException):
- """ Duplicate header! """
-
- ret = 2
- ags = ('name', 'first_module', 'second_module')
- msg = _("The '{name}' public header exists in both {first_module} "
- "and {second_module}!")
-
-# End of file.
diff --git a/tools/Internals/gettext.py b/tools/Internals/gettext.py
deleted file mode 100755
index 7acd946..0000000
--- a/tools/Internals/gettext.py
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env python3
-""" The libcarrot version and configuration of gettext. """
-
-__all__ = ["gettext"]
-
-# Placeholder.
-gettext = lambda s: s
-
-# End of file.
diff --git a/tools/Internals/headers/__init__.py b/tools/Internals/headers/__init__.py
deleted file mode 100755
index 107f1c0..0000000
--- a/tools/Internals/headers/__init__.py
+++ /dev/null
@@ -1,411 +0,0 @@
-#!/usr/bin/env python3
-""" The header manager, used for all internal operations.
- Lists headers, opens them (and bits), updates the cache, and stuff.
-
- The includes is a dictionary of {name: details}, where details is a
- dictionary containing the following keys:
-
- - 'bits': the bits name list.
- - 'path': the source file's path.
- - 'mtime': the source file's mtime.
- - 'mname': the module name.
- - 'role': the file's role.
- - 'authors': the copyright list.
- - 'license': the source file's license.
- - 'content': the parsed content of the header.
-
- The bits is a dictionary of {name: [details, ...]}, where each details
- is a dictionary containing the following keys:
-
- - 'path': the bit's path.
- - 'mtime': the bit's mtime.
- - 'authors': the bit's authors.
- - 'license': the bit's license.
- - 'content': the parsed content of the bit.
-"""
-
-import os as _os
-import itertools as _itertools
-
-from .parse import *
-from .output import *
-from .eval import *
-
-from ..topc import *
-from ..copyright import *
-
-#__all__ = ["HeaderManager"]
-
-class HeaderManager:
- _VER = 'blitz'
-
- def __split_path(self, path):
- """ Split a path. """
-
- tree, leaf = _os.path.split(path)
- if not tree: return (leaf,)
- return self.__split_path(tree) + (leaf,)
-
- def __init__(self, outdir, modules, cachemgr):
- """ Initialize the object.
- Loads all of the includes and bits, checks which ones are to
- make again, and other cool stuff. """
-
- # Keep those, they could be useful.
- self.__outdir = outdir
- self.__modules = modules
- self.__cachemgr = cachemgr
-
- # Get the old includes and bits data from the cache.
- self.__cache = self.__cachemgr.get('headers', {})
- if 'magic' not in self.__cache or self.__cache['magic'] != self._VER:
- self.__cache.clear()
- self.__cache['magic'] = self._VER
- if not 'bits' in self.__cache:
- self.__cache['bits'] = {}
- if not 'inc' in self.__cache:
- self.__cache['inc'] = {}
- if not 'out' in self.__cache:
- self.__cache['out'] = ""
-
- # Prepare for the includes and the bits.
- self.__inc = {}
- self.__bits = {}
-
- # Optimized/converted includes.
- self.__made_inc = {}
-
- # Prepare the updated include and bit information.
- self.__updated_inc = []
- self.__updated_bits = []
-
- # Look for all of the includes.
- for module_name, module in modules.items():
- for nm in module.getfiles('include', ext=['h', 'hpp', None]):
- name = '/'.join(self.__split_path(nm))
- if name in self.__inc:
- raise DuplicateHeaderException(name, incs[name][1],
- module_name)
-
- path = module.getpath('include', nm)
- role = module.getrole('include', nm)
- authors, license = module.getcopyright('include', nm)
-
- # Check if should remake.
- updated = False
- if not name in self.__cache['inc'] \
- or inc['mtime'] > self.__cache['inc'][name]['mtime']:
- content = self.__loadinc(path, name)
- bits = self.__listbits(content)
- updated = True # XXX: user's will?
- else:
- content = cache['inc'][name]['content']
- bits = cache['inc'][name]['bits']
-
- for bitname in bits:
- self.__getbits(bitname)
- if bitname in self.__updated_bits:
- updated = True
- for bit in self.__bits[bitname]:
- raw = merge_copyrights(\
- {'authors': authors, 'license': license},
- {'authors': bit['authors'],
- 'license': bit['license']})
- authors = raw['authors']
- license = raw['license']
-
- inc = {
- 'bits': bits,
- 'path': path,
- 'mtime': _os.path.getmtime(path),
- 'mname': module_name,
- 'role': role,
- 'authors': authors,
- 'license': license,
- 'content': content
- }
-
- if name in self.__cache['inc'] \
- and inc != cache['inc'][name]:
- updated = True
-
- if updated:
- self.__updated_inc.append(name)
- self.__inc[name] = inc
-
- def __getbits(self, name):
- """ Gather the bits corresponding to a name. """
-
- if name in self.__bits:
- return self.__bits[name]
-
- bits = []
- name_path = name.split('/')
- name_path = _os.path.join('bits', *name_path)
-
- gbitcache = self.__cache['bits'][name] \
- if name in self.__cache['bits'] else []
-
- for module_name, module in self.__modules.items():
- # Get the bit.
- path = module.getpath(name_path)
- isfl = _os.path.isfile(path)
- if not isfl: continue
-
- # Get the bit cache.
- try:
- bcache = next(i for i in gbitcache if i['path'] == path)
- except StopIteration:
- bcache = {}
-
- authors, license = module.getcopyright(name_path)
- mtime = _os.path.getmtime(path)
-
- if bcache and mtime <= bcache['mtime']:
- content = bcache['content']
- else:
- content = parse_header(path)
-
- bit = {
- 'path': path,
- 'mtime': mtime,
- 'authors': authors,
- 'license': license,
- 'content': content
- }
-
- bits.append(bit)
-
- self.__bits[name] = bits
- if not name in self.__cache['bits'] \
- or self.__bits[name] != self.__cache['bits'][name]:
- self.__updated_bits.append(name)
-
- return bits
-
- def save(self):
- """ Save the data into the cache. """
-
- self.__cachemgr.set('headers', { \
- 'bits': self.__bits, 'inc': self.__inc})
-
- def __loadinc(self, path, name):
- """ Parse a header file, add the include guards. """
-
- # Parse the file.
- content = parse_header(path)
-
- # Return the content.
- return content
-
- def __listbits(self, content):
- """ List all of the `include_bits` parameters in a parsed file.
-
- This is very naïve: even behind impossible conditions, it
- will load the bits, because when this is called, the file
- content isn't optimized yet (as dependency headers might
- not be loaded yet). """
-
- bits = set()
- for line in content:
- if type(line) == CppIncludeBits:
- bits.add(line.name)
- elif type(line) == CppIf:
- for expr, ins in line.conds:
- bits.union(self.__listbits(ins))
- bits.union(self.__listbits(line.eins))
- return bits
-
- def __fusion(self, known, *evolved):
- """ Fusions reference and all evolutions.
- Caution: modifies the first entry! """
-
- # Collect the keys to check.
- keys = set(known)
- for e in evolved:
- keys.union(e)
-
- for key in keys:
- # If key is the same in reference and conditions, do not
- # touch it.
- if all(key in e and e[key] == known[key] for e in evolved):
- continue
-
- # If key has disappeared in at least one of the conditions.
- if key in known and any(not key in e for e in evolved):
- del known[key]
- continue
-
- # If key is the same in all conditions.
- if key in evolved[0] and all(key in e \
- and e[key] == evolved[0][key] for e in evolved[1:]):
- known[key] = evolved[0][key]
- elif all(key in e and e[key] != False for e in evolved):
- known[key] = True
- elif key in known:
- del known[key]
-
- return known
-
- def __loadbits(self, name):
- """ Get the content corresponding to a set of bits. """
-
- ins = []
- first = True
- for bit in self.__bits[name]:
- if not bit['content']: continue
-
- if first: first = False
- else: ins += [CppRaw([""])]
- ins.extend(bit['content'])
-
- return ins
-
- def __process_rec(self, content, known={}):
- """ Process recursively a content, optimize it. """
-
- made = []
- for ins in content:
- if type(ins) == CppDefine:
- if ins.name in known and known[ins.name] != False:
- # FIXME: already defined!
- pass
- known[ins.name] = ins.expr
- made.append(ins)
- elif type(ins) == CppUndef:
- # XXX: not defined?
- known[ins.name] = False
- made.append(ins)
- elif type(ins) == CppInclude:
- # FIXME: profile.
- pass
- elif type(ins) == CppIncludeBits:
- sub = self.__loadbits(ins.name)
- made += self.__process_rec(sub, known)
- elif type(ins) == CppIf:
- conds = ins.conds.copy()
- keep_if = False
- while True:
- if not conds:
- sub = self.__process_rec(ins.eins, known)
- made += sub
- break
-
- cond, sub = conds.pop(0)
- ev = evaluate(cond, known.copy())
-
- if ev == False:
- # always false, just skip.
- continue
- elif ev == True:
- # has been evaluated at always true!
- sub = self.__process_rec(sub, known)
- made += sub
- break
- else:
- # result is unknown.
- # evaluate the rest.
- keep_if = True
- conds.insert(0, (cond, sub))
- break
-
- # Keep the if.
- if keep_if:
- knowns = []
- for i in range(len(conds)):
- knowns.append(known.copy())
- conds[i] = (conds[i][0],
- self.__process_rec(conds[i][1]), knowns[-1])
- knowns.append(known.copy())
- eins = self.__process_rec(ins.eins, knowns[-1])
-
- # Make it evolve.
- known = self.__fusion(known, *knowns)
-
- # Make the 'new' if.
- newif = CppIf(conds[0][0], conds[0][1])
- for cond in conds[1:]:
- newif.addcond(cond[0], cond[1])
- newif.setelse(eins)
- made.append(newif)
- else:
- made.append(ins)
-
- return made
-
- def __makeguards(self, name):
- # Get the include guard.
- if name[-2:].lower() == '.h':
- inc = name[:-2].upper().replace('/', '_')
- #gds = ['_{}_H']
- gds = ['_{}_H', '_{}_H', '__{}_H', '__{}_H__', '_{}', '__{}',
- '__{}_H_INCLUDED__']
- elif name[-4:].lower() == '.hpp':
- inc = name[:-4].upper().replace('/', '_')
- gds = ['_{}_HPP']
- else:
- inc = name.upper().replace('/', '_')
- gds = ['__{}_NOEXT']
-
- return list(map(lambda gd: gd.format(inc), gds))
-
- def __processinc(self, name):
- if name in self.__made_inc:
- return self.__made_inc[name]
-
- # Get the content.
- content = self.__inc[name]['content']
- gds = self.__makeguards(name)
-
- # Define the include guards.
- for gd in gds:
- content[0:0] = [CppDefine(gd, '1')]
-
- # Put the if. (one for all defines)
- conds = ['!defined({})'.format(gds[0])]
- for gd in gds[1:]:
- add = '&& !defined({})'.format(gd)
- if len(conds[-1]) + 1 + len(add) >= 72:
- conds += ['\t' + add]
- else:
- conds[-1] += ' ' + add
- content = [CppIf('\n'.join(conds), content)]
-
- # Then check that all of the include guards are defined.
- if len(gds) >= 2:
- content.append(CppRaw(['',
- '/* Make sure the include guards are defined. */', '']))
- for gd in gds:
- content.append(CppIf(['!defined({})'.format(gd)],
- [CppDefine(gd, '1')]))
-
- # Process through the recursive function.
- self.__made_inc[name] = self.__process_rec(content)
- return self.__made_inc[name]
-
- def makeheader(self, name):
- """ Make a header. """
-
- info = self.__inc[name]
- content = self.__processinc(name)
- topc = make_top_comment(info['mname'], name, info['role'],
- info['authors'], info['license'])
- output_header(topc, content)
-
- def process(self):
- self.makeheader('alloca.h')
- #print(self.__updated_inc)
- pass
-
-# ---
-# Main function.
-# ---
-
-def process_headers(outdir, modules, cachemgr):
- """ Process the headers (public function). """
-
- mgr = HeaderManager(outdir, modules, cachemgr)
- mgr.process()
- mgr.save()
-
-# End of file.
diff --git a/tools/Internals/headers/elements.py b/tools/Internals/headers/elements.py
deleted file mode 100644
index 4a8ceec..0000000
--- a/tools/Internals/headers/elements.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/env python3
-""" Preprocessor instruction types.
-
- Check out "The C Programming Language" section 4.11 for more information
- about the C preprocessor.
-"""
-
-__all__ = ["CppRaw", "CppDefine", "CppUndef", "CppInclude", "CppIncludeBits",
- "CppIf", "CppError"]
-
-class CppRaw:
- """ Raw text left as is by the C preprocessor (said another way,
- not a preprocessor instruction).
-
- The `content` property contains the text separated by Unix-style
- newlines. """
-
- def __init__(self, content):
- self.content = content
-
- def addcontent(self, content):
- self.content += '\n' + content
-
- def __repr__(self):
- return '<CppRaw>'
-
-class CppDefine:
- """ Preprocessor constant or macro definition.
-
- The `name` property is the name of the macro, and `expr` is the
- expression. The `args` property contains either `None` if the macro
- doesn't have arguments, or a string array if it does.
-
- An internal macro means that the macro shouldn't be defined in the
- user headers.
- A raw macro means that the expression should not be confronted
- to existing macros while optimizing/evaluating. """
-
- def __init__(self, is_internal, is_raw, name, expr, args=None):
- self.name = name
- self.args = args
- self.expr = expr
- self.int = is_internal
- self.raw = is_raw
-
- def __repr__(self):
- flags = ""
- if self.raw:
- flags += "R"
- if self.int:
- flags += "I"
- if flags:
- flags = "[{}]".format(flags)
- return '<CppDefine{} "{}">'.format(flags, self.name)
-
-class CppUndef:
- """ Preprocessor constant or macro “undefinition”.
- Unsets the constant or macro corresponding to the content of
- the `name` property. """
-
- def __init__(self, name):
- self.name = name
-
- def __repr__(self):
- return '<CppUndef "{}">'.format(self.name)
-
-class CppInclude:
- """ Preprocessor file inclusion.
- Includes the file corresponding to the content of the `name` property.
-
- There are three types of inclusion:
- - `local`: name surrounded by quotes, for inclusion starting from
- the current directory;
- - `path`: search for the path in the include path;
- - `expr`: expression.
- """
-
- def __init__(self, typ, name):
- self.name = name
- self.typ = typ
-
- def __repr__(self):
- if self.typ == "local":
- name = '"{}"'.format(self.name)
- elif self.typ == "path":
- name = '{' + '{}'.format(self.name) + '}'
- else:
- name = self.name
- return '<CppInclude {}>'.format(name)
-
-class CppIncludeBits:
- """ Preprocessor file bits inclusion.
- Includes the bits corresponding to the content of the `name` property.
-
- Can include zero, one or more bits, depending on the bits and
- appropriate folders. """
-
- def __init__(self, typ, name):
- self.name = name
- self.typ = typ
-
- def __repr__(self):
- return '<CppIncludeBits "{}">'.format(self.name)
-
-class CppIf:
- """ Preprocessor conditional instructions.
-
- The `conds` properties is the (conditions, instructions) list
- in failover condition order, and the `eins` property is the
- instructions that are used if all of the conditions have been
- evaluated to false.
- """
-
- def __init__(self, cond, ins):
- self.conds = [(cond, ins)]
- self.eins = []
-
- def addcond(self, cond, ins):
- self.conds.append((cond, ins))
-
- def setelse(self, ins):
- self.eins = ins
-
- def __repr__(self):
- s = '<CppIf '
- for cond, ins in self.conds:
- s += '"{}" => {}, '.format(cond, ins)
- s += '{}>'.format(self.eins)
- return s
-
-class CppError:
- """ Preprocessor error raiser instruction. """
-
- def __init__(self, message):
- self.message = message
-
- def __repr__(self):
- s = '<CppError "{}">'.format(self.message)
-
-# End of file.
diff --git a/tools/Internals/headers/eval.py b/tools/Internals/headers/eval.py
deleted file mode 100755
index 2125faf..0000000
--- a/tools/Internals/headers/eval.py
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env python3
-""" Placeholder. Lephenixnoir's working on this. """
-
-def evaluate(expr, known = {}):
- return None
-
-# End of file.
diff --git a/tools/Internals/headers/output.py b/tools/Internals/headers/output.py
deleted file mode 100755
index ca29331..0000000
--- a/tools/Internals/headers/output.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env python3
-""" Output a header. """
-
-import sys as _sys
-import string as _string
-
-from .elements import *
-
-__all__ = ["output_header"]
-
-def __validmacroname(name):
- return all(c in _string.ascii_letters + '_' for c in name)
-
-def __output_recursive(content, out=_sys.stdout, sep='\n'):
- """ Output the content in a recursive manner. """
-
- for ins in content:
- if type(ins) == CppRaw:
- nxt = sep.join(ins.content.split('\n'))
- elif type(ins) == CppDefine:
- nxt = "#define {}".format(ins.name)
- if ins.args != None:
- nxt += "({})".format(', '.join(ins.args))
- nxt += " {}".format((' \\' + sep).join(ins.expr.split('\n')))
- elif type(ins) == CppDefineRaw:
- nxt = "#define {} {}".format(ins.name, ins.expr)
- elif type(ins) == CppUndef:
- nxt = "#undef {}".format(ins.name)
- elif type(ins) == CppInclude:
- nxt = ins.name
- if ins.typ == "local":
- nxt = '"{}"'.format(nxt)
- elif ins.typ == "path":
- nxt = '<{}>'.format(nxt)
- nxt = "#include {}".format(nxt)
- elif type(ins) == CppError:
- nxt = '#error "{}"'.format(nxt)
- elif type(ins) == CppIf:
- cond, sub = ins.conds[0]
- expr = (' \\' + sep).join(cond.split('\n'))
- if expr[0:8] == 'defined(' and expr[-1] == ')' \
- and __validmacroname(expr[8:-1].strip()):
- print("#ifdef {}".format(expr[8:-1].strip()),
- end=sep, file=out)
- elif expr[0:9] == '!defined(' and expr[-1] == ')' \
- and __validmacroname(expr[9:-1].strip()):
- print("#ifndef {}".format(expr[9:-1].strip()),
- end=sep, file=out)
- else:
- print("#if {}".format(expr), end=sep, file=out)
-
- __output_recursive(sub, out=out, sep=sep)
-
- for cond, sub in ins.conds[1:]:
- print('#elif {}'.format(cond),
- sep=sep, end=sep, file=out)
- __output_recursive(sub, out=out, sep=sep)
-
- if ins.eins:
- print('#else')
- __output_recursive(ins.eins, out=out, sep=sep)
-
- nxt = '#endif'
- else:
- # We really shouldn't be here.
- # But in case, here is a way to identify the problem.
- nxt = '#<{}>'.format(type(ins).__name__)
-
- print(nxt, end=sep, file=out)
-
-def output_header(topc, content, out=_sys.stdout, sep='\n'):
- """ Output a header from its parsed form. """
-
- print(sep.join(topc.split('\n')), end='', file=out)
- __output_recursive(content, out=out, sep=sep)
-
-# End of file.
diff --git a/tools/Internals/headers/parse.py b/tools/Internals/headers/parse.py
deleted file mode 100755
index a0da718..0000000
--- a/tools/Internals/headers/parse.py
+++ /dev/null
@@ -1,243 +0,0 @@
-#!/usr/bin/env python3
-""" Parse a file on the C preprocessor view, with libcarrot extensions.
- Returns a tree-like directive list.
-"""
-
-from .elements import *
-
-__all__ = ["parse_header"]
-
-# ---
-# Read C content, line by line.
-# ---
-
-class _Getlines:
- """ Lines generator for the preprocessor parsing functions.
- Removes comments of all kinds ('/*' + '*'/', '//'). """
-
- def __init__(self, path):
- self._lines = []
- self.file = open(path, 'r')
-
- def _readline(self):
- """ Read one line from the file. """
-
- lines = []
- while True:
- tmp = self.file.readline()
- if tmp == '':
- break
-
- tmp = tmp.splitlines()[0]
- hasnext = tmp and tmp[-1] == '\\'
- lines += [tmp[:-1].rstrip() if hasnext else tmp.rstrip()]
- if not hasnext:
- break
-
- if not lines: return None
- return '\n'.join(lines)
-
- def __iter__(self):
- return self
-
- def __next__(self):
- """ Iterate on the lines. """
-
- # If lines have been re-added, put them first.
- if self._lines:
- return self._lines.pop(0)
-
- line = self._readline()
- if line == None:
- raise StopIteration
-
- # Check if there is a /* */ comment.
- while True:
- index = line.find('/*')
- if index < 0:
- break
-
- while True:
- rindex = line.find('*/', index)
- if rindex >= 0:
- line = line[:index] + line[rindex + 2:]
- break
-
- line += '\n' + self._readline()
-
- # Check if there is a // comment.
- index = line.find('//')
- if index >= 0:
- line = line[:index]
-
- # Yield the current line.
- return line
-
- def append(self, line):
- self._lines.append(line)
-
-# ---
-# Sub-parsing functions.
-# ---
-
-def _parse_define(raw):
- """ Get the define details out of the string, e.g. "CONSTANT some constant"
- or "MY_MACRO(and_some, fancy_parameters) and_some - fancy_parameters".
- Returns either (macro, None, value) or (macro, args, value). """
-
- first = raw.split()[0]
- if first.find('(') >= 0:
- # Is a macro with arguments!
- name = first.split('(')[0]
- rest = raw[len(name) + 1:]
- rpar = rest.find(')')
- if rpar < 0:
- raise Exception("Missing ')' in macro parameter list.")
-
- # Get the argument list.
- alst = rest[:rpar]
- if alst.find('(') >= 0:
- raise Exception("'(' cannot appear in macro list.")
- args = ()
- for arg in map(str.strip, alst.split(',')):
- for c in (c for c in arg if c.isspace()):
- raise Exception("Macro params. should be spl. using commas.")
- args = args + (arg,)
-
- # Get the expression to evaluate, return.
- rest = rest[rpar + 1:].lstrip()
- return (name, rest, args)
-
- rest = raw[len(first) + 1:].lstrip()
- return (first, rest, None)
-
-def _parse_name(raw):
- """ Get a macro name out of a raw string. """
-
- ret = raw.strip()
- # TODO: check that the name is good (ANSI, stuff).
- return ret
-
-def _parse_header_ref(raw):
- """ Get the header reference, such as "header.h" (for local references),
- <header.h> (for path references) or VARIABLE_NAME (for variables). """
-
- raw = raw.strip()
- if raw[0] == '<' and raw[-1] == '>':
- return ('path', raw[1:-1].strip())
- if raw[0] == '"' and raw[-1] == '"':
- return ('local', raw[1:-1].strip())
- return ('var', _parse_name(raw))
-
-def _get_inst(raw):
- """ Get the instruction name and its parameters from a line group. """
-
- full = raw.lstrip()
-
- # Check if is a preprocessor directive.
- if not full or full[0] != '#':
- return False
-
- # Get the preprocessor directive.
- tmp = full[1:].split()
- if not tmp: return '===SKIP==='
- inst = tmp[0]
-
- # Get the rest.
- rest = full[1:].lstrip()[len(inst):].lstrip()
- return (inst, rest)
-
-# ---
-# Main parsing function.
-# ---
-
-def _parse_header_rec(lines):
- """ The recursive function. """
-
- ins = []
- for line in lines:
- # Get the instruction and arguments.
- result = _get_inst(line)
- if result == '===SKIP===':
- continue
- if not result:
- if not ins or type(ins[-1]) != CppRaw:
- ins.append(CppRaw(line))
- else:
- ins[-1].addcontent(line)
- continue
- inst, rest = result
-
- # Check using it:
- # include, define, undef, if, elif, else, ifdef, ifndef
- #
- # Extensions: elifdef, elifndef, error
- if inst == 'include':
- obj = CppInclude(*_parse_header_ref(rest))
- ins.append(obj)
- elif inst == 'error':
- ins.append(CppError(rest)) # FIXME: string?
- elif inst == 'include_bits':
- ins.append(CppIncludeBits(*_parse_header_ref(rest)))
- elif inst in ('define', 'defint', 'define_int', 'define_internal', \
- 'defraw', 'define_raw'):
- result = _parse_define(rest)
- is_int = result[0][:2] == '__' or inst in ('defint', \
- 'define_int', 'define_internal')
- is_raw = inst in ('defraw', 'define_raw')
-
- # XXX: there is no interest in using raw macros with arguments,
- # as the arguments will not be evaluated. Should we forbit that?
- ins.append(CppDefine(is_int, is_raw, *result))
- elif inst == 'undef':
- ins.append(CppUndef(_parse_name(rest)))
- elif inst == 'if' or inst == 'ifdef' or inst == 'ifndef':
- if inst == 'if':
- ini_check = rest
- elif inst == 'ifdef':
- ini_check = 'defined(%s)' % _parse_name(rest)
- elif inst == 'ifndef':
- ini_check = '!defined(%s)' % _parse_name(rest)
- obj = CppIf(ini_check, _parse_header_rec(lines))
-
- while True:
- try: line = next(lines)
- except:
- raise Exception("#endif expected!")
- inst, rest = _get_inst(line)
- if inst in ('else', 'endif'):
- break
-
- if inst == 'elif':
- check = rest
- elif inst == 'elifdef':
- check = 'defined(%s)' % _parse_name(rest)
- elif inst == 'elifndef':
- check = '!defined(%s)' % _parse_name(rest)
- sins = _parse_header_rec(lines)
- obj.addcond(check, sins)
-
- if inst == 'else':
- sins = _parse_header_rec(lines)
- obj.setelse(sins)
- if not lines:
- raise Exception("#endif expected!")
- inst, rest = _get_inst(next(lines))
- if inst != 'endif':
- raise Exception("#endif expected!")
- ins.append(obj)
- elif inst in ('elif', 'elifdef', 'elifndef', 'else', 'endif'):
- lines.append(line) # reinsert the line so that it is re-read.
- break
- else:
- # Invalid instruction!
- raise Exception("Unknown preprocessor directive #%s"%inst)
-
- return ins
-
-def parse_header(path):
- """ Parse the header. """
-
- return _parse_header_rec(_Getlines(path))
-
-# End of file.
diff --git a/tools/Internals/headers/profile.py b/tools/Internals/headers/profile.py
deleted file mode 100755
index 6a0dc17..0000000
--- a/tools/Internals/headers/profile.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env python3
-""" This file profiles a header.
-
-"""
-
-def profile(instructions, known = {}):
- """ Update the known variables. """
-
- for ins in instructions:
- if type(ins) == CppInclude:
- # TODO: Profile the included file.
- pass
- elif type(ins) == CppIncludeBits:
- # TODO: Profile the included bits.
- pass
- elif type(ins) == CppDefine:
- name, args, value = ins[1:]
- if name in known:
- # TODO: hey, already defined!
- pass
- else:
- known[name] = (args, value)
- elif type(ins) == CppUndef:
- name = ins[1]
- if name in known:
- known[name] = None
- elif type(ins) == CppIf:
- # Check each conditions.
- go_with = None
- conds = ins[1:-1]
- while conds:
- check, then_ins = conds[0]
- typ = checks[0]
- if typ == "defined" or typ == "!defined":
- name = check[1]
- if not name in known:
- # FIXME: Hey, it is unknown!
- pass
- if (typ == "defined" and known[name] != None) \
- or (typ == "!defined" and known[name] == None):
- go_with = then_ins
- break
- # This check is false.
- elif typ == "equal":
- first, second = check[1:]
- first = __eval(first)
- second = __eval(second)
- if False: # TODO: one of them is unknown
- break
- if first == second:
- go_with = then_ins
-
- # This condition has been evaluated as False,
- # so just take it off.
- conds = conds[1:]
-
- # Look what was going on.
- if conds:
- # TODO: A condition has been evaluated as unknown.
- # Go through all of the instructions in the left conditions,
- # keeping in mind that we don't know if the final preprocessor
- # is going to get through here.
- pass
- elif go_with:
- # TODO: A condition has been evaluated as true.
- # Evaluate these.
- pass
- else:
- # TODO: All conditions have been evaluated as false.
- # Evaluate the else instructions.
- go_with = conds[-1]
- pass
-
-# End of file.
diff --git a/tools/Internals/topc.py b/tools/Internals/topc.py
deleted file mode 100755
index a653233..0000000
--- a/tools/Internals/topc.py
+++ /dev/null
@@ -1,181 +0,0 @@
-#!/usr/bin/env python3
-""" Top comment generator and management.
-
- The top comment contains the file name and role, the module containing
- it, and the license statement.
-"""
-
-import os, textwrap
-
-# ---
-# License statements.
-# ---
-
-__proprietary_statement = """\
-This file is in the {module} module from libcarrot. The {module} module from \
-libcarrot is proprietary software; all rights on it are reserved."""
-
-__free_statement = """\
-This file is in the {module} module from libcarrot. The {module} module from \
-libcarrot is free software; you can use, modify and redistribute it under \
-the terms of the libcarrot free software license version 1.0 as published by \
-the libcarrot upstream maintainers.
-
-The {module} module from libcarrot is distributed in the hope that it \
-will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty \
-of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \
-See the libcarrot free software license for more details.
-
-You should have received a copy of the libcarrot free software license along \
-with this module; if not, see <https://libcarrot.touhey.fr/free-license.html>.
-"""
-
-def __get_license_statement(license):
- """ Get the license statement. """
-
- if license == 'free':
- return __free_statement
- return __proprietary_statement
-
-# ---
-# Make the top comment text.
-# ---
-
-def __make_topc_text(mname, name, role, authors, license, width=75):
- """ Make the top comment text. """
-
- text = "%s -- " % name
- text += '\n'.join(textwrap.wrap(role, width=(width - len(text)),
- subsequent_indent=" "*len(text)))
- text += '\n'
-
- max_ds_line = 0
- for (start, end), name, mail in authors:
- ds = '%s-%s' % (start, end) if start < end else '%s' % start
- if max_ds_line < len(ds): max_ds_line = len(ds)
-
- for (start, end), name, mail in authors:
- ds = '%s-%s' % (start, end) if start < end else '%s' % start
- copystart = "Copyright (C) %*s "%(max_ds_line, ds)
- copyline = copystart + "%s <%s>" % (name, mail)
- copyline = textwrap.wrap(copyline, width=width,
- subsequent_indent=" "*len(copystart))
- text += '\n'.join(copyline) + "\n"
-
- statement = __get_license_statement(license)
- if statement:
- text += "\n" + statement.format(module=mname)
-
- wtab = []
- for stline in text.splitlines():
- par = textwrap.wrap(stline, width=width, replace_whitespace=None)
- if not par: par = ['']
- for line in par:
- wtab.append(line)
-
- return '\n'.join(wtab)
-
-# ---
-# Make the top comment for specific languages, out of text.
-# ---
-
-def __make_topc_c(sep='\n', **params):
- """ Make a top comment in C using text. """
-
- __top = '/* ' + '*' * 76
- __bot = ' * ' + '*' * 73 + ' */'
-
- params['width'] = 76
- msg = __make_topc_text(**params)
-
- mid = sep.join(map(lambda x: ' *' + (' ' if x else '') + x,
- msg.splitlines()))
- fin = sep.join((__top, mid, __bot)) + sep
- return fin
-
-def __make_topc_sh(sep='\n', **params):
- """ Make a bootiful header. """
-
- __sep = '#' + '*' * 78
-
- params['width'] = 77
- msg = __make_topc_text(**params)
-
- mid = sep.join(map(lambda x: '#' + (' ' if x else '') + x,
- msg.splitlines()))
- fin = sep.join((__sep, mid, __sep)) + sep
- return fin
-
-def __make_topc_asmsh(sep='\n', **params):
- """ Make a not-so-nice header. """
-
- __sep = '; ' + '-' * 77
-
- params['width'] = 77
- msg = __make_topc_text(**params)
-
- mid = sep.join(map(lambda x: ';' + (' ' if x else '') + x,
- msg.splitlines()))
- fin = sep.join((__sep, mid, __sep)) + sep
- return fin
-
-# ---
-# Main interface:
-# Make the top comment, and get the file content after the top comment.
-# ---
-
-def get_source_content(path, sep='\n', syntax='c'):
- """ Get a source file content after the top comment. """
-
- if syntax in ['c', 'c++']:
- is_str = lambda x: x[:3] == '/* ' and \
- all(c == '*' for c in x[3:])
- is_end = lambda x: x[:3] == ' * ' and \
- all(c == '*' for c in x[3:-3]) and x[-3:] == ' */'
- elif syntax in ['asmsh']:
- is_str = lambda x: x[:2] == '; ' and \
- all(c == '-' for c in x[2:])
- is_end = is_str
- else:
- is_str = lambda x: x[0] == '#' and \
- all(c == '*' for c in x[1:])
- is_end = isstr
-
- with open(path) as src:
- line = src.readline()
- while True:
- if not line or not is_str(line.splitlines()[0]):
- break
-
- while True:
- line = src.readline()
- if not line or is_end(line.splitlines()[0]):
- break
-
- line = src.readline()
-
- oneline = lambda x:x.splitlines()[0] if x else ""
- line = oneline(line)
- return sep.join([line] + list(map(oneline, src.readlines())) + [''])
-
-def make_top_comment(module_name, name, role, authors, license, syntax='c'):
- """ Make a top comment using different syntaxes. """
-
- params = {
- 'mname': module_name,
- 'name': name,
- 'role': role,
- 'authors': authors,
- 'license': license
- }
-
- if syntax in ['c', 'c++']:
- text = __make_topc_c(**params)
- elif syntax in ['asmsh']:
- text = __make_topc_asmsh(**params)
- else:
- text = __make_topc_sh(**params)
-
- return text
-
-# End of file.
diff --git a/tools/Pipfile b/tools/Pipfile
new file mode 100644
index 0000000..3c91d2a
--- /dev/null
+++ b/tools/Pipfile
@@ -0,0 +1,11 @@
+[[source]]
+url = 'https://pypi.python.org/simple'
+verify_ssl = true
+name = 'pypi'
+
+[requires]
+python_version = '3.7'
+
+[packages]
+toml = '*'
+click = '*'
diff --git a/tools/Pipfile.lock b/tools/Pipfile.lock
new file mode 100644
index 0000000..07aef8b
--- /dev/null
+++ b/tools/Pipfile.lock
@@ -0,0 +1,37 @@
+{
+ "_meta": {
+ "hash": {
+ "sha256": "8dff2a17ae5961adc39235311de1fef80d4de3bb0bdd66d0255c153523df4dba"
+ },
+ "pipfile-spec": 6,
+ "requires": {
+ "python_version": "3.7"
+ },
+ "sources": [
+ {
+ "name": "pypi",
+ "url": "https://pypi.python.org/simple",
+ "verify_ssl": true
+ }
+ ]
+ },
+ "default": {
+ "click": {
+ "hashes": [
+ "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13",
+ "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7"
+ ],
+ "index": "pypi",
+ "version": "==7.0"
+ },
+ "toml": {
+ "hashes": [
+ "sha256:229f81c57791a41d65e399fc06bf0848bab550a9dfd5ed66df18ce5f05e73d5c",
+ "sha256:235682dd292d5899d361a811df37e04a8828a5b1da3115886b73cf81ebc9100e"
+ ],
+ "index": "pypi",
+ "version": "==0.10.0"
+ }
+ },
+ "develop": {}
+}
diff --git a/tools/configure.py b/tools/configure.py
deleted file mode 100755
index ec97348..0000000
--- a/tools/configure.py
+++ /dev/null
@@ -1,286 +0,0 @@
-#!/usr/bin/env python3
-""" This tool serves for user configuration of the libcarrot.
- Basically, it takes the user parameters (architecture, system,
- additional modules, build tools), and makes a configuration that the
- actual tool, 'make.py', can read to know what he is supposed to do.
-
- It is responsible for finding the modules corresponding to what the
- user asks, finding a configuration of the build tools that work and
- produce the expected result, and warn if what the user asks for is
- incorrect or if there are any mistakes in the involved
- global, system or module configurations.
-"""
-
-import os, sys, platform, shlex
-from subprocess import call
-
-import yaml
-from Internals import *
-_ = gettext
-
-def __getsystem():
- """ Internal function to get the current system. """
- return platform.system().lower()
-
-def __getarch():
- """ Internal function to get the current architecture. """
- return platform.machine().lower()
-
-def __getendian():
- """ Internal function to get the current endianness. """
- return sys.byteorder
-
-def __from_root(*x):
- """ Get the path from the project root. """
-
- return os.path.normpath(os.path.join(os.path.dirname(__file__), '..', *x))
-
-# ---
-# Parse the command line arguments.
-# ---
-
-def get_args(argv = sys.argv[1:]):
- """ Get the arguments using an argument parser. """
-
- argparser = CarrotArgumentParser(\
- description=_("Configures libcarrot to adapt it to many kinds " \
- "of configurations."),
- usage="%(prog)s [OPTION]...")
-
- # Main arguments.
-
- argparser.add_argument('-v', '/V', '--version', dest='version',
- action='store_true', help=_("show the version message and exit"))
- argparser.add_argument('/-maintainer', action='store_true')
- argparser.add_argument('-q', '--quiet', '/-silent', dest='silent',
- action='store_true', help=_("disable the configuration logging"))
-
- # Locations.
- # Options are there to override what is defined in the main project
- # information file.
-
- grp = argparser.add_argument_group(_('Build files and directories'))
-
- grp.add_argument('-p', '--project', dest='projectfile',
- default=__from_root('project.yml'),
- help=_("the path to the project information file"))
-
- grp.add_argument('-m', '--modroot', dest='mroot',
- default=None, help=_("override the modules root"))
- grp.add_argument('-B', '/O', '--build', '/-obj', dest='builddir',
- default=None, help=_("override the build root"))
-
- grp.add_argument('-o', '--output', '/-config-cache', dest='out',
- default=None, help=_("override the output configuration file path"))
- grp.add_argument('-C', '--cache', dest='cache',
- default=None, help=_("override the cache file path"))
-
- # Build-related configuration elements.
-
- grp = argparser.add_argument_group(_('Build options'))
-
- grp.add_argument('-t', '--target', dest='target', default=None,
- help=_("the target for the library"))
- grp.add_argument('/-arch', dest='arch', default=__getarch())
- grp.add_argument('/-system', dest='system', default=__getsystem())
- grp.add_argument('/-abi', dest='abi', default=None)
- grp.add_argument('-e', '--endian', '/-endianness', dest='endian',
- default=None, help=_("the architecture endianness"))
- grp.add_argument('-a', '--add', dest='modules',
- default=[], action='append', help=_("add a module in the configuration "
- "(cumulative)"))
- grp.add_argument('-F', '--flavour', '/-flavor', dest='flavour',
- default='elf', help=_("the development files flavour"))
- grp.add_argument('-T', '--tooldir', dest='tooldir', default=None,
- help=_("add a tools directory (cumulative)"))
- grp.add_argument('/-shared')
- grp.add_argument('/-static')
-
- # TODO: Options for maintainers, to prefer a compiler.
-
- argparser.add_argument('/-prefer-cc', dest='pref_cc', default=None)
- argparser.add_argument('/-prefer-cxx', dest='pref_cxx', default=None)
- argparser.add_argument('/-prefer-asm', dest='pref_asm', default=None)
- argparser.add_argument('/-prefer-pack', dest='pref_pack', default=None)
- argparser.add_argument('/-prefer-link', dest='pref_link', default=None)
- argparser.add_argument('/-prefer-bin', dest='pref_bin', default=None)
-
- # TODO: Installation-related elements.
-
- grp = argparser.add_argument_group(_('Installation directories'))
-
- grp.add_argument('--root', default="",
- help=_("root (do not use DESTDIR)"))
- grp.add_argument('--prefix', default="${root}/usr",
- help=_("architecture-independent files"))
- grp.add_argument('--exec-prefix', dest='EXECPREFIX',
- default="${prefix}",
- help=_("architecture-dependant files"))
- grp.add_argument('--datarootdir', default="${prefix}/share",
- help=_("read-only architecture-independent data root"))
-
- grp.add_argument('--bindir', default="${root}/bin",
- help=_("user executables"))
- grp.add_argument('--sbindir', default="${root}/sbin",
- help=_("system admin executables"))
- grp.add_argument('--libexecdir', default="${root}/libexec",
- help=_("program executables"))
- grp.add_argument('--libdir', default="${prefix}/lib",
- help=_("directory for libraries"))
- grp.add_argument('--includedir', '/-oldincludedir',
- default="${prefix}/include",
- help=_("directory for development headers"))
- grp.add_argument('--datadir', default="${datarootdir}",
- help=_("read-only architecture-independent data"))
- grp.add_argument('--sysconfdir', default="${prefix}/etc",
- help=_("read-only single-machine data"))
- grp.add_argument('--sharedstatedir', dest='SHAREDSDIR',
- default="${prefix}/com",
- help=_("modifiable architecture-independent data"))
- grp.add_argument('--localstatedir', dest='LOCALSDIR',
- default="${prefix}/var",
- help=_("modifiable single-machine data"))
-
- grp.add_argument('--infodir', default="${datarootdir}/info",
- help=_("info documentation"))
- grp.add_argument('--mandir', default="${datarootdir}/man",
- help=_("man documentation"))
- grp.add_argument('--docdir', default="${datarootdir}/doc/libcarrot",
- help=_("documentation root"))
- grp.add_argument('--localedir', default="${datarootdir}/locale",
- help=_("locale-dependent data"))
-
- grp.add_argument('--htmldir', default="${docdir}",
- help=_("html documentation"))
- grp.add_argument('--dvidir', default="${docdir}",
- help=_("dvi documentation"))
- grp.add_argument('--pdfdir', default="${docdir}",
- help=_("pdf documenation"))
- grp.add_argument('--psdir', default="${docdir}",
- help=_("ps documentation"))
-
- # Reserved arguments for features (from the glibc configure script).
-
- argparser.add_argument('/-disable-option-checking', action='store_true')
- argparser.add_argument('/-disable-sanity-checks', action='store_true')
- argparser.add_argument('/-enable-shared', action='store_true')
- argparser.add_argument('/-enable-profile', action='store_true')
- argparser.add_argument('/-disable-timezone-tools', action='store_true')
- argparser.add_argument('/-enable-hardcoded-path-in-tests',
- action='store_true')
- argparser.add_argument('/-enable-stackguard-randomization',
- action='store_true')
- argparser.add_argument('/-enable-lock-elision', choices=('yes', 'no'),
- default='no')
- argparser.add_argument('/-disable-hidden-plt', action='store_true')
-
- # Parse the arguments!
-
- return argparser.parse_args(argv)
-
-# ---
-# Write the configuration.
-# ---
-
-def main():
- """ Main function for the configure script. """
-
- args = get_args()
- cfg = UserConfig(args.out)
-
- # Get the arch and system from the eventual target.
-
- if args.target:
- args.arch, *tab = args.target.split('-')
- if not tab:
- raise MissingSystemInTargetException
- if len(tab) > 1:
- *tab, args.arch = tab
- args.system = '-'.join(tab)
- if not args.system:
- raise MissingSystemInTargetException
-
- # Get the arch family, processor and endianness.
-
- thing = get_arch_detail(args.arch)
- if not thing: raise UnsupportedArchException(args.arch)
- args.family, args.arch, endian = thing
-
- if args.endian:
- if endian: raise RedundantEndiannessException
- else:
- if not endian: raise MissingEndiannessException
- args.endian = endian
-
- # Get the additional modules.
-
- addm = []
- for arg in args.modules:
- addm += arg.split(',')
- args.modules = addm
-
- # Get the global source.
-
- g = Project(args.projectfile)
- if args.version:
- print(_("libcarrot {}").format(str(g.version)))
- print(_("Maintained by {}.").format(str(g.maintainer)))
- return
-
- # Get the platform.
-
- s = g.getsystem(args.system)
- if s.meta:
- raise MetaSystemException(s.name)
- if not args.abi:
- args.abi = s.abi[0]
- if not args.abi in s.abi:
- raise ABINotFound(s.name, args.abi)
- if s.arch and all(map(lambda x: not x in ((args.arch, args.endian), \
- (args.arch, None)), s.arch)):
- raise UnsupportedArchForSystemException(args.arch, args.endian, s.name)
-
- # Clean the repository.
-
- ret = call(['python3', os.path.join('tools', 'make.py'), 'mrproper'])
- if ret: Raise(SilentException)
-
- # Find the tools.
-
- found_tools = tools.find(args.arch, args.endian, args.system,
- args.abi, args.flavour)
- tools.setup(found_tools)
-
- # List the modules.
-
- mods = g.findmodules(args.arch, args.endian, args.system,
- tools.get('compiler'), tools.get('compiler'), args.modules)
- modules = list(mods.keys())
-
- # XXX: shall we order modules by output type?
- # If we do, it's instead of the previous `modules = list(mods.keys())`
- # instruction!
-
- #modules = {}
- #for name, module in mods.items():
- # if not module.out in modules:
- # modules[module.out] = []
- # modules[module.out].append(name)
-
- # Set the locations.
- root = os.path.dirname(args.out)
- cfg.source = os.path.relpath('modules', root)
- cfg.cache = os.path.relpath(args.cache, root)
- cfg.build = os.path.relpath(args.builddir, root)
-
- # Write the configuration.
- cfg.write()
-
- # Tell the user we're done.
- if not args.silent:
- print(_("Configuration loaded, you can make now."))
-
-if __name__ == "__main__":
- do_main(main)
-
-# End of file.
diff --git a/tools/make.py b/tools/make.py
deleted file mode 100755
index be53076..0000000
--- a/tools/make.py
+++ /dev/null
@@ -1,379 +0,0 @@
-#!/usr/bin/env python3
-""" This tool is responsable for actually building the library.
- It takes the configuration from the file generated by 'configure.py',
- which contains the modules to build and the build tools configuration,
- finds out what is left to do, what has been updated (to re-build),
- and finishes the job.
-
- It is possible to make several times out of a single configuration,
- and this is cool when you are just programming in one or more modules.
-"""
-
-import os, sys, traceback
-from shutil import rmtree, copyfile
-
-import yaml
-from Internals import *
-_ = gettext
-
-# ---
-# Commands.
-# ---
-
-def placeholder(args):
- """ Placeholder for non-ready commands. """
-
- print(_("Command `{cmd}` is not ready yet!").format(cmd=args.command),
- file=sys.stderr)
-
-def clean(args):
- """ Clean the project (remove generated files in order to
- force rebuild). """
-
- # Remove the caches.
- for cachefile in ('.makeinc-cache', '.cache.yml'):
- try: os.remove(cachefile)
- except FileNotFoundError: pass
-
- # Remove the build folders.
- for directory in ('include', 'obj', 'build'):
- try: rmtree(directory)
- except FileNotFoundError: pass
-
-def mrproper(args):
- """ Clean the project for distribution (remove generated files and
- configurations). """
-
- # Clean generated files.
- clean(args)
-
- # Remove the configuration.
- try: os.remove('.config.yml')
- except FileNotFoundError: pass
-
-def build(args):
- """ Build the project with the current configuration. """
-
- # Load the root.
- # The `os.path.join()` usage here is for directories such as `.`,
- # to replace `.config.yml` by `./.config.yml` for example.
- root = os.path.dirname(args.config)
- configpath = os.path.join(root, os.path.basename(args.config))
-
- # Load the user configuration.
- try: args.config = yaml.load(open(args.config).read())
- except FileNotFoundError: raise MissingConfigurationException
- source_root = os.path.join(root, args.config['paths']['source'])
- cache_path = os.path.join(root, args.config['paths']['cache'])
- incdir = os.path.join(root, args.config['paths']['incdir'])
- objdir = os.path.join(root, args.config['paths']['objdir'])
-
- # Load the cache.
- args.cache = CacheManager(cache_path)
-
- # Get the copyright rules.
- rules = get_copyright_rules(root)
-
- # Get the global source.
- g = SourceGlobal(source_root, os.path.getmtime(configpath),
- rules=rules)
-
- # Gather the modules.
- modules = g.getmodules(args.config['modules'])
-
- # Make the includes folder.
- process_headers(incdir, modules, args.cache)
- return # XXX: temp debug
-
- # Setup the tools.
- tools.setup(args.config['tools'])
-
- # Get the maximum header modification time.
- # TODO: only check the things for what is actually included in the
- # source file!
- incmtimes = {}
- for root, _, nms in os.walk(args.incdir):
- for nm in nms:
- nm = os.path.join(root, nm)[len(os.path.join(args.incdir, '')):]
- incmtimes[nm] = os.path.getmtime(os.path.join(args.incdir, nm))
- incmtime = max(incmtimes.values())
-
- # Make the objects.
- objs = []
- for name, module in map(lambda x:(x, modules[x]), sorted(modules)):
- objdir = os.path.join(args.objdir,
- name.split('/')[0], name.split('/')[1])
-
- # C files
- for source in module.getfiles('src', tools.get('cc_ext')):
- objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
- objs.append(objpath)
-
- incdirs = []
- if not os.path.exists(objpath): objmtime = -1
- else: objmtime = os.path.getmtime(objpath)
- depmtime = os.path.getmtime(module.getpath('src', source))
- depmtime = max(depmtime, incmtime)
-
- if objmtime < depmtime:
- # Make the object directory.
- try: os.makedirs(os.path.dirname(objpath))
- except FileExistsError: True
-
- # Do the command.
- print('[%s] CC %s'%(name, source))
- srcfile = module.getpath('src', source)
- if tools.cc(objpath, srcfile, [args.incdir]):
- exit(1)
-
- # C++ files
- for source in module.getfiles('src', tools.get('cxx_ext')):
- objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
- objs.append(objpath)
-
- incdirs = []
- if not os.path.exists(objpath): objmtime = -1
- else: objmtime = os.path.getmtime(objpath)
- depmtime = os.path.getmtime(module.getpath('src', source))
- depmtime = max(depmtime, incmtime)
-
- if objmtime < depmtime:
- # Make the object directory.
- try: os.makedirs(os.path.dirname(objpath))
- except FileExistsError: True
-
- # Do the command.
- print('[%s] CXX %s'%(name, source))
- srcfile = module.getpath('src', source)
- if tools.cxx(objpath, srcfile, [args.incdir]):
- exit(1)
-
- # Assembly
- for source in module.getfiles('src', tools.get('asm_ext')):
- objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
- objs.append(objpath)
-
- if not os.path.exists(objpath): objmtime = -1
- else: objmtime = os.path.getmtime(objpath)
- if objmtime < os.path.getmtime(module.getpath('src', source)):
- # Make the object directory.
- try: os.makedirs(os.path.dirname(objpath))
- except FileExistsError: True
-
- # Do the command.
- print('[%s] ASM %s'%(name, source))
- if tools.asm(objpath, module.getpath('src', source)):
- exit(1)
-
- # Make something out of those objects.
- libs = {}
- for name, module in map(lambda x:(x, modules[x]), sorted(modules)):
- objdir = os.path.join('obj',
- name.split('/')[0], name.split('/')[1], '')
- objs = []
- for rt, _, nms in os.walk(objdir):
- for nm in nms:
- objs.append(os.path.join(rt, nm)[len(objdir):])
- objp = list(map(lambda x:os.path.join(objdir, x), objs))
-
- if module.out[:3] == 'lib':
- lib = module.out[3:]
- if not lib in libs: libs[lib] = []
- libs[lib] += objp
- elif module.out[:3] in ['obj', 'crt']:
- for obj in objs:
- copyfile(os.path.join(objdir, obj),
- os.path.join('obj', obj.split('.')[0] + '.o'))
-
- # Make the libraries.
- for name in libs:
- libname = 'lib%s.%s'%(name, tools.get('lib_ext'))
- try:
- mtim = os.path.getmtime(os.path.join('obj', libname))
- maxm = max(map(lambda x: os.path.getmtime(x), libs[lib]))
- if mtim > maxm: continue
- except: pass
-
- print('AR %s'%libname)
- if tools.pack(os.path.join('obj', libname), libs[lib]):
- exit(1)
-
-def build_docs(args):
- """ Build the documentation. """
-
-def install(args):
- pass
-
- #TODO:
- #try:
- # (installing things)
- #except PermissionError:
- # (check if has admin privileges using `os.getgid() == 0` on Unix
- # or `win32com.shell.IsUserAnAdmin()` on Windows)
- # (if not, try sudoing the same command)
-
-def getcopyright(args):
- """ Get the copyright information. """
-
- # Get the project root.
- root = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
- rules = get_copyright_rules(root)
-
- paths = []
- for path in args.path:
- if not os.path.exists(path):
- raise FileNotFoundException(path)
- elif os.path.isdir(path):
- if not args.rec: continue
- for rt, _, nms in os.walk(path):
- for nm in nms:
- paths.append(os.path.join(rt, nm))
- else:
- paths.append(path)
-
- first = True
- for path in sorted(set(paths)):
- # Correct the path.
- p0 = os.path.relpath(root, os.getcwd())
- p1 = os.path.relpath(os.path.join('.', path), root)
- p = os.path.join(p0, p1)
-
- # Get the copyright information.
- msg = None
- authors, license = [], ''
- try:
- authors, license = get_copyright(rules, p)
- except (NotAFileException, IgnoredFileException):
- continue
- except NoCopyrightException as e:
- if args.hidepub: continue
- msg = str(e)
- else:
- msg = ''
- for (start, end), name, mail in authors:
- ds = '%s-%s'%(start, end) if start < end else '%s'%start
- msg += 'Copyright (C) %s %s <%s>\n'%(ds, name, mail)
-
- # Put the information.
- if first: first = False
- else: print('')
- print('%s:'%path)
- msg = map(lambda x:' %s' % x, msg.splitlines())
- print(*msg, sep=os.linesep)
-
-# ---
-# Parse the command line arguments.
-# ---
-
-__carrot = """\
- ___
- `-._\ / `~~"--.,_
- ------>| `~~"--.,_
- _.-'/ '.____,,,,----\"""~~```'
-"""
-
-def get_args(argv = sys.argv):
- """ Get the arguments using an argument parser. """
-
- argparser = CarrotArgumentParser(description=\
- _("Makes various operations."))
- argparser.add_argument('-c', '--config', dest='config',
- default=os.path.join(os.path.dirname(__file__), '..', '.config.yml'),
- help=_("the configuration file path"))
- subs = argparser.add_subparsers(title=_("Subcommands"), dest='command',
- metavar='<command>')
-
- commands = [
- ('build', "build the project",
- ['all', 'libcarrot']),
- ('clean', "clean the project",
- []),
- ('distclean', "clean the project completely",
- ['mrproper']),
- ('re', "rebuild the project",
- ['rebuild']),
- ('docs', "build the HTML docs",
- ['html']),
-
- ('help', "print help",
- ['halp']),
- ('carrot', "print an ASCII art carrot",
- []),
- ('getcopyright', "get the copyright information",
- ['getcopy', 'gcpy']),
-
- ('listcmds', "(ignored)",
- []),
- ('nothing', "(ignored)",
- ['Makefile', 'ignore'], ),
- ]
-
- # Hack.
- # I would have preferred to use `action="store_const"` and the `const`
- # property on the subparsers, but... this will work.
-
- def listcmds(args):
- """ List the commands. """
-
- lst = []
- for cmd, _, als in commands:
- lst.append(cmd)
- #lst.extend([cmd] + als)
- print(*lst, sep=os.linesep)
-
- cmds = {
- 'help': lambda args: argparser.print_help(),
- 'carrot': lambda args: print(__carrot),
- 'build': build, 'clean': clean,
- 'distclean': mrproper,
- 're': lambda args: (clean(args), build(args)),
- 'getcopyright': getcopyright,
- 'docs': build_docs,
- 'listcmds': listcmds
- }
-
- # Add all of the commands.
-
- for cmd, hlp, als in commands:
- sub = subs.add_parser(cmd, help=_(hlp), aliases=als)
- cmds[cmd] = (cmds[cmd] if cmd in cmds else lambda x: 0, sub)
-
- # Add specific options.
-
- cmds['docs'][1].add_argument('-d', dest='hroot',
- default='html', help=_("the html root"))
- cmds['getcopyright'][1].add_argument('path', nargs='+',
- help=_("the files to check"))
- cmds['getcopyright'][1].add_argument('-R', '--recursive',
- dest='rec', action='store_true',
- help=_("go through the folders recursively"))
- cmds['getcopyright'][1].add_argument('--hide-public',
- dest='hidepub', action='store_true',
- help=_("hide files for which copyright is unavailable"))
-
-# ---
-# Main interface.
-# ---
-
-def main():
- """ Main function, checks the command and runs the appropriate
- function. """
-
- # Parse the arguments, execute the command.
- # `argparse` actually returns the alias instead of the canonical command,
- # so as a hack (XXX), we'll find the canonical command name ourselves.
-
- args = argparser.parse_args()
- for cmd, _, als in commands:
- if args.command in als:
- args.command = cmd
- break
- if not args.command in cmds:
- exit(0)
- ret = cmds[args.command][0](args)
- exit(ret)
-
-if __name__ == "__main__":
- do_main(main)
-
-# End of file.
diff --git a/tools/potato.bat b/tools/potato.bat
new file mode 100644
index 0000000..5a73e55
--- /dev/null
+++ b/tools/potato.bat
@@ -0,0 +1,2 @@
+cd %~p0
+py -3 -m potato %*
diff --git a/tools/potato.sh b/tools/potato.sh
new file mode 100755
index 0000000..b006e8b
--- /dev/null
+++ b/tools/potato.sh
@@ -0,0 +1,102 @@
+#!/bin/sh
+cd "$(dirname $0)"
+
+# ---
+# Utilities.
+# ---
+
+is_command() {
+ if ! command -v "$1" 1>/dev/null 2>/dev/null; then
+ return 1
+ fi
+}
+
+say() {
+ if is_command tput; then
+ HIGH="`tput setf 3 || tput setaf 3`"
+ RSET="`tput sgr0`"
+ else
+ HIGH="\033[0;33m" # yellow
+ RSET="\033[0m"
+ fi
+
+ printf "${HIGH}== $*${RSET}\n"
+}
+
+error() {
+ if is_command tput; then
+ HIGH="`tput setf 1 || tput setaf 1`"
+ RSET="`tput sgr0`"
+ else
+ HIGH="\033[0;31m" # red
+ RSET="\033[0m"
+ fi
+
+ printf "${HIGH}== $*${RSET}\n"
+}
+
+is_python3() {
+ if ! is_command "$1"; then
+ return 1
+ fi
+
+ # Check the version.
+
+ ver="`$@ --version 2>/dev/null`"
+ if ! [ $? -eq 0 ] || ! [ x"${ver:0:9}" = x"Python 3." ]; then
+ return 1
+ fi
+
+ return 0
+}
+
+is_pipenv() {
+ pe="$1"
+ if ! is_command "$pe"; then
+ return 1
+ fi
+
+ # Install the dependencies.
+
+ say "Installing the Pipfile dependencies"
+ $pe install 1>/dev/null
+}
+
+# ---
+# Main Python utility search (with and without pipenv).
+# ---
+
+# Get pipenv.
+
+pe=
+for command in 'pipenv'; do
+ if is_pipenv $command; then
+ pe="$command run "
+ break
+ fi
+done
+
+# Get python.
+
+py=
+for command in 'python3' 'python' 'py -3' '/usr/bin/python3' \
+'/usr/bin/python'; do
+ if is_python3 $pe$command; then
+ py="$pe$command"
+ break
+ fi
+done
+
+if [ x"$py" = x"" ]; then
+ err "An appropriate version of Python 3 could not be found."
+ exit 1
+fi
+
+# ---
+# Run the thing.
+# ---
+
+say "Running $py $0"
+PYTHONPATH="$(dirname $0):$PYTHONPATH" $py -m potato "$@"
+
+# End of file.
diff --git a/tools/potato/__init__.py b/tools/potato/__init__.py
new file mode 100755
index 0000000..6fbdcfa
--- /dev/null
+++ b/tools/potato/__init__.py
@@ -0,0 +1,6 @@
+#!/usr/bin/env python3
+""" Build tool for libcarrot. """
+
+# Yet to come: imports for the different components of the tool.
+
+# End of file.
diff --git a/tools/potato/__main__.py b/tools/potato/__main__.py
new file mode 100755
index 0000000..65056ad
--- /dev/null
+++ b/tools/potato/__main__.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+""" Entry point for the tool. """
+
+import os.path as _path
+import sys as _sys
+import platform as _platform
+import click as _click
+
+from . import PotatoException as _PotatoException, \
+ SilentException as _SilentException
+
+# ---
+# Declare the tool.
+# ---
+
+def print_version(ctx, param, value):
+ """ Print the version message and exit. """
+
+ if not value or ctx.resilient_parsing:
+ return
+
+ print("potato v0.1")
+ ctx.exit()
+
+@_click.group(invoke_without_command = True)
+@_click.option('--config', '-c',
+ default = _path.join(_path.dirname(__file__), '..', '.config.toml'))
+@_click.option('-q', '--quiet', '--silent',
+ is_flag = True, help = 'disable the logging')
+@_click.option('--version', '-v', is_eager = True, is_flag = True,
+ callback = print_version, help = "Print the version message and exit.")
+def cli(config, *args, **kwargs):
+ pass
+
+# ---
+# Help commands.
+# ---
+
+__carrot = """\
+ ___
+ `-._\ / `~~"--.,_
+ ------>| `~~"--.,_
+ _.-'/ '.____,,,,----\"""~~```'
+"""
+
+@cli.command()
+def carrot():
+ """ Print an ASCII art carrot. """
+
+ print(__carrot)
+
+@cli.command()
+def help():
+ """ Print help. """
+
+ # FIXME: aliases: halp
+
+ print("help")
+
+@cli.command()
+def nothing():
+ """ Do nothing. """
+
+ # FIXME: Makefile, ignore
+
+ pass
+
+# ---
+# Configure command.
+# ---
+
+@cli.command()
+@_click.option('-p', '--project',
+ default = _path.join(_path.dirname(__file__), '..', 'project.toml'),
+ help = "the path to the project information file")
+@_click.option('-m', '--modroot',
+ default = None, help = "override the modules root")
+@_click.option('-B', '-O', '--build', '--obj',
+ default = None, help = "override the build root")
+@_click.option("-o", "--output", "--config-cache",
+ default = None, help = "override the output configuration file path")
+@_click.option("-C", "--cache",
+ default = None, help = "override the cache file path")
+@_click.option("-t", "--target",
+ default = None, help = "the target for the library")
+@_click.option("--arch", "--architecture",
+ default = _platform.machine().lower(),
+ help = "the architecture for which to build")
+@_click.option("-e", "--endian", "--endianness",
+ default = None, help = "the architecture endianness")
+@_click.option("--system",
+ default = _platform.system().lower(),
+ help = "the system for which to build")
+@_click.option("--abi",
+ default = None, help = "the ABI for which to build")
+@_click.option("-a", "--add",
+ multiple = True, help = "add a module in the configuration (cumulative)")
+@_click.option("-F", "--flavour", "--flavor",
+ default = 'elf', help = "the development files flavour")
+@_click.option("-T", "--tooldir",
+ multiple = True, help = "add a tools directory (cumulative)")
+@_click.option("--shared/--static", is_flag = True,
+ help = "whether to prefer shared or static libraries")
+def configure(*args, **kwargs):
+ """ Configure the project for building.
+
+ This command takes the user parameters (architecture, system,
+ additional modules, build tools), finds the modules corresponding
+ to what the user asks, finds a configuration of the build tools,
+ and warn if any mistake occured during the global, system or
+ module configurations. """
+
+ print(args)
+ print(kwargs)
+
+# ---
+# Run the script.
+# ---
+
+if __name__ == '__main__':
+ try:
+ cli()
+ exit(0)
+ except _SilentException:
+ exit(1)
+ except _PotatoException as e:
+ print(f"Error: {str(e)}", file = _sys.stderr)
+ exit(e.ret)
+
+# End of file.
diff --git a/tools/Internals/module.py b/tools/potato/_module.py
index 8d56fff..3e5644a 100755
--- a/tools/Internals/module.py
+++ b/tools/potato/_module.py
@@ -15,6 +15,9 @@ from .exceptions import *
from .copyright import *
from .arch import *
+__all__ = ["SourceMaintainer", "SourceVersion", "ModuleName", \
+ "SourceModule", "SourceSystem"]
+
# ---
# Internals.
# ---
@@ -31,9 +34,9 @@ class SourceMaintainer:
""" The global maintainer. """
def __init__(self, raw):
- self.name = raw[0]
- if len(raw) > 1:
- self.mail = raw[1]
+ self.name = raw['name']
+ if 'mail' in raw:
+ self.mail = raw['mail']
def __str__(self):
s = '{}'.format(self.name)
@@ -90,6 +93,7 @@ class SourceModule:
"""
# Open the module configuration.
+
mconfigpath = os.path.join(root, 'info.yml')
try:
mconfig = yaml.load(open(mconfigpath))
@@ -97,15 +101,18 @@ class SourceModule:
Raise(ModuleNotFoundException(name))
# Check the difference to the reference time.
+
if mtim != None:
if os.path.getmtime(mconfigpath) > mtim:
Raise(UpdatedModuleException(name))
# Check the magic.
+
if 'magic' in mconfig and mconfig['magic'] != 'potatosdk-1.0':
Raise(SystemNotFoundException(name))
# Keep the arguments.
+
self.root = root
self.name = name
self.__root = root
@@ -113,12 +120,14 @@ class SourceModule:
self.mtim = os.path.getmtime(mconfigpath)
# Get the usual things.
+
self.description = mconfig['description']
self.out = mconfig['out'] if 'out' in mconfig else 'libc'
self.deps = mconfig['deps'] if 'deps' in mconfig else []
self.conflicts = mconfig['conflicts'] if 'conflicts' in mconfig else []
# Get the requirements.
+
self.compilers = []
self.hcompilers = []
self.arch = []
@@ -164,6 +173,7 @@ class SourceModule:
elements = elements[1:]
# Join it all and send it back!
+
return os.path.join(rt, *elements)
def getcopyright(self, *elements):
@@ -176,6 +186,7 @@ class SourceModule:
""" Get the role of a file. """
# Split the path.
+
path = os.path.join(*elements)
if path in self.roles:
return self.roles[path]
@@ -184,10 +195,10 @@ class SourceModule:
def getfiles(self, *path, ext=[], full=False):
""" Get the list of files in a directory. """
- # Get the root.
root = os.path.join(self.getpath(*path), '')
# Get the source files.
+
files = []
for r, _, filenames in os.walk(root):
if not full:
@@ -219,6 +230,7 @@ class SourceSystem:
"""
# Check that it is a system, load the configuration.
+
pconfigpath = os.path.join(root, 'info.yml')
try:
pconfig = yaml.load(open(pconfigpath))
@@ -226,21 +238,25 @@ class SourceSystem:
Raise(SystemNotFoundException(name))
# Check the difference to the reference time.
+
if mtim != None:
if os.path.getmtime(pconfigpath) > mtim:
Raise(UpdatedSystemException(name))
# Check the magic.
+
if 'magic' in pconfig and pconfig['magic'] != 'potatosdk-1.0':
Raise(SystemNotFoundException(name))
# Keep the arguments.
+
self.__root = root
self.name = name
self.__mtim = mtim
self.__rules = rules
# Get the properties.
+
self.description = pconfig['description']
if 'abi' in pconfig and type(pconfig['abi']) == list \
and len(pconfig['abi']) > 0:
@@ -258,6 +274,7 @@ class SourceSystem:
self.arch = list(map(_getarch, r['arch']))
# Loaded modules.
+
self.__loaded = {}
def getmodule(self, name):
diff --git a/tools/Internals/project.py b/tools/potato/_project.py
index 57de154..f6e21ca 100755
--- a/tools/Internals/project.py
+++ b/tools/potato/_project.py
@@ -3,11 +3,13 @@
Everything should be managed through this class.
"""
-import os as _os, re as _re
-import fnmatch as _fnmatch, datetime as _datetime
-import yaml as _yaml
+import os.path as _path
+import re as _re
+import datetime as _datetime
+import toml as _toml
-from .module import *
+from ._module import SourceMaintainer as _SourceMaintainer, \
+ SourceVersion as _SourceVersion, SourceSystem as _SourceSystem
__all__ = ["Project"]
@@ -15,154 +17,154 @@ class Project:
""" The project class.
Extracts data from the filesystem. """
- def __init__(self, path, mtim = None):
+ def __init__(self, root, path, from_config = False):
""" Initialize the class, gather the information about the source,
and deduce properties out of it.
- `path` is the project path (`project.yml` by default).
- `mtim` is the reference modification time not to edit after.
+ `path` is the project path (`project.toml` by default).
+ `from_config` is whether the path corresponds to a configuration
+ which is references a project file (True), or to a
+ project file directly (False).
"""
- # Open the configuration.
+ # Set the defaults.
+
+ self.__doc_path = None
+ self.__modules_path = None
+ self.__build_path = None
+ self.__config_path = None
+ self.__project_file_path = None
+ self.__authors_path = None
+
+ self.__version = None
+ self.__maintainer = None
+
+ self.__modules = None
+ self.__tools = None
+ self.__orig = None
+
+ # Load the files.
+
+ path = _makepath(path)
+ if from_config:
+ self.__load_config(path)
+ self.__load_project_info(self.__project_file_path)
+ else:
+ self.__load_project_info(path)
+
+ self.__load_authors(self.__authors)
+
+ def __load_config(self, path):
+ """ Load the configuration file. """
try:
- cfg = _yaml.load(open(path))
- except (FileNotFoundError,):
- Raise(GlobalNotFoundException)
+ cfg = _toml.load(open(path))
+ except Exception as e:
+ Raise(ConfigFileError(e))
+
+ # Check the magic.
+
+ if 'magic' in cfg and cfg['magic'] != 'potatosdk-1.0':
+ es = f"Unknown magic {repr(cfg['magic'])}"
+ Raise(ConfigFileError(Exception(es)))
+
+ # Get the locations.
+ # FIXME: exceptions
- # Check the difference to the reference time.
+ _makepath = lambda x: _path.join(_path.dirname(path),
+ *_re.split('/|\\\\', x))
- if mtim != None:
- if _os.path.getmtime(path) > mtim:
- Raise(UpdatedGlobalException)
+ self.__doc_path = _makepath(cfg['locations']['doc'])
+ self.__modules_path = _makepath(cfg['locations']['modules'])
+ self.__build_path = _makepath(cfg['locations']['build'])
+ self.__project_file_path = _makepath(cfg['locations']['project'])
+ self.__config_path = path
+
+ # Get the original command line.
+
+ self.__orig = cfg['orig']
+
+ # FIXME: tools, modules
+
+ def write_config(self, path):
+ """ Write the configuration file. """
+
+ cfg = {
+ 'magic': 'potatosdk-1.0',
+ 'orig': self.__orig,
+ 'locations': {
+ 'doc': self.__doc_path,
+ 'modules': self.__modules_path,
+ 'build': self.__build_path,
+ 'project': self.__project_path},
+ }
+
+ _toml.dump(cfg, open('path', 'rw'))
+
+ def __load_project_info(self, path):
+ """ Load the project information file. """
+
+ try:
+ cfg = _toml.load(open(path))
+ except (FileNotFoundError,):
+ Raise(ConfigFileError(e))
# Check the magic, get the properties.
if 'magic' in cfg and cfg['magic'] != 'potatosdk-1.0':
- Raise(GlobalNotFoundException)
+ es = f"Unknown magic {repr(cfg['magic'])}"
+ Raise(ConfigFileError(Exception(es)))
- self.maintainer = SourceMaintainer(cfg['maintainer'])
- self.version = SourceVersion(cfg['version'])
+ # Maintainer, version.
+ # FIXME: exceptions
- prefix = os.path.dirname(path)
- self.__prefix = prefix
- self.docroot = cfg['locations']['docroot']
- self.modroot = cfg['locations']['modules']
- self.config = cfg['locations']['config']
- self.build = cfg['locations']['build']
+ self.maintainer = _SourceMaintainer(cfg['maintainer'])
+ self.version = _SourceVersion(cfg['version'])
- # Keep the arguments.
- self.__root = os.path.join(self.__prefix, self.modroot)
- self.__mtim = mtim
- self.__rules = None
+ # Get the locations.
+ # FIXME: exceptions
- # Loaded systems.
- self.__loaded = {}
+ _makepath = lambda x: _path.join(_path.dirname(path),
+ *_re.split('/|\\\\', x))
- def __loadrules(self, root):
- """ Load the copyright rules from the project root. """
+ doc_path = _makepath(cfg['locations']['doc'])
+ modules_path = _makepath(cfg['locations']['modules'])
+ build_path = _makepath(cfg['locations']['build'])
+ config_path = _makepath(cfg['locations']['config'])
+ authors_path = _makepath(cfg['locations']['authors'])
- root = _os.path.join(root, '')
- rules = {}
+ if not self.__doc_path:
+ self.__doc_path = doc_path
+ if not self.__modules_path:
+ self.__modules_path = modules_path
+ if not self.__build_path:
+ self.__build_path = build_path
+ if not self.__project_file_path:
+ self.__project_file_path = path
+ if not self.__config_path:
+ self.__config_path = config_path
+ if not self.__authors_path:
+ self.__authors_path = authors_path
- # Copyright file thing.
- for rt, _, _ in _os.walk(root):
- # Ignore file.
- try:
- with open(_os.path.join(rt, '.gitignore')) as f:
- rulz = []
- for line in f.readlines():
- # Get what's before the comment.
- line = _re.sub('([^\\\\](\\\\\\\\)*)#.*$', '\\1', line)
- line = _re.sub('\\\\(.*)', '\\1', line)
- line = line.strip()
-
- if line: rulz.append(line)
-
- for l in rulz:
- if l[0] == '/':
- nm = l[1:].split('/')
- bases = [_os.path.join(rt, *nm)]
- else:
- nm = l.split('/')
- bases = [_os.path.join(rt, *nm),
- _os.path.join(rt, '**', *nm)]
-
- for base in bases:
- rules[base] = '===IGNORED==='
- except FileNotFoundError:
- pass
-
- # Copyright file.
- try:
- with open(_os.path.join(rt, 'copyright.yml')) as f:
- d_rules = _yaml.load_all(f.read())
-
- # Read each rule.
- for rule in d_rules:
- ml = rule['files']
- if type(ml) != list:
- ml = [ml]
-
- l = rule['license'] if 'license' in rule else 'free'
- authors = []
- if 'copyright' in rule:
- for author in rule['copyright']:
- if len(author) == 3:
- authors.append(((author[0], author[0]),
- author[1], author[2]))
- else:
- authors.append(((author[0], author[1]),
- author[2], author[3]))
- if not authors:
- authors.append(__default_maintainer)
-
- for m in ml:
- spl = m.split('/')
- m = _os.path.join(rt, *spl)
- rules[m] = {'authors': authors, 'license': l}
- except FileNotFoundError:
- pass
-
- self.rules = rules
-
- def getcopyright(self, path):
- """ Get a copyright rule. """
-
- if not self.__rules:
- self.__loadrules(self.__prefix)
-
- if not _os.path.isfile(path):
- raise NotAFileException
- if _os.path.basename(path) == 'copyright.yml':
- raise IgnoredFileException
-
- match = None
-
- for rule in rules:
- # Check if the rule matches the path.
- if not __match(rule, path):
- continue
+ # FIXME: copyrights
- # Check if it is the first thing.
- if not match:
- match = rule
- continue
+ def __load_authors(self, path):
+ """ Load the authors. """
+
+ pass # TODO
- # If the current rule is more precise, take it instead.
- # TODO: of course that length rule is stupid and doesn't take into
- # account things such as "arch/**/info.yml is more precise than
- # arch/mysystem/mymodule/*", but it's a quick hack.
+ def isignored(self, path):
+ """ Check if a path is ignored by the `.gitignore`s. """
- if len(rule) > len(match):
- match = rule
+ path = _os.path.normpath(path)
- if not match:
- raise NoCopyrightException
- rule = rules[match]
- if rule == '===IGNORED===':
- raise IgnoredFileException
- return (rule['authors'], rule['license'])
+ while path:
+ if __match(rule, path):
+ return True
+
+ path = _os.path.dirname(p)
+
+ return False
def getsystem(self, name):
""" Get a system using its name, e.g. "casiowin". """
@@ -180,15 +182,19 @@ class Project:
systems = {}
for name in os.listdir(self.__root):
- try: system = self.getsystem(name)
- except SystemNotFoundException: continue
+ try:
+ system = self.getsystem(name)
+ except SystemNotFoundException:
+ continue
systems[name] = system
+
return systems
def getmodule(self, name):
""" Get a module. """
system = self.getsystem(name.system)
+
return system.getmodule(name.module)
def getmodules(self, names):
@@ -197,6 +203,7 @@ class Project:
modules = {}
for name in names:
modules[name] = self.getmodule(ModuleName(name))
+
return modules
def getallmodules(self):
@@ -207,6 +214,7 @@ class Project:
for module_name, module in system.getallmodules().items():
nm = ModuleName(system_name, module_name)
modules[str(nm)] = module
+
return modules
def findmodules(self, arch, endian, system = None,
@@ -221,14 +229,10 @@ class Project:
modules = {}
- # In 'hand-written' information files, the user ain't using the
- # '!!python/tuple' trick, so we're just going to use a list instead
- # of a tuple.
- compiler = list(compiler)
-
# Get the language defaults for the systems.
# 'ds' means 'default systems', 'ls' means 'loaded systems',
# 'sn' means 'system name'.
+
default = []
ds = [system]
ls = []
@@ -246,6 +250,7 @@ class Project:
default += sys.defaults
# Gather the additional modules.
+
for name in set(addition):
module = self.getmodule(name)
if module.arch and all(not x in module.arch \
@@ -259,13 +264,17 @@ class Project:
# Gather the defaults for the languages.
# 'dm' means 'default modules', 'ldm' means 'language default modules'.
+
dm = []
for ldm in map(lambda x:default[x], languages):
dm.extend(ldm)
+
for name in dm:
module = self.getmodule(name)
- if module.arch and all(not x in module.arch \
- for x in ((arch, endian), (arch, None))):
+ unsupported_arch = lambda: all(not x in module.arch \
+ for x in ((arch, endian), (arch, None)))
+
+ if module.arch and unsupported_arch():
continue
if module.compilers and not compiler in module.compilers:
continue
@@ -275,10 +284,12 @@ class Project:
# 'newdeps' is a list of tuples, where the first element of each tuple
# is the name of the module to gather, and the second is modules from
# which the dependency comes from (for logging).
+
newdeps = []
blacklist = []
while True:
# Get the previous dependencies.
+
for dep in newdeps:
name = dep[0]
try:
@@ -297,6 +308,7 @@ class Project:
newdeps = []
# Check the dependencies.
+
for name, module in modules.items():
for dep in module.deps:
if not dep in modules and not dep in blacklist:
@@ -305,11 +317,13 @@ class Project:
else: ndep[1].append(name)
# No dependency? Good!
+
if not newdeps:
break
# TODO: check conflicts.
# We're done!
+
return modules
# End of file.
diff --git a/tools/potato/_utils.py b/tools/potato/_utils.py
new file mode 100644
index 0000000..532492c
--- /dev/null
+++ b/tools/potato/_utils.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+""" General utilities for the libcarrot build tools. """
+
+__al__ = ["PotatoException", "PotatoWarning"]
+
+# ---
+# Base exception utilities.
+# ---
+
+class PotatoException(Exception):
+ """ The base class for PotatoSDK exceptions. """
+
+ ret = 1
+ ags = ()
+ msg = None
+
+ def __init__(self, *args):
+ if self.msg == None:
+ message = f"Internal exception '{type(self).__name__}'"
+ else:
+ try: args = self.prepare(args)
+ except: pass
+
+ kw = dict(zip(self.ags, args))
+ message = self.msg.format(**kw)
+
+ super(PotatoException, self).__init__(message)
+
+class PotatoWarning(Warning):
+ """ The base class for PotatoSDK warnings. """
+
+ def __init__(self, *args):
+ kw = dict(zip(self.ags, args))
+ super(PotatoWarning, self).__init__(self.msg.format(**kw))
+
+class SilentException(PotatoException):
+ """ The silent exception, for exiting silently (usually because the
+ error messages have already been put, eventually by sub-commands). """
+
+ def __init__(self):
+ super().__init__("")
+
+def Raise(e):
+ """ Raise the exception or warning. """
+
+ try:
+ raise e from None
+ except PotatoWarning as e:
+ print(f"Warning: {str(e)}", file = _sys.stderr)
+
+# ---
+# Module-related exceptions.
+# ---
+
+class ProjectFileError(PotatoException):
+ """ Could not read or decode the project file. """
+
+ def __init__(self, e):
+ super().__init__(f"Opening project information file failed: {str(e)}")
+ self.__exc = e
+
+ @property
+ def exc(self):
+ """ Exception that occured while opening project information file. """
+
+ return self.__exc
+
+class ConfigFileError(PotatoException):
+ """ Could not read or decode the configuration file. """
+
+ def __init__(self, e):
+ super().__init__(f"Opening configuration file failed: {str(e)}")
+ self.__exc = e
+
+ @property
+ def exc(self):
+ """ Exception that occured while opening configuration file. """
+
+ return self.__exc
+
+# End of file.
diff --git a/tools/python3.sh b/tools/python3.sh
deleted file mode 100755
index 715736b..0000000
--- a/tools/python3.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/sh
-is_python3() {
- if ! command -v "$1" 1>/dev/null 2>/dev/null; then
- return 1
- fi
- ver="`$@ --version`"
- if ! [ $? -eq 0 ] || ! [ x"${ver:0:9}" = x"Python 3." ]; then
- return 1
- fi
-
- return 0
-}
-
-py=
-for command in 'env python3' '/usr/bin/env python3' 'python3' 'py -3' \
-'/usr/bin/python3'; do
- if is_python3 "$command"; then
- py="$command"
- break
- fi
-done
-if [ x"$py" = x"" ]; then
- echo "Python 3.x not found." >&2
- exit 1
-fi
-
-$py "$@"
-exit $?
-
-# End of file.
diff --git a/tools/testthings.py b/tools/testthings.py
deleted file mode 100644
index 4ee5509..0000000
--- a/tools/testthings.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python3
-from Internals import *
-
-# XXX: test utility
-# XXX: shall remove once tested
-
-if __name__ == '__main__':
- hdr = parse_header('arch/casiowin/fxlib/include/dispbios.h')
- output_header('', hdr)
-
-# End of file.
diff --git a/tools/updatesource.py b/tools/updatesource.py
deleted file mode 100755
index 18a6948..0000000
--- a/tools/updatesource.py
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/env python3
-""" This tool updates the top comment on each source and include file
- using the copyright.yml and roles.yml files.
-"""
-
-import os, textwrap
-from Internals import *
-
-# ---
-# Set up the argument parser.
-# ---
-
-argparser = CarrotArgumentParser(_(\
- "Updates the top comments of the module source, include files and "
- "header bits using the machine-readable copyright and roles files."))
-
-# ---
-# Main function and data.
-# ---
-
-__file_groups = [
- ('include', ['h', 'hpp', None]),
- ('bits', ['h', 'hpp', None]),
- ('src', ['c', 'cpp', 'cc', 'cp', 'cxx', 'c++'])
-]
-
-def __split_path(path):
- """ Split a path. """
-
- tree, leaf = os.path.split(path)
- if not tree: return (leaf,)
- return __split_path(tree) + (leaf,)
-
-def __repeat(element):
- """ Simple generator that repeateadly repeats a given element. """
-
- while True:
- yield element
-
-def __get_files(name, module):
- """ Returns the (name, path, role, copyrights, license) list. """
-
- files = []
- for directory, ext in __file_groups:
- lst = module.getfiles(directory, ext=ext)
-
- fp = map(lambda x: module.getpath(directory, x), lst)
- names = map(lambda x: '/'.join(__split_path(x)), lst)
- roles = map(lambda x: module.getrole(directory, x), lst)
- files.extend(zip(names, fp, roles, __repeat(name)))
-
- return files
-
-def main():
- """ Main function for the `update_license.py` program. """
-
- # Parse the arguments.
- args = argparser.parse_args()
-
- # Get the project root.
- root = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))
-
- # Get the copyright rules.
- rules = get_copyright_rules(root)
-
- # Print the list of all available modules.
- g = SourceGlobal(os.path.join(root, 'arch'))
- modules = g.getallmodules()
-
- # Get all of the files in the available modules.
- files = []
- for key, module in modules.items():
- files.extend(__get_files(key, module))
-
- # Print the information.
- for name, path, role, module_name in files:
- authors, license = get_copyright(rules, path)
- content = get_source_content(path)
-
- topc = make_top_comment(module_name, name, role, authors, license)
- swap_path = os.path.join(os.path.dirname(path),
- '.%s.chg' % os.path.basename(path))
-
- with open(swap_path, 'w') as swp:
- swp.write(topc)
- swp.write(content)
-
- # Comment the next line if you're doing experiments, so that the
- # source file isn't affected.
- os.rename(swap_path, path)
-
-if __name__ == "__main__":
- do_main(main)
-
-# End of file.