libc: сплит «1 функция = 1 модуль» — вся библиотека, wildcard-сборка

- bios/conio/env/errno/gfx/io/mem/mouse/stdio/stdlib/string/sys/time/
  video разложены по модулям: общие статики и helpers — в internal
  _-модулях (_conio.h/_mouse.h/_gfx.h/_palette.h/_atexit.h/_time.h)
- lib/Makefile: LIBC_C = wildcard libc/*/*.c — гранулярность файлов
  = гранулярность DCE линкера
- эффект _CODE: gfx_text 6986→2568 Б, gfx_mous −1745, gfx_demo/d16
  −542; ранее timedir −3270, ls −3098, stattest −2995
- комментарии оставшихся модулей переведены на русский; puts: убран
  мёртвый pchars; videomode_raw разложен на get/set
- docs/libc-split-asm-cases.md — правила asm-связок между модулями;
  docs/libc-roadmap.md — план этапа
- восстановлен examples/mdview/SAMPLE.MD (нужен make floppy)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-06 16:08:58 +03:00
parent 46553f4e07
commit 4a081501d8
237 changed files with 4830 additions and 3933 deletions
+49 -48
View File
@@ -1,31 +1,33 @@
/*
* dec_print.c — compact decimal print primitives ported from solid-c
* (third_party/solid-c/SRC/CLIB/STDLIB.ASM, modules dec8/dec16/dec32).
* dec_print.c — компактная десятичная печать, портировано из solid-c
* (third_party/solid-c/SRC/CLIB/STDLIB.ASM, модули dec8/dec16/dec32).
*
* void dec8 (uint8_t v) — no-leading-zero "0" .. "255"
* void dec16(uint16_t v) — no-leading-zero "0" .. "65535"
* void dec32(uint32_t v) — no-leading-zero "0" .. "4294967295"
* void dec8 (uint8_t v) — без ведущих нулей, "0" .. "255"
* void dec16(uint16_t v) — без ведущих нулей, "0" .. "65535"
* void dec32(uint32_t v) — без ведущих нулей, "0" .. "4294967295"
*
* Algorithm: subtract-power-of-10 with running counter, then emit the
* digit unless we are still on leading zeros. 32-bit values use a
* BC/DE/HL pair plus the shadow set (exx) for the high half.
* Алгоритм: вычитание степени десяти со счётчиком, цифра печатается,
* если ведущие нули уже кончились. 32-битные значения живут в паре
* BC/DE/HL плюс теневой набор (exx) для старшей половины.
*
* Layout: dec32 is the master routine; dec8/dec16 are tiny wrappers
* that prepare state and jump to internal entry points (__dec_entry3
* for "last 3 digits", __dec_entry5 for "last 5") — same idea as
* solid-c, sharing most of the per-digit code.
* Раскладка: dec32 — главная рутина; dec8/dec16 — крошечные обёртки,
* готовящие состояние и прыгающие на внутренние входы (__dec_entry3
* «последние 3 цифры», __dec_entry5 — «последние 5») — как в solid-c,
* per-digit код общий. Поэтому файл сознательно НЕ разрезан на три
* модуля: dec8 всё равно притянул бы тело dec32
* (см. docs/libc-split-asm-cases.md, случай 1).
*
* ESTEX PUTCHAR ($5B) preserves IX (empirically verified) so no
* push/pop ix around the RST.
* ESTEX PUTCHAR ($5B) сохраняет IX (проверено эмпирически), так что
* push/pop ix вокруг RST не нужен.
*/
#include <stdio.h>
#include <stdint.h>
/* Leading-zero suppression flag — 0 means "still skipping zeros",
* non-zero means "first non-zero digit seen, print everything from
* here on (including subsequent zeros)". */
static uint8_t dec_flag = 0;
/* Флаг подавления ведущих нулей: 0 — «всё ещё пропускаем нули»,
* не-0 — «первая значащая цифра встречена, дальше печатаем всё
* (включая последующие нули)». */
static uint8_t dec_flag;
void dec8(uint8_t v) __naked
{
@@ -33,9 +35,9 @@ void dec8(uint8_t v) __naked
__asm
;; A = v.
ld l, a
ld h, #0 ; HL = value
ld h, #0 ; HL = значение
xor a, a
ld (_dec_flag), a ; reset suppress-leading-zero flag
ld (_dec_flag), a ; сбросить флаг подавления нулей
jp __dec_entry3
__endasm;
}
@@ -46,7 +48,7 @@ void dec16(uint16_t v) __naked
__asm
;; HL = v.
exx
ld hl, #0 ; HL alt = 0 (high 16 of composite)
ld hl, #0 ; HL-альт = 0 (старшие 16 составного)
exx
xor a, a
ld (_dec_flag), a
@@ -58,17 +60,17 @@ void dec32(uint32_t v) __naked
{
(void)v;
__asm
;; HL = high16, DE = low16 on entry (SDCC HLDE).
;; Move high16 into HL alt (shadow set), low16 into HL.
;; На входе HL = high16, DE = low16 (SDCC HLDE).
;; Старшие 16 в HL-альт (теневой набор), младшие в HL.
push hl
exx
pop hl ; HL alt = high16
pop hl ; HL-альт = high16
exx
ex de, hl ; HL = low16
xor a, a
ld (_dec_flag), a
;; ---- 5 most-significant decades (1e9..1e5) ----
;; ---- 5 старших декад (1e9..1e5) ----
ld de, #0xCA00
exx
ld de, #0x3B9A ; 0x3B9ACA00 = 1,000,000,000
@@ -99,7 +101,7 @@ void dec32(uint32_t v) __naked
exx
call _dec_get_d32
__dec_entry5:: ; entered from dec16
__dec_entry5:: ; вход из dec16
ld de, #10000
exx
ld de, #0
@@ -109,38 +111,38 @@ void dec32(uint32_t v) __naked
ld de, #1000
call _dec_get_d16
__dec_entry3:: ; entered from dec8
__dec_entry3:: ; вход из dec8
ld de, #100
call _dec_get_d16
ld de, #10
call _dec_get_d16
;; Units digit always emitted (so dec*(0) prints "0").
;; Цифра единиц печатается всегда (dec*(0) выводит "0").
ld a, l
add a, #0x30
ld c, #0x5B
rst #0x10
ret
;; ---- 32-bit: how many times DE+DE_alt fits in HL+HL_alt ----
;; ---- 32 бита: сколько раз DE+DE-альт укладывается в HL+HL-альт ----
_dec_get_d32:
ld a, #0x2F ; 0x2F = '0' minus 1 (pre-decrement)
ld a, #0x2F ; 0x2F = символ перед 0 (пред-декремент)
and a, a ; CF = 0
_dec_get_d32_loop:
inc a
sbc hl, de ; low half
sbc hl, de ; младшая половина
exx
sbc hl, de ; high half (with chained borrow)
sbc hl, de ; старшая половина (с цепочкой заёма)
exx
jp nc, _dec_get_d32_loop
;; Overshot restore the last good value.
;; Перебрали вернуть последнее корректное значение.
add hl, de
exx
adc hl, de
exx
jr _dec_emit_or_skip
;; ---- 16-bit: how many times DE fits in HL ----
;; ---- 16 бит: сколько раз DE укладывается в HL ----
_dec_get_d16:
ld a, #0x2F
and a, a
@@ -149,28 +151,27 @@ void dec32(uint32_t v) __naked
sbc hl, de
jp nc, _dec_get_d16_loop
add hl, de
;; Fall through to emit/skip.
;; Fall-through в emit/skip.
_dec_emit_or_skip:
;; A = digit char in 0x30..0x39. If non-'0', latch the flag.
;; Print only if flag is non-zero.
ld b, a ; save digit across the flag test
;; A = символ цифры 0x30..0x39. Не-ноль защёлкивает флаг.
;; Печатаем только при взведённом флаге.
ld b, a ; спасти цифру на время проверки флага
cp a, #0x30
jr z, _dec_check_flag
ld (_dec_flag), a ; non-zero digit seen
ld (_dec_flag), a ; встречена значащая цифра
_dec_check_flag:
ld a, (_dec_flag)
or a, a
ld a, b ; restore digit (ld does not touch flags)
ret z ; leading zero skip print
ld a, b ; вернуть цифру (ld флаги не трогает)
ret z ; ведущий ноль печать пропустить
;; ESTEX PUTCHAR ($5B) preserves the main register set (BC, DE,
;; HL, IX) but CLOBBERS the shadow set (BC alt, DE alt, HL alt).
;; The 32-bit subtract-power-of-10 loop in _dec_get_d32 keeps
;; the high 16 bits of the running remainder in HL alt, so we
;; save/restore HL alt around the RST. Main HL (= low 16 of
;; remainder) survives the call untouched, no save needed.
;; See memory/estex_putchar_abi.md.
;; ESTEX PUTCHAR ($5B) сохраняет основной набор (BC, DE, HL,
;; IX), но КЛОББЕРИТ теневой (BC/DE/HL-альт). Цикл вычитания
;; степени десяти в _dec_get_d32 держит старшие 16 бит остатка
;; в HL-альт, поэтому HL-альт сохраняем вокруг RST. Основной
;; HL (младшие 16 остатка) переживает вызов сам, спасать не
;; нужно. См. memory/estex_putchar_abi.md.
exx
push hl
exx
+6 -5
View File
@@ -1,11 +1,12 @@
/*
* getchar via ESTEX RST 10h.
* getchar — через ESTEX RST 10h.
*
* ESTEX 0x30 (WAITKEY): blocks until a key, returns
* A = scan code, D = position code, E = ASCII,
* C = mode flags, B = shift flags.
* ESTEX 0x30 (WAITKEY): блокируется до нажатия клавиши, возвращает
* A = скан-код, D = позиционный код, E = ASCII,
* C = флаги режима, B = флаги шифтов.
*
* IX is preserved (RST 10h clobbers it; callers rely on it as frame pointer).
* IX сохраняется (RST 10h его клобберит; для вызывающего это frame
* pointer).
*/
#include <stdio.h>
+22
View File
@@ -0,0 +1,22 @@
/*
* hex16 — печать uint16 всегда четырьмя hex-цифрами ("0000".."FFFF"):
* два вызова hex8 (старший байт call, младший — tail-call jp).
* Кросс-модульные переходы по имени функции — работают через линкер.
*/
#include <stdio.h>
#include <stdint.h>
void hex16(uint16_t v) __naked
{
(void)v;
__asm
;; HL = v на входе.
ld a, h
push hl
call _hex8
pop hl
ld a, l
jp _hex8 ; tail-call
__endasm;
}
+19
View File
@@ -0,0 +1,19 @@
/*
* hex32 — печать uint32 всегда восемью hex-цифрами: два вызова hex16
* (старшая половина call, младшая — tail-call jp).
*/
#include <stdio.h>
#include <stdint.h>
void hex32(uint32_t v) __naked
{
(void)v;
__asm
;; HL = старшие 16, DE = младшие 16 на входе (SDCC HLDE).
push de
call _hex16
pop hl
jp _hex16 ; tail-call
__endasm;
}
+35
View File
@@ -0,0 +1,35 @@
/*
* hex8 — печать uint8 всегда двумя hex-цифрами ("00".."FF") через
* ESTEX PUTCHAR ($5B). Каждый нибл — классический трюк Z80
* `cp 10 / sbc 0x69 / daa` (5 байт на нибл). Self-call на _hex8_digit
* для старшего нибла, затем проваливание на младший.
*
* ESTEX PUTCHAR сохраняет IX (проверено эмпирически) — push/pop ix
* вокруг RST не нужен. Портировано из solid-c STDLIB.ASM.
*/
#include <stdio.h>
#include <stdint.h>
void hex8(uint8_t v) __naked
{
(void)v;
__asm
;; A = v на входе.
push af
rra
rra
rra
rra
call _hex8_digit
pop af
_hex8_digit:
and a, #0x0F
cp a, #10
sbc a, #0x69
daa
ld c, #0x5B
rst #0x10
ret
__endasm;
}
-68
View File
@@ -1,68 +0,0 @@
/*
* hex_print.c — compact hex print primitives ported from solid-c
* (third_party/solid-c/SRC/CLIB/STDLIB.ASM, modules hex8/hex16/hex32).
*
* void hex8 (uint8_t v) — always-2-digit "00" .. "FF"
* void hex16(uint16_t v) — always-4-digit "0000" .. "FFFF"
* void hex32(uint32_t v) — always-8-digit "00000000" .. "FFFFFFFF"
*
* Each nibble is emitted via the classic Z80 `cp 10 / sbc 0x69 / daa`
* trick — 5 bytes per nibble. hex8 self-calls for the high nibble
* then falls through for the low nibble. hex16/hex32 split into two
* hex8/hex16 calls.
*
* ESTEX PUTCHAR ($5B) preserves IX (empirically verified) so we skip
* the usual push/pop ix around the RST.
*/
#include <stdio.h>
#include <stdint.h>
void hex8(uint8_t v) __naked
{
(void)v;
__asm
;; A = v on entry.
push af
rra
rra
rra
rra
call _hex8_digit
pop af
_hex8_digit:
and a, #0x0F
cp a, #10
sbc a, #0x69
daa
ld c, #0x5B
rst #0x10
ret
__endasm;
}
void hex16(uint16_t v) __naked
{
(void)v;
__asm
;; HL = v on entry.
ld a, h
push hl
call _hex8
pop hl
ld a, l
jp _hex8 ; tail-call
__endasm;
}
void hex32(uint32_t v) __naked
{
(void)v;
__asm
;; HL = high16, DE = low16 on entry (SDCC HLDE).
push de
call _hex16
pop hl
jp _hex16 ; tail-call
__endasm;
}
+9 -9
View File
@@ -1,16 +1,16 @@
/*
* putchar — emit one character via ESTEX PUTCHAR ($5B).
* putchar — вывести один символ через ESTEX PUTCHAR ($5B).
*
* Turbo-C convention: this stdio.h function is the FAST path with NO
* attribute control. Whatever ESTEX has cached for the cursor cell is
* used (typically the shell's default colour). Translates '\n' to
* CR LF for C-string semantics.
* Конвенция Turbo-C: эта stdio.h-функция — БЫСТРЫЙ путь БЕЗ управления
* атрибутом. Используется то, что ESTEX закэшировал для ячейки курсора
* (обычно цвет шелла по умолчанию). '\n' транслируется в CR LF по
* семантике C-строк.
*
* For coloured output, use putch() / cputs() / cprintf() from <conio.h>
* — those honour textattr / g_text_attr at the cost of being ~10× slower.
* Для цветного вывода — putch() / cputs() / cprintf() из <conio.h>:
* они учитывают textattr / g_text_attr ценой ~10-кратного замедления.
*
* SDCC __sdcccall(1): char arg in L (low byte of HL=int). Returns the
* char in DE (SDCC int return).
* SDCC __sdcccall(1): char-аргумент в L (младший байт HL=int).
* Возврат символа в DE (int-возврат SDCC).
*/
#include <stdio.h>
+11 -27
View File
@@ -1,39 +1,23 @@
/*
* puts — C99 fputs(s, stdout) + '\n'.
* puts — C99: вывести строку + '\n'.
*
* Turbo-C convention: stdio's `puts` is the FAST path with NO attribute
* control — backed by ESTEX PCHARS ($5C). Cursor cell attributes are
* whatever ESTEX has cached (usually the shell's default).
* Конвенция Turbo-C: stdio-шный puts — БЫСТРЫЙ путь БЕЗ управления
* атрибутом; атрибуты ячеек — какие ESTEX закэшировал (обычно цвет
* шелла). Для цветного вывода — cputs() / cprintf() из <conio.h>.
*
* For coloured output use cputs() / cprintf() from <conio.h>.
*
* Implementation notes:
* - PCHARS does NOT translate '\n' to CR LF, so we copy the string
* into a static buffer expanding each '\n' to CR LF, then append
* the trailing CR LF before the NUL.
* - Avoid trailing PUTCHAR after PCHARS — empirically that sometimes
* drops the next char. Embed the line ending inside the PCHARS
* buffer instead.
* Реализация: посимвольный цикл через putchar (он транслирует '\n' в
* CR LF), в конце — putchar('\n'). Быстрый путь через ESTEX PCHARS
* ($5C) не используется: PCHARS не транслирует '\n', а добивать хвост
* через PUTCHAR после PCHARS нельзя — эмпирически это иногда теряло
* следующий символ.
*/
#include <stdio.h>
#include <stdint.h>
static void pchars(const char *s) __naked
{
(void)s;
__asm
push ix
ld c, #0x5C
rst #0x10
pop ix
ret
__endasm;
}
char puts(const char *s) __naked
{
(void)s;
(void)s;
__asm
puts_:
ld a, (hl)
@@ -47,7 +31,7 @@ char puts(const char *s) __naked
inc hl
jp puts_
;
fin_:
fin_:
ld l, #0x0A
ld h, #0
call _putchar