Compare commits

..
Author SHA1 Message Date
waozi c26b7ec943 Fix web build: include <stddef.h> for NULL in platform_thread.c
platform_thread.c uses NULL but only included <stdlib.h> under _WIN32.
On native, <pthread.h> (pulled in by platform.h) transitively provides
NULL, so the build passed. Emscripten's stricter header setup under
-DUI_EMBEDDED_ONLY does not, causing:

  error: use of undeclared identifier 'NULL'

Add the standard <stddef.h> include unconditionally.
2026-07-26 10:58:16 -05:00
877 changed files with 24200 additions and 206893 deletions

No files matched your search

-68
View File
@@ -1,68 +0,0 @@
name: Automatic Release Version
on:
workflow_run:
workflows: [CI]
types: [completed]
permissions:
contents: write
actions: write
concurrency:
group: kryon-auto-release
cancel-in-progress: false
jobs:
bump-and-release:
if: >-
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'master'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
- name: Skip an already released commit
id: guard
run: |
if git tag --points-at HEAD --list 'v*' | grep -q .; then
echo 'release=false' >> "$GITHUB_OUTPUT"
else
echo 'release=true' >> "$GITHUB_OUTPUT"
fi
- name: Resolve next version
if: steps.guard.outputs.release == 'true'
id: version
run: |
current=$(make -s version)
if git rev-parse -q --verify "refs/tags/$current" >/dev/null; then
version=$(scripts/bump-version.sh patch)
else
version=$current
fi
echo "tag=$version" >> "$GITHUB_OUTPUT"
- name: Commit version
if: steps.guard.outputs.release == 'true'
run: |
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git add include/kryon_version.h
if ! git diff --cached --quiet; then
git commit -m "release: bump version to ${{ steps.version.outputs.tag }}"
git push origin HEAD:master
fi
- name: Start release workflow
if: steps.guard.outputs.release == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: >-
gh workflow run release.yml --ref master
-f version=${{ steps.version.outputs.tag }}
-f prerelease=false
-174
View File
@@ -1,174 +0,0 @@
name: CI
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
# Cancel a superseded run on the same ref.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
guard-submodule-urls:
name: Submodule URLs are public HTTPS
runs-on: ubuntu-latest
steps:
# Plain checkout on purpose: the guard must not depend on fetching
# the submodules it validates (an SSH URL would break that fetch).
- name: Checkout Repository
uses: actions/checkout@v7
- name: Reject non-HTTPS submodule URLs
run: sh scripts/check-submodule-urls.sh
test-linux:
name: Build and test (Linux)
needs: guard-submodule-urls
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v7
with:
submodules: recursive
- name: Install Packages
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake libssl-dev pkg-config \
zlib1g-dev libzstd-dev libbrotli-dev \
libglib2.0-dev libgtk-3-dev \
libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev \
ripgrep python3 xvfb xauth xdotool imagemagick libgl1-mesa-dev libx11-dev
- name: Build
run: |
set -euo pipefail
make clean CMAKE=/usr/bin/cmake
make all CMAKE=/usr/bin/cmake
- name: Test
run: make test CMAKE=/usr/bin/cmake
- name: Native rendering and widget catalog audit
run: |
set -euo pipefail
make overlay-paint-test CMAKE=/usr/bin/cmake
xvfb-run -a make texture-scope-test CMAKE=/usr/bin/cmake
xvfb-run -a -s '-screen 0 1920x1080x24' python3 tests/widget_catalog_audit.py
- name: Upload native widget audit
if: always()
uses: actions/upload-artifact@v7
with:
name: widget-catalog-audit-linux
path: |
build/widget-catalog-audit/*.json
build/widget-catalog-audit/*.png
build/widget-catalog-audit/*.log
if-no-files-found: ignore
- name: Text input latency gate
run: |
set -euo pipefail
make perf-text-input CMAKE=/usr/bin/cmake | grep '^{' | tee text-input-perf.jsonl
cat text-input-perf.jsonl >> "$GITHUB_STEP_SUMMARY"
- name: Upload text input measurements
uses: actions/upload-artifact@v7
with:
name: text-input-perf-linux
path: text-input-perf.jsonl
if-no-files-found: error
test-freebsd:
name: Build and test (FreeBSD)
needs: guard-submodule-urls
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v7
with:
submodules: recursive
- name: Build and test on FreeBSD VM
uses: vmactions/freebsd-vm@v1
with:
usesh: true
mem: 4096
prepare: |
set -eu
pkg install -y gmake cmake pkgconf \
sdl2 libdrm mesa-libs gtk3 \
curl openssl zstd brotli \
git go python3 ripgrep
run: |
set -eu
gmake clean
gmake all
gmake test
if ! gmake perf-text-input; then
echo "FreeBSD text-input measurements are non-gating during calibration" >&2
fi
sanitizers:
name: Memory safety (${{ matrix.sanitizer }})
needs: guard-submodule-urls
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
sanitizer: [asan, ubsan]
steps:
- name: Checkout Repository
uses: actions/checkout@v7
with:
submodules: recursive
- name: Install Packages
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake libssl-dev pkg-config \
zlib1g-dev libzstd-dev libbrotli-dev libglib2.0-dev libgtk-3-dev \
libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev
- name: Run sanitizer suite
run: make test-${{ matrix.sanitizer }} CMAKE=/usr/bin/cmake
portable-go:
name: Pure Go runtime (${{ matrix.goos }})
needs: guard-submodule-urls
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
goos: [linux, windows, darwin]
steps:
- name: Checkout Repository
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: go/kryon/go.mod
- name: Compile tests
working-directory: go/kryon
env:
GOOS: ${{ matrix.goos }}
CGO_ENABLED: 0
run: go test -c -o "kryon.test.${GOOS}" .
- name: Run native Go tests
if: matrix.goos == 'linux'
working-directory: go/kryon
env:
CGO_ENABLED: 0
run: go test ./...
+124
View File
@@ -0,0 +1,124 @@
name: Netlify
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: netlify-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: Build Site
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Packages
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake cmark zlib1g-dev zip
- name: Set Up Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EMSDK=$HOME/emsdk" >> "$GITHUB_ENV"
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk" >> "$GITHUB_PATH"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Build Site
run: |
set -euo pipefail
make docs-site CMAKE=/usr/bin/cmake
test -f build/site/index.html
test -f build/site/api.html
test -f build/site/icons/kryon.png
test -f build/site/icons/c.png
test ! -f build/site/API.md
- name: Upload Site Artifact
uses: actions/upload-artifact@v4
with:
name: kryon-site
path: build/site
if-no-files-found: error
deploy-preview:
name: Deploy Preview
runs-on: ubuntu-latest
needs: build
if: github.event_name == 'pull_request'
steps:
- name: Download Site Artifact
uses: actions/download-artifact@v4
with:
name: kryon-site
path: build/site
- name: Install Netlify CLI
run: npm install --global netlify-cli
- name: Deploy Preview To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
test -n "$auth_token" || { echo "::error::NETLIFY_AUTH_TOKEN is empty or missing"; exit 1; }
test -n "$site_id" || { echo "::error::NETLIFY_SITE_ID is empty or missing; use the Netlify Site ID, not the site URL"; exit 1; }
netlify deploy \
--dir build/site \
--alias "pr-${{ github.event.pull_request.number }}" \
--message "Preview ${{ github.event.pull_request.number }}" \
--auth "$auth_token" \
--site "$site_id"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
deploy-production:
name: Deploy Production
runs-on: ubuntu-latest
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
steps:
- name: Download Site Artifact
uses: actions/download-artifact@v4
with:
name: kryon-site
path: build/site
- name: Install Netlify CLI
run: npm install --global netlify-cli
- name: Deploy Production To Netlify
run: |
set -euo pipefail
auth_token="$(printf '%s' "$NETLIFY_AUTH_TOKEN" | tr -d '\r\n')"
site_id="$(printf '%s' "$NETLIFY_SITE_ID" | tr -d '\r\n')"
test -n "$auth_token" || { echo "::error::NETLIFY_AUTH_TOKEN is empty or missing"; exit 1; }
test -n "$site_id" || { echo "::error::NETLIFY_SITE_ID is empty or missing; use the Netlify Site ID, not the site URL"; exit 1; }
netlify deploy \
--dir build/site \
--prod \
--message "Production ${{ github.sha }}" \
--auth "$auth_token" \
--site "$site_id"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
-105
View File
@@ -1,105 +0,0 @@
name: Cloudflare Pages
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: pages-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: Build Site
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v7
with:
submodules: recursive
- name: Install Packages
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake cmark zlib1g-dev zip
- name: Set Up Emscripten
run: |
set -euo pipefail
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$HOME/emsdk"
"$HOME/emsdk/emsdk" install latest
"$HOME/emsdk/emsdk" activate latest
echo "EMSDK=$HOME/emsdk" >> "$GITHUB_ENV"
echo "EM_CONFIG=$HOME/emsdk/.emscripten" >> "$GITHUB_ENV"
echo "$HOME/emsdk" >> "$GITHUB_PATH"
echo "$HOME/emsdk/upstream/emscripten" >> "$GITHUB_PATH"
- name: Build Site
run: |
set -euo pipefail
make docs-site CMAKE=/usr/bin/cmake SITE_BUILD_DIR=build/site
test -f build/site/index.html
test -f build/site/api.html
test -f build/site/ide.html
test -f build/site/ide.js
test -f build/site/ide-tools/k2kir.js
test -f build/site/ide-tools/k2kir.wasm
test -f build/site/ide-tools/k2b.js
test -f build/site/ide-tools/k2b.wasm
test -f build/site/icons/proj/kryon.png
test ! -f build/site/API.md
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Upload Site Artifact
uses: actions/upload-artifact@v7
with:
name: kryon-site
path: build/site
if-no-files-found: error
deploy-preview:
name: Deploy Preview
runs-on: ubuntu-latest
needs: build
if: github.event_name == 'pull_request'
steps:
- name: Download Site Artifact
uses: actions/download-artifact@v4
with:
name: kryon-site
path: build/site
- name: Deploy Preview To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=kryon --branch=${{ github.head_ref || github.ref_name }}
deploy-production:
name: Deploy Production
runs-on: ubuntu-latest
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
steps:
- name: Download Site Artifact
uses: actions/download-artifact@v4
with:
name: kryon-site
path: build/site
- name: Deploy Production To Cloudflare Pages
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build/site --project-name=kryon --branch=master
+6 -34
View File
@@ -33,7 +33,7 @@ jobs:
steps:
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: recursive
@@ -51,11 +51,6 @@ jobs:
v[0-9]*.[0-9]*.[0-9]*) ;;
*) echo "Version must look like v0.1.0" >&2; exit 1 ;;
esac
header_tag="$(sed -n 's/^#define KRYON_VERSION_STRING "\([^"]*\)".*/\1/p' include/kryon_version.h)"
if [ "$tag" != "$header_tag" ]; then
echo "Requested $tag but include/kryon_version.h contains $header_tag" >&2
exit 1
fi
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
echo "Tag $tag already exists; nothing to release."
echo "tag=" >> "$GITHUB_OUTPUT"
@@ -135,7 +130,7 @@ jobs:
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v4
with:
ref: ${{ steps.ref.outputs.tag }}
submodules: recursive
@@ -145,7 +140,7 @@ jobs:
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y build-essential cmake libssl-dev pkg-config zlib1g-dev libzstd-dev libbrotli-dev libglib2.0-dev libgtk-3-dev libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev ripgrep
sudo apt-get install -y build-essential cmake libssl-dev pkg-config zlib1g-dev libzstd-dev libbrotli-dev libsdl2-dev libdrm-dev libgbm-dev libegl1-mesa-dev libgles2-mesa-dev
- name: Build And Test
run: |
@@ -163,40 +158,17 @@ jobs:
test -n "$archive"
echo "KRYON_STATIC_ARCHIVE=$archive" >> "$GITHUB_ENV"
- name: Package Every Kryon Tool
run: |
set -euo pipefail
make dist-tools CMAKE=/usr/bin/cmake VERSION="${{ steps.ref.outputs.tag }}"
make check-tools-package CMAKE=/usr/bin/cmake VERSION="${{ steps.ref.outputs.tag }}"
archive="$(find dist -maxdepth 1 -type f -name 'kryon-*-tools-*.tar.gz' | head -n 1)"
test -n "$archive"
echo "KRYON_TOOLS_ARCHIVE=$archive" >> "$GITHUB_ENV"
- name: Write Checksums
run: |
sha256sum "$KRYON_STATIC_ARCHIVE" "$KRYON_TOOLS_ARCHIVE" > SHA256SUMS
- name: Upload Static Library Artifact
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: kryon-static-library-${{ steps.ref.outputs.tag }}
path: ${{ env.KRYON_STATIC_ARCHIVE }}
if-no-files-found: error
- name: Upload Tools Artifact
uses: actions/upload-artifact@v7
with:
name: kryon-tools-${{ steps.ref.outputs.tag }}
path: ${{ env.KRYON_TOOLS_ARCHIVE }}
if-no-files-found: error
- name: Publish GitHub Release
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ref.outputs.tag }}
name: Kryon ${{ steps.ref.outputs.tag }}
prerelease: ${{ github.event_name == 'workflow_dispatch' && inputs.prerelease || false }}
files: |
${{ env.KRYON_STATIC_ARCHIVE }}
${{ env.KRYON_TOOLS_ARCHIVE }}
SHA256SUMS
files: ${{ env.KRYON_STATIC_ARCHIVE }}
-114
View File
@@ -1,114 +0,0 @@
name: renderers
# Build downloadable KRB renderers for every platform: the headless
# renderer (krb-run) as native binaries, and the web player (krb-web)
# as static files any site can host.
on:
push:
branches: [master]
tags: ["v*"]
workflow_dispatch:
permissions:
contents: write
jobs:
native:
strategy:
fail-fast: false
matrix:
include:
- { os: ubuntu-latest, cc: cc, suffix: linux-x86_64, build_dir: build/linux-x86_64 }
- { os: ubuntu-latest, cc: x86_64-w64-mingw32-gcc, suffix: windows-x86_64, build_dir: build/linux-x86_64 }
- { os: macos-latest, cc: /usr/bin/clang, suffix: macos-arm64, build_dir: build/macos-arm64 }
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Install mingw (windows cross)
if: matrix.suffix == 'windows-x86_64'
run: sudo apt-get update && sudo apt-get install -y mingw-w64
- name: Install GNU make (macOS)
if: runner.os == 'macOS'
run: brew install make
- name: Build krb-run
# The Makefile's KRY_SW_SRCS is the single source of truth for what
# every renderer build links; never pin a copy of the list here.
run: |
target="${{ matrix.build_dir }}/bin/krb-run"
if [ "${{ runner.os }}" = macOS ]; then
env -u MAKE -u MAKEFLAGS -u MFLAGS -u MAKEFILES \
CC=${{ matrix.cc }} /opt/homebrew/bin/gmake -e -f ./Makefile "$target"
else
make "$target" CC=${{ matrix.cc }}
fi
[ "${{ matrix.suffix }}" = windows-x86_64 ] && target="$target.exe"
cp "$target" build/krb-run
- name: Rename
run: cp build/krb-run krb-run-${{ matrix.suffix }}${{ matrix.suffix == 'windows-x86_64' && '.exe' || '' }}
- uses: actions/upload-artifact@v7
with:
name: krb-run-${{ matrix.suffix }}
path: krb-run-${{ matrix.suffix }}*
web:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- uses: mymindstorm/setup-emsdk@v14
with:
version: latest
- name: Build web player
run: make krb-web
- name: Package
run: |
mkdir -p krb-player-web && cp build/linux-x86_64/web/krb-web/* krb-player-web/
cp examples/02_buttons.kry /tmp/ 2>/dev/null || true
- uses: actions/upload-artifact@v7
with:
name: krb-player-web
path: krb-player-web/
exactness:
# Cross-engine byte-exactness needs no GL (SDL dummy + software).
# The native pixel-compare vs the inbe C build additionally needs a
# working screenshot pipeline: xvfb-run, as inbe's own CI does.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
- name: Build tools
run: |
sudo apt-get update
sudo apt-get install -y libsdl2-dev
make build/linux-x86_64/bin/k2b \
build/linux-x86_64/bin/krb-run \
build/linux-x86_64/bin/krb-sdl \
build/linux-x86_64/tests/krb_logic_test \
build/linux-x86_64/tests/krb_asset_test
- name: Cross-engine exactness
run: sh tests/krb_exact_test.sh .
- name: Unit tests
run: |
build/linux-x86_64/tests/krb_logic_test
build/linux-x86_64/tests/krb_asset_test
# Native gate: once inbe CI checks out kryon master as its vendor,
# run tests/krb_exact_native_test.sh per ported screen under xvfb:
# xvfb-run -a ./inbe --screenshot native.png --screenshot-scene language ...
release:
if: startsWith(github.ref, 'refs/tags/')
needs: [native, web]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
- run: |
mkdir rel && cp -r krb-run-* krb-player-web rel/
- uses: softprops/action-gh-release@v3
with:
files: rel/*
-7
View File
@@ -2,12 +2,9 @@
*.o
*.so
*.dll
*.pyc
*~
*.tmp
__pycache__/
.zcode
.kryon-ide-state
# Build output
build/
@@ -15,7 +12,3 @@ dist/
assets/fonts/*
tools/otfchop/otfchop
# native plan9 cpp-stage intermediates
src/**/*.i
src/**/*.8
+3 -6
View File
@@ -10,9 +10,6 @@
[submodule "vendor/cmark-gfm"]
path = vendor/cmark-gfm
url = https://github.com/github/cmark-gfm.git
[submodule "vendor/box2d"]
path = vendor/box2d
url = https://github.com/erincatto/box2d.git
[submodule "vendor/monocypher"]
path = vendor/monocypher
url = https://github.com/LoupVaillant/Monocypher.git
[submodule "vendor/clay"]
path = vendor/clay
url = https://github.com/nicbarker/clay.git
-63
View File
@@ -1,63 +0,0 @@
# Kryon Repository Rules
Kryon is the canonical runtime. Keep it small, direct, and free of stale
surfaces.
## Clean API Rule
Do not introduce new public generated-runtime APIs with stale prefixes or
compatibility names. New `.kry` generated code must target the clean runtime
surface:
- `BeginFrame`
- `EndFrame`
- `Text`
- `Button`
- `TextField`
- `TextArea`
- `Row`
- `Column`
Do not add `kryc`. The supported transpilers are `k2go` for native Go, `k2c`
for native C, and `k2cpp` for native C++ (C++ codegen over the C runtime).
Generated Go must be native Go and must not use cgo, `go/kryui`, `kryruntime`,
or an injected `rt` runtime object. Generated C must not call stale prefixed UI
symbols such as `DrawUI*`, `UIText*`, `TextInputControl`, or `UIRender*`.
Existing compatibility code may only remain while actively migrating callers.
Do not expand it, duplicate it under another alias, or use it from generated
output. Remove compatibility code once no maintained app or fixture depends on
it.
## Canonical Widget Rule
One widget concept has one public implementation. Variations such as wrapping,
clipping, color, alignment, and disabled state belong in that widget's props;
do not create parallel helpers such as `TextWrapped`, `TextColored`, or
`TextDisabled`. Migrate maintained callers when consolidating an older split
surface, then remove the duplicate entry points and generated output.
`Text` has exactly one public signature: `Text(TextProps)`. Every maintained C
and `.kry` caller must pass one explicit `TextProps` value. Position, bounds,
wrapping, clipping, color, alignment, and disabled state belong in those props.
Do not restore the positional `Text(text, x, y, font, color)` form or hide it
behind a helper, macro, overload, generated shim, or compatibility alias.
## Test Rule
Any change to k2go, k2c, k2cpp, the Go runtime, or the C runtime surface must keep the
generated-output scanners and runtime parity tests passing. If a new widget or
semantic is added, add it to both generated runtimes and to parity coverage in
the same change.
Run `python3 scripts/check-clean-text-api.py <changed-source-roots>` when a
maintained app or fixture changes text rendering. Downstream repositories must
wire this check into their normal test target.
## Readability Rule
Write conventional, fully readable code. Do not compress multiple statements,
branches, or error checks onto one line. Handlers and protocol code must use
descriptive names, explicit control flow, and focused helpers. Run the language
formatter and inspect the resulting diff before considering a change complete.
+4 -1748
View File
File diff suppressed because it is too large. Load diff
+108 -954
View File
File diff suppressed because it is too large. Load diff
+39 -151
View File
@@ -1,21 +1,17 @@
<p align="center">
<img src="assets/app/readme-banner.png" alt="Kryon" width="100%">
</p>
# Kryon
Kryon is a small C support library for raylib-style applications. It keeps a
raylib-compatible public surface available through `kryon.h`, then adds the
pieces shared by downstream apps: UI controls, Tk-style toolkit widgets, layout
helpers, text rendering, themes, embedded assets, locale loading, file dialogs,
desktop tray support, runtime asset downloads, and optional account/sync helpers.
desktop tray support, runtime asset downloads, and Lyra account/sync helpers.
## Layout
- `include/` - public headers, including `kryon.h` and generated raylib
compatibility declarations
- `src/` - Kryon implementation files, with reusable UI modules under `src/ui/`
- `icons/` - MingCute UI and full-color spritesheets embedded by `src/ui/ui_icon_assets.c`
- `icons/` and `pfp/` - PNG icon inputs embedded into `src/ui/ui_icon_assets.c`
- `themes/` - built-in theme files for the runtime theme loader
- `fonts/noto/` - bundled Noto Sans TTF/OTF font assets
- `mk/` - Make fragments for native, web, Android, Windows, packaging, and
@@ -35,27 +31,19 @@ Kryon builds with the repository Makefile:
make
```
On FreeBSD, use the repository `makefile` entrypoint. It delegates to the GNU
Make build while keeping `make` as the command downstream apps can run:
```bash
make bsd-check
```
Run the focused tests with:
```bash
make test
```
Backend selection is link-time via `KRYON_BACKEND`. Supported backends are:
- [`raylib`](https://github.com/raysan5/raylib) - the default desktop,
Android, Windows, and WebGL path, with SDL2/OpenGL integration in the build
rules.
- [`canvas`](docs/CANVAS2D_PARITY.md) - the HTML5 Canvas2D/WebAudio backend
for Emscripten web builds.
- [`dom`](src/backend/dom_backend.c) - the browser DOM/CSS backend for web UI
surfaces.
- [`libdraw`](https://9fans.github.io/plan9port/man/man3/draw.html) - the
plan9port libdraw/devdraw backend.
- [`termi`](src/backend/termi_backend.c) - the terminal-cell backend.
- `null` - generated no-op stubs for headless tests and unsupported surface
areas.
Build a distributable static-library archive with:
```bash
@@ -71,12 +59,6 @@ manifest, and the submodule revisions used to build it. Validate it with:
make check-static-package
```
Run the full release readiness gate with:
```bash
make release-preflight
```
`libkryon.a` stays focused on Kryon object files. Companion libraries are shipped
beside it and linked through `lib/pkgconfig/kryon.pc`. OpenSSL is still treated
as an external system/toolchain dependency unless explicit OpenSSL static library
@@ -84,19 +66,11 @@ paths are supplied at build time.
## Releases
Every successful CI run on `master` automatically advances the patch version,
commits `include/kryon_version.h`, and starts the tag-driven `Release` workflow.
The workflow validates the version, creates an annotated tag, builds and tests
Kryon, and publishes both the static SDK and a checksummed native tools bundle.
The tools bundle contains `k2c`, `k2cpp`, `k2go`, `k2js`, `k2kir`, `k2b`, `kt`, `kryon`,
`kryon-preview`, `krb-run`, and `krb-sdl`. The renderer workflow also attaches
the Linux, Windows, and macOS `krb-run` builds plus the web player to the same
release.
Maintainers can still run `Release` manually for the checked-in version. Use
`scripts/bump-version.sh minor` / `major` before pushing when a non-patch bump is
required. Pushing a matching `v*` tag manually uses the same build-and-publish
path; releases reject tags that disagree with the public version header.
Kryon releases are tag-driven. Run the `Release` GitHub Actions workflow with a
version such as `v0.1.0`; the workflow validates the version, creates and pushes
the annotated tag, checks out that tag, builds and tests Kryon, packages the
static-library archive, uploads it as an artifact, and attaches it to the GitHub
release. Pushing a `v*` tag manually uses the same build-and-publish path.
## Integration
@@ -106,15 +80,9 @@ To integrate Kryon into your project:
2. Include `kryon.h` for the raylib-compatible API plus Kryon modules
3. Compile Kryon sources from `src/` and `src/ui/`, or use the `mk/` fragments
to let Kryon assemble source lists and platform flags
4. Kryon's checked-in `icons/` tree is the source of truth for the finished
MingCute Core UI sheet, a separate full-color logo sheet, and the full-color platform,
payment, language, tile, and profile sheets. `make icons-embed` refreshes the embedded C assets from
those sheets. Use `DrawIcon` or the generated `Icon` widget with a runtime
`Color`; no per-color files or per-icon textures are needed. Downstream apps
can call `vendor/kryon/scripts/sync-icons.sh` to copy the sheets. Maintainers
can refresh the UI subset from an upstream checkout with
`make icons-import-mingcute MINGCUTE_DIR=/path/to/mingcute-icons`.
`scripts/embed-assets.sh` remains available for non-icon assets.
4. Use `scripts/embed-icons.sh` and `scripts/embed-assets.sh` when your app
needs custom embedded icons, locale files, fonts, themes, or image/audio
assets
5. Include `mk/vendor.mk` when your app enables curl or liboqs-backed features
Applications should keep build artifacts in their own build directories, but
@@ -124,77 +92,43 @@ variables through to the vendored curl CMake build.
## App Builds
Kryon owns the app command surface through `kryon`. From an app repository:
Kryon owns the app command surface through `kryon-app`. From an app repository:
```sh
kryon build native
kryon build web
kryon build android-debug
kryon package linux-desktop
kryon package appimage
kryon preview
kryon-app build native
kryon-app build web
kryon-app build android-debug
kryon-app package appimage
kryon-app preview
```
For local development against a sync backend, run a Daochi node in the
foreground. `dev-backend` locates the server source at `$DAOCHI_DIR` or as a
sibling checkout (`../daochi`), isolates its data under `<project>/.kryon/`, and
prints the sync URL to point your app at. Tokens are regenerated each start,
so it is for local development only:
```sh
kryon dev-backend # serves http://127.0.0.1:8080
```
Apps can keep startup simple with one `SyncNodePool`: add the shipped public
node as `SYNC_NODE_PUBLIC`, add LAN or remote nodes learned through explicit
pairing as `SYNC_NODE_PAIRED`, then call `RunSyncWithNodes`. The pool tries a
paired local node first, another paired node second, and the public node last.
Temporary connectivity and authentication failures fall through automatically;
credentials and clock state remain isolated per node.
App `project.kryon` files should use `target` entries that call `kryon`
App `project.kryon` files should use `target` entries that call `kryon-app`
rather than embedding platform-specific build commands directly. Existing app
Makefiles can remain as backend glue while repeated native, web, Android, and
packaging logic moves into Kryon `mk/` fragments.
## Preview Projects
Krait, the standalone Kryon IDE (a separate `kryonlabs/krait` repo that vendors
Kryon), previews `.kry` source by compiling it to an app host and loading it
into the embedded viewport. On each source change Krait rebuilds the project's
app host (`make kryon-host`, producing `build/kryon/app_host.so`), `dlopen`s
it, and resolves `CreateAppHost`/`DestroyAppHost`. The build runs in the
background (`fork` + non-blocking pipe, drained each frame) so the window stays
responsive during the compile; once it finishes the new app host is loaded and
the preview updates. Source changes are polled a few times per second. Kryon
itself owns the preview host tooling (`kryon-preview`); it must not depend on
Krait.
A project can add `project.kryon` metadata such as `preview_size`,
`preview_asset_root`, and `preview_scene` to control the embedded viewport.
Kryon IDE can host richer project previews without requiring the project to be
rewritten as `.kry` screens. A project can add `project.kryon` metadata such as
`preview_size`, `preview_asset_root`, and `preview_scene`, then provide a
`build_live` command that builds `build/kryon/live_preview.so`. The live module
continues to expose the normal `CreateKryonLivePreview`/`AppHost` entry point,
and can optionally expose `CreateKryonPreviewHost` for future scene/layer editing
metadata. This keeps gameplay or simulation code in the app while letting Kryon
IDE select scenes, draw interactive previews, and eventually edit shared preview
layers.
## Conventions
Kryon follows raylib-style C conventions where practical: lowercase module
filenames, simple C structs, and public functions named like raylib APIs
(`InitWindow`, `DrawTexture`, `BeginUIFrame`, `ButtonNode`). Internal helpers
(`InitWindow`, `DrawTexture`, `BeginUIFrame`, `DrawUIButton`). Internal helpers
stay private to `src/` unless a downstream app needs the API in `include/`.
## Documentation
- `docs/API.md` documents the public API.
- `docs/KRY_LANGUAGE_SPEC.md` is the canonical `.kry` language and KIR
contract.
- `docs/FEATURE_MATRIX.md` maps widget and feature support across the C, Go,
and KRB targets and every renderer backend.
- `docs/BACKENDS.md` documents the backend architecture and selection.
- `docs/BACKEND_CAPABILITIES.json` is the checked backend inventory used by
backend drift checks.
- `docs/ARCHITECTURE.md` maps the main Kryon subsystems and ownership lines.
- `docs/BOUNDARIES.md` defines what belongs in Kryon and what stays in
downstream applications.
- `docs/PUBLIC_API_SNAPSHOT.txt` tracks public Kryon identifiers for API drift
checks.
- `docs/site/` contains the static documentation website.
- `docs/AGENTS.md` documents how downstream apps should use Kryon, including
modal/input capture and submodule update rules.
@@ -207,55 +141,9 @@ immediate-mode drawing, and no builder objects or scripting runtime. The numbere
examples `09_geometry` through `18_accessibility` demonstrate each toolkit
feature family.
## Kry Language
## Kry Language Direction
`docs/KRY_LANGUAGE_SPEC.md` is the canonical Kry language contract. Kry source
lowers into KIR, a debuggable intermediate representation with source spans.
From there `k2c` emits readable C for native apps, `k2cpp` emits C++ with C
linkage against the same C runtime, `k2go` emits pure Go source
against the native Go runtime, while `k2b` emits a portable `.krb` cartridge
(`docs/KRB_FORMAT.md`) for renderers that implement the Kryon runtime contract.
The intended tool set is Unix-shaped:
```text
k2kir app.kry # .kry -> .kir
k2c app.kry|app.kir
k2cpp app.kry # .kry -> C++ (extern "C" decls over the C runtime)
k2go app.kry # .kry -> Go (native Go runtime, no cgo)
k2b app.kry|app.kir
```
Generated Go imports `github.com/waozixyz/kryon/go/kryon` as `kryon` and uses
clean qualified widget names such as `kryon.Button`, `kryon.TextField`,
`kryon.Text`, `kryon.Row`, `kryon.Column`, `kryon.BeginFrame`, and
`kryon.EndFrame`. Pure Kry and Go-native externs must not use `import "C"`,
the removed bridge package, injected runtime objects, dot-imported runtime
names, or generated calls to stale prefixed C APIs. Explicit C externs with a
`c.` target, such as `#extern "c.abs"`, are the opt-in exception: `k2go` emits
their `import "C"` bridge in a separate generated `*_cgo.go` file.
Handwritten Go can use the same package directly. Generated code keeps the
explicit props form (`kryon.Button(kryon.ButtonProps{...})`,
`kryon.TextField(kryon.TextFieldProps{...})`) for deterministic layout/state,
while app code may use shorter direct calls such as `kryon.Button("Save")` and
`kryon.TextField("Name", &name)`.
The native Go runtime records each frame as pure Go `FrameOp` values available
through `FrameOps()`. That operation stream is the host boundary for native Go
windows/renderers: it carries resolved bounds, text, colors, focus, button
state, and redacted secure text without importing cgo or the removed bridge.
`RenderFrame` and `RenderCurrentFrame` provide a dependency-free software
renderer that turns those operations into an `image.RGBA`.
`NewHost` owns a persistent native Go runtime, runs generated or handwritten
frame functions, queues input, exposes frame operations, and renders frames
without cgo.
`k2go` output is compiled against that native runtime by the test suite, and the
generated Go/C parity tests drive both runtimes through the same scripted input.
This is an executable compatibility gate, not only a textual generated-source
check.
`k2c`, `k2js`, and `k2b` accept `.kry` source and run the KIR frontend
internally. Native platform, storage, and performance-sensitive C code remains
first-class through the C backend and through explicit KRB capabilities or host
imports.
`docs/KRY_LANGUAGE_PLAN.md` describes the migration path for making `.kry` a
C-close, C-transpiled app language with direct C interoperability. The goal is
for apps to move product UI and screen controllers into Kry while keeping native
platform, storage, and performance-sensitive code in C.
+1 -5
View File
@@ -7,12 +7,8 @@ submodules listed in `SUBMODULES.txt`.
- liboqs: MIT license, see `vendor/liboqs/LICENSE.txt` in the source tree.
- curl/libcurl: curl license, see `vendor/curl/COPYING` in the source tree.
- cmark-gfm: BSD-style license, see `vendor/cmark-gfm/COPYING` in the source tree.
- Clay: zlib/libpng license, see `vendor/clay/LICENSE.md` in the source tree.
- Noto fonts: SIL Open Font License 1.1, see `fonts/noto/LICENSE.txt` in the source tree.
- MingCute Core icons: Apache License 2.0, see
`licenses/mingcute/LICENSE.txt` in the source tree. Kryon embeds only the
selected, renamed monochrome subset used by its UI in `icons/ui.png`.
Apache 2.0 does not grant rights to third-party trademarks depicted by some
brand icons; applications remain responsible for appropriate trademark use.
OpenSSL is not vendored into the package by default. When `kryon.pc` lists
`-lssl -lcrypto`, those libraries are expected to come from the target system or
Binary file not shown.

Before

Width:  |  Height:  |  Size: 429 KiB

-116
View File
@@ -1,116 +0,0 @@
include_guard(GLOBAL)
function(kryon_generate_kry_sources out_sources out_include_dir)
set(options NO_MAIN)
set(one_value_args KRYON_DIR ROOT OUT_DIR TARGET)
set(multi_value_args SOURCES)
cmake_parse_arguments(KRYGEN "${options}" "${one_value_args}" "${multi_value_args}" ${ARGN})
if(NOT KRYGEN_KRYON_DIR)
message(FATAL_ERROR "kryon_generate_kry_sources requires KRYON_DIR")
endif()
if(NOT KRYGEN_ROOT)
message(FATAL_ERROR "kryon_generate_kry_sources requires ROOT")
endif()
if(NOT KRYGEN_OUT_DIR)
message(FATAL_ERROR "kryon_generate_kry_sources requires OUT_DIR")
endif()
if(NOT KRYGEN_TARGET)
message(FATAL_ERROR "kryon_generate_kry_sources requires TARGET")
endif()
if(NOT KRYGEN_SOURCES)
message(FATAL_ERROR "kryon_generate_kry_sources requires SOURCES")
endif()
file(GLOB KRYGEN_K2C_SOURCES CONFIGURE_DEPENDS "${KRYGEN_KRYON_DIR}/cmd/k2c/*.c")
list(APPEND KRYGEN_K2C_SOURCES
"${KRYGEN_KRYON_DIR}/cmd/kir/kir.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_parse.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_text.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_token.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_expr.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_cleanup.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_check.c"
"${KRYGEN_KRYON_DIR}/cmd/kir/kir_emit.c")
if(KRYON_HOST_CC)
set(KRYGEN_HOST_CC "${KRYON_HOST_CC}")
else()
foreach(krygen_host_cc_candidate
/usr/bin/cc
/bin/cc
/usr/bin/gcc
/usr/bin/clang
/usr/local/bin/cc
/usr/local/bin/gcc
/usr/local/bin/clang
/opt/homebrew/bin/cc
/opt/homebrew/bin/gcc
/opt/homebrew/bin/clang)
if(NOT KRYGEN_HOST_CC AND EXISTS "${krygen_host_cc_candidate}")
set(KRYGEN_HOST_CC "${krygen_host_cc_candidate}")
endif()
endforeach()
endif()
if(NOT KRYGEN_HOST_CC)
find_program(KRYGEN_HOST_CC
NAMES cc gcc clang
NO_CMAKE_FIND_ROOT_PATH)
endif()
if(NOT KRYGEN_HOST_CC)
message(FATAL_ERROR "kryon_generate_kry_sources requires a host C compiler; set KRYON_HOST_CC")
endif()
set(KRYGEN_K2C "${CMAKE_BINARY_DIR}/kryon-host-tools/k2c")
set(krygen_generated_sources)
set(krygen_generated_headers)
set(krygen_command_sources)
foreach(kry_source ${KRYGEN_SOURCES})
file(RELATIVE_PATH kry_rel "${KRYGEN_ROOT}" "${kry_source}")
list(APPEND krygen_command_sources "${kry_rel}")
get_filename_component(kry_rel_dir "${kry_rel}" DIRECTORY)
get_filename_component(kry_name "${kry_rel}" NAME_WE)
list(APPEND krygen_generated_sources "${KRYGEN_OUT_DIR}/${kry_rel_dir}/${kry_name}.c")
list(APPEND krygen_generated_headers "${KRYGEN_OUT_DIR}/${kry_rel_dir}/${kry_name}.h")
endforeach()
set(krygen_flags)
if(KRYGEN_NO_MAIN)
list(APPEND krygen_flags --no-main)
endif()
add_custom_command(
OUTPUT
${krygen_generated_sources}
${krygen_generated_headers}
"${KRYGEN_OUT_DIR}/kryon_project.c"
"${KRYGEN_OUT_DIR}/kryon_project.h"
COMMAND ${CMAKE_COMMAND} -E remove_directory "${KRYGEN_OUT_DIR}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${KRYGEN_OUT_DIR}"
COMMAND "${KRYGEN_K2C}" ${krygen_flags} --root "${KRYGEN_ROOT}" -o "${KRYGEN_OUT_DIR}" ${krygen_command_sources}
DEPENDS ${KRYGEN_SOURCES} "${KRYGEN_K2C}"
WORKING_DIRECTORY "${KRYGEN_ROOT}"
VERBATIM
)
add_custom_command(
OUTPUT "${KRYGEN_K2C}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_BINARY_DIR}/kryon-host-tools"
COMMAND "${KRYGEN_HOST_CC}" -Wall -Wextra -O2
-I${KRYGEN_KRYON_DIR}/cmd/kir
-I${KRYGEN_KRYON_DIR}/cmd/k2c
-o "${KRYGEN_K2C}"
${KRYGEN_K2C_SOURCES}
DEPENDS ${KRYGEN_K2C_SOURCES}
VERBATIM
)
add_custom_target("${KRYGEN_TARGET}" DEPENDS
${krygen_generated_sources}
${krygen_generated_headers}
"${KRYGEN_OUT_DIR}/kryon_project.c"
"${KRYGEN_OUT_DIR}/kryon_project.h"
)
set(${out_sources} ${krygen_generated_sources} PARENT_SCOPE)
set(${out_include_dir} "${KRYGEN_OUT_DIR}" PARENT_SCOPE)
endfunction()
-240
View File
@@ -1,240 +0,0 @@
#include "k2b_atlas.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include "../../vendor/raylib/src/external/stb_truetype.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ATLAS_W 512
static void
put_u16(unsigned char *p, unsigned v)
{
p[0] = (unsigned char)v;
p[1] = (unsigned char)(v >> 8);
}
static void
put_u32(unsigned char *p, unsigned long v)
{
p[0] = (unsigned char)v;
p[1] = (unsigned char)(v >> 8);
p[2] = (unsigned char)(v >> 16);
p[3] = (unsigned char)(v >> 24);
}
/* Layout: "KFA1" u32 | size_count u16 | per-size 16-byte records
* (px u16 | glyphs u16 | w u16 | h u16 | table_off u32 | pixels_off u32),
* per-glyph 18-byte records (cp u32 | x,y,w,h u16 | xoff,yoff i16 |
* adv u16 in 1/256 px fixed point), then per-size RGBA8 white-on-alpha
* bitmaps.
*
* Rasterization is raylib-identical: per-glyph
* stbtt_GetCodepointBitmap at stbtt_ScaleForPixelHeight(size) with
* advances from stbtt_GetCodepointHMetrics * scale — the same calls
* rtext.c LoadFontData(FONT_DEFAULT) makes, so glyph coverage matches
* the native renderer bit-for-bit. Glyphs row-pack first-fit. */
unsigned char *
k2b_bake_atlas(const char *ttf_path, const unsigned int *codepoints,
int cp_count, const int *sizes, int size_count,
unsigned *out_len)
{
unsigned char *ttf = NULL;
long ttf_len;
FILE *f;
stbtt_fontinfo font;
unsigned char *buf = NULL;
unsigned buf_cap;
unsigned buf_len;
int s;
if(out_len != NULL)
*out_len = 0;
if(ttf_path == NULL || codepoints == NULL || cp_count <= 0 ||
sizes == NULL || size_count <= 0)
return NULL;
f = fopen(ttf_path, "rb");
if(f == NULL)
return NULL;
fseek(f, 0, SEEK_END);
ttf_len = ftell(f);
fseek(f, 0, SEEK_SET);
ttf = malloc((size_t)ttf_len);
if(ttf == NULL || fread(ttf, 1, (size_t)ttf_len, f) != (size_t)ttf_len) {
fclose(f);
free(ttf);
return NULL;
}
fclose(f);
if(!stbtt_InitFont(&font, ttf, 0)) {
free(ttf);
return NULL;
}
buf_len = 6 + (unsigned)size_count * 16;
buf_cap = buf_len + 4096;
buf = malloc(buf_cap);
if(buf == NULL) {
free(ttf);
return NULL;
}
put_u32(buf, 0x3141464Bu); /* "KFA1" */
put_u16(buf + 4, (unsigned)size_count);
for(s = 0; s < size_count; s++) {
int px = sizes[s];
float scale = stbtt_ScaleForPixelHeight(&font, (float)px);
int ascent = 0;
int descent = 0;
int line_gap = 0;
/* rtext.c line 730: offsetY += (int)(ascent*scale) — raylib's
* glyph offset is line-top-relative, not baseline-relative */
stbtt_GetFontVMetrics(&font, &ascent, &descent, &line_gap);
unsigned char *raw_px;
unsigned rec_bytes = (unsigned)cp_count * 18;
unsigned table_off;
unsigned pixels_off;
int height;
int i;
/* rec is recomputed after every realloc of buf */
{
int total_h = 1;
int row_h = 0;
int cur_x = 0;
for(i = 0; i < cp_count; i++) {
int x0 = 0;
int y0 = 0;
int x1 = 0;
int y1 = 0;
int w;
int h;
stbtt_GetCodepointBitmapBox(&font, (int)codepoints[i], scale,
scale, &x0, &y0, &x1, &y1);
w = x1 - x0;
h = y1 - y0;
if(w < 0)
w = 0;
if(h < 0)
h = 0;
if(cur_x + w > ATLAS_W) {
total_h += row_h > 0 ? row_h : 1;
row_h = 0;
cur_x = 0;
}
cur_x += w + 1;
if(h > row_h)
row_h = h;
}
height = total_h + row_h + 1;
}
while(buf_len + rec_bytes + (unsigned)ATLAS_W * height * 4 >
buf_cap) {
unsigned char *nb = realloc(buf, buf_cap * 2);
if(nb == NULL)
break;
buf = nb;
buf_cap *= 2;
}
if(buf_len + rec_bytes + (unsigned)ATLAS_W * height * 4 > buf_cap)
continue;
raw_px = calloc((size_t)ATLAS_W * height, 1);
if(raw_px == NULL)
continue;
table_off = buf_len;
{
int row_y = 0;
int row_h = 0;
int cur_x = 0;
unsigned char *tab = buf + table_off;
for(i = 0; i < cp_count; i++) {
int w = 0;
int h = 0;
int xoff = 0;
int yoff = 0;
int advance = 0;
int lsb = 0;
unsigned char *bm;
unsigned char *g = tab + (unsigned)i * 18;
bm = stbtt_GetCodepointBitmap(&font, scale, scale,
(int)codepoints[i], &w, &h,
&xoff, &yoff);
if(cur_x + w > ATLAS_W) {
row_y += row_h > 0 ? row_h : 1;
row_h = 0;
cur_x = 0;
}
if(w > 0 && h > 0 && bm != NULL && w <= ATLAS_W &&
row_y + h <= height && cur_x + w <= ATLAS_W) {
int gy;
for(gy = 0; gy < h; gy++)
memcpy(raw_px + (size_t)(row_y + gy) * ATLAS_W +
cur_x, bm + (size_t)gy * w, (size_t)w);
}
stbtt_FreeBitmap(bm, NULL);
stbtt_GetCodepointHMetrics(&font, (int)codepoints[i],
&advance, &lsb);
put_u32(g, codepoints[i]);
put_u16(g + 4, (unsigned short)cur_x);
put_u16(g + 6, (unsigned short)row_y);
put_u16(g + 8, (unsigned short)(w > 0 ? w : 0));
put_u16(g + 10, (unsigned short)(h > 0 ? h : 0));
put_u16(g + 12, (unsigned short)(short)xoff);
put_u16(g + 14,
(unsigned short)(short)(yoff +
(int)((float)ascent * scale)));
put_u16(g + 16, (unsigned short)(int)((float)advance *
scale * 256.0f + 0.5f));
cur_x += w + 1;
if(h > row_h)
row_h = h;
}
buf_len += rec_bytes;
}
pixels_off = buf_len;
{
unsigned char *rgba = buf + pixels_off;
long n = (long)ATLAS_W * height;
long k;
for(k = 0; k < n; k++) {
rgba[k * 4 + 0] = 0xff;
rgba[k * 4 + 1] = 0xff;
rgba[k * 4 + 2] = 0xff;
rgba[k * 4 + 3] = raw_px[k];
}
buf_len += (unsigned)n * 4;
}
free(raw_px);
{
unsigned char *rec = buf + 6 + (unsigned)s * 16;
put_u16(rec, (unsigned)px);
put_u16(rec + 2, (unsigned)cp_count);
put_u16(rec + 4, ATLAS_W);
put_u16(rec + 6, (unsigned)height);
put_u16(rec + 2, (unsigned)cp_count);
put_u16(rec + 4, ATLAS_W);
put_u16(rec + 6, (unsigned)height);
put_u32(rec + 8, table_off);
put_u32(rec + 12, pixels_off);
}
}
free(ttf);
if(buf_len <= 6 + (unsigned)size_count * 16) {
free(buf);
return NULL;
}
if(out_len != NULL)
*out_len = buf_len;
return buf;
}
-19
View File
@@ -1,19 +0,0 @@
#ifndef K2B_ATLAS_H
#define K2B_ATLAS_H
#include <stddef.h>
/* Bake a KFA1 glyph atlas (cartridge asset kind 1) from a TTF for the
* given charset and pixel sizes. Returns malloc'd bytes and length, or
* NULL when the font can't be loaded. Layout:
* u32 'KFA1' | u16 size_count
* per size: u16 px, u16 glyph_count, u16 w, u16 h, u32 table_off,
* u32 pixels_off (offsets from buffer start)
* glyph (16B): u32 cp | u16 x,y,w,h | i16 xoff,yoff | u16 advance
* RGBA8 pixels, white with alpha coverage. */
unsigned char *k2b_bake_atlas(const char *ttf_path,
const unsigned int *codepoints, int cp_count,
const int *sizes, int size_count,
unsigned *out_len);
#endif
-3767
View File
File diff suppressed because it is too large. Load diff
-23
View File
@@ -1,23 +0,0 @@
#include "k2b_stb.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_PSD
#define STBI_NO_TGA
#define STBI_NO_GIF
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_PNM
#include "../../vendor/raylib/src/external/stb_image.h"
#include <stdlib.h>
int
k2b_decode_image(const char *file, unsigned char **rgba, int *w, int *h)
{
int n;
if(file == NULL || rgba == NULL || w == NULL || h == NULL)
return -1;
*rgba = stbi_load(file, w, h, &n, 4);
return *rgba != NULL ? 0 : -1;
}
-10
View File
@@ -1,10 +0,0 @@
#ifndef K2B_STB_H
#define K2B_STB_H
/* Image decoding for cartridge embedding, on the stb_image vendored with
* raylib. Returns 0 and fills *rgba (malloc'd, top-down RGBA8 rows) on
* success. */
int k2b_decode_image(const char *file, unsigned char **rgba, int *w, int *h);
#endif
-181
View File
@@ -1,181 +0,0 @@
/*
* k2b util — small path/string helpers used by the codegen.
*/
#include "krb.h"
#include "kir.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
void
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "k2b: ");
vfprintf(stderr, fmt, ap);
fputc('\n', stderr);
va_end(ap);
exit(1);
}
void
path_join(char *dst, size_t dst_size, const char *a, const char *b)
{
if(a == NULL || a[0] == '\0')
snprintf(dst, dst_size, "%s", b);
else if(a[strlen(a) - 1] == '/')
snprintf(dst, dst_size, "%s%s", a, b);
else
snprintf(dst, dst_size, "%s/%s", a, b);
}
void
mkdir_parent(const char *path)
{
char tmp[KIR_PATH_MAX];
size_t i;
snprintf(tmp, sizeof(tmp), "%s", path);
for(i = 1; i < strlen(tmp); i++) {
if(tmp[i] != '/')
continue;
tmp[i] = '\0';
if(mkdir(tmp, 0755) != 0 && errno != EEXIST)
die("%s: mkdir failed: %s", tmp, strerror(errno));
tmp[i] = '/';
}
}
void
header_guard(char *dst, size_t dst_size, const char *rel)
{
size_t n = 0;
if(dst_size > 4) {
dst[n++] = 'K';
dst[n++] = '2';
dst[n++] = 'B';
dst[n++] = '_';
}
for(const char *p = rel; *p != '\0' && n + 1 < dst_size; p++) {
char c = *p;
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9'))
dst[n++] = (c >= 'a' && c <= 'z') ? (char)(c - 'a' + 'A') : c;
else
dst[n++] = '_';
}
dst[n] = '\0';
}
void
strip_kry_ext(char *dst, size_t dst_size, const char *path)
{
size_t len;
if(path == NULL) {
if(dst_size > 0)
dst[0] = '\0';
return;
}
len = strlen(path);
if(len > 4 && strcmp(path + len - 4, ".kry") == 0)
len -= 4;
if(len >= dst_size)
len = dst_size - 1;
memcpy(dst, path, len);
dst[len] = '\0';
}
void
replace_path_basename(char *dst, size_t dst_size, const char *path,
const char *base)
{
const char *slash = NULL;
size_t dir_len;
if(dst_size == 0)
return;
for(const char *p = path; p != NULL && *p != '\0'; p++) {
if(*p == '/' || *p == '\\')
slash = p;
}
if(slash == NULL) {
snprintf(dst, dst_size, "%s", base);
return;
}
dir_len = (size_t)(slash - path + 1);
if(dir_len >= dst_size)
dir_len = dst_size - 1;
memcpy(dst, path, dir_len);
dst[dir_len] = '\0';
snprintf(dst + dir_len, dst_size - dir_len, "%s", base);
}
/* Path relative to root. Handles the common cases (path under root, or path
* already relative); does not fully normalize, which is enough for emitting
* cartridge output paths next to their source. */
const char *
relative_path(const char *root, const char *path)
{
static char rel[KIR_PATH_MAX];
size_t n;
if(root == NULL || root[0] == '\0')
return path;
n = strlen(root);
if(strncmp(path, root, n) == 0 && path[n] == '/')
snprintf(rel, sizeof(rel), "%s", path + n + 1);
else
snprintf(rel, sizeof(rel), "%s", path);
return rel;
}
int
is_ident_text(const char *text)
{
if(text == NULL || text[0] == '\0')
return 0;
if(!(isalpha((unsigned char)text[0]) || text[0] == '_'))
return 0;
for(const char *p = text + 1; *p != '\0'; p++) {
if(!(isalnum((unsigned char)*p) || *p == '_'))
return 0;
}
return 1;
}
void
c_string_literal(char *dst, size_t dst_size, const char *src)
{
size_t n = 0;
if(dst_size == 0)
return;
dst[n++] = '"';
for(const char *p = src != NULL ? src : ""; *p != '\0' && n + 2 < dst_size; p++) {
if(*p == '"' || *p == '\\') {
if(n + 2 >= dst_size)
break;
dst[n++] = '\\';
dst[n++] = *p;
} else if(*p == '\n') {
if(n + 2 >= dst_size)
break;
dst[n++] = '\\';
dst[n++] = 'n';
} else {
dst[n++] = *p;
}
}
if(n + 1 < dst_size)
dst[n++] = '"';
dst[n] = '\0';
}
-96
View File
@@ -1,96 +0,0 @@
/*
* k2b - .kry -> .krb cartridge compiler. Shares the Kir frontend with k2c:
* every .kry parses into a KirProgram (kir_parse.c), then lowers to a .krb
* cartridge + C host (k2b_krb.c). One frontend, two backends.
*/
#include "kir.h"
#include "kir_parse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void write_krb(const KirModule *m, const char *root, const char *out_dir,
int no_main, int allow_unsupported);
static int
validate_asserts(const KirModule *m)
{
for(int i = 0; i < m->assert_count; i++) {
const KirAssert *a = &m->asserts[i];
if(a->guard[0] != '\0') {
fprintf(stderr,
"k2b: %s:%d: guarded #assert is not supported by KRB: %s\n",
a->span.path, a->span.line, a->message);
return 0;
}
if(!a->known) {
fprintf(stderr,
"k2b: %s:%d: unresolved #assert is not supported by KRB: %s\n",
a->span.path, a->span.line, a->condition);
return 0;
}
if(!a->value) {
fprintf(stderr, "k2b: %s:%d: #assert failed: %s\n",
a->span.path, a->span.line, a->message);
return 0;
}
}
return 1;
}
static void
usage(void)
{
fprintf(stderr, "usage: k2b [--no-main] [--allow-unsupported] --root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int no_main = 0;
int allow_unsupported = 0;
int i;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(strcmp(argv[i], "--allow-unsupported") == 0) {
allow_unsupported = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
break;
}
}
if(root == NULL || out_dir == NULL || i >= argc) {
usage();
return 1;
}
for(; i < argc; i++) {
KirProgram *prog = kir_parse_file(argv[i], root);
if(prog == NULL) {
fprintf(stderr, "k2b: failed to parse %s\n", argv[i]);
return 1;
}
for(int m = 0; m < prog->module_count; m++) {
if(!validate_asserts(&prog->modules[m])) {
KirProgramFree(prog);
return 1;
}
write_krb(&prog->modules[m], root, out_dir, no_main,
allow_unsupported);
}
KirProgramFree(prog);
}
return 0;
}
-1648
View File
File diff suppressed because it is too large. Load diff
-37
View File
@@ -1,37 +0,0 @@
#ifndef K2C_LOWER_H
#define K2C_LOWER_H
#include "kir.h"
/* Cross-module symbol table: for each parsed module (by its slash-path),
* every function's .kry name -> full C name. Built by main after parsing all
* inputs; used to resolve alias-qualified calls (start.draw_start_page(...)
* -> ide_start_page_draw_start_page_kry_draw(...)). */
typedef struct K2cModuleSyms {
char module_stem[KIR_PATH_MAX]; /* source path minus .kry */
char module_slash[KIR_PATH_MAX];
struct {
char kry[KIR_NAME_MAX];
char c[KIR_NAME_MAX * 3];
} fns[256];
int fn_count;
} K2cModuleSyms;
/* Lower a KirProgram to C source (.c/.h). restab/restab_count resolve
* cross-module calls; pass NULL/0 to resolve same-module only. */
void k2c_lower(const KirProgram *program, const char *root,
const char *out_dir, const K2cModuleSyms *restab,
int restab_count);
/* Build the symbol table entry for one program into out. */
void k2c_build_syms(const KirProgram *program, K2cModuleSyms *out);
/* Full C name for a function (module prefix, colon naming, _kry_draw). */
void k2c_function_c_name(const KirModule *m, const KirFunction *fn,
char *dst, size_t dst_size);
/* k2c_project.c — kryon_project.h/.c (app-host ABI) after all files lower. */
void k2c_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main);
#endif
-1801
View File
File diff suppressed because it is too large. Load diff
-42
View File
@@ -1,42 +0,0 @@
#ifndef K2C_PLAN9_H
#define K2C_PLAN9_H
/* Post-lowering pass that makes k2c output safe for the native Plan 9
* compilers (8c has no __auto_type, no multi-designator compound
* literals, and no declarations inside for()). Only runs under --plan9;
* the default output is byte-identical to before.
*
* The pass is purely syntactic: types are recovered from cast-literal
* expressions or from a return-type map built by scanning the project's
* headers (--include-dir), the same way the kryon surface declares
* single-line prototypes. */
/* Add a directory scanned (recursively, .h files) for prototypes when
* resolving __auto_type initializers. Call before k2c_lower. */
void k2c_plan9_add_include_dir(const char *dir);
/* Enable --plan9 output post-processing (off by default; the default
* output is unchanged). */
void k2c_plan9_set_enabled(int enabled);
int k2c_plan9_enabled(void);
/* Rewrite one generated C source for 8c. Returns a malloc'd buffer; the
* caller frees. Returns NULL on out-of-memory (caller keeps original). */
char *k2c_plan9_rewrite(const char *text);
/* Rewrite a generated file in place when the plan9 pass is enabled
* (weak-declaration exposure for project files, then the generic pass).
* Returns 0 on success. */
int k2c_plan9_rewrite_file(const char *path, int is_project);
/* Number of __auto_type declarations left unresolved by the last
* k2c_plan9_rewrite call (reported once per run by main). */
int k2c_plan9_unresolved(void);
/* Drop the __GNUC__ guard around the weak app-lifecycle declarations in
* generated project files: the native cpp does not define __GNUC__, so
* the guarded block would compile out and leave the calls without
* prototypes. */
char *k2c_plan9_rewrite_project(const char *text);
#endif
-447
View File
@@ -1,447 +0,0 @@
/*
* k2c_project.c — emit kryon_project.h/.c after all files lower. The
* app-host ABI (CreateAppHost/DestroyAppHost + route table) consumed by
* the preview tool and IDE host builds. Routes auto-collect from #ui
* functions. Explicit route{} blocks supply route id/title/group metadata
* when present.
*/
#include "k2c_lower.h"
#include "k2c_plan9.h"
#include "kir.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
typedef struct K2cRoute {
char id[KIR_NAME_MAX];
char title[KIR_NAME_MAX];
char group[KIR_NAME_MAX];
char source_path[KIR_PATH_MAX];
const KirModule *m;
const KirFunction *fn;
} K2cRoute;
#define K2C_ROUTE_MAX 512
static const KirFunction *
find_ui_function(const KirModule *mod, const char *name)
{
if(mod == NULL || name == NULL || name[0] == '\0')
return NULL;
for(int i = 0; i < mod->function_count; i++) {
const KirFunction *fn = &mod->functions[i];
if(fn->is_public && fn->is_ui && strcmp(fn->name, name) == 0)
return fn;
}
return NULL;
}
static int
function_has_explicit_route(const KirModule *mod, const KirFunction *fn)
{
if(mod == NULL || fn == NULL)
return 0;
for(int i = 0; i < mod->route_count; i++) {
if(strcmp(mod->routes[i].page, fn->name) == 0)
return 1;
}
return 0;
}
static void
mkdir_parent_local(const char *path)
{
char tmp[KIR_PATH_MAX];
size_t i;
snprintf(tmp, sizeof(tmp), "%s", path);
for(i = 1; i < strlen(tmp); i++) {
if(tmp[i] == '/') {
tmp[i] = '\0';
mkdir(tmp, 0755);
tmp[i] = '/';
}
}
}
static void
c_str(char *dst, size_t dst_size, const char *src)
{
size_t n = 0;
dst[n++] = '"';
for(const char *p = src != NULL ? src : "";
*p != '\0' && n + 3 < dst_size; p++) {
if(*p == '"' || *p == '\\') {
dst[n++] = '\\';
dst[n++] = *p;
} else if(*p == '\n') {
dst[n++] = '\\';
dst[n++] = 'n';
} else {
dst[n++] = *p;
}
}
if(n < dst_size)
dst[n++] = '"';
dst[n] = '\0';
}
static int
collect_routes(KirProgram *const *progs, int prog_count,
K2cRoute *routes, int max_routes)
{
int count = 0;
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
for(int j = 0; j < mod->route_count; j++) {
const KirRoute *route = &mod->routes[j];
const KirFunction *fn = find_ui_function(mod, route->page);
if(fn == NULL) {
fprintf(stderr, "%s:%d: route `%s` references missing #ui page `%s`\n",
route->span.path, route->span.line,
route->id, route->page);
continue;
}
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
route->id);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
route->title[0] != '\0' ? route->title : route->id);
snprintf(routes[count].group, sizeof(routes[0].group), "%s",
route->group[0] != '\0' ? route->group : "Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
for(int j = 0; j < mod->function_count; j++) {
const KirFunction *fn = &mod->functions[j];
if(!fn->is_public || !fn->is_ui || fn->name[0] == '\0')
continue;
if(function_has_explicit_route(mod, fn))
continue;
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
fn->name);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
fn->name);
snprintf(routes[count].group, sizeof(routes[0].group),
"Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
}
}
return count;
}
void
k2c_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main)
{
K2cRoute routes[K2C_ROUTE_MAX];
char path[KIR_PATH_MAX];
const KirModule *appmod = NULL;
FILE *out;
int count;
(void)root;
if(progs == NULL || prog_count <= 0)
return;
count = collect_routes(progs, prog_count, routes, K2C_ROUTE_MAX);
/* the one app{} module (for main()) */
for(int i = 0; i < prog_count && appmod == NULL; i++) {
if(progs[i] == NULL)
continue;
for(int m = 0; m < progs[i]->module_count; m++)
if(progs[i]->modules[m].app.has_app) {
appmod = &progs[i]->modules[m];
break;
}
}
/* --- kryon_project.h --- */
snprintf(path, sizeof(path), "%s/kryon_project.h", out_dir);
mkdir_parent_local(path);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2c from project Kry files. */\n");
fprintf(out, "#ifndef K_KRYON_PROJECT_H\n#define K_KRYON_PROJECT_H\n\n");
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
char stem[KIR_PATH_MAX];
size_t n = strlen(mod->source_path);
if(n > 4 && strcmp(mod->source_path + n - 4, ".kry") == 0)
n -= 4;
if(n >= sizeof(stem))
n = sizeof(stem) - 1;
memcpy(stem, mod->source_path, n);
stem[n] = '\0';
fprintf(out, "#include \"%s.h\"\n", stem);
}
}
fprintf(out, "\n#endif\n");
fclose(out);
if(count <= 0)
return;
/* --- kryon_project.c --- */
snprintf(path, sizeof(path), "%s/kryon_project.c", out_dir);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2c from project Kry files. */\n");
fprintf(out, "#include \"kryon_project.h\"\n");
fprintf(out, "#include \"app_runtime.h\"\n");
fprintf(out, "#include \"web.h\"\n");
if(appmod != NULL && appmod->app.font_examples)
fprintf(out, "#include \"kryon_example_font.h\"\n");
fprintf(out, "\n");
fprintf(out, "#if defined(__GNUC__) || defined(__clang__)\n");
fprintf(out, "void *CreateApp(const char *project_path) __attribute__((weak));\n");
fprintf(out, "void DestroyApp(void *app) __attribute__((weak));\n");
fprintf(out, "void ApplyRoute(void *app, const AppRouteInfo *route) __attribute__((weak));\n");
fprintf(out, "void BeginScreenDraw(void *app, Rectangle viewport) __attribute__((weak));\n");
fprintf(out, "#endif\n\n");
for(int i = 0; i < count; i++) {
char cname[KIR_NAME_MAX * 3];
char wrapper[64];
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
k2c_function_c_name(routes[i].m, routes[i].fn, cname, sizeof(cname));
fprintf(out, "static void\n%s(void *app, Rectangle viewport)\n{\n",
wrapper);
fprintf(out, " if(BeginScreenDraw != 0)\n");
fprintf(out, " BeginScreenDraw(app, viewport);\n");
if(strstr(routes[i].fn->args, "Rectangle") != NULL)
fprintf(out, " (void)app;\n %s(viewport);\n", cname);
else if(routes[i].fn->args[0] != '\0')
fprintf(out, " (void)viewport;\n %s(app);\n", cname);
else
fprintf(out, " (void)app;\n (void)viewport;\n %s();\n",
cname);
fprintf(out, "}\n\n");
}
fprintf(out, "static const AppRouteInfo kryon_project_routes[%d];\n\n",
count);
fprintf(out, "static void\nkryon_project_enter(void *app, int index)\n{\n");
fprintf(out, " if(ApplyRoute == 0 || index < 0 || index >= %d)\n",
count);
fprintf(out, " return;\n");
fprintf(out, " ApplyRoute(app, &kryon_project_routes[index]);\n");
fprintf(out, "}\n\n");
fprintf(out, "static const AppRouteInfo kryon_project_routes[] = {\n");
for(int i = 0; i < count; i++) {
char id[KIR_NAME_MAX * 2];
char title[KIR_NAME_MAX * 2];
char group[KIR_NAME_MAX * 2];
char source[KIR_PATH_MAX * 2];
char wrapper[64];
c_str(id, sizeof(id), routes[i].id);
c_str(title, sizeof(title), routes[i].title);
c_str(group, sizeof(group), routes[i].group);
c_str(source, sizeof(source), routes[i].source_path);
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
fprintf(out, " {%s, %s, %s, %s, kryon_project_enter, %s},\n",
id, group, title, source, wrapper);
}
fprintf(out, "};\n\n");
fprintf(out, "static App kryon_project_runtime;\n");
fprintf(out, "static AppHost kryon_project_host;\n\n");
fprintf(out, "AppHost *\nCreateAppHost(int abi_version, const char *project_path)\n{\n");
fprintf(out, " void *app = 0;\n");
fprintf(out, " if(abi_version != APP_HOST_ABI_VERSION)\n");
fprintf(out, " return 0;\n");
fprintf(out, " if(CreateApp != 0) {\n");
fprintf(out, " app = CreateApp(project_path);\n");
fprintf(out, " if(app == 0)\n");
fprintf(out, " return 0;\n");
fprintf(out, " } else {\n");
fprintf(out, " (void)project_path;\n");
fprintf(out, " }\n");
fprintf(out, " kryon_project_runtime.app = app;\n");
fprintf(out, " kryon_project_runtime.routes = kryon_project_routes;\n");
fprintf(out, " kryon_project_runtime.route_count = (int)(sizeof(kryon_project_routes) / sizeof(kryon_project_routes[0]));\n");
fprintf(out, " kryon_project_runtime.selected_route = 0;\n");
fprintf(out, " BindAppHost(&kryon_project_runtime, &kryon_project_host);\n");
fprintf(out, " SetAppScreen(&kryon_project_host, 0);\n");
fprintf(out, " return &kryon_project_host;\n}\n\n");
fprintf(out, "void\nDestroyAppHost(AppHost *host)\n{\n");
fprintf(out, " if(host == 0 || host != &kryon_project_host)\n");
fprintf(out, " return;\n");
fprintf(out, " if(DestroyApp != 0 && kryon_project_runtime.app != 0)\n");
fprintf(out, " DestroyApp(kryon_project_runtime.app);\n");
fprintf(out, " kryon_project_runtime = (App){0};\n");
fprintf(out, " kryon_project_host = (AppHost){0};\n}\n");
fclose(out);
k2c_plan9_rewrite_file(path, 1);
/* --- main() (hook-driven, from KirAppMeta) --- */
if(no_main || appmod == NULL)
return;
out = fopen(path, "ab");
if(out == NULL)
return;
{
int width = appmod->app.width > 0 ? appmod->app.width : 800;
int height = appmod->app.height > 0 ? appmod->app.height : 600;
int fps = appmod->app.fps > 0 ? appmod->app.fps : 60;
int route_host_main = appmod->app.frame[0] == '\0' && count > 0;
char title[KIR_NAME_MAX * 2];
c_str(title, sizeof(title), appmod->app.title);
fprintf(out, "\nint\nmain(void)\n{\n");
if(route_host_main) {
fprintf(out, " AppHost *host;\n");
fprintf(out, " int route_version = -1;\n");
}
fprintf(out, " int width = %d;\n", width);
fprintf(out, " int height = %d;\n", height);
fprintf(out, "#if defined(PLATFORM_WEB)\n");
fprintf(out, " SetConfigFlags(GetWebWindowFlags());\n");
fprintf(out, " GetWebViewportSize(width, height, &width, &height);\n");
fprintf(out, "#endif\n");
fprintf(out, " InitWindow(width, height, %s);\n", title);
fprintf(out, " SetTargetFPS(%d);\n", fps);
if(appmod->app.font_examples)
fprintf(out, " LoadExampleUIFont();\n");
fprintf(out, " InitUI(width, height, GetUIScale());\n");
if(appmod->app.theme[0] != '\0') {
fprintf(out, " SetThemeSource(THEME_SOURCE_APP);\n");
fprintf(out, " SetThemeMode(%s);\n",
appmod->app.dark_mode ? "THEME_MODE_DARK"
: "THEME_MODE_LIGHT");
fprintf(out, " SetCurrentTheme(%s, %d);\n",
appmod->app.theme, appmod->app.dark_mode);
}
if(appmod->app.init[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.init) == 0) {
k2c_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.init);
}
if(route_host_main) {
fprintf(out, " host = CreateAppHost(APP_HOST_ABI_VERSION, \".\");\n");
fprintf(out, " if(host == 0) {\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 1;\n");
fprintf(out, " }\n");
}
fprintf(out, " while(!WindowShouldClose()) {\n");
if(appmod->app.frame[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
const KirFunction *entry = NULL;
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.frame) == 0) {
k2c_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
entry = &appmod->functions[j];
found = 1;
}
}
if(entry != NULL && entry->is_ui) {
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginTree(Key(\"%s\"));\n", hook);
if(strstr(entry->args, "Rectangle") != NULL) {
fprintf(out, " %s((Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n",
hook);
} else {
fprintf(out, " %s();\n", hook);
}
fprintf(out, " EndTree();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " %s();\n",
found ? hook : appmod->app.frame);
}
} else if(route_host_main) {
fprintf(out, " int next_route_version = GetRouteVersion();\n");
fprintf(out, " if(next_route_version != route_version) {\n");
fprintf(out, " if(!SetAppScreenFromRoute(host))\n");
fprintf(out, " ReplaceAppScreenRoute(host, 0);\n");
fprintf(out, " route_version = GetRouteVersion();\n");
fprintf(out, " }\n");
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginTree(Key(\"kryon_project\"));\n");
fprintf(out, " DrawAppScreen(host, (Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n");
fprintf(out, " EndTree();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " ;\n");
}
fprintf(out, " }\n");
if(appmod->app.shutdown[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.shutdown) == 0) {
k2c_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.shutdown);
}
if(route_host_main)
fprintf(out, " DestroyAppHost(host);\n");
if(appmod->app.font_examples)
fprintf(out, " UnloadExampleUIFont();\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 0;\n}\n");
}
fclose(out);
k2c_plan9_rewrite_file(path, 1);
}
-107
View File
@@ -1,107 +0,0 @@
/*
* k2c - .kry -> C compiler. Kir is the only pipeline: every .kry parses
* into a KirProgram (kir_parse.c) and lowers to C (k2c_lower.c). All inputs
* are parsed first so cross-module calls resolve through one symbol table.
*/
#include "kir.h"
#include "kir_parse.h"
#include "kir_check.h"
#include "k2c_lower.h"
#include "k2c_plan9.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2c [--strict] [--no-main] [--plan9] [--include-dir DIR] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int no_main = 0;
int strict = 0;
int plan9 = 0;
int unresolved = 0;
KirProgram **progs;
K2cModuleSyms *syms;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(strcmp(argv[i], "--plan9") == 0) {
plan9 = 1;
} else if(strcmp(argv[i], "--include-dir") == 0 && i + 1 < argc) {
k2c_plan9_add_include_dir(argv[++i]);
} else if(strcmp(argv[i], "--strict") == 0) {
strict = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
syms = calloc((size_t)file_count, sizeof(*syms));
if(progs == NULL || syms == NULL) {
fprintf(stderr, "k2c: out of memory\n");
return 1;
}
k2c_plan9_set_enabled(plan9);
/* Pass 1: parse every file, build the cross-module symbol table. */
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2c: failed to parse %s\n",
argv[first_file + i]);
return 1;
}
k2c_build_syms(progs[i], &syms[i]);
}
if(!KirCheckPrograms(progs, file_count, strict)) {
for(i = 0; i < file_count; i++) KirProgramFree(progs[i]);
free(progs);
free(syms);
return 1;
}
/* Pass 2: lower with full cross-module resolution. */
for(i = 0; i < file_count; i++)
k2c_lower(progs[i], root, out_dir, syms, file_count);
k2c_write_project(progs, file_count, root, out_dir, no_main);
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
free(syms);
unresolved = k2c_plan9_unresolved();
if(plan9 && unresolved > 0) {
/* Unresolved declarations are usually inside platform guards the
* native build compiles out; the in-guest compile is the final
* arbiter, so warn rather than fail. */
fprintf(stderr,
"k2c: --plan9 left %d __auto_type declarations unresolved "
"(guarded code compiles out; the rest must be resolvable)\n",
unresolved);
}
return 0;
}
File diff suppressed because it is too large. Load diff
-37
View File
@@ -1,37 +0,0 @@
#ifndef K2CPP_LOWER_H
#define K2CPP_LOWER_H
#include "kir.h"
/* Cross-module symbol table: for each parsed module (by its slash-path),
* every function's .kry name -> full C name. Built by main after parsing all
* inputs; used to resolve alias-qualified calls (start.draw_start_page(...)
* -> ide_start_page_draw_start_page_kry_draw(...)). */
typedef struct K2cppModuleSyms {
char module_stem[KIR_PATH_MAX]; /* source path minus .kry */
char module_slash[KIR_PATH_MAX];
struct {
char kry[KIR_NAME_MAX];
char c[KIR_NAME_MAX * 3];
} fns[256];
int fn_count;
} K2cppModuleSyms;
/* Lower a KirProgram to C++ source (.cpp/.hpp). restab/restab_count resolve
* cross-module calls; pass NULL/0 to resolve same-module only. */
void k2cpp_lower(const KirProgram *program, const char *root,
const char *out_dir, const K2cppModuleSyms *restab,
int restab_count);
/* Build the symbol table entry for one program into out. */
void k2cpp_build_syms(const KirProgram *program, K2cppModuleSyms *out);
/* Full C name for a function (module prefix, colon naming, _kry_draw). */
void k2cpp_function_c_name(const KirModule *m, const KirFunction *fn,
char *dst, size_t dst_size);
/* k2cpp_project.c — kryon_project.h/.c (app-host ABI) after all files lower. */
void k2cpp_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main);
#endif
-446
View File
@@ -1,446 +0,0 @@
/*
* k2cpp_project.c — emit kryon_project.h/.c after all files lower (the
* project files stay plain C; the generated module headers are .hpp but
* self-guard their extern "C" so C translation units include them too). The
* app-host ABI (CreateAppHost/DestroyAppHost + route table) consumed by
* the preview tool and IDE host builds. Routes auto-collect from #ui
* functions. Explicit route{} blocks supply route id/title/group metadata
* when present.
*/
#include "k2cpp_lower.h"
#include "kir.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
typedef struct K2cppRoute {
char id[KIR_NAME_MAX];
char title[KIR_NAME_MAX];
char group[KIR_NAME_MAX];
char source_path[KIR_PATH_MAX];
const KirModule *m;
const KirFunction *fn;
} K2cppRoute;
#define K2CPP_ROUTE_MAX 512
static const KirFunction *
find_ui_function(const KirModule *mod, const char *name)
{
if(mod == NULL || name == NULL || name[0] == '\0')
return NULL;
for(int i = 0; i < mod->function_count; i++) {
const KirFunction *fn = &mod->functions[i];
if(fn->is_public && fn->is_ui && strcmp(fn->name, name) == 0)
return fn;
}
return NULL;
}
static int
function_has_explicit_route(const KirModule *mod, const KirFunction *fn)
{
if(mod == NULL || fn == NULL)
return 0;
for(int i = 0; i < mod->route_count; i++) {
if(strcmp(mod->routes[i].page, fn->name) == 0)
return 1;
}
return 0;
}
static void
mkdir_parent_local(const char *path)
{
char tmp[KIR_PATH_MAX];
size_t i;
snprintf(tmp, sizeof(tmp), "%s", path);
for(i = 1; i < strlen(tmp); i++) {
if(tmp[i] == '/') {
tmp[i] = '\0';
mkdir(tmp, 0755);
tmp[i] = '/';
}
}
}
static void
c_str(char *dst, size_t dst_size, const char *src)
{
size_t n = 0;
dst[n++] = '"';
for(const char *p = src != NULL ? src : "";
*p != '\0' && n + 3 < dst_size; p++) {
if(*p == '"' || *p == '\\') {
dst[n++] = '\\';
dst[n++] = *p;
} else if(*p == '\n') {
dst[n++] = '\\';
dst[n++] = 'n';
} else {
dst[n++] = *p;
}
}
if(n < dst_size)
dst[n++] = '"';
dst[n] = '\0';
}
static int
collect_routes(KirProgram *const *progs, int prog_count,
K2cppRoute *routes, int max_routes)
{
int count = 0;
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
for(int j = 0; j < mod->route_count; j++) {
const KirRoute *route = &mod->routes[j];
const KirFunction *fn = find_ui_function(mod, route->page);
if(fn == NULL) {
fprintf(stderr, "%s:%d: route `%s` references missing #ui page `%s`\n",
route->span.path, route->span.line,
route->id, route->page);
continue;
}
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
route->id);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
route->title[0] != '\0' ? route->title : route->id);
snprintf(routes[count].group, sizeof(routes[0].group), "%s",
route->group[0] != '\0' ? route->group : "Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
for(int j = 0; j < mod->function_count; j++) {
const KirFunction *fn = &mod->functions[j];
if(!fn->is_public || !fn->is_ui || fn->name[0] == '\0')
continue;
if(function_has_explicit_route(mod, fn))
continue;
if(count >= max_routes)
return count;
snprintf(routes[count].id, sizeof(routes[0].id), "%s",
fn->name);
snprintf(routes[count].title, sizeof(routes[0].title), "%s",
fn->name);
snprintf(routes[count].group, sizeof(routes[0].group),
"Project");
snprintf(routes[count].source_path,
sizeof(routes[0].source_path), "%s",
mod->source_path);
routes[count].m = mod;
routes[count].fn = fn;
count++;
}
}
}
return count;
}
void
k2cpp_write_project(KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, int no_main)
{
K2cppRoute routes[K2CPP_ROUTE_MAX];
char path[KIR_PATH_MAX];
const KirModule *appmod = NULL;
FILE *out;
int count;
(void)root;
if(progs == NULL || prog_count <= 0)
return;
count = collect_routes(progs, prog_count, routes, K2CPP_ROUTE_MAX);
/* the one app{} module (for main()) */
for(int i = 0; i < prog_count && appmod == NULL; i++) {
if(progs[i] == NULL)
continue;
for(int m = 0; m < progs[i]->module_count; m++)
if(progs[i]->modules[m].app.has_app) {
appmod = &progs[i]->modules[m];
break;
}
}
/* --- kryon_project.h --- */
snprintf(path, sizeof(path), "%s/kryon_project.h", out_dir);
mkdir_parent_local(path);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2cpp from project Kry files. */\n");
fprintf(out, "#ifndef K_KRYON_PROJECT_H\n#define K_KRYON_PROJECT_H\n\n");
for(int i = 0; i < prog_count; i++) {
const KirProgram *prog = progs[i];
if(prog == NULL)
continue;
for(int m = 0; m < prog->module_count; m++) {
const KirModule *mod = &prog->modules[m];
char stem[KIR_PATH_MAX];
size_t n = strlen(mod->source_path);
if(n > 4 && strcmp(mod->source_path + n - 4, ".kry") == 0)
n -= 4;
if(n >= sizeof(stem))
n = sizeof(stem) - 1;
memcpy(stem, mod->source_path, n);
stem[n] = '\0';
fprintf(out, "#include \"%s.hpp\"\n", stem);
}
}
fprintf(out, "\n#endif\n");
fclose(out);
if(count <= 0)
return;
/* --- kryon_project.c --- */
snprintf(path, sizeof(path), "%s/kryon_project.c", out_dir);
out = fopen(path, "wb");
if(out == NULL)
return;
fprintf(out, "/* Generated by k2cpp from project Kry files. */\n");
fprintf(out, "#include \"kryon_project.h\"\n");
fprintf(out, "#include \"app_runtime.h\"\n");
fprintf(out, "#include \"web.h\"\n");
if(appmod != NULL && appmod->app.font_examples)
fprintf(out, "#include \"kryon_example_font.h\"\n");
fprintf(out, "\n");
fprintf(out, "#if defined(__GNUC__) || defined(__clang__)\n");
fprintf(out, "void *CreateApp(const char *project_path) __attribute__((weak));\n");
fprintf(out, "void DestroyApp(void *app) __attribute__((weak));\n");
fprintf(out, "void ApplyRoute(void *app, const AppRouteInfo *route) __attribute__((weak));\n");
fprintf(out, "void BeginScreenDraw(void *app, Rectangle viewport) __attribute__((weak));\n");
fprintf(out, "#endif\n\n");
for(int i = 0; i < count; i++) {
char cname[KIR_NAME_MAX * 3];
char wrapper[64];
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
k2cpp_function_c_name(routes[i].m, routes[i].fn, cname, sizeof(cname));
fprintf(out, "static void\n%s(void *app, Rectangle viewport)\n{\n",
wrapper);
fprintf(out, " if(BeginScreenDraw != 0)\n");
fprintf(out, " BeginScreenDraw(app, viewport);\n");
if(strstr(routes[i].fn->args, "Rectangle") != NULL)
fprintf(out, " (void)app;\n %s(viewport);\n", cname);
else if(routes[i].fn->args[0] != '\0')
fprintf(out, " (void)viewport;\n %s(app);\n", cname);
else
fprintf(out, " (void)app;\n (void)viewport;\n %s();\n",
cname);
fprintf(out, "}\n\n");
}
fprintf(out, "static const AppRouteInfo kryon_project_routes[%d];\n\n",
count);
fprintf(out, "static void\nkryon_project_enter(void *app, int index)\n{\n");
fprintf(out, " if(ApplyRoute == 0 || index < 0 || index >= %d)\n",
count);
fprintf(out, " return;\n");
fprintf(out, " ApplyRoute(app, &kryon_project_routes[index]);\n");
fprintf(out, "}\n\n");
fprintf(out, "static const AppRouteInfo kryon_project_routes[] = {\n");
for(int i = 0; i < count; i++) {
char id[KIR_NAME_MAX * 2];
char title[KIR_NAME_MAX * 2];
char group[KIR_NAME_MAX * 2];
char source[KIR_PATH_MAX * 2];
char wrapper[64];
c_str(id, sizeof(id), routes[i].id);
c_str(title, sizeof(title), routes[i].title);
c_str(group, sizeof(group), routes[i].group);
c_str(source, sizeof(source), routes[i].source_path);
snprintf(wrapper, sizeof(wrapper), "kryon_project_draw_%d", i);
fprintf(out, " {%s, %s, %s, %s, kryon_project_enter, %s},\n",
id, group, title, source, wrapper);
}
fprintf(out, "};\n\n");
fprintf(out, "static App kryon_project_runtime;\n");
fprintf(out, "static AppHost kryon_project_host;\n\n");
fprintf(out, "AppHost *\nCreateAppHost(int abi_version, const char *project_path)\n{\n");
fprintf(out, " void *app = 0;\n");
fprintf(out, " if(abi_version != APP_HOST_ABI_VERSION)\n");
fprintf(out, " return 0;\n");
fprintf(out, " if(CreateApp != 0) {\n");
fprintf(out, " app = CreateApp(project_path);\n");
fprintf(out, " if(app == 0)\n");
fprintf(out, " return 0;\n");
fprintf(out, " } else {\n");
fprintf(out, " (void)project_path;\n");
fprintf(out, " }\n");
fprintf(out, " kryon_project_runtime.app = app;\n");
fprintf(out, " kryon_project_runtime.routes = kryon_project_routes;\n");
fprintf(out, " kryon_project_runtime.route_count = (int)(sizeof(kryon_project_routes) / sizeof(kryon_project_routes[0]));\n");
fprintf(out, " kryon_project_runtime.selected_route = 0;\n");
fprintf(out, " BindAppHost(&kryon_project_runtime, &kryon_project_host);\n");
fprintf(out, " SetAppScreen(&kryon_project_host, 0);\n");
fprintf(out, " return &kryon_project_host;\n}\n\n");
fprintf(out, "void\nDestroyAppHost(AppHost *host)\n{\n");
fprintf(out, " if(host == 0 || host != &kryon_project_host)\n");
fprintf(out, " return;\n");
fprintf(out, " if(DestroyApp != 0 && kryon_project_runtime.app != 0)\n");
fprintf(out, " DestroyApp(kryon_project_runtime.app);\n");
fprintf(out, " kryon_project_runtime = (App){0};\n");
fprintf(out, " kryon_project_host = (AppHost){0};\n}\n");
fclose(out);
/* --- main() (hook-driven, from KirAppMeta) --- */
if(no_main || appmod == NULL)
return;
out = fopen(path, "ab");
if(out == NULL)
return;
{
int width = appmod->app.width > 0 ? appmod->app.width : 800;
int height = appmod->app.height > 0 ? appmod->app.height : 600;
int fps = appmod->app.fps > 0 ? appmod->app.fps : 60;
int route_host_main = appmod->app.frame[0] == '\0' && count > 0;
char title[KIR_NAME_MAX * 2];
c_str(title, sizeof(title), appmod->app.title);
fprintf(out, "\nint\nmain(void)\n{\n");
if(route_host_main) {
fprintf(out, " AppHost *host;\n");
fprintf(out, " int route_version = -1;\n");
}
fprintf(out, " int width = %d;\n", width);
fprintf(out, " int height = %d;\n", height);
fprintf(out, "#if defined(PLATFORM_WEB)\n");
fprintf(out, " SetConfigFlags(GetWebWindowFlags());\n");
fprintf(out, " GetWebViewportSize(width, height, &width, &height);\n");
fprintf(out, "#endif\n");
fprintf(out, " InitWindow(width, height, %s);\n", title);
fprintf(out, " SetTargetFPS(%d);\n", fps);
if(appmod->app.font_examples)
fprintf(out, " LoadExampleUIFont();\n");
fprintf(out, " InitUI(width, height, GetUIScale());\n");
if(appmod->app.theme[0] != '\0') {
fprintf(out, " SetThemeSource(THEME_SOURCE_APP);\n");
fprintf(out, " SetThemeMode(%s);\n",
appmod->app.dark_mode ? "THEME_MODE_DARK"
: "THEME_MODE_LIGHT");
fprintf(out, " SetCurrentTheme(%s, %d);\n",
appmod->app.theme, appmod->app.dark_mode);
}
if(appmod->app.init[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.init) == 0) {
k2cpp_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.init);
}
if(route_host_main) {
fprintf(out, " host = CreateAppHost(APP_HOST_ABI_VERSION, \".\");\n");
fprintf(out, " if(host == 0) {\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 1;\n");
fprintf(out, " }\n");
}
fprintf(out, " while(!WindowShouldClose()) {\n");
if(appmod->app.frame[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
const KirFunction *entry = NULL;
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.frame) == 0) {
k2cpp_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
entry = &appmod->functions[j];
found = 1;
}
}
if(entry != NULL && entry->is_ui) {
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginTree(Key(\"%s\"));\n", hook);
if(strstr(entry->args, "Rectangle") != NULL) {
fprintf(out, " %s((Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n",
hook);
} else {
fprintf(out, " %s();\n", hook);
}
fprintf(out, " EndTree();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " %s();\n",
found ? hook : appmod->app.frame);
}
} else if(route_host_main) {
fprintf(out, " int next_route_version = GetRouteVersion();\n");
fprintf(out, " if(next_route_version != route_version) {\n");
fprintf(out, " if(!SetAppScreenFromRoute(host))\n");
fprintf(out, " ReplaceAppScreenRoute(host, 0);\n");
fprintf(out, " route_version = GetRouteVersion();\n");
fprintf(out, " }\n");
fprintf(out, " BeginFrame();\n");
fprintf(out, " BeginUIFrame(GetFrameWidth(), "
"GetFrameHeight(), GetFrameScale());\n");
fprintf(out, " BeginTree(Key(\"kryon_project\"));\n");
fprintf(out, " DrawAppScreen(host, (Rectangle){0, 0, "
"(float)GetFrameWidth(), (float)GetFrameHeight()});\n");
fprintf(out, " EndTree();\n");
fprintf(out, " EndUIFrame();\n");
fprintf(out, " EndFrame();\n");
} else {
fprintf(out, " ;\n");
}
fprintf(out, " }\n");
if(appmod->app.shutdown[0] != '\0') {
char hook[KIR_NAME_MAX * 3];
int found = 0;
for(int j = 0; j < appmod->function_count && !found; j++) {
if(strcmp(appmod->functions[j].name, appmod->app.shutdown) == 0) {
k2cpp_function_c_name(appmod, &appmod->functions[j],
hook, sizeof(hook));
found = 1;
}
}
fprintf(out, " %s();\n",
found ? hook : appmod->app.shutdown);
}
if(route_host_main)
fprintf(out, " DestroyAppHost(host);\n");
if(appmod->app.font_examples)
fprintf(out, " UnloadExampleUIFont();\n");
fprintf(out, " CloseWindow();\n");
fprintf(out, " return 0;\n}\n");
}
fclose(out);
}
-92
View File
@@ -1,92 +0,0 @@
/*
* k2cpp - .kry -> C++ compiler. Kir is the only pipeline: every .kry parses
* into a KirProgram (kir_parse.c) and lowers to C++ source that calls the
* C Kryon runtime through extern "C" (k2cpp_lower.c). All inputs are parsed
* first so cross-module calls resolve through one symbol table. Emitted
* declarations keep C linkage so generated modules interop with k2c output
* and the plain-C kryon_project files.
*/
#include "kir.h"
#include "kir_parse.h"
#include "kir_check.h"
#include "k2cpp_lower.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2cpp [--strict] [--no-main] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int no_main = 0;
int strict = 0;
KirProgram **progs;
K2cppModuleSyms *syms;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(strcmp(argv[i], "--strict") == 0) {
strict = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
syms = calloc((size_t)file_count, sizeof(*syms));
if(progs == NULL || syms == NULL) {
fprintf(stderr, "k2cpp: out of memory\n");
return 1;
}
/* Pass 1: parse every file, build the cross-module symbol table. */
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2cpp: failed to parse %s\n",
argv[first_file + i]);
return 1;
}
k2cpp_build_syms(progs[i], &syms[i]);
}
if(!KirCheckPrograms(progs, file_count, strict)) {
for(i = 0; i < file_count; i++) KirProgramFree(progs[i]);
free(progs);
free(syms);
return 1;
}
/* Pass 2: lower with full cross-module resolution. */
for(i = 0; i < file_count; i++)
k2cpp_lower(progs[i], root, out_dir, syms, file_count);
k2cpp_write_project(progs, file_count, root, out_dir, no_main);
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
free(syms);
return 0;
}
File diff suppressed because it is too large. Load diff
-23
View File
@@ -1,23 +0,0 @@
#ifndef K2GO_LOWER_H
#define K2GO_LOWER_H
#include "kir.h"
/*
* k2go_lower - Kir -> Go backend.
*
* Emits one .go file per module into out_dir, all in one Go package. The
* generated code calls the native Go Kryon package API. It does not thread a
* cgo bridge or runtime object through generated functions.
*
* v1 scope: the declarative app subset translates fully — state blocks,
* app metadata (-> generated main unless --no-main), frames, widget calls,
* and scalar expressions (compound literals, casts, state refs). Imperative
* constructs are best-effort; anything unsupported is emitted as a
* commented TODO line instead of silently miscompiling.
*/
int k2go_lower(const KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir, const char *pkg,
int no_main);
#endif
-92
View File
@@ -1,92 +0,0 @@
/*
* k2go - .kry -> Go compiler. Shares the Kir frontend with k2c/k2b: every
* .kry parses into a KirProgram (kir_parse.c), then lowers to Go source
* (k2go_lower.c) that calls the native Go Kryon runtime. One frontend, three
* backends.
*
* usage: k2go [--strict] [--no-main] [--pkg NAME] --root DIR -o DIR file.kry ...
*/
#include "kir.h"
#include "kir_parse.h"
#include "kir_check.h"
#include "k2go_lower.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2go [--strict] [--no-main] [--pkg NAME] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
const char *pkg = "krygen";
int no_main = 0;
int strict = 0;
KirProgram **progs;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--pkg") == 0 && i + 1 < argc) {
pkg = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(strcmp(argv[i], "--strict") == 0) {
strict = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
if(progs == NULL) {
fprintf(stderr, "k2go: out of memory\n");
return 1;
}
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2go: failed to parse %s\n", argv[first_file + i]);
return 1;
}
}
if(!KirCheckPrograms(progs, file_count, strict)) {
for(i = 0; i < file_count; i++) KirProgramFree(progs[i]);
free(progs);
return 1;
}
if(k2go_lower((const KirProgram *const *)progs, file_count, root, out_dir,
pkg, no_main) != 0) {
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 1;
}
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 0;
}
File diff suppressed because it is too large. Load diff
-17
View File
@@ -1,17 +0,0 @@
#ifndef K2JS_LOWER_H
#define K2JS_LOWER_H
#include "kir.h"
/*
* k2js_lower - Kir -> JavaScript backend.
*
* Emits one ESM .js file per module. Generated code imports the small
* web/kryon-runtime.js recorder/runtime and exports createState(), app
* metadata, all non-extern functions, frame(), and optionally main().
*/
int k2js_lower(const KirProgram *const *progs, int prog_count,
const char *root, const char *out_dir,
const char *runtime_import, int no_main);
#endif
-91
View File
@@ -1,91 +0,0 @@
/*
* k2js - .kry -> JavaScript compiler. Shares the Kir frontend with k2c/k2go/k2b:
* every .kry parses into a KirProgram (kir_parse.c), then lowers to ESM that
* calls the web Kryon runtime.
*
* usage: k2js [--strict] [--no-main] [--runtime PATH] --root DIR -o DIR file.kry ...
*/
#include "kir.h"
#include "kir_parse.h"
#include "kir_check.h"
#include "k2js_lower.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
usage(void)
{
fprintf(stderr,
"usage: k2js [--strict] [--no-main] [--runtime PATH] "
"--root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
const char *runtime_import = NULL;
int no_main = 0;
int strict = 0;
KirProgram **progs;
int file_count;
int i;
int first_file = 0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(strcmp(argv[i], "--runtime") == 0 && i + 1 < argc) {
runtime_import = argv[++i];
} else if(strcmp(argv[i], "--no-main") == 0) {
no_main = 1;
} else if(strcmp(argv[i], "--strict") == 0) {
strict = 1;
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
first_file = i;
break;
}
}
if(root == NULL || out_dir == NULL || first_file == 0) {
usage();
return 1;
}
file_count = argc - first_file;
progs = calloc((size_t)file_count, sizeof(*progs));
if(progs == NULL) {
fprintf(stderr, "k2js: out of memory\n");
return 1;
}
for(i = 0; i < file_count; i++) {
progs[i] = kir_parse_file(argv[first_file + i], root);
if(progs[i] == NULL) {
fprintf(stderr, "k2js: failed to parse %s\n", argv[first_file + i]);
free(progs);
return 1;
}
}
if(!KirCheckPrograms(progs, file_count, strict)) {
for(i = 0; i < file_count; i++) KirProgramFree(progs[i]);
free(progs);
return 1;
}
if(k2js_lower((const KirProgram *const *)progs, file_count, root, out_dir,
runtime_import, no_main) != 0) {
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 1;
}
for(i = 0; i < file_count; i++)
KirProgramFree(progs[i]);
free(progs);
return 0;
}
-93
View File
@@ -1,93 +0,0 @@
/*
* k2kir - emit a debuggable KIR text artifact from .kry source.
* Thin wrapper around the shared kir_parse_file frontend.
*/
#include "kir.h"
#include "kir_parse.h"
#include "kir_check.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
static void
usage(void)
{
fprintf(stderr, "usage: k2kir --root DIR -o DIR file.kry ...\n");
}
int
main(int argc, char **argv)
{
const char *root = NULL;
const char *out_dir = NULL;
int i;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--root") == 0 && i + 1 < argc) {
root = argv[++i];
} else if(strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
out_dir = argv[++i];
} else if(argv[i][0] == '-') {
usage();
return 1;
} else {
break;
}
}
if(root == NULL || out_dir == NULL || i >= argc) {
usage();
return 1;
}
for(; i < argc; i++) {
KirProgram *program = kir_parse_file(argv[i], root);
if(program == NULL)
return 1;
if(!KirCheckPrograms(&program, 1, 0)) {
KirProgramFree(program);
return 1;
}
/* Write the .kir dump using the module's source_path (relative to root)
* so directory structure is preserved. */
if(program->module_count > 0) {
const char *src = program->modules[0].source_path;
size_t slen = strlen(src);
char stem[512];
char out_path[1024];
FILE *out;
if(slen > 4 && strcmp(src + slen - 4, ".kry") == 0)
slen -= 4;
if(slen >= sizeof(stem))
slen = sizeof(stem) - 1;
memcpy(stem, src, slen);
stem[slen] = '\0';
snprintf(out_path, sizeof(out_path), "%s/%s.kir", out_dir, stem);
/* mkdir -p */
{
char tmp[1024];
size_t j;
snprintf(tmp, sizeof(tmp), "%s", out_path);
for(j = 1; j < strlen(tmp); j++) {
if(tmp[j] == '/') {
tmp[j] = '\0';
mkdir(tmp, 0755);
tmp[j] = '/';
}
}
}
out = fopen(out_path, "wb");
if(out == NULL) {
fprintf(stderr, "k2kir: %s: open failed\n", out_path);
KirProgramFree(program);
return 1;
}
KirProgramDump(program, out);
fclose(out);
}
KirProgramFree(program);
}
return 0;
}
+4540
View File
File diff suppressed because it is too large. Load diff
+105
View File
@@ -0,0 +1,105 @@
#ifndef KRYON_KC_INTERNAL_H
#define KRYON_KC_INTERNAL_H
#include <stddef.h>
enum {
KC_PATH_MAX = 1024,
KC_TEXT_MAX = 1024 * 1024,
KC_NAME_MAX = 128,
KC_INCLUDE_MAX = 64,
KC_USE_MAX = 32,
KC_CALL_MAX = 64,
KC_CONST_MAX = 64,
KC_DEFINE_MAX = 64,
KC_TYPE_MAX = 256,
KC_RAW_MAX = 1024,
KC_STATE_MAX = 128,
KC_BODY_MAX = 512,
KC_BODY_LINE_MAX = 1024,
};
typedef struct KryFunction {
char screen[KC_NAME_MAX];
char args[512];
char return_type[KC_NAME_MAX];
char guard[KC_BODY_LINE_MAX];
int exact_name;
int is_public;
int global_name;
char calls[KC_CALL_MAX][512];
char body[KC_BODY_MAX][KC_BODY_LINE_MAX];
int body_line[KC_BODY_MAX];
int call_count;
int body_count;
} KryFunction;
typedef struct KryFile {
char *path;
const char *root;
char *text;
char app_title[256];
int app_width;
int app_height;
int app_fps;
int app_font_examples;
char app_theme[KC_NAME_MAX];
int app_dark_mode;
int no_main;
char raw[KC_RAW_MAX][KC_BODY_LINE_MAX];
char public_types[KC_TYPE_MAX][KC_BODY_LINE_MAX];
char private_types[KC_TYPE_MAX][KC_BODY_LINE_MAX];
char state[KC_STATE_MAX][KC_BODY_LINE_MAX];
char public_globals[KC_STATE_MAX][KC_BODY_LINE_MAX];
char globals[KC_STATE_MAX][KC_BODY_LINE_MAX];
char includes[KC_INCLUDE_MAX][KC_PATH_MAX];
char include_guards[KC_INCLUDE_MAX][KC_BODY_LINE_MAX];
char const_names[KC_CONST_MAX][KC_NAME_MAX];
char const_exprs[KC_CONST_MAX][KC_BODY_LINE_MAX];
char define_names[KC_DEFINE_MAX][KC_NAME_MAX];
char define_values[KC_DEFINE_MAX][KC_BODY_LINE_MAX];
char define_guards[KC_DEFINE_MAX][KC_BODY_LINE_MAX];
char module[KC_NAME_MAX];
char module_file[KC_NAME_MAX];
char use_aliases[KC_USE_MAX][KC_NAME_MAX];
char use_modules[KC_USE_MAX][KC_NAME_MAX];
KryFunction *functions;
int raw_count;
int public_type_count;
int private_type_count;
int state_count;
int public_global_count;
int global_count;
int include_count;
int const_count;
int define_count;
int use_count;
int function_count;
int function_cap;
int current_line;
KryFunction *current;
} KryFile;
typedef struct KryMacroFrame {
char condition[KC_BODY_LINE_MAX];
char excluded[KC_BODY_LINE_MAX];
} KryMacroFrame;
void add_raw_line(KryFile *file, const char *line);
void add_type_line(KryFile *file, int is_public, const char *fmt, ...);
void add_state_line(KryFile *file, const char *line);
void expand_compile_expr(char *dst, size_t dst_size, const KryFile *file,
const char *src);
void add_guard_line(KryFile *file, const char *guard, int is_public_type,
int is_type, int is_state);
void add_guard_end(KryFile *file, int is_public_type, int is_type,
int is_state);
void combine_compile_guards(char *dst, size_t dst_size, const char *left,
const char *right);
void current_macro_guard(char *dst, size_t dst_size,
const KryMacroFrame *macros, int macro_count);
void append_macro_excluded(char *dst, size_t dst_size, const char *current,
const char *next);
#endif
+74
View File
@@ -0,0 +1,74 @@
#include "kc_internal.h"
#include <stdio.h>
#include <string.h>
void
add_guard_line(KryFile *file, const char *guard, int is_public_type,
int is_type, int is_state)
{
char line[KC_BODY_LINE_MAX];
if(guard == NULL || guard[0] == '\0')
return;
snprintf(line, sizeof(line), "#if %s", guard);
if(is_type)
add_type_line(file, is_public_type, "%s", line);
else if(is_state)
add_state_line(file, line);
else
add_raw_line(file, line);
}
void
add_guard_end(KryFile *file, int is_public_type, int is_type, int is_state)
{
if(is_type)
add_type_line(file, is_public_type, "#endif");
else if(is_state)
add_state_line(file, "#endif");
else
add_raw_line(file, "#endif");
}
void
combine_compile_guards(char *dst, size_t dst_size, const char *left,
const char *right)
{
const char *a = left != NULL ? left : "";
const char *b = right != NULL ? right : "";
if(a[0] == '\0') {
snprintf(dst, dst_size, "%s", b);
} else if(b[0] == '\0') {
snprintf(dst, dst_size, "%s", a);
} else {
snprintf(dst, dst_size, "(%s) && (%s)", a, b);
}
}
void
current_macro_guard(char *dst, size_t dst_size, const KryMacroFrame *macros,
int macro_count)
{
char guard[KC_BODY_LINE_MAX] = "";
for(int i = 0; i < macro_count; i++) {
char next[KC_BODY_LINE_MAX];
combine_compile_guards(next, sizeof(next), guard,
macros[i].condition);
snprintf(guard, sizeof(guard), "%s", next);
}
snprintf(dst, dst_size, "%s", guard);
}
void
append_macro_excluded(char *dst, size_t dst_size, const char *current,
const char *next)
{
if(current == NULL || current[0] == '\0')
snprintf(dst, dst_size, "%s", next);
else
snprintf(dst, dst_size, "(%s) || (%s)", current, next);
}
+5429
View File
File diff suppressed because it is too large. Load diff
-556
View File
@@ -1,556 +0,0 @@
#include "kir.h"
#include <stdlib.h>
#include <string.h>
static void *
kir_realloc_array(void *ptr, int *cap, int count, size_t elem_size)
{
void *next;
int ncap;
if(count < *cap)
return ptr;
ncap = *cap == 0 ? 4 : *cap * 2;
next = realloc(ptr, (size_t)ncap * elem_size);
if(next == NULL)
return NULL;
memset((char *)next + (size_t)(*cap) * elem_size, 0,
(size_t)(ncap - *cap) * elem_size);
*cap = ncap;
return next;
}
void
kir_copy(char *dst, size_t dst_size, const char *src)
{
if(dst_size == 0)
return;
if(src == NULL)
src = "";
snprintf(dst, dst_size, "%s", src);
}
KirProgram *
KirProgramNew(void)
{
return calloc(1, sizeof(KirProgram));
}
void
KirProgramFree(KirProgram *program)
{
int i;
if(program == NULL)
return;
for(i = 0; i < program->module_count; i++) {
KirModule *m = &program->modules[i];
int j;
for(j = 0; j < m->function_count; j++) {
free(m->functions[j].stmts);
free(m->functions[j].exprs);
}
free(m->state_fields);
free(m->globals);
free(m->imports);
free(m->functions);
free(m->defines);
free(m->asserts);
free(m->types);
free(m->routes);
}
free(program->modules);
free(program);
}
KirSourceSpan
KirSpan(const char *path, int line, int column)
{
KirSourceSpan span;
memset(&span, 0, sizeof(span));
kir_copy(span.path, sizeof(span.path), path);
span.line = line;
span.column = column;
return span;
}
KirModule *
KirProgramAddModule(KirProgram *program, const char *name,
const char *source_path, KirSourceSpan span)
{
KirModule *modules;
KirModule *m;
if(program == NULL)
return NULL;
modules = kir_realloc_array(program->modules, &program->module_cap,
program->module_count, sizeof(KirModule));
if(modules == NULL)
return NULL;
program->modules = modules;
m = &program->modules[program->module_count++];
memset(m, 0, sizeof(*m));
kir_copy(m->name, sizeof(m->name), name);
kir_copy(m->source_path, sizeof(m->source_path), source_path);
m->span = span;
return m;
}
KirStateField *
KirModuleAddStateField(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span)
{
KirStateField *fields;
KirStateField *f;
if(module == NULL)
return NULL;
fields = kir_realloc_array(module->state_fields, &module->state_cap,
module->state_count, sizeof(KirStateField));
if(fields == NULL)
return NULL;
module->state_fields = fields;
f = &module->state_fields[module->state_count++];
memset(f, 0, sizeof(*f));
kir_copy(f->name, sizeof(f->name), name);
kir_copy(f->type, sizeof(f->type), type);
kir_copy(f->init, sizeof(f->init), init);
f->span = span;
return f;
}
KirImport *
KirModuleAddImport(KirModule *module, KirImportKind kind, const char *name,
const char *target, const char *signature, int required,
KirSourceSpan span)
{
KirImport *imports;
KirImport *imp;
if(module == NULL)
return NULL;
imports = kir_realloc_array(module->imports, &module->import_cap,
module->import_count, sizeof(KirImport));
if(imports == NULL)
return NULL;
module->imports = imports;
imp = &module->imports[module->import_count++];
memset(imp, 0, sizeof(*imp));
imp->kind = kind;
kir_copy(imp->name, sizeof(imp->name), name);
kir_copy(imp->target, sizeof(imp->target), target);
kir_copy(imp->signature, sizeof(imp->signature), signature);
imp->required = required;
imp->span = span;
return imp;
}
KirFunction *
KirModuleAddFunction(KirModule *module, const char *name, const char *args,
const char *return_type, int exported, KirSourceSpan span)
{
KirFunction *functions;
KirFunction *fn;
if(module == NULL)
return NULL;
functions = kir_realloc_array(module->functions, &module->function_cap,
module->function_count, sizeof(KirFunction));
if(functions == NULL)
return NULL;
module->functions = functions;
fn = &module->functions[module->function_count++];
memset(fn, 0, sizeof(*fn));
kir_copy(fn->name, sizeof(fn->name), name);
kir_copy(fn->args, sizeof(fn->args), args);
kir_copy(fn->return_type, sizeof(fn->return_type), return_type);
fn->exported = exported;
fn->span = span;
return fn;
}
void
KirModuleAddGlobal(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span)
{
KirGlobal *globals;
if(module == NULL)
return;
globals = kir_realloc_array(module->globals, &module->global_cap,
module->global_count, sizeof(KirGlobal));
if(globals == NULL)
return;
module->globals = globals;
memset(&module->globals[module->global_count], 0, sizeof(KirGlobal));
kir_copy(module->globals[module->global_count].name,
sizeof(module->globals[0].name), name);
kir_copy(module->globals[module->global_count].type,
sizeof(module->globals[0].type), type);
kir_copy(module->globals[module->global_count].init,
sizeof(module->globals[0].init), init);
module->globals[module->global_count].span = span;
module->global_count++;
}
void
KirModuleAddStatic(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span)
{
KirModuleAddGlobal(module, name, type, init, span);
if(module != NULL && module->global_count > 0)
module->globals[module->global_count - 1].is_static = 1;
}
KirDefine *
KirModuleAddDefine(KirModule *module, const char *name, const char *value,
KirSourceSpan span)
{
KirDefine *defines;
KirDefine *d;
if(module == NULL)
return NULL;
defines = kir_realloc_array(module->defines, &module->define_cap,
module->define_count, sizeof(KirDefine));
if(defines == NULL)
return NULL;
module->defines = defines;
d = &module->defines[module->define_count++];
memset(d, 0, sizeof(*d));
kir_copy(d->name, sizeof(d->name), name);
kir_copy(d->value, sizeof(d->value), value);
d->span = span;
return d;
}
KirAssert *
KirModuleAddAssert(KirModule *module, const char *condition,
const char *message, KirSourceSpan span)
{
KirAssert *asserts;
KirAssert *a;
if(module == NULL)
return NULL;
asserts = kir_realloc_array(module->asserts, &module->assert_cap,
module->assert_count, sizeof(KirAssert));
if(asserts == NULL)
return NULL;
module->asserts = asserts;
a = &module->asserts[module->assert_count++];
memset(a, 0, sizeof(*a));
kir_copy(a->condition, sizeof(a->condition), condition);
kir_copy(a->message, sizeof(a->message), message);
a->span = span;
return a;
}
KirType *
KirModuleAddType(KirModule *module, const char *name, KirSourceSpan span)
{
KirType *types;
if(module == NULL)
return NULL;
types = kir_realloc_array(module->types, &module->type_cap,
module->type_count, sizeof(KirType));
if(types == NULL)
return NULL;
module->types = types;
memset(&module->types[module->type_count], 0, sizeof(KirType));
kir_copy(module->types[module->type_count].name,
sizeof(module->types[0].name), name);
module->types[module->type_count].span = span;
return &module->types[module->type_count++];
}
KirRoute *
KirModuleAddRoute(KirModule *module, const char *id, KirSourceSpan span)
{
KirRoute *routes;
KirRoute *route;
if(module == NULL)
return NULL;
routes = kir_realloc_array(module->routes, &module->route_cap,
module->route_count, sizeof(KirRoute));
if(routes == NULL)
return NULL;
module->routes = routes;
route = &module->routes[module->route_count++];
memset(route, 0, sizeof(*route));
kir_copy(route->id, sizeof(route->id), id);
kir_copy(route->title, sizeof(route->title), id);
kir_copy(route->group, sizeof(route->group), "Project");
kir_copy(route->page, sizeof(route->page), id);
route->span = span;
return route;
}
KirStmt *
KirFunctionAddStmt(KirFunction *fn, KirStmtKind kind, const char *text,
const char *widget, KirSourceSpan span)
{
KirStmt *stmts;
KirStmt *st;
if(fn == NULL)
return NULL;
stmts = kir_realloc_array(fn->stmts, &fn->stmt_cap, fn->stmt_count,
sizeof(KirStmt));
if(stmts == NULL)
return NULL;
fn->stmts = stmts;
st = &fn->stmts[fn->stmt_count++];
memset(st, 0, sizeof(*st));
st->kind = kind;
kir_copy(st->text, sizeof(st->text), text);
kir_copy(st->widget, sizeof(st->widget), widget);
st->expr_root = -1;
st->lhs_root = -1;
st->span = span;
return st;
}
KirStmt *
KirFunctionAddWidget(KirFunction *fn, const char *widget, const char *args,
const char *text, KirSourceSpan span)
{
KirStmt *st = KirFunctionAddStmt(fn, KIR_STMT_WIDGET, text, widget, span);
if(st != NULL)
kir_copy(st->args, sizeof(st->args), args);
return st;
}
KirExpr *
KirFunctionAddExpr(KirFunction *fn, KirExprKind kind, const char *text,
KirSourceSpan span)
{
KirExpr *exprs;
KirExpr *expr;
if(fn == NULL)
return NULL;
exprs = kir_realloc_array(fn->exprs, &fn->expr_cap, fn->expr_count,
sizeof(KirExpr));
if(exprs == NULL)
return NULL;
fn->exprs = exprs;
expr = &fn->exprs[fn->expr_count++];
memset(expr, 0, sizeof(*expr));
expr->kind = kind;
expr->left = -1;
expr->right = -1;
expr->first_child = -1;
expr->next_sibling = -1;
expr->third = -1;
kir_copy(expr->text, sizeof(expr->text), text);
expr->span = span;
return expr;
}
const char *
KirImportKindName(KirImportKind kind)
{
switch(kind) {
case KIR_IMPORT_HEADER: return "header";
case KIR_IMPORT_MODULE: return "module";
case KIR_IMPORT_EXTERN: return "extern";
case KIR_IMPORT_INTRINSIC: return "intrinsic";
case KIR_IMPORT_CAPABILITY: return "capability";
case KIR_IMPORT_HOST: return "host";
default: return "unknown";
}
}
const char *
KirExternKindName(KirExternKind kind)
{
switch(kind) {
case KIR_EXTERN_HOST: return "host";
case KIR_EXTERN_GO: return "go";
case KIR_EXTERN_C: return "c";
default: return "none";
}
}
const char *
KirExprKindName(KirExprKind kind)
{
switch(kind) {
case KIR_EXPR_IDENT: return "ident";
case KIR_EXPR_INT: return "int";
case KIR_EXPR_FLOAT: return "float";
case KIR_EXPR_STRING: return "string";
case KIR_EXPR_CALL: return "call";
case KIR_EXPR_BINARY: return "binary";
case KIR_EXPR_UNARY: return "unary";
case KIR_EXPR_MEMBER: return "member";
case KIR_EXPR_POINTER_MEMBER: return "pointer_member";
case KIR_EXPR_INDEX: return "index";
case KIR_EXPR_CAST: return "cast";
case KIR_EXPR_COMPOUND: return "compound";
case KIR_EXPR_SIZEOF: return "sizeof";
case KIR_EXPR_CHAR: return "char";
case KIR_EXPR_CONDITIONAL: return "conditional";
case KIR_EXPR_POSTFIX: return "postfix";
default: return "unknown";
}
}
const char *
KirStmtKindName(KirStmtKind kind)
{
switch(kind) {
case KIR_STMT_BLOCK_OPEN: return "block_open";
case KIR_STMT_BLOCK_CLOSE: return "block_close";
case KIR_STMT_DECL: return "decl";
case KIR_STMT_ASSIGN: return "assign";
case KIR_STMT_EXPR: return "expr";
case KIR_STMT_IF: return "if";
case KIR_STMT_WHILE: return "while";
case KIR_STMT_FOR: return "for";
case KIR_STMT_SWITCH: return "switch";
case KIR_STMT_CASE: return "case";
case KIR_STMT_RETURN: return "return";
case KIR_STMT_BREAK: return "break";
case KIR_STMT_CONTINUE: return "continue";
case KIR_STMT_GOTO: return "goto";
case KIR_STMT_LABEL: return "label";
case KIR_STMT_DEFER: return "defer";
case KIR_STMT_UNUSED: return "unused";
case KIR_STMT_RAW: return "raw";
case KIR_STMT_WIDGET: return "widget";
default: return "unknown";
}
}
static void
kir_dump_span(FILE *out, KirSourceSpan span)
{
fprintf(out, "%s:%d:%d", span.path, span.line, span.column);
}
static void
kir_dump_expr(const KirFunction *fn, int index, FILE *out, int indent)
{
const KirExpr *expr;
if(fn == NULL || index < 0 || index >= fn->expr_count)
return;
expr = &fn->exprs[index];
for(int i = 0; i < indent; i++)
fputs(" ", out);
fprintf(out, "expr %s text %s name %s op %s span ",
KirExprKindName(expr->kind), expr->text, expr->name, expr->op);
kir_dump_span(out, expr->span);
if(expr->type[0]) fprintf(out, " type %s", expr->type);
fprintf(out, "\n");
if(expr->left >= 0)
kir_dump_expr(fn, expr->left, out, indent + 1);
if(expr->right >= 0)
kir_dump_expr(fn, expr->right, out, indent + 1);
if(expr->third >= 0)
kir_dump_expr(fn, expr->third, out, indent + 1);
for(int child = expr->first_child; child >= 0 &&
child < fn->expr_count; child = fn->exprs[child].next_sibling)
kir_dump_expr(fn, child, out, indent + 1);
}
void
KirProgramDump(const KirProgram *program, FILE *out)
{
int i;
if(out == NULL)
return;
fprintf(out, "kir 1\n");
if(program == NULL)
return;
for(i = 0; i < program->module_count; i++) {
const KirModule *m = &program->modules[i];
int j;
fprintf(out, "module %s source %s span ", m->name, m->source_path);
kir_dump_span(out, m->span);
fprintf(out, "\n");
if(m->app.has_app) {
fprintf(out, " app title %s size %dx%d fps %d theme %s "
"dark %d font_examples %d frame %s init %s scene %s "
"shutdown %s\n",
m->app.title[0] ? m->app.title : "\"\"",
m->app.width, m->app.height, m->app.fps,
m->app.theme[0] ? m->app.theme : "",
m->app.dark_mode, m->app.font_examples,
m->app.frame[0] ? m->app.frame : "",
m->app.init[0] ? m->app.init : "",
m->app.scene[0] ? m->app.scene : "",
m->app.shutdown[0] ? m->app.shutdown : "");
}
for(j = 0; j < m->import_count; j++) {
const KirImport *imp = &m->imports[j];
fprintf(out, " import %s %s target %s",
KirImportKindName(imp->kind), imp->name, imp->target);
if(imp->kind == KIR_IMPORT_EXTERN)
fprintf(out, " extern_kind %s extern_symbol %s",
KirExternKindName(imp->extern_kind),
imp->extern_symbol);
fprintf(out, " required %d signature %s span ",
imp->required, imp->signature);
kir_dump_span(out, imp->span);
fprintf(out, "\n");
}
for(j = 0; j < m->state_count; j++) {
const KirStateField *f = &m->state_fields[j];
fprintf(out, " state %s type %s init %s span ",
f->name, f->type, f->init);
kir_dump_span(out, f->span);
fprintf(out, "\n");
}
for(j = 0; j < m->route_count; j++) {
const KirRoute *route = &m->routes[j];
fprintf(out, " route %s title %s group %s page %s span ",
route->id, route->title, route->group, route->page);
kir_dump_span(out, route->span);
fprintf(out, "\n");
}
for(j = 0; j < m->assert_count; j++) {
const KirAssert *a = &m->asserts[j];
fprintf(out, " assert condition %s known %d value %d message %s span ",
a->condition, a->known, a->value, a->message);
kir_dump_span(out, a->span);
fprintf(out, "\n");
}
for(j = 0; j < m->function_count; j++) {
const KirFunction *fn = &m->functions[j];
int k;
fprintf(out, " function %s args %s return %s exported %d span ",
fn->name, fn->args, fn->return_type, fn->exported);
kir_dump_span(out, fn->span);
fprintf(out, "\n");
for(k = 0; k < fn->stmt_count; k++) {
const KirStmt *st = &fn->stmts[k];
fprintf(out, " stmt %s widget %s args %s text %s span ",
KirStmtKindName(st->kind), st->widget, st->args,
st->text);
kir_dump_span(out, st->span);
fprintf(out, "\n");
if(st->expr_root >= 0)
kir_dump_expr(fn, st->expr_root, out, 3);
if(st->lhs_root >= 0)
kir_dump_expr(fn, st->lhs_root, out, 3);
}
}
}
}
-294
View File
@@ -1,294 +0,0 @@
/*
* kir.h - Kryon intermediate representation.
*
* KIR is the shared compiler representation between .kry source and the C/KRB
* backends. This module owns the tree shape, explicit allocation, source spans,
* and deterministic dumps used by tools and tests.
*/
#ifndef KRYON_KIR_H
#define KRYON_KIR_H
#include <stdio.h>
enum {
KIR_PATH_MAX = 1024,
KIR_NAME_MAX = 128,
KIR_TEXT_MAX = 4096
};
typedef enum KirImportKind {
KIR_IMPORT_HEADER = 1,
KIR_IMPORT_MODULE,
KIR_IMPORT_EXTERN,
KIR_IMPORT_INTRINSIC,
KIR_IMPORT_CAPABILITY,
KIR_IMPORT_HOST
} KirImportKind;
typedef enum KirExternKind {
KIR_EXTERN_NONE = 0,
KIR_EXTERN_HOST,
KIR_EXTERN_GO,
KIR_EXTERN_C
} KirExternKind;
typedef enum KirStmtKind {
KIR_STMT_UNKNOWN = 0,
KIR_STMT_BLOCK_OPEN,
KIR_STMT_BLOCK_CLOSE,
KIR_STMT_DECL,
KIR_STMT_ASSIGN,
KIR_STMT_EXPR,
KIR_STMT_IF,
KIR_STMT_WHILE,
KIR_STMT_FOR,
KIR_STMT_SWITCH,
KIR_STMT_CASE,
KIR_STMT_RETURN,
KIR_STMT_BREAK,
KIR_STMT_CONTINUE,
KIR_STMT_GOTO,
KIR_STMT_LABEL,
KIR_STMT_DEFER,
KIR_STMT_UNUSED,
KIR_STMT_RAW,
KIR_STMT_WIDGET
} KirStmtKind;
typedef enum KirExprKind {
KIR_EXPR_UNKNOWN = 0,
KIR_EXPR_IDENT,
KIR_EXPR_INT,
KIR_EXPR_FLOAT,
KIR_EXPR_STRING,
KIR_EXPR_CALL,
KIR_EXPR_BINARY,
KIR_EXPR_UNARY,
KIR_EXPR_MEMBER,
KIR_EXPR_POINTER_MEMBER,
KIR_EXPR_INDEX,
KIR_EXPR_CAST,
KIR_EXPR_COMPOUND,
KIR_EXPR_SIZEOF,
KIR_EXPR_CHAR,
KIR_EXPR_CONDITIONAL,
KIR_EXPR_POSTFIX
} KirExprKind;
typedef struct KirSourceSpan {
char path[KIR_PATH_MAX];
int line;
int column;
} KirSourceSpan;
typedef struct KirStateField {
char name[KIR_NAME_MAX];
char type[KIR_NAME_MAX];
char init[KIR_TEXT_MAX];
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirStateField;
typedef struct KirImport {
KirImportKind kind;
KirExternKind extern_kind;
char name[KIR_NAME_MAX];
char target[KIR_PATH_MAX];
char extern_symbol[KIR_NAME_MAX];
char signature[KIR_TEXT_MAX];
char args[KIR_TEXT_MAX]; /* parsed extern parameters */
char return_type[KIR_NAME_MAX];
int required;
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirImport;
typedef struct KirStmt {
KirStmtKind kind;
char text[KIR_TEXT_MAX];
char widget[KIR_NAME_MAX];
char args[KIR_TEXT_MAX];
int expr_root; /* index into enclosing function exprs, or -1 */
int lhs_root; /* structured assignment destination, or -1 */
char name[KIR_NAME_MAX]; /* declaration binding */
char type[KIR_NAME_MAX]; /* declared or inferred type */
char assignment_op[4];
KirSourceSpan span;
} KirStmt;
typedef struct KirExpr {
KirExprKind kind;
char text[KIR_TEXT_MAX];
char name[KIR_NAME_MAX];
char op[8];
int left;
int right;
int first_child;
int next_sibling;
int third; /* false arm of conditional, or -1 */
char type[KIR_NAME_MAX]; /* resolved type; empty means unresolved */
KirSourceSpan span;
} KirExpr;
typedef struct KirFunction {
char name[KIR_NAME_MAX];
char args[KIR_TEXT_MAX];
char return_type[KIR_NAME_MAX];
int exported;
int is_extern;
KirExternKind extern_kind;
int is_colon; /* 'Name :: (...) {' form: C name has no _kry_draw suffix */
int is_ui; /* '#ui' function: declares a retained UI hierarchy */
int is_public; /* exported function or project route */
int checked; /* shared checker resolved the function without errors */
char extern_target[KIR_NAME_MAX]; /* '#extern "pkg.Fn"' quoted symbol */
char extern_symbol[KIR_NAME_MAX]; /* stripped C symbol for c.* externs */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
KirStmt *stmts;
int stmt_count;
int stmt_cap;
KirExpr *exprs;
int expr_count;
int expr_cap;
} KirFunction;
typedef struct KirGlobal {
char name[KIR_NAME_MAX];
char type[KIR_TEXT_MAX];
char init[KIR_TEXT_MAX];
int is_static; /* 'static name: T = init' — internal linkage */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirGlobal;
/* A `Name :: #define value` module constant — emitted as a real C #define. */
typedef struct KirDefine {
char name[KIR_NAME_MAX];
char value[KIR_TEXT_MAX];
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirDefine;
typedef struct KirAssert {
char condition[KIR_TEXT_MAX]; /* expanded C preprocessor condition */
char message[KIR_TEXT_MAX]; /* C #error payload */
int known; /* condition resolved by Kry frontend */
int value; /* boolean value when known */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirAssert;
/* A `Name :: struct { fields }` type declaration. body holds the raw field
* lines (one per line, no braces). */
typedef struct KirType {
char name[KIR_NAME_MAX];
char body[KIR_TEXT_MAX * 2];
int is_enum; /* 'Name :: enum' — emit typedef enum, not struct */
char guard[KIR_TEXT_MAX]; /* enclosing '#if' condition (expanded) */
KirSourceSpan span;
} KirType;
typedef struct KirAppMeta {
int has_app;
char title[KIR_NAME_MAX];
int width;
int height;
int fps;
char theme[KIR_NAME_MAX];
int dark_mode;
int font_examples;
char frame[KIR_NAME_MAX];
char init[KIR_NAME_MAX];
char scene[KIR_NAME_MAX];
char shutdown[KIR_NAME_MAX];
} KirAppMeta;
typedef struct KirRoute {
char id[KIR_NAME_MAX];
char title[KIR_NAME_MAX];
char group[KIR_NAME_MAX];
char page[KIR_NAME_MAX];
char guard[KIR_TEXT_MAX];
KirSourceSpan span;
} KirRoute;
typedef struct KirModule {
char name[KIR_NAME_MAX];
char source_path[KIR_PATH_MAX];
KirSourceSpan span;
KirAppMeta app;
KirGlobal *globals;
int global_count;
int global_cap;
KirDefine *defines;
int define_count;
int define_cap;
KirAssert *asserts;
int assert_count;
int assert_cap;
KirType *types;
int type_count;
int type_cap;
KirStateField *state_fields;
int state_count;
int state_cap;
KirImport *imports;
int import_count;
int import_cap;
KirRoute *routes;
int route_count;
int route_cap;
KirFunction *functions;
int function_count;
int function_cap;
} KirModule;
typedef struct KirProgram {
KirModule *modules;
int module_count;
int module_cap;
} KirProgram;
KirProgram *KirProgramNew(void);
void KirProgramFree(KirProgram *program);
void kir_copy(char *dst, size_t dst_size, const char *src);
KirSourceSpan KirSpan(const char *path, int line, int column);
KirModule *KirProgramAddModule(KirProgram *program, const char *name,
const char *source_path, KirSourceSpan span);
KirStateField *KirModuleAddStateField(KirModule *module, const char *name,
const char *type, const char *init,
KirSourceSpan span);
KirImport *KirModuleAddImport(KirModule *module, KirImportKind kind,
const char *name, const char *target,
const char *signature, int required,
KirSourceSpan span);
KirFunction *KirModuleAddFunction(KirModule *module, const char *name,
const char *args, const char *return_type,
int exported, KirSourceSpan span);
void KirModuleAddGlobal(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span);
void KirModuleAddStatic(KirModule *module, const char *name, const char *type,
const char *init, KirSourceSpan span);
KirDefine *KirModuleAddDefine(KirModule *module, const char *name,
const char *value, KirSourceSpan span);
KirAssert *KirModuleAddAssert(KirModule *module, const char *condition,
const char *message, KirSourceSpan span);
KirType *KirModuleAddType(KirModule *module, const char *name,
KirSourceSpan span);
KirRoute *KirModuleAddRoute(KirModule *module, const char *id,
KirSourceSpan span);
KirStmt *KirFunctionAddStmt(KirFunction *fn, KirStmtKind kind,
const char *text, const char *widget,
KirSourceSpan span);
KirStmt *KirFunctionAddWidget(KirFunction *fn, const char *widget,
const char *args, const char *text,
KirSourceSpan span);
const char *KirImportKindName(KirImportKind kind);
const char *KirStmtKindName(KirStmtKind kind);
const char *KirExprKindName(KirExprKind kind);
KirExpr *KirFunctionAddExpr(KirFunction *fn, KirExprKind kind,
const char *text, KirSourceSpan span);
void KirProgramDump(const KirProgram *program, FILE *out);
#endif /* KRYON_KIR_H */
-288
View File
@@ -1,288 +0,0 @@
#include "kir_check.h"
#include "kir_text.h"
#include "kir_emit.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
typedef struct Binding {
char name[KIR_NAME_MAX];
char type[KIR_NAME_MAX];
int depth;
} Binding;
typedef struct Checker {
KirProgram **programs;
int program_count;
KirModule *module;
KirFunction *fn;
Binding *bindings;
int count, capacity, depth, strict, errors, failed;
} Checker;
const char *
KirScalarType(const char *type)
{
static const struct { const char *source, *type; } types[] = {
{"int", "i32"}, {"unsigned int", "u32"}, {"unsigned", "u32"},
{"int8_t", "i8"}, {"int16_t", "i16"}, {"int32_t", "i32"}, {"int64_t", "i64"},
{"uint8_t", "u8"}, {"uint16_t", "u16"}, {"uint32_t", "u32"}, {"uint64_t", "u64"},
{"float", "f32"}, {"double", "f64"}, {"intptr_t", "isize"}, {"uintptr_t", "usize"},
{"size_t", "usize"}, {"ptrdiff_t", "isize"}, {"char", "char"},
{"bool", "bool"}, {"void", "void"}, {"i8", "i8"}, {"u8", "u8"},
{"i16", "i16"}, {"u16", "u16"}, {"i32", "i32"}, {"u32", "u32"},
{"i64", "i64"}, {"u64", "u64"}, {"isize", "isize"}, {"usize", "usize"},
{"f32", "f32"}, {"f64", "f64"}, {NULL, NULL}
};
for(int i = 0; types[i].source; i++)
if(!strcmp(type, types[i].source)) return types[i].type;
return "";
}
static void
error(Checker *c, KirSourceSpan span, const char *message, const char *detail)
{
c->errors++;
if(!c->strict) return;
fprintf(stderr, "%s:%d:%d: %s%s%s\n", span.path, span.line, span.column,
message, detail && *detail ? ": " : "", detail ? detail : "");
}
static void
bind(Checker *c, const char *name, const char *type, KirSourceSpan span)
{
if(!*name) return;
for(int i = c->count - 1; i >= 0 && c->bindings[i].depth == c->depth; i--)
if(!strcmp(c->bindings[i].name, name)) {
error(c, span, "duplicate binding", name);
return;
}
if(c->count == c->capacity) {
int size = c->capacity ? c->capacity * 2 : 32;
Binding *next = realloc(c->bindings, (size_t)size * sizeof(*next));
if(!next) { c->errors++; c->failed=1; return; }
c->bindings = next; c->capacity = size;
}
kir_copy(c->bindings[c->count].name, KIR_NAME_MAX, name);
kir_copy(c->bindings[c->count].type, KIR_NAME_MAX, type);
c->bindings[c->count++].depth = c->depth;
}
static const KirFunction *
function(Checker *c, const char *name)
{
for(int f = 0; f < c->module->function_count; f++)
if(!strcmp(c->module->functions[f].name, name)) return &c->module->functions[f];
for(int p = 0; p < c->program_count; p++)
for(int m = 0; m < c->programs[p]->module_count; m++) {
const KirModule *module = &c->programs[p]->modules[m];
for(int f = 0; f < module->function_count; f++)
if(!strcmp(module->functions[f].name, name)) return &module->functions[f];
}
return NULL;
}
static const char *
lookup(Checker *c, const char *name)
{
for(int i = c->count - 1; i >= 0; i--)
if(!strcmp(c->bindings[i].name, name)) return c->bindings[i].type;
for(int i = 0; i < c->module->state_count; i++)
if(!strcmp(c->module->state_fields[i].name, name)) return c->module->state_fields[i].type;
for(int i = 0; i < c->module->global_count; i++)
if(!strcmp(c->module->globals[i].name, name)) return c->module->globals[i].type;
return "";
}
static int
numeric(const char *type)
{
return !strcmp(type, "integer") || !strcmp(type, "real") ||
(*type && strchr("iuf", type[0]) && *KirScalarType(type)) || !strcmp(type, "char");
}
static int
compatible(const char *to, const char *from)
{
const char *canonical = KirScalarType(to);
if(*canonical) to = canonical;
if(!*to || !*from) return 1;
if(!strcmp(to, from)) return 1;
if(!strcmp(from, "integer") && numeric(to)) return 1;
if(!strcmp(from, "real") && (to[0] == 'f')) return 1;
return 0;
}
static int
assignable(Checker *c, int index)
{
const KirExpr *e;
if(index < 0 || index >= c->fn->expr_count) return 0;
e = &c->fn->exprs[index];
return (e->kind == KIR_EXPR_IDENT && strcmp(e->name, "true") && strcmp(e->name, "false")) ||
e->kind == KIR_EXPR_INDEX || e->kind == KIR_EXPR_MEMBER ||
e->kind == KIR_EXPR_POINTER_MEMBER || (e->kind == KIR_EXPR_UNARY && !strcmp(e->op, "*"));
}
static const char *
expression_type(Checker *c, int index)
{
KirExpr *e;
const char *type = "", *left = "", *right = "";
if(index < 0 || index >= c->fn->expr_count) return "";
e = &c->fn->exprs[index];
if(e->left >= 0) left = expression_type(c, e->left);
if(e->right >= 0) right = expression_type(c, e->right);
switch(e->kind) {
case KIR_EXPR_INT: type = "integer"; break;
case KIR_EXPR_FLOAT: type = "real"; break;
case KIR_EXPR_CHAR: type = "char"; break;
case KIR_EXPR_STRING: type = "const char*"; break;
case KIR_EXPR_IDENT:
if(!strcmp(e->name, "true") || !strcmp(e->name, "false")) type = "bool";
else type = lookup(c, e->name);
if(!*type) error(c, e->span, "unresolved name", e->name);
break;
case KIR_EXPR_CALL: {
const KirFunction *callee = function(c, e->name);
const char *args = callee ? callee->args : NULL;
const char *return_type = callee ? callee->return_type : "";
char (*parts)[KIR_TEXT_MAX] = calloc(64, sizeof(*parts));
int actual = 0, expected;
if(!parts) { c->errors++; c->failed=1; break; }
if(*lookup(c, e->name)) error(c, e->span, "binding is not a callable function", e->name);
if(!callee) for(int i = 0; i < c->module->import_count; i++) {
const KirImport *imp = &c->module->imports[i];
if(imp->kind == KIR_IMPORT_EXTERN && !strcmp(imp->name, e->name)) {
args = imp->args; return_type = imp->return_type; break;
}
}
expected = args && *kir_skip_ws(args) ? kir_split_top(args, parts[0], 64, sizeof(parts[0])) : 0;
for(int child = e->first_child; child >= 0; child = c->fn->exprs[child].next_sibling) {
const char *arg_type = expression_type(c, child);
if(args && actual < expected) {
char *colon = strchr(parts[actual], ':');
if(colon && !compatible(kir_skip_ws(colon + 1), arg_type))
error(c, c->fn->exprs[child].span, "argument type mismatch", e->name);
if(colon && (!strcmp(arg_type, "integer") || !strcmp(arg_type, "real"))) {
const char *context = KirScalarType(kir_skip_ws(colon + 1));
if(*context) kir_copy(c->fn->exprs[child].type, KIR_NAME_MAX, context);
}
}
actual++;
}
if(args) {
type = return_type;
if(actual != expected) error(c, e->span, "argument count mismatch", e->name);
} else error(c, e->span, "unresolved function", e->name);
free(parts);
break;
}
case KIR_EXPR_BINARY:
if((!strcmp(e->op, "&") || !strcmp(e->op, "|") || !strcmp(e->op, "^") ||
!strcmp(e->op, "<<") || !strcmp(e->op, ">>") || !strcmp(e->op, "%")) &&
(left[0] == 'f' || right[0] == 'f' || !strcmp(left, "real") || !strcmp(right, "real")))
error(c, e->span, "integer operands required", e->op);
if((!strcmp(e->op, "&&") || !strcmp(e->op, "||")) &&
(strcmp(left, "bool") || strcmp(right, "bool")))
error(c, e->span, "logical operands require bool", e->op);
if(!compatible(left, right) && !compatible(right, left))
error(c, e->span, "operand types differ; use an explicit cast", e->op);
if(!strcmp(e->op, "==") || !strcmp(e->op, "!=") || !strcmp(e->op, "<") ||
!strcmp(e->op, "<=") || !strcmp(e->op, ">") || !strcmp(e->op, ">=") ||
!strcmp(e->op, "&&") || !strcmp(e->op, "||")) type = "bool";
else if(numeric(left) && numeric(right))
type = (!strcmp(left, "integer") || !strcmp(left, "real")) ? right : left;
else if(*left && *right) error(c, e->span, "numeric operands required", e->op);
break;
case KIR_EXPR_UNARY:
if(!strcmp(e->op, "!") && strcmp(right, "bool"))
error(c, e->span, "logical operand requires bool", e->op);
if((!strcmp(e->op, "++") || !strcmp(e->op, "--")) && !assignable(c, e->right))
error(c, e->span, "increment requires an assignable expression", "");
if(!strcmp(e->op, "!")) type = "bool";
else if(numeric(right)) type = right;
else error(c, e->span, "unresolved unary operation", e->op);
break;
case KIR_EXPR_POSTFIX:
if(!assignable(c, e->left)) error(c, e->span, "increment requires an assignable expression", "");
type = left;
break;
case KIR_EXPR_CAST: type = e->name; break;
case KIR_EXPR_CONDITIONAL: {
const char *third = expression_type(c, e->third);
if(strcmp(left, "bool")) error(c, e->span, "conditional requires bool", left);
if(!compatible(right, third) && !compatible(third, right))
error(c, e->span, "conditional arms have different types", "");
type = !strcmp(right, "integer") ? third : right;
break;
}
default: error(c, e->span, "expression is not supported by strict checking", e->text); break;
}
if(*KirScalarType(type)) type = KirScalarType(type);
kir_copy(e->type, sizeof(e->type), type);
return e->type;
}
int
KirCheckPrograms(KirProgram **programs, int count, int strict)
{
Checker c = {0};
c.programs = programs; c.program_count = count; c.strict = strict;
for(int p = 0; p < count; p++) for(int m = 0; m < programs[p]->module_count; m++) {
c.module = &programs[p]->modules[m];
for(int f = 0; f < c.module->function_count; f++) {
int errors_before = c.errors;
char params[64][KIR_TEXT_MAX];
int n;
c.fn = &c.module->functions[f]; c.count = 0; c.depth = 0;
n = *kir_skip_ws(c.fn->args) ? kir_split_top(c.fn->args, params[0], 64, sizeof(params[0])) : 0;
for(int a = 0; a < n; a++) {
char *colon = strchr(params[a], ':');
if(colon) {
*colon++ = 0; kir_trim_in_place(params[a]); kir_trim_in_place(colon);
bind(&c, params[a], colon, c.fn->span);
} else error(&c, c.fn->span, "strict parameters require name: type", params[a]);
}
for(int i = 0; i < c.fn->stmt_count; i++) {
KirStmt *st = &c.fn->stmts[i];
const char *type;
if(st->kind == KIR_STMT_BLOCK_CLOSE) {
while(c.count && c.bindings[c.count - 1].depth == c.depth) c.count--;
if(c.depth) c.depth--;
}
type = expression_type(&c, st->expr_root);
if(st->kind == KIR_STMT_DECL) {
if(!*st->type) kir_copy(st->type, sizeof(st->type),
!strcmp(type, "integer") ? "int" : !strcmp(type, "real") ? "double" : type);
else if(!compatible(st->type, type)) error(&c, st->span, "initializer type mismatch", st->name);
bind(&c, st->name, st->type, st->span);
} else if(st->kind == KIR_STMT_ASSIGN) {
const char *lhs = expression_type(&c, st->lhs_root);
if(!assignable(&c, st->lhs_root)) error(&c, st->span, "assignment requires an assignable destination", "");
if(!compatible(lhs, type)) error(&c, st->span, "assignment type mismatch", st->text);
} else if(st->kind == KIR_STMT_RETURN) {
if(!compatible(c.fn->return_type, type)) error(&c, st->span, "return type mismatch", c.fn->name);
if((st->expr_root < 0) != !strcmp(c.fn->return_type, "void"))
error(&c, st->span, "return value does not match function signature", c.fn->name);
} else if(st->kind == KIR_STMT_IF || st->kind == KIR_STMT_WHILE) {
if(*type && strcmp(type, "bool")) error(&c, st->span, "condition requires bool", type);
} else if(st->kind == KIR_STMT_RAW || st->kind == KIR_STMT_UNKNOWN ||
st->kind == KIR_STMT_FOR || st->kind == KIR_STMT_GOTO ||
st->kind == KIR_STMT_LABEL || st->kind == KIR_STMT_WIDGET)
error(&c, st->span, "statement is not supported by strict checking", st->text);
if(st->kind == KIR_STMT_BLOCK_OPEN || st->kind == KIR_STMT_IF ||
st->kind == KIR_STMT_WHILE || st->kind == KIR_STMT_FOR || st->kind == KIR_STMT_SWITCH)
c.depth++;
}
c.fn->checked = c.errors == errors_before;
if(strict && c.fn->checked && !c.fn->is_extern && !KirCanEmitBody(c.fn)) {
error(&c,c.fn->span,"function is not supported by portable scalar emission",c.fn->name);
c.fn->checked=0;
}
}
}
free(c.bindings);
return !c.failed && (!strict || c.errors == 0);
}
-9
View File
@@ -1,9 +0,0 @@
#ifndef KIR_CHECK_H
#define KIR_CHECK_H
#include "kir.h"
/* Resolve scalar expression types and lexical bindings. Strict mode rejects
* unresolved expressions instead of delegating them to target-language text. */
int KirCheckPrograms(KirProgram **programs, int count, int strict);
const char *KirScalarType(const char *type);
#endif
-290
View File
@@ -1,290 +0,0 @@
#include "kir_cleanup.h"
#include "kir_text.h"
#include "kir_token.h"
#include "kir_expr.h"
#include <stdlib.h>
#include <string.h>
typedef struct Cleanup {
KirStmt statement;
int depth;
} Cleanup;
static int append(KirFunction *out, const KirStmt *st);
static int
fail(const KirStmt *st, const char *message)
{
fprintf(stderr, "%s:%d:%d: %s\n", st->span.path, st->span.line,
st->span.column, message);
return 0;
}
static int
mentions(const char *text, const char *name)
{
KirLexer lexer;
KirToken token;
KirLexerInit(&lexer, text, "");
do {
token = KirLexerNext(&lexer);
if(token.kind == KIR_TOKEN_IDENT && !strcmp(token.text, name)) return 1;
} while(token.kind != KIR_TOKEN_EOF);
return 0;
}
static int
action_kind(const char *text, KirStmt *action)
{
KirLexer lexer;
KirToken token;
KirFunction temporary = {0};
int valid;
action->kind = KIR_STMT_EXPR;
KirLexerInit(&lexer, text, action->span.path);
token = KirLexerNext(&lexer);
if(!strcmp(token.text, "return") || !strcmp(token.text, "break") ||
!strcmp(token.text, "continue") || !strcmp(token.text, "goto") ||
!strcmp(token.text, "defer") || !strcmp(token.text, "if") ||
!strcmp(token.text, "while") || !strcmp(token.text, "for")) return 0;
KirLexerInit(&lexer, text, action->span.path);
do {
token = KirLexerNext(&lexer);
if(!strcmp(token.text, "=") || !strcmp(token.text, "+=") ||
!strcmp(token.text, "-=") || !strcmp(token.text, "*=") ||
!strcmp(token.text, "/=") || !strcmp(token.text, "%=") ||
!strcmp(token.text, "&=") || !strcmp(token.text, "|=") ||
!strcmp(token.text, "^=") || !strcmp(token.text, "<<=") || !strcmp(token.text, ">>="))
action->kind = KIR_STMT_ASSIGN;
} while(token.kind != KIR_TOKEN_EOF);
kir_copy(action->text, sizeof(action->text), text);
if(!append(&temporary, action)) return 0;
KirStructureFunction(&temporary, NULL);
valid = temporary.stmts[0].expr_root >= 0 &&
temporary.exprs[temporary.stmts[0].expr_root].kind != KIR_EXPR_UNKNOWN;
free(temporary.stmts); free(temporary.exprs);
return valid;
}
static int
append(KirFunction *out, const KirStmt *st)
{
KirStmt *copy = KirFunctionAddStmt(out, st->kind, st->text, st->widget,
st->span);
if(!copy)
return 0;
*copy = *st;
return 1;
}
static int
emit(KirFunction *out, Cleanup *entries, int count, int minimum)
{
for(int i = count - 1; i >= 0 && entries[i].depth >= minimum; i--)
if(!append(out, &entries[i].statement))
return 0;
return 1;
}
static int
opens(KirStmtKind kind)
{
return kind == KIR_STMT_BLOCK_OPEN || kind == KIR_STMT_IF ||
kind == KIR_STMT_WHILE || kind == KIR_STMT_FOR || kind == KIR_STMT_SWITCH;
}
static int
end_block(const KirFunction *fn, int start, int end)
{
int depth = 1;
for(int i = start + 1; i < end; i++) {
if(opens(fn->stmts[i].kind)) depth++;
if(fn->stmts[i].kind == KIR_STMT_BLOCK_CLOSE && !--depth) return i;
}
return end;
}
static int
falls_through(const KirFunction *fn, int start, int end)
{
for(int i = start; i < end; i++) {
KirStmtKind kind = fn->stmts[i].kind;
if(kind == KIR_STMT_RETURN || kind == KIR_STMT_BREAK || kind == KIR_STMT_CONTINUE)
return 0;
if(opens(kind)) {
int close = end_block(fn, i, end);
int falls = falls_through(fn, i + 1, close);
if(kind == KIR_STMT_BLOCK_OPEN && !falls) return 0;
if(kind == KIR_STMT_IF) {
int has_else = 0;
while(close + 1 < end && fn->stmts[close + 1].kind == KIR_STMT_IF &&
strncmp(fn->stmts[close + 1].text, "else", 4) == 0) {
int next = close + 1;
has_else = strncmp(kir_skip_ws(fn->stmts[next].text + 4), "if", 2) != 0;
close = end_block(fn, next, end);
falls |= falls_through(fn, next + 1, close);
}
if(has_else && !falls) return 0;
}
i = close;
}
}
return 1;
}
int
KirLowerCleanup(KirFunction *fn)
{
int has_cleanup = 0, depth = 0, count = 0, serial = 0, ok = 0;
Cleanup *entries;
KirStmtKind *scopes;
int *scope_start;
KirFunction out = {0};
for(int i = 0; i < fn->stmt_count; i++)
has_cleanup |= fn->stmts[i].kind == KIR_STMT_DEFER;
if(!has_cleanup)
return 1;
entries = calloc((size_t)fn->stmt_count + 1, sizeof(*entries));
scopes = calloc((size_t)fn->stmt_count + 1, sizeof(*scopes));
scope_start = calloc((size_t)fn->stmt_count + 1, sizeof(*scope_start));
if(!entries || !scopes || !scope_start)
goto done;
for(int i = 0; i < fn->stmt_count; i++) {
const KirStmt *st = &fn->stmts[i];
if(st->kind == KIR_STMT_IF && !strncmp(st->text, "guard ", 6)) {
fail(st, "guard with defer requires an explicit if and return");
goto done;
}
if(st->kind == KIR_STMT_GOTO || st->kind == KIR_STMT_LABEL) {
fail(st, "goto and labels in functions with defer are not supported");
goto done;
}
if(st->kind == KIR_STMT_RAW) {
fail(st, "raw C and conditional preprocessing in functions with defer are not supported");
goto done;
}
if(st->kind == KIR_STMT_DECL) {
KirLexer lexer;
KirToken name;
KirLexerInit(&lexer, st->text, st->span.path);
name = KirLexerNext(&lexer);
for(int d = 0; d < count; d++) {
if(mentions(entries[d].statement.text, name.text)) {
fail(st, "a declaration cannot shadow a name referenced by an active defer");
goto done;
}
}
}
if(st->kind == KIR_STMT_FOR) {
for(int d = 0; d < count; d++) {
KirLexer lexer;
KirToken token;
KirLexerInit(&lexer, st->text, st->span.path);
do {
token = KirLexerNext(&lexer);
if(token.kind == KIR_TOKEN_IDENT &&
mentions(entries[d].statement.text, token.text)) {
fail(st, "a for header cannot reuse a name referenced by an active defer; use a while loop");
goto done;
}
} while(token.kind != KIR_TOKEN_EOF);
}
}
if(st->kind == KIR_STMT_DEFER) {
const char *body = kir_skip_ws(st->text + 5);
KirStmt *action = &entries[count].statement;
if(scopes[depth] == KIR_STMT_SWITCH) {
fail(st, "defer in a switch case requires an explicit block");
goto done;
}
/* Cleanup actions are expressions or assignments, never jumps or
* declarations. Keep their source span for backend diagnostics. */
*action = *st;
if(!action_kind(body, action)) {
fail(st, "defer requires one expression or assignment");
goto done;
}
action->expr_root = -1;
kir_copy(action->text, sizeof(action->text), body);
entries[count++].depth = depth;
continue;
}
if(st->kind == KIR_STMT_RETURN && count) {
KirStmt result = *st;
const char *value = kir_skip_ws(st->text + 6);
if(*value && strcmp(value, ";")) {
char name[KIR_NAME_MAX];
int collision;
/* Reserve a fresh local without reserving user identifiers. */
do {
snprintf(name, sizeof(name), "cleanup_return_%d", serial++);
collision = strstr(fn->args, name) != NULL;
for(int k = 0; k < fn->stmt_count; k++)
collision |= strstr(fn->stmts[k].text, name) != NULL;
} while(collision);
result.kind = KIR_STMT_DECL;
result.expr_root = st->expr_root;
if(snprintf(result.text, sizeof(result.text), "%s: %s = %s",
name, fn->return_type, value) >= (int)sizeof(result.text)) {
fail(st, "return expression exceeds cleanup lowering limit");
goto done;
}
if(!append(&out, &result))
goto done;
result.kind = KIR_STMT_RETURN;
result.expr_root = -1;
snprintf(result.text, sizeof(result.text), "return %s", name);
}
if(!emit(&out, entries, count, 0) || !append(&out, &result))
goto done;
continue;
}
if(st->kind == KIR_STMT_BREAK || st->kind == KIR_STMT_CONTINUE) {
int target = depth;
while(target > 0 && scopes[target] != KIR_STMT_FOR &&
scopes[target] != KIR_STMT_WHILE &&
!(st->kind == KIR_STMT_BREAK && scopes[target] == KIR_STMT_SWITCH))
target--;
if(!target) {
fail(st, "loop control outside a loop or switch");
goto done;
}
if(!emit(&out, entries, count, target))
goto done;
}
if(st->kind == KIR_STMT_BLOCK_CLOSE) {
if(!depth) {
fail(st, "unbalanced cleanup scope");
goto done;
}
if(falls_through(fn, scope_start[depth], i) &&
!emit(&out, entries, count, depth))
goto done;
while(count && entries[count - 1].depth >= depth)
count--;
depth--;
}
if(!append(&out, st))
goto done;
if(opens(st->kind)) {
scopes[++depth] = st->kind;
scope_start[depth] = i + 1;
}
}
if(falls_through(fn, 0, fn->stmt_count) && !emit(&out, entries, count, 0))
goto done;
free(fn->stmts);
fn->stmts = out.stmts;
fn->stmt_count = out.stmt_count;
fn->stmt_cap = out.stmt_cap;
out.stmts = NULL;
ok = 1;
done:
free(out.stmts);
free(entries);
free(scopes);
free(scope_start);
return ok;
}
-7
View File
@@ -1,7 +0,0 @@
#ifndef KIR_CLEANUP_H
#define KIR_CLEANUP_H
#include "kir.h"
/* Lower lexical cleanup once, before backend emission. Returns zero on error. */
int KirLowerCleanup(KirFunction *fn);
#endif
-571
View File
@@ -1,571 +0,0 @@
#include "kir_emit.h"
#include "kir_check.h"
#include "kir_text.h"
#include "kir_expr.h"
#include <ctype.h>
#include <errno.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
static int
format(char *out, size_t size, const char *format_string, ...)
{
va_list ap;
va_start(ap,format_string);
int n=vsnprintf(out,size,format_string,ap);
va_end(ap);
if(n<0 || (size_t)n>=size) {
fprintf(stderr,"generated expression exceeds output limit\n"); exit(1);
}
return n;
}
static const char *
canonical(const char *type)
{
const char *result = KirScalarType(type);
if(!strcmp(type, "integer")) return "i32";
if(!strcmp(type, "real")) return "f64";
return result;
}
const char *
KirTargetType(const char *type, KirTarget target)
{
static const struct { const char *type, *c, *go; } map[] = {
{"i8", "int8_t", "int8"}, {"i16", "int16_t", "int16"},
{"i32", "int32_t", "int32"}, {"i64", "int64_t", "int64"},
{"u8", "uint8_t", "uint8"}, {"u16", "uint16_t", "uint16"},
{"u32", "uint32_t", "uint32"}, {"u64", "uint64_t", "uint64"},
{"f32", "float", "float32"}, {"f64", "double", "float64"},
{"bool", "bool", "bool"}, {"void", "void", ""}, {NULL, NULL, NULL}
};
type = canonical(type);
for(int i = 0; map[i].type; i++)
if(!strcmp(type, map[i].type)) return target == KIR_GO ? map[i].go : map[i].c;
return NULL;
}
static int width(const char *type) { return (*type == 'i' || *type == 'u') ? atoi(type + 1) : 0; }
static int signed_type(const char *type) { return *type == 'i'; }
static int
supported_expression(const KirFunction *fn, int index)
{
const KirExpr *e;
if(index < 0) return 1;
e = &fn->exprs[index];
if(!KirTargetType(e->type, KIR_C)) return 0;
switch(e->kind) {
case KIR_EXPR_INT: case KIR_EXPR_FLOAT: case KIR_EXPR_IDENT: break;
case KIR_EXPR_BINARY: case KIR_EXPR_CONDITIONAL: break;
case KIR_EXPR_UNARY:
if(!strcmp(e->op, "&") || !strcmp(e->op, "*")) return 0;
break;
case KIR_EXPR_POSTFIX: break;
case KIR_EXPR_CAST:
if(!KirTargetType(e->name, KIR_C)) return 0;
break;
case KIR_EXPR_CALL: if(!e->name[0]) return 0; break;
default: return 0;
}
if(!supported_expression(fn, e->left) || !supported_expression(fn, e->right) ||
!supported_expression(fn, e->third)) return 0;
for(int child = e->first_child; child >= 0; child = fn->exprs[child].next_sibling)
if(!supported_expression(fn, child)) return 0;
return 1;
}
int
KirCanEmitBody(const KirFunction *fn)
{
char params[64][KIR_TEXT_MAX];
int count;
if(!fn->checked || fn->is_extern || fn->is_ui || !KirTargetType(fn->return_type, KIR_C)) return 0;
count = *kir_skip_ws(fn->args) ? kir_split_top(fn->args, params[0], 64, sizeof(params[0])) : 0;
for(int i = 0; i < count; i++) {
char *colon = strchr(params[i], ':');
if(!colon || !KirTargetType(kir_skip_ws(colon + 1), KIR_C)) return 0;
}
for(int i = 0; i < fn->stmt_count; i++) {
const KirStmt *st = &fn->stmts[i];
switch(st->kind) {
case KIR_STMT_DECL: if(!KirTargetType(st->type, KIR_C)) return 0; break;
case KIR_STMT_ASSIGN:
if(st->lhs_root < 0 || fn->exprs[st->lhs_root].kind != KIR_EXPR_IDENT) return 0;
break;
case KIR_STMT_IF: if(!strncmp(st->text, "guard", 5)) return 0; break;
case KIR_STMT_BLOCK_OPEN: case KIR_STMT_BLOCK_CLOSE:
case KIR_STMT_WHILE: case KIR_STMT_RETURN: case KIR_STMT_BREAK:
case KIR_STMT_CONTINUE: case KIR_STMT_UNUSED: case KIR_STMT_EXPR: break;
default: return 0;
}
if(!supported_expression(fn, st->expr_root) || !supported_expression(fn, st->lhs_root)) return 0;
}
return 1;
}
static void
number_prefix(const KirModule *module, char *out, size_t size)
{
uint32_t hash = 2166136261u;
for(const unsigned char *p = (const unsigned char *)module->source_path; *p; p++)
hash = (hash ^ *p) * 16777619u;
format(out, size, "number_%08x", hash);
}
void
KirEmitNumbers(FILE *out, const KirModule *module, KirTarget target)
{
char p[64];
int used = 0;
for(int i = 0; i < module->function_count; i++) used |= KirCanEmitBody(&module->functions[i]);
if(!used) return;
number_prefix(module, p, sizeof(p));
if(target == KIR_C || target == KIR_CPP) {
fprintf(out, "#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n\n");
fprintf(out,
"static inline int64_t %s_signed(uint64_t x, int w) {\n"
" uint64_t mask = w == 64 ? UINT64_MAX : (UINT64_C(1) << w) - 1;\n"
" x &= mask;\n"
" return x <= (mask >> 1) ? (int64_t)x : -1 - (int64_t)(mask - x);\n}\n", p);
fprintf(out,
"static inline uint64_t %s_bits(uint64_t a, uint64_t b, int w, int sign, int op) {\n"
" uint64_t mask = w == 64 ? UINT64_MAX : (UINT64_C(1) << w) - 1;\n"
" uint64_t shift = b; a &= mask; b &= mask;\n"
" switch(op) {\n"
" case 0: return a; case 1: return (a + b) & mask;\n"
" case 2: return (a - b) & mask; case 3: return (a * b) & mask;\n"
" case 4: case 5:\n"
" if(!b) abort();\n"
" if(sign) { int64_t x = %s_signed(a,w), y = %s_signed(b,w);\n"
" if(x == INT64_MIN && y == -1) return op == 4 ? a : 0;\n"
" return (uint64_t)(op == 4 ? x / y : x %% y) & mask; }\n"
" return op == 4 ? a / b : a %% b;\n"
" case 6: case 7:\n"
" if(shift >= (uint64_t)w) abort();\n"
" if(op == 6) return (a << shift) & mask;\n"
" if(!shift) return a;\n"
" return (a >> shift) | ((sign && (a & (UINT64_C(1) << (w-1)))) ? mask ^ (mask >> shift) : 0);\n"
" case 8: return a & b; case 9: return a | b; case 10: return a ^ b;\n"
" default: abort(); }\n}\n\n", p, p, p);
fprintf(out,
"static inline uint64_t %s_float(double x, int w, int sign) {\n"
" double bound = 1; for(int i = 0; i < w-sign; i++) bound *= 2;\n"
" if(!(x >= (sign ? -bound : 0) && x < bound)) abort();\n"
" return sign ? (uint64_t)(int64_t)x : (uint64_t)x;\n}\n", p);
} else if(target == KIR_GO) {
fprintf(out,
"func %s_float(x float64, w uint, sign bool) uint64 {\n"
" bits := w; if sign { bits-- }; bound := float64(1); for i := uint(0); i < bits; i++ { bound *= 2 }; lower := float64(0); if sign { lower = -bound }\n"
" if !(x >= lower && x < bound) { panic(\"float conversion out of range\") }; if sign { return uint64(int64(x)) }; return uint64(x)\n}\n", p);
fprintf(out,
"func %s_bits(a, b uint64, w uint, sign bool, op int) uint64 {\n"
" mask := ^uint64(0); if w < 64 { mask = (uint64(1) << w) - 1 }; shift := b; a &= mask; b &= mask\n"
" switch op {\n"
" case 0: return a\n case 1: return (a+b)&mask\n case 2: return (a-b)&mask\n case 3: return (a*b)&mask\n"
" case 4,5:\n if b == 0 { panic(\"integer division by zero\") }\n"
" if sign { x := int64(a << (64-w)) >> (64-w); y := int64(b << (64-w)) >> (64-w); if op == 4 { return uint64(x/y)&mask }; return uint64(x%%y)&mask }; if op == 4 { return a/b }; return a%%b\n"
" case 6,7:\n if shift >= uint64(w) { panic(\"invalid shift count\") }; if op == 6 { return (a<<shift)&mask }; if shift == 0 { return a }; result := a>>shift; if sign && (a & (uint64(1)<<(w-1))) != 0 { result |= mask ^ (mask>>shift) }; return result\n"
" case 8: return a&b\n case 9: return a|b\n case 10: return a^b\n }; panic(\"invalid numeric operation\")\n}\n\n", p);
} else {
fprintf(out,
"function %s_float(x, w, sign) {\n"
" const bound = 2 ** (w - (sign ? 1 : 0));\n"
" if(!(x >= (sign ? -bound : 0) && x < bound)) throw new RangeError('float conversion out of range');\n"
" return BigInt(Math.trunc(x));\n}\n", p);
fprintf(out,
"function %s_value(x, w, sign) {\n"
" if (typeof x === 'number' && !Number.isSafeInteger(x)) throw new RangeError('integer argument requires an exact value');\n"
" x = sign ? BigInt.asIntN(w, BigInt(x)) : BigInt.asUintN(w, BigInt(x));\n"
" return w > 32 ? x : Number(x);\n}\n"
"function %s_bool(x) { if(typeof x !== 'boolean') throw new TypeError('boolean value required'); return x; }\n"
"function %s_bits(a, b, w, sign, op) {\n"
" const shift = BigInt(b); a = BigInt.asUintN(w, BigInt(a)); b = BigInt.asUintN(w, BigInt(b));\n"
" let result;\n"
" switch (op) {\n"
" case 0: result=a; break; case 1: result=a+b; break; case 2: result=a-b; break; case 3: result=a*b; break;\n"
" case 4: case 5:\n"
" if(b === 0n) throw new RangeError('integer division by zero');\n"
" if(sign) { a=BigInt.asIntN(w,a); b=BigInt.asIntN(w,b); }\n"
" result=op === 4 ? a/b : a%%b; break;\n"
" case 6: case 7:\n"
" if(shift < 0n || shift >= BigInt(w)) throw new RangeError('invalid shift count');\n"
" result=op === 6 ? a<<shift : (sign ? BigInt.asIntN(w,a) : a)>>shift; break;\n"
" case 8: result=a&b; break; case 9: result=a|b; break; case 10: result=a^b; break;\n"
" default: throw new Error('invalid numeric operation');\n"
" }\n return %s_value(result,w,sign);\n}\n\n", p, p, p, p);
}
}
typedef struct Local { char name[KIR_NAME_MAX]; int depth; } Local;
typedef struct Emitter {
FILE *out;
const KirModule *module;
const KirFunction *fn;
KirTarget target;
KirResolveTarget resolve;
void *context;
int indent, serial, depth, local_count;
Local *locals;
char numbers[64];
} Emitter;
static void
line(Emitter *e, const char *format, ...)
{
va_list ap;
for(int i = 0; i < e->indent; i++) fputs(" ", e->out);
va_start(ap, format); vfprintf(e->out, format, ap); va_end(ap);
fputc('\n', e->out);
}
static void
fatal(const KirExpr *expr, const char *message)
{
fprintf(stderr, "%s:%d:%d: %s: %s\n", expr->span.path, expr->span.line,
expr->span.column, message, expr->text);
exit(1);
}
static void
fresh(Emitter *e, char *name)
{
int collision;
do {
format(name, KIR_NAME_MAX, "value_%d", e->serial++);
collision = strstr(e->fn->args, name) != NULL;
for(int i = 0; i < e->fn->stmt_count; i++) collision |= strstr(e->fn->stmts[i].text, name) != NULL;
for(int i = 0; i < e->module->state_count; i++) collision |= !strcmp(e->module->state_fields[i].name, name);
for(int i = 0; i < e->module->global_count; i++) collision |= !strcmp(e->module->globals[i].name, name);
for(int i = 0; i < e->module->define_count; i++) collision |= !strcmp(e->module->defines[i].name, name);
for(int i = 0; i < e->module->function_count; i++) collision |= !strcmp(e->module->functions[i].name, name);
} while(collision);
}
static void
declare(Emitter *e, const char *name, const char *type, const char *value)
{
const char *target_type = KirTargetType(type, e->target);
if(e->target == KIR_GO) line(e, "var %s %s = %s", name, target_type, value);
else if(e->target == KIR_JS && width(canonical(type)))
line(e,"let %s = %s_value(%s,%d,%s);",name,e->numbers,value,width(canonical(type)),signed_type(canonical(type))?"true":"false");
else if(e->target == KIR_JS && !strcmp(canonical(type),"bool"))
line(e,"let %s = %s_bool(%s);",name,e->numbers,value);
else if(e->target == KIR_JS) line(e, "let %s = %s;", name, value);
else line(e, "%s %s = %s;", target_type, name, value);
}
static void
resolve(Emitter *e, const char *name, char *out, size_t size)
{
for(int i = e->local_count - 1; i >= 0; i--)
if(!strcmp(e->locals[i].name, name)) { kir_copy(out,size,name); return; }
e->resolve(e->context, name, out, size);
}
static int
operation(const char *op)
{
static const char *const ops[] = {"", "+", "-", "*", "/", "%", "<<", ">>", "&", "|", "^"};
for(int i = 1; i <= 10; i++) if(!strcmp(op,ops[i])) return i;
return 0;
}
static void
number(Emitter *e, const char *type, const char *a, const char *b, int op, char *out, size_t size)
{
char bits[KIR_TEXT_MAX];
int w = width(type), sign = signed_type(type);
if(e->target == KIR_GO) {
format(bits,sizeof(bits),"%s_bits(uint64(%s),uint64(%s),%d,%s,%d)",e->numbers,a,b,w,sign?"true":"false",op);
format(out,size,"%s(%s)",KirTargetType(type,e->target),bits);
} else if(e->target == KIR_JS) {
format(out,size,"%s_bits(%s,%s,%d,%s,%d)",e->numbers,a,b,w,sign?"true":"false",op);
} else {
format(bits,sizeof(bits),"%s_bits((uint64_t)(%s),(uint64_t)(%s),%d,%d,%d)",e->numbers,a,b,w,sign,op);
if(sign) format(out,size,"(%s)%s_signed(%s,%d)",KirTargetType(type,e->target),e->numbers,bits,w);
else format(out,size,"(%s)(%s)",KirTargetType(type,e->target),bits);
}
}
static void emit_expr(Emitter *e, int index, const char *expected, char *out, size_t size);
static void
literal(Emitter *e, const KirExpr *expr, const char *type, int negative, char *out, size_t size)
{
char raw[KIR_TEXT_MAX], *end;
size_t length = 0;
unsigned long long value;
for(const char *p = expr->text; *p; p++) if(*p != '_') raw[length++] = *p;
raw[length] = 0;
errno = 0;
value = strtoull(raw,&end,0);
if(end == raw || errno == ERANGE) fatal(expr,"integer literal is out of range");
if(*end && strcmp(end,"u") && strcmp(end,"U") && strcmp(end,"l") && strcmp(end,"L") &&
strcmp(end,"ll") && strcmp(end,"LL") && strcmp(end,"ull") && strcmp(end,"ULL")) fatal(expr,"invalid integer literal");
int w = width(type);
if(w) {
uint64_t max = w == 64 ? UINT64_MAX : (UINT64_C(1)<<w)-1;
if(signed_type(type)) max = (max>>1) + (negative ? 1 : 0);
if(value > max || (negative && !signed_type(type) && value != 0)) fatal(expr,"integer literal does not fit its type");
}
if(e->target == KIR_JS) format(out,size,"%s%llu%s",negative?"-":"",value,w>32?"n":"");
else if(e->target == KIR_GO) format(out,size,"%s%llu",negative?"-":"",value);
else if(negative && value == (UINT64_C(1)<<63)) format(out,size,"(-INT64_C(9223372036854775807)-1)");
else format(out,size,"%s%llu%s",negative?"-":"",value,w>32?(signed_type(type)?"LL":"ULL"):"");
}
int
KirScalarLiteral(const char *type, const char *text, KirTarget target,
KirSourceSpan span, char *out, size_t size)
{
KirFunction fn={0};Emitter e={0};int ok=0;
type=canonical(type);e.target=target;
if(!*type)return 0;
if(!strcmp(type,"bool")) {
if(!strcmp(text,"true") || !strcmp(text,"false")) {kir_copy(out,size,text);return 1;}
return 0;
}
int index=KirParseExpr(&fn,NULL,text,span);
if(index>=0) {
KirExpr *expr=&fn.exprs[index];
if(expr->kind==KIR_EXPR_INT && width(type)) {
literal(&e,expr,type,0,out,size);ok=1;
} else if(expr->kind==KIR_EXPR_UNARY && !strcmp(expr->op,"-") &&
fn.exprs[expr->right].kind==KIR_EXPR_INT && width(type)) {
literal(&e,&fn.exprs[expr->right],type,1,out,size);ok=1;
} else if((expr->kind==KIR_EXPR_FLOAT || expr->kind==KIR_EXPR_INT) && type[0]=='f') {
kir_copy(out,size,text);size_t n=strlen(out);
if(n && (out[n-1]=='f'||out[n-1]=='F'))out[n-1]=0;
ok=1;
}
}
free(fn.exprs);return ok;
}
static void
emit_call(Emitter *e, const KirExpr *expr, char *out, size_t size)
{
char text[KIR_TEXT_MAX];
int count=0;
size_t n=(size_t)format(text,sizeof(text),"%s(",expr->name);
for(int child=expr->first_child;child>=0;child=e->fn->exprs[child].next_sibling) {
char argument[KIR_TEXT_MAX],capture[KIR_NAME_MAX];
emit_expr(e,child,e->fn->exprs[child].type,argument,sizeof(argument));
fresh(e,capture);
declare(e,capture,e->fn->exprs[child].type,argument);
n+=(size_t)format(text+n,sizeof(text)-n,"%s%s",count?",":"",capture);
count++;
}
format(text+n,sizeof(text)-n,")");
e->resolve(e->context,text,out,size);
}
static void
emit_expr(Emitter *e, int index, const char *expected, char *out, size_t size)
{
const KirExpr *expr=&e->fn->exprs[index];
const char *type=canonical(expr->type);
char a[KIR_TEXT_MAX],b[KIR_TEXT_MAX],result[KIR_TEXT_MAX],temp[KIR_NAME_MAX];
if(!strcmp(expr->type,"integer") || !strcmp(expr->type,"real")) {
const char *want=canonical(expected); if(*want && strcmp(want,"bool") && strcmp(want,"void")) type=want;
}
switch(expr->kind) {
case KIR_EXPR_IDENT: resolve(e,expr->name,result,sizeof(result));break;
case KIR_EXPR_INT: literal(e,expr,type,0,result,sizeof(result));break;
case KIR_EXPR_FLOAT: {
kir_copy(result,sizeof(result),expr->text);size_t n=strlen(result);
if(n && (result[n-1]=='f' || result[n-1]=='F')) result[n-1]=0;
break;
}
case KIR_EXPR_CALL:
emit_call(e,expr,result,sizeof(result));
if(!strcmp(type,"void")) {line(e,"%s%s",result,e->target==KIR_GO?"":";");out[0]=0;return;}
break;
case KIR_EXPR_CONDITIONAL:
emit_expr(e,expr->left,"bool",a,sizeof(a));fresh(e,temp);
declare(e,temp,type,!strcmp(type,"bool")?"false":e->target==KIR_JS&&width(type)>32?"0n":"0");
line(e,e->target==KIR_GO?"if %s {":"if (%s) {",a);e->indent++;
emit_expr(e,expr->right,type,b,sizeof(b));line(e,"%s = %s%s",temp,b,e->target==KIR_GO?"":";");e->indent--;
line(e,"} else {");e->indent++;emit_expr(e,expr->third,type,b,sizeof(b));
line(e,"%s = %s%s",temp,b,e->target==KIR_GO?"":";");e->indent--;line(e,"}");kir_copy(out,size,temp);return;
case KIR_EXPR_BINARY: {
const char *operand_type=type;
if(!strcmp(type,"bool")) {
operand_type=canonical(e->fn->exprs[expr->left].type);
if(!strcmp(e->fn->exprs[expr->left].type,"integer") || !strcmp(e->fn->exprs[expr->left].type,"real")) operand_type=canonical(e->fn->exprs[expr->right].type);
}
emit_expr(e,expr->left,operand_type,a,sizeof(a));
if(!strcmp(expr->op,"&&") || !strcmp(expr->op,"||")) {
fresh(e,temp);declare(e,temp,"bool",a);
line(e,e->target==KIR_GO?"if %s%s {":"if (%s%s) {",!strcmp(expr->op,"||")?"!":"",temp);e->indent++;
emit_expr(e,expr->right,"bool",b,sizeof(b));line(e,"%s = %s%s",temp,b,e->target==KIR_GO?"":";");
e->indent--;line(e,"}");kir_copy(out,size,temp);return;
}
emit_expr(e,expr->right,(!strcmp(expr->op,"<<")||!strcmp(expr->op,">>"))?"i32":operand_type,b,sizeof(b));
if(width(type) && operation(expr->op)) number(e,type,a,b,operation(expr->op),result,sizeof(result));
else format(result,sizeof(result),"%s %s %s",a,expr->op,b);
break;
}
case KIR_EXPR_UNARY:
if(!strcmp(expr->op,"-") && e->fn->exprs[expr->right].kind==KIR_EXPR_INT) {
literal(e,&e->fn->exprs[expr->right],type,1,result,sizeof(result));break;
}
if(!strcmp(expr->op,"++") || !strcmp(expr->op,"--")) {
resolve(e,e->fn->exprs[expr->right].name,a,sizeof(a));
if(width(type)) number(e,type,a,"1",expr->op[0]=='+'?1:2,result,sizeof(result));
else format(result,sizeof(result),e->target==KIR_JS&&!strcmp(type,"f32")?"Math.fround(%s %c 1)":"(%s %c 1)",a,expr->op[0]);
line(e,"%s = %s%s",a,result,e->target==KIR_GO?"":";");
kir_copy(result,sizeof(result),a);break;
}
emit_expr(e,expr->right,type,a,sizeof(a));
if(width(type) && !strcmp(expr->op,"-")) number(e,type,"0",a,2,result,sizeof(result));
else if(width(type) && !strcmp(expr->op,"~")) {
number(e,type,a,e->target==KIR_GO?"^uint64(0)":e->target==KIR_JS?"-1n":"UINT64_MAX",10,result,sizeof(result));
} else format(result,sizeof(result),"%s%s",expr->op,a);
break;
case KIR_EXPR_POSTFIX:
resolve(e,e->fn->exprs[expr->left].name,a,sizeof(a));fresh(e,temp);declare(e,temp,type,a);
if(width(type)) number(e,type,a,"1",expr->op[0]=='+'?1:2,result,sizeof(result));
else format(result,sizeof(result),e->target==KIR_JS&&!strcmp(type,"f32")?"Math.fround(%s %c 1)":"(%s %c 1)",a,expr->op[0]);
line(e,"%s = %s%s",a,result,e->target==KIR_GO?"":";");kir_copy(out,size,temp);return;
case KIR_EXPR_CAST:
emit_expr(e,expr->right,e->fn->exprs[expr->right].type,a,sizeof(a));
if(!strcmp(type,"bool")) {
format(result,sizeof(result),"%s != %s",a,!strcmp(canonical(e->fn->exprs[expr->right].type),"bool")?"false":"0");
} else if(!strcmp(canonical(e->fn->exprs[expr->right].type),"bool")) {
fresh(e,temp);declare(e,temp,type,"0");
line(e,e->target==KIR_GO?"if %s {":"if (%s) {",a);e->indent++;
line(e,"%s = %s%s",temp,e->target==KIR_JS&&width(type)>32?"1n":"1",e->target==KIR_GO?"":";");
e->indent--;line(e,"}");kir_copy(out,size,temp);return;
} else if(width(type)) {
if(canonical(e->fn->exprs[expr->right].type)[0]=='f') {
if(e->target==KIR_GO) format(b,sizeof(b),"%s_float(float64(%s),%d,%s)",e->numbers,a,width(type),signed_type(type)?"true":"false");
else format(b,sizeof(b),"%s_float(%s,%d,%s)",e->numbers,a,width(type),signed_type(type)?"true":"false");
number(e,type,b,"0",0,result,sizeof(result));
} else number(e,type,a,"0",0,result,sizeof(result));
}
else if(e->target==KIR_JS) format(result,sizeof(result),"%s(%s)",!strcmp(type,"f32")?"Math.fround":!strcmp(type,"bool")?"Boolean":"Number",a);
else if(e->target==KIR_GO) format(result,sizeof(result),"%s(%s)",KirTargetType(type,e->target),a);
else format(result,sizeof(result),"(%s)(%s)",KirTargetType(type,e->target),a);
break;
default: fatal(expr,"unsupported structured expression");
}
if(e->target==KIR_JS && !strcmp(type,"f32")) {kir_copy(a,sizeof(a),result);format(result,sizeof(result),"Math.fround(%s)",a);}
fresh(e,temp);declare(e,temp,type,result);kir_copy(out,size,temp);
}
static int
block_end(const KirFunction *fn,int begin,int end)
{
int depth=1;
for(int i=begin+1;i<end;i++) {
KirStmtKind k=fn->stmts[i].kind;
if(k==KIR_STMT_IF||k==KIR_STMT_WHILE||k==KIR_STMT_BLOCK_OPEN)depth++;
if(k==KIR_STMT_BLOCK_CLOSE && !--depth)return i;
}
return end;
}
static void emit_sequence(Emitter *e,int begin,int end);
static int
emit_if(Emitter *e,int i,int end)
{
char cond[KIR_TEXT_MAX];
int close=block_end(e->fn,i,end);
emit_expr(e,e->fn->stmts[i].expr_root,"bool",cond,sizeof(cond));
line(e,e->target==KIR_GO?"if %s {":"if (%s) {",cond);e->indent++;
emit_sequence(e,i+1,close);e->indent--;
if(close+1<end && e->fn->stmts[close+1].kind==KIR_STMT_IF && !strncmp(e->fn->stmts[close+1].text,"else",4)) {
int next=close+1;
line(e,"} else {");e->indent++;
if(e->fn->stmts[next].expr_root>=0)close=emit_if(e,next,end);
else {close=block_end(e->fn,next,end);emit_sequence(e,next+1,close);}
e->indent--;
}
line(e,"}");return close;
}
static void
emit_sequence(Emitter *e,int begin,int end)
{
int saved=e->local_count;e->depth++;
for(int i=begin;i<end;i++) {
const KirStmt *st=&e->fn->stmts[i];
char value[KIR_TEXT_MAX],lhs[KIR_TEXT_MAX],result[KIR_TEXT_MAX];
switch(st->kind) {
case KIR_STMT_DECL:
if(st->expr_root>=0)emit_expr(e,st->expr_root,st->type,value,sizeof(value));
else kir_copy(value,sizeof(value),!strcmp(canonical(st->type),"bool")?"false":e->target==KIR_JS&&width(canonical(st->type))>32?"0n":"0");
declare(e,st->name,st->type,value);
kir_copy(e->locals[e->local_count].name,KIR_NAME_MAX,st->name);e->locals[e->local_count++].depth=e->depth;
break;
case KIR_STMT_ASSIGN:
resolve(e,e->fn->exprs[st->lhs_root].name,lhs,sizeof(lhs));
if(strcmp(st->assignment_op,"=")) {
char old[KIR_NAME_MAX];fresh(e,old);
declare(e,old,e->fn->exprs[st->lhs_root].type,lhs);
emit_expr(e,st->expr_root,e->fn->exprs[st->lhs_root].type,value,sizeof(value));
char op[4];kir_copy(op,sizeof(op),st->assignment_op);op[strlen(op)-1]=0;
const char *type=canonical(e->fn->exprs[st->lhs_root].type);
if(width(type))number(e,type,old,value,operation(op),result,sizeof(result));
else format(result,sizeof(result),e->target==KIR_JS&&!strcmp(type,"f32")?"Math.fround(%s %s %s)":"%s %s %s",old,op,value);
} else {
emit_expr(e,st->expr_root,e->fn->exprs[st->lhs_root].type,value,sizeof(value));
kir_copy(result,sizeof(result),value);
}
line(e,"%s = %s%s",lhs,result,e->target==KIR_GO?"":";");break;
case KIR_STMT_RETURN:
if(st->expr_root>=0) {emit_expr(e,st->expr_root,e->fn->return_type,value,sizeof(value));line(e,"return %s%s",value,e->target==KIR_GO?"":";");}
else line(e,e->target==KIR_GO?"return":"return;");
e->local_count=saved;e->depth--;return;
case KIR_STMT_IF:i=emit_if(e,i,end);break;
case KIR_STMT_WHILE: {
int close=block_end(e->fn,i,end);
line(e,e->target==KIR_GO?"for {":"while (true) {");e->indent++;
emit_expr(e,st->expr_root,"bool",value,sizeof(value));
line(e,e->target==KIR_GO?"if !%s { break }":"if (!%s) { break; }",value);
emit_sequence(e,i+1,close);e->indent--;line(e,"}");i=close;break;
}
case KIR_STMT_BLOCK_OPEN: {
int close=block_end(e->fn,i,end);line(e,"{");e->indent++;emit_sequence(e,i+1,close);e->indent--;line(e,"}");i=close;break;
}
case KIR_STMT_BREAK:case KIR_STMT_CONTINUE:
line(e,"%s%s",st->kind==KIR_STMT_BREAK?"break":"continue",e->target==KIR_GO?"":";");
e->local_count=saved;e->depth--;return;
case KIR_STMT_EXPR:case KIR_STMT_UNUSED:
if(st->expr_root>=0) {
emit_expr(e,st->expr_root,e->fn->exprs[st->expr_root].type,value,sizeof(value));
if(*value)line(e,e->target==KIR_GO?"_ = %s":e->target==KIR_JS?"void %s;":"(void)%s;",value);
}break;
default:break;
}
}
e->local_count=saved;e->depth--;
}
int
KirEmitBody(FILE *out,const KirModule *module,const KirFunction *fn,KirTarget target,KirResolveTarget resolver,void *context)
{
Emitter e={0};char params[64][KIR_TEXT_MAX];int count;
if(!KirCanEmitBody(fn))return 0;
e.out=out;e.module=module;e.fn=fn;e.target=target;e.resolve=resolver;e.context=context;e.indent=1;
e.locals=calloc((size_t)fn->stmt_count+65,sizeof(*e.locals));
if(!e.locals) { fprintf(stderr,"out of memory during scalar emission\n"); exit(1); }
number_prefix(module,e.numbers,sizeof(e.numbers));
count=*kir_skip_ws(fn->args)?kir_split_top(fn->args,params[0],64,sizeof(params[0])):0;
for(int i=0;i<count;i++) {
char *colon=strchr(params[i],':');*colon++=0;kir_trim_in_place(params[i]);
kir_copy(e.locals[e.local_count++].name,KIR_NAME_MAX,params[i]);
const char *type=canonical(kir_skip_ws(colon));
if(target==KIR_JS && width(type))line(&e,"%s = %s_value(%s,%d,%s);",params[i],e.numbers,params[i],width(type),signed_type(type)?"true":"false");
if(target==KIR_JS && !strcmp(type,"bool"))line(&e,"%s = %s_bool(%s);",params[i],e.numbers,params[i]);
if(target==KIR_JS && !strcmp(type,"f32"))line(&e,"%s = Math.fround(%s);",params[i],params[i]);
}
emit_sequence(&e,0,fn->stmt_count);free(e.locals);return 1;
}
-16
View File
@@ -1,16 +0,0 @@
#ifndef KIR_EMIT_H
#define KIR_EMIT_H
#include "kir.h"
typedef enum KirTarget { KIR_C, KIR_CPP, KIR_GO, KIR_JS } KirTarget;
/* Resolve target symbol spelling and call ABI. Input contains identifiers and
* captured argument names only, never a source expression to reinterpret. */
typedef void (*KirResolveTarget)(void *context, const char *text, char *out, size_t size);
const char *KirTargetType(const char *type, KirTarget target);
int KirScalarLiteral(const char *type, const char *text, KirTarget target,
KirSourceSpan span, char *out, size_t size);
int KirCanEmitBody(const KirFunction *fn);
void KirEmitNumbers(FILE *out, const KirModule *module, KirTarget target);
int KirEmitBody(FILE *out, const KirModule *module, const KirFunction *fn,
KirTarget target, KirResolveTarget resolve, void *context);
#endif
-316
View File
@@ -1,316 +0,0 @@
#include "kir_expr.h"
#include "kir_token.h"
#include "kir_text.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
typedef struct ExprParser {
KirLexer lexer;
KirToken token;
KirFunction *fn;
const KirModule *module;
KirSourceSpan span;
const char *source;
size_t begin;
int failed, depth;
} ExprParser;
static void
next(ExprParser *p)
{
p->token = KirLexerNext(&p->lexer);
p->begin = p->lexer.pos - strlen(p->token.text);
}
static int
is(ExprParser *p, const char *s)
{
return strcmp(p->token.text, s) == 0;
}
static int
take(ExprParser *p, const char *s)
{
if(!is(p, s)) return 0;
next(p);
return 1;
}
static void
expect(ExprParser *p, const char *s)
{
if(!take(p, s)) p->failed = 1;
}
static int
node(ExprParser *p, KirExprKind kind, size_t start, const char *name,
const char *op, int left, int right)
{
char text[KIR_TEXT_MAX];
size_t n = p->begin > start ? p->begin - start : 0;
KirSourceSpan span = p->span;
KirExpr *e;
if(n >= sizeof(text)) { p->failed = 1; return -1; }
memcpy(text, p->source + start, n);
text[n] = 0;
kir_trim_in_place(text);
span.column += (int)start;
e = KirFunctionAddExpr(p->fn, kind, text, span);
if(!e) { p->failed = 1; return -1; }
kir_copy(e->name, sizeof(e->name), name);
kir_copy(e->op, sizeof(e->op), op);
e->left = left;
e->right = right;
return p->fn->expr_count - 1;
}
static int
type_name(const ExprParser *p, const char *s)
{
static const char *const names[] = {
"void", "bool", "char", "int", "float", "double", "short", "long",
"signed", "unsigned", "const", "volatile", "size_t", "ptrdiff_t",
"int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t",
"uint32_t", "uint64_t", "intptr_t", "uintptr_t", "i8", "i16", "i32",
"i64", "u8", "u16", "u32", "u64", "isize", "usize", "f32", "f64", NULL
};
for(int i = 0; names[i]; i++) if(!strcmp(s, names[i])) return 1;
if(p->module)
for(int i = 0; i < p->module->type_count; i++)
if(!strcmp(s, p->module->types[i].name)) return 1;
return 0;
}
static int expression(ExprParser *p, int minimum);
static int
prefix(ExprParser *p)
{
size_t start = p->begin;
KirToken tok = p->token;
int result = -1;
if(++p->depth > 128) { p->failed = 1; p->depth--; return -1; }
if(take(p, "sizeof")) {
int right;
if(take(p, "(")) {
if(type_name(p, p->token.text)) {
size_t ts = p->begin;
while(p->token.kind != KIR_TOKEN_EOF && !is(p, ")")) next(p);
right = node(p, KIR_EXPR_IDENT, ts, "", "", -1, -1);
expect(p, ")");
} else {
right = expression(p, 1);
expect(p, ")");
}
} else right = prefix(p);
result = node(p, KIR_EXPR_SIZEOF, start, "", "", -1, right);
} else if(is(p, "+") || is(p, "-") || is(p, "!") || is(p, "~") ||
is(p, "*") || is(p, "&") || is(p, "++") || is(p, "--")) {
int right;
next(p);
right = prefix(p);
result = node(p, KIR_EXPR_UNARY, start, "", tok.text, -1, right);
} else if(take(p, "(")) {
if(type_name(p, p->token.text)) {
char type[KIR_NAME_MAX];
size_t ts = p->begin, length;
while(p->token.kind == KIR_TOKEN_IDENT || is(p, "*")) next(p);
length = p->begin - ts;
if(length >= sizeof(type)) { p->failed = 1; length = 0; }
memcpy(type, p->source + ts, length); type[length] = 0;
kir_trim_in_place(type);
expect(p, ")");
if(is(p, "{")) {
/* Compound initializers remain explicitly opaque until their
* designated-field representation is available. */
int depth = 0;
do {
if(is(p, "{")) depth++;
if(is(p, "}")) depth--;
next(p);
} while(depth && p->token.kind != KIR_TOKEN_EOF);
if(depth) p->failed = 1;
result = node(p, KIR_EXPR_COMPOUND, start, "", "", -1, -1);
} else {
int right = prefix(p);
result = node(p, KIR_EXPR_CAST, start, type, "", -1, right);
}
} else {
result = expression(p, 1);
expect(p, ")");
/* Unknown imported C types still preserve compound literals. */
if(is(p, "{")) {
int depth = 0;
do {
if(is(p, "{")) depth++;
if(is(p, "}")) depth--;
next(p);
} while(depth && p->token.kind != KIR_TOKEN_EOF);
if(depth) p->failed = 1;
result = node(p, KIR_EXPR_COMPOUND, start, "", "", -1, -1);
}
}
} else {
KirExprKind kind;
switch(tok.kind) {
case KIR_TOKEN_IDENT: kind = KIR_EXPR_IDENT; break;
case KIR_TOKEN_INT: kind = KIR_EXPR_INT; break;
case KIR_TOKEN_FLOAT: kind = KIR_EXPR_FLOAT; break;
case KIR_TOKEN_STRING: kind = KIR_EXPR_STRING; break;
case KIR_TOKEN_CHAR: kind = KIR_EXPR_CHAR; break;
default: p->failed = 1; p->depth--; return -1;
}
next(p);
result = node(p, kind, start, kind == KIR_EXPR_IDENT ? tok.text : "", "", -1, -1);
}
while(!p->failed) {
if(take(p, "[")) {
int index = expression(p, 1);
expect(p, "]");
result = node(p, KIR_EXPR_INDEX, start, "", "", result, index);
} else if(is(p, ".") || is(p, "->")) {
int pointer = is(p, "->");
char name[KIR_NAME_MAX];
next(p);
if(p->token.kind != KIR_TOKEN_IDENT) p->failed = 1;
kir_copy(name, sizeof(name), p->token.text);
next(p);
result = node(p, pointer ? KIR_EXPR_POINTER_MEMBER : KIR_EXPR_MEMBER,
start, name, pointer ? "->" : ".", result, -1);
} else if(take(p, "(")) {
int first = -1, last = -1;
char name[KIR_NAME_MAX] = "";
int callee = result;
if(callee >= 0 && p->fn->exprs[callee].kind == KIR_EXPR_IDENT)
kir_copy(name, sizeof(name), p->fn->exprs[callee].name);
if(!is(p, ")")) do {
int child = expression(p, 1);
if(child < 0) { p->failed = 1; break; }
if(last >= 0) p->fn->exprs[last].next_sibling = child;
else first = child;
last = child;
} while(take(p, ","));
expect(p, ")");
result = node(p, KIR_EXPR_CALL, start, name, "", name[0] ? -1 : callee, -1);
if(result >= 0) p->fn->exprs[result].first_child = first;
} else if(is(p, "++") || is(p, "--")) {
char op[8]; kir_copy(op, sizeof(op), p->token.text); next(p);
result = node(p, KIR_EXPR_POSTFIX, start, "", op, result, -1);
} else break;
}
p->depth--;
return result;
}
static int
precedence(const char *op)
{
if(!strcmp(op, "?")) return 1;
if(!strcmp(op, "||")) return 2;
if(!strcmp(op, "&&")) return 3;
if(!strcmp(op, "|")) return 4;
if(!strcmp(op, "^")) return 5;
if(!strcmp(op, "&")) return 6;
if(!strcmp(op, "==") || !strcmp(op, "!=")) return 7;
if(!strcmp(op, "<") || !strcmp(op, "<=") || !strcmp(op, ">") || !strcmp(op, ">=")) return 8;
if(!strcmp(op, "<<") || !strcmp(op, ">>")) return 9;
if(!strcmp(op, "+") || !strcmp(op, "-")) return 10;
if(!strcmp(op, "*") || !strcmp(op, "/") || !strcmp(op, "%")) return 11;
return 0;
}
static int
expression(ExprParser *p, int minimum)
{
size_t start = p->begin;
int left = prefix(p), prec;
if(++p->depth > 128) { p->failed = 1; p->depth--; return -1; }
while(!p->failed && (prec = precedence(p->token.text)) >= minimum) {
char op[8];
int right;
kir_copy(op, sizeof(op), p->token.text);
next(p);
right = expression(p, !strcmp(op, "?") ? 1 : prec + 1);
if(!strcmp(op, "?")) {
int third;
expect(p, ":");
third = expression(p, 1);
left = node(p, KIR_EXPR_CONDITIONAL, start, "", "?", left, right);
if(left >= 0) p->fn->exprs[left].third = third;
} else left = node(p, KIR_EXPR_BINARY, start, "", op, left, right);
}
p->depth--;
return left;
}
int
KirParseExpr(KirFunction *fn, const KirModule *module, const char *text, KirSourceSpan span)
{
ExprParser p = {0};
int initial = fn->expr_count, result;
if(!*kir_skip_ws(text)) return -1;
p.fn = fn; p.module = module; p.span = span; p.source = text;
KirLexerInit(&p.lexer, text, span.path);
next(&p);
result = expression(&p, 1);
take(&p, ";");
if(p.failed || p.token.kind != KIR_TOKEN_EOF || result < 0) {
fn->expr_count = initial;
if(!KirFunctionAddExpr(fn, KIR_EXPR_UNKNOWN, text, span)) return -1;
return fn->expr_count - 1;
}
return result;
}
void
KirStructureFunction(KirFunction *fn, const KirModule *module)
{
free(fn->exprs); fn->exprs = NULL; fn->expr_count = fn->expr_cap = 0;
for(int i = 0; i < fn->stmt_count; i++) {
KirStmt *st = &fn->stmts[i];
char text[KIR_TEXT_MAX];
char *value = NULL;
kir_copy(text, sizeof(text), st->text);
st->expr_root = st->lhs_root = -1;
if(st->kind == KIR_STMT_DECL) {
char *colon = strchr(text, ':');
if(colon) {
*colon++ = 0; kir_trim_in_place(text);
kir_copy(st->name, sizeof(st->name), text);
value = strchr(colon, '=');
if(value) *value++ = 0;
kir_trim_in_place(colon);
kir_copy(st->type, sizeof(st->type), colon);
}
} else if(st->kind == KIR_STMT_ASSIGN) {
KirLexer lexer; KirToken tok;
KirLexerInit(&lexer, text, st->span.path);
do {
tok = KirLexerNext(&lexer);
if(!strcmp(tok.text, "=") || !strcmp(tok.text, "+=") ||
!strcmp(tok.text, "-=") || !strcmp(tok.text, "*=") ||
!strcmp(tok.text, "/=") || !strcmp(tok.text, "%=") ||
!strcmp(tok.text, "&=") || !strcmp(tok.text, "|=") ||
!strcmp(tok.text, "^=") || !strcmp(tok.text, "<<=") || !strcmp(tok.text, ">>=")) {
value = text + lexer.pos;
kir_copy(st->assignment_op, sizeof(st->assignment_op), tok.text);
text[lexer.pos - strlen(tok.text)] = 0;
st->lhs_root = KirParseExpr(fn, module, text, st->span);
break;
}
} while(tok.kind != KIR_TOKEN_EOF);
} else if(st->kind == KIR_STMT_RETURN) value = text + 6;
else if(st->kind == KIR_STMT_UNUSED) value = text + 6;
else if(st->kind == KIR_STMT_EXPR || st->kind == KIR_STMT_WIDGET) value = text;
else if(st->kind == KIR_STMT_WHILE || st->kind == KIR_STMT_IF || st->kind == KIR_STMT_SWITCH) {
kir_strip_block_brace(text);
value = text;
if(!strncmp(value, "else", 4)) value = (char *)kir_skip_ws(value + 4);
while(*value && !isspace((unsigned char)*value) && *value != '(') value++;
}
if(value && strcmp(kir_skip_ws(value), ";"))
st->expr_root = KirParseExpr(fn, module, value, st->span);
}
}
-9
View File
@@ -1,9 +0,0 @@
#ifndef KIR_EXPR_H
#define KIR_EXPR_H
#include "kir.h"
/* Parse with token precedence; unsupported syntax is an explicit unknown node. */
int KirParseExpr(KirFunction *fn, const KirModule *module, const char *text,
KirSourceSpan span);
void KirStructureFunction(KirFunction *fn, const KirModule *module);
#endif
-2687
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
#ifndef KRYON_KIR_PARSE_H
#define KRYON_KIR_PARSE_H
#include "kir.h"
/*
* Parse a .kry source file into a KirProgram. Returns a heap-allocated
* program (caller frees with KirProgramFree), or NULL on fatal error.
* This is the shared Kir frontend used by k2kir (dump), k2c (C backend),
* and k2b (krb backend).
*/
KirProgram *kir_parse_file(const char *path, const char *root);
#endif /* KRYON_KIR_PARSE_H */
-139
View File
@@ -1,139 +0,0 @@
#include "kir_text.h"
#include <ctype.h>
#include <string.h>
int
kir_is_ident_char(int c)
{
return isalnum((unsigned char)c) || c == '_';
}
const char *
kir_skip_ws(const char *s)
{
while(s != NULL && isspace((unsigned char)*s))
s++;
return s;
}
const char *
kir_skip_inline_ws(const char *s)
{
while(s != NULL && (*s == ' ' || *s == '\t'))
s++;
return s;
}
char *
kir_trim(char *s)
{
char *e;
if(s == NULL)
return NULL;
while(isspace((unsigned char)*s))
s++;
e = s + strlen(s);
while(e > s && isspace((unsigned char)e[-1]))
*--e = '\0';
return s;
}
char *
kir_trim_in_place(char *s)
{
char *p;
if(s == NULL)
return NULL;
p = kir_trim(s);
if(p != s)
memmove(s, p, strlen(p) + 1);
return s;
}
void
kir_strip_block_brace(char *s)
{
size_t n;
if(s == NULL)
return;
n = strlen(s);
while(n > 0 && isspace((unsigned char)s[n - 1]))
n--;
if(n > 0 && s[n - 1] == '{')
n--;
while(n > 0 && isspace((unsigned char)s[n - 1]))
n--;
s[n] = '\0';
}
void
kir_camel_ident(const char *s, char *dst, size_t dst_size)
{
size_t n = 0;
int up = 1;
if(dst_size == 0)
return;
for(const char *p = s; p != NULL && *p != '\0' && n + 1 < dst_size; p++) {
if(isalnum((unsigned char)*p)) {
dst[n++] = up ? (char)toupper((unsigned char)*p) : *p;
up = 0;
} else {
up = 1;
}
}
if(n == 0 && n + 1 < dst_size)
dst[n++] = 'X';
if(n > 0 && isdigit((unsigned char)dst[0]) && n + 1 < dst_size) {
memmove(dst + 1, dst, n + 1);
dst[0] = 'M';
n++;
}
dst[n] = '\0';
}
int
kir_split_top(const char *s, char *parts, int max, size_t part_size)
{
int depth = 0;
int n = 0;
const char *start = s;
if(s == NULL || parts == NULL || max <= 0 || part_size == 0)
return 0;
for(const char *p = s; ; p++) {
if(*p == '"' || *p == '\'') {
char q = *p++;
while(*p != '\0' && *p != q) {
if(*p == '\\' && p[1] != '\0')
p++;
p++;
}
} else if(*p == '\0' || (*p == ',' && depth == 0)) {
size_t len = (size_t)(p - start);
if(n < max && len < part_size) {
char *part = parts + ((size_t)n * part_size);
memcpy(part, start, len);
part[len] = '\0';
kir_trim_in_place(part);
n++;
}
if(*p == '\0')
break;
start = p + 1;
} else if(*p == '(' || *p == '[' || *p == '{') {
depth++;
} else if(*p == ')' || *p == ']' || *p == '}') {
if(depth > 0)
depth--;
}
}
return n;
}
-15
View File
@@ -1,15 +0,0 @@
#ifndef KRYON_KIR_TEXT_H
#define KRYON_KIR_TEXT_H
#include <stddef.h>
int kir_is_ident_char(int c);
const char *kir_skip_ws(const char *s);
const char *kir_skip_inline_ws(const char *s);
char *kir_trim(char *s);
char *kir_trim_in_place(char *s);
void kir_strip_block_brace(char *s);
void kir_camel_ident(const char *s, char *dst, size_t dst_size);
int kir_split_top(const char *s, char *parts, int max, size_t part_size);
#endif /* KRYON_KIR_TEXT_H */
-180
View File
@@ -1,180 +0,0 @@
#include "kir_token.h"
#include <ctype.h>
#include <string.h>
static int
is_ident_start(int c)
{
return isalpha((unsigned char)c) || c == '_';
}
static int
is_ident_continue(int c)
{
return isalnum((unsigned char)c) || c == '_';
}
static void
lexer_advance(KirLexer *lx)
{
if(lx->src[lx->pos] == '\n') {
lx->line++;
lx->column = 1;
} else {
lx->column++;
}
lx->pos++;
}
static void
token_copy(KirToken *tok, const char *src, size_t begin, size_t end)
{
size_t n = end > begin ? end - begin : 0;
if(n >= sizeof(tok->text))
n = sizeof(tok->text) - 1;
memcpy(tok->text, src + begin, n);
tok->text[n] = '\0';
}
void
KirLexerInit(KirLexer *lx, const char *src, const char *path)
{
memset(lx, 0, sizeof(*lx));
lx->src = src != NULL ? src : "";
lx->path = path != NULL ? path : "";
lx->line = 1;
lx->column = 1;
}
KirToken
KirLexerNext(KirLexer *lx)
{
KirToken tok;
size_t begin;
int start_line;
int start_column;
int c;
memset(&tok, 0, sizeof(tok));
while(isspace((unsigned char)lx->src[lx->pos]))
lexer_advance(lx);
begin = lx->pos;
start_line = lx->line;
start_column = lx->column;
c = (unsigned char)lx->src[lx->pos];
tok.span = KirSpan(lx->path, start_line, start_column);
if(c == '\0') {
tok.kind = KIR_TOKEN_EOF;
return tok;
}
if(c == '#') {
lexer_advance(lx);
while(is_ident_continue((unsigned char)lx->src[lx->pos]))
lexer_advance(lx);
tok.kind = KIR_TOKEN_DIRECTIVE;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(is_ident_start(c)) {
lexer_advance(lx);
while(is_ident_continue((unsigned char)lx->src[lx->pos]))
lexer_advance(lx);
tok.kind = KIR_TOKEN_IDENT;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(isdigit(c) || (c == '.' && isdigit((unsigned char)lx->src[lx->pos + 1]))) {
int seen_dot = c == '.';
int hexadecimal = c == '0' && (lx->src[lx->pos + 1] == 'x' || lx->src[lx->pos + 1] == 'X');
lexer_advance(lx);
while(isalnum((unsigned char)lx->src[lx->pos]) ||
lx->src[lx->pos] == '_' || lx->src[lx->pos] == '.' ||
((lx->src[lx->pos] == '+' || lx->src[lx->pos] == '-') &&
strchr(hexadecimal ? "pP" : "eE", lx->src[lx->pos - 1]))) {
if(lx->src[lx->pos] == '.')
seen_dot = 1;
if(strchr(hexadecimal ? "pP" : "eE", lx->src[lx->pos]))
seen_dot = 1;
lexer_advance(lx);
}
tok.kind = seen_dot ? KIR_TOKEN_FLOAT : KIR_TOKEN_INT;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(c == '"' || c == '\'') {
int quote = c;
lexer_advance(lx);
while(lx->src[lx->pos] != '\0') {
if(lx->src[lx->pos] == '\\' && lx->src[lx->pos + 1] != '\0') {
lexer_advance(lx);
lexer_advance(lx);
continue;
}
if(lx->src[lx->pos] == quote) {
lexer_advance(lx);
break;
}
lexer_advance(lx);
}
tok.kind = quote == '"' ? KIR_TOKEN_STRING : KIR_TOKEN_CHAR;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
if(strchr("{}()[],;", c) != NULL ||
(c == ':' && lx->src[lx->pos + 1] != ':' && lx->src[lx->pos + 1] != '=')) {
lexer_advance(lx);
tok.kind = KIR_TOKEN_PUNCT;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
{
static const char *const ops[] = {
"::", ":=", "++", "--", "->", "==", "!=", "<=", ">=", "&&", "||", "+=", "-=",
"*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<", ">>",
NULL
};
for(int i = 0; ops[i] != NULL; i++) {
size_t n = strlen(ops[i]);
if(strncmp(lx->src + lx->pos, ops[i], n) == 0) {
while(n-- > 0)
lexer_advance(lx);
tok.kind = KIR_TOKEN_OPERATOR;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
}
}
if(strchr("+-*/%=!<>.&|^?~", c) != NULL) {
lexer_advance(lx);
tok.kind = KIR_TOKEN_OPERATOR;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
lexer_advance(lx);
tok.kind = KIR_TOKEN_UNKNOWN;
token_copy(&tok, lx->src, begin, lx->pos);
return tok;
}
const char *
KirTokenKindName(KirTokenKind kind)
{
switch(kind) {
case KIR_TOKEN_EOF: return "eof";
case KIR_TOKEN_IDENT: return "ident";
case KIR_TOKEN_INT: return "int";
case KIR_TOKEN_FLOAT: return "float";
case KIR_TOKEN_STRING: return "string";
case KIR_TOKEN_CHAR: return "char";
case KIR_TOKEN_DIRECTIVE: return "directive";
case KIR_TOKEN_OPERATOR: return "operator";
case KIR_TOKEN_PUNCT: return "punct";
default: return "unknown";
}
}
-39
View File
@@ -1,39 +0,0 @@
#ifndef KRYON_KIR_TOKEN_H
#define KRYON_KIR_TOKEN_H
#include "kir.h"
#include <stddef.h>
typedef enum KirTokenKind {
KIR_TOKEN_EOF = 0,
KIR_TOKEN_IDENT,
KIR_TOKEN_INT,
KIR_TOKEN_FLOAT,
KIR_TOKEN_STRING,
KIR_TOKEN_CHAR,
KIR_TOKEN_DIRECTIVE,
KIR_TOKEN_OPERATOR,
KIR_TOKEN_PUNCT,
KIR_TOKEN_UNKNOWN
} KirTokenKind;
typedef struct KirToken {
KirTokenKind kind;
char text[KIR_TEXT_MAX];
KirSourceSpan span;
} KirToken;
typedef struct KirLexer {
const char *src;
const char *path;
size_t pos;
int line;
int column;
} KirLexer;
void KirLexerInit(KirLexer *lx, const char *src, const char *path);
KirToken KirLexerNext(KirLexer *lx);
const char *KirTokenKindName(KirTokenKind kind);
#endif /* KRYON_KIR_TOKEN_H */
-133
View File
@@ -1,133 +0,0 @@
/*
* krb-run — headless KRB cartridge runner (plan 11, phase 1).
*
* Loads a .krb, renders it with the kry_sw software rasterizer
* (optionally wrapped in the recording backend), and writes the frame as
* a PNG and/or the vtable call stream as text. Golden files for engine
* conformance are produced with --png/--record and compared by
* tests/krb_engine_test.sh.
*
* Usage: krb-run [--png out.png] [--record out.txt] [--w W] [--h H]
* [--frames N] file.krb
*/
#include "krb.h"
#include "kry_backend_rec.h"
#include "kry_sw.h"
#include "png_write.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
const char *png_path = NULL;
const char *rec_path = NULL;
const char *krb_path = NULL;
int w = 800;
int h = 600;
int frames = 1;
int i;
KrbImage img;
KrySw sw;
KryBackendRec rec;
long calls = -1;
FILE *recf = NULL;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--png") == 0 && i + 1 < argc)
png_path = argv[++i];
else if(strcmp(argv[i], "--record") == 0 && i + 1 < argc)
rec_path = argv[++i];
else if(strcmp(argv[i], "--w") == 0 && i + 1 < argc)
w = atoi(argv[++i]);
else if(strcmp(argv[i], "--h") == 0 && i + 1 < argc)
h = atoi(argv[++i]);
else if(strcmp(argv[i], "--frames") == 0 && i + 1 < argc)
frames = atoi(argv[++i]);
else if(argv[i][0] != '-' && krb_path == NULL)
krb_path = argv[i];
else {
fprintf(stderr,
"usage: krb-run [--png out.png] [--record out.txt]"
" [--w W] [--h H] [--frames N] file.krb\n");
return 2;
}
}
if(krb_path == NULL) {
fprintf(stderr, "krb-run: no cartridge given\n");
return 2;
}
memset(&img, 0, sizeof(img));
if(KrbLoadFile(&img, krb_path) != 0) {
fprintf(stderr, "krb-run: load failed: %s\n", krb_path);
return 1;
}
if(KrySwInit(&sw, NULL, w, h) != 0) {
fprintf(stderr, "krb-run: rasterizer init failed\n");
return 1;
}
{
const char *uis = getenv("KRB_RUN_UI_SCALE");
if(uis != NULL) {
int pm = (int)(atof(uis) * 1000.0f + 0.5f);
if(pm > 0 && pm <= 8000)
sw.scale = pm;
}
}
if(getenv("KRB_RUN_THEME_LIGHT") != NULL) {
KrySwSetTheme(&sw, KRY_THEME_BACKGROUND, 0xffffffffu);
KrySwSetTheme(&sw, KRY_THEME_SURFACE, 0xfbfbfbffu);
KrySwSetTheme(&sw, KRY_THEME_ICON, 0xd3d3d3ffu);
KrySwSetTheme(&sw, KRY_THEME_TEXT, 0x00000000u | 0xffu);
KrySwSetTheme(&sw, KRY_THEME_BUTTON, 0xffffffffu);
}
if(0) {
fprintf(stderr, "krb-run: rasterizer init failed\n");
return 1;
}
KrbAutoMount(&img);
if(rec_path != NULL) {
recf = fopen(rec_path, "w");
if(recf == NULL) {
fprintf(stderr, "krb-run: cannot write %s\n", rec_path);
return 1;
}
KryBackendSelect(KryBackendRecBackend(&rec, recf, KrySwBackend(&sw)));
} else {
{
const unsigned char *ad = NULL;
unsigned al = 0;
unsigned ak = 0;
if(KrbAssetFind(&img, "@atlas", &ad, &al, &ak, NULL, NULL) == 0 &&
ak == 1)
KrySwSetAtlas(&sw, ad, al);
}
KryBackendSelect(KrySwBackend(&sw));
}
{
int f;
for(f = 0; f < frames; f++) {
KrySwAdvance(&sw, 1.0f / 60.0f);
KrbDraw(&img, 0, 0, w, h);
}
}
if(recf != NULL) {
fclose(recf);
calls = KryBackendRecCalls(&rec);
}
if(png_path != NULL && krb_png_write(png_path, sw.pixels, sw.w, sw.h) != 0) {
fprintf(stderr, "krb-run: cannot write %s\n", png_path);
return 1;
}
KrbFree(&img);
KrySwFree(&sw);
printf("krb-run ok %s %dx%d calls=%ld\n", krb_path, w, h, calls);
return 0;
}
-154
View File
@@ -1,154 +0,0 @@
/*
* Minimal PNG writer for krb-run: 8-bit RGBA, stored (uncompressed)
* deflate blocks. No external dependencies, deterministic output.
*/
#include "png_write.h"
#include <stdlib.h>
#include <string.h>
static unsigned
crc32_buf(const unsigned char *p, size_t n)
{
static unsigned table[256];
static int built = 0;
unsigned crc = 0xffffffffu;
size_t i;
if(!built) {
int i;
for(i = 0; i < 256; i++) {
unsigned c = (unsigned)i;
int k;
for(k = 0; k < 8; k++)
c = (c & 1) ? 0xedb88320u ^ (c >> 1) : c >> 1;
table[i] = c;
}
built = 1;
}
for(i = 0; i < n; i++)
crc = table[(crc ^ p[i]) & 0xff] ^ (crc >> 8);
return crc ^ 0xffffffffu;
}
static void
be32(unsigned char *p, unsigned v)
{
p[0] = (unsigned char)(v >> 24);
p[1] = (unsigned char)(v >> 16);
p[2] = (unsigned char)(v >> 8);
p[3] = (unsigned char)v;
}
static void
png_chunk(FILE *f, const char *type, const unsigned char *data, size_t len)
{
unsigned char hdr[8];
unsigned char *buf;
unsigned crc;
buf = malloc(4 + len);
if(buf == NULL)
return;
memcpy(buf, type, 4);
if(len > 0 && data != NULL)
memcpy(buf + 4, data, len);
crc = crc32_buf(buf, 4 + len);
be32(hdr, (unsigned)len);
memcpy(hdr + 4, type, 4);
fwrite(hdr, 1, 8, f);
if(len > 0)
fwrite(data, 1, len, f);
be32(hdr, crc);
fwrite(hdr, 1, 4, f);
free(buf);
}
static unsigned
adler32_buf(const unsigned char *p, size_t n)
{
unsigned a = 1;
unsigned b = 0;
size_t i;
for(i = 0; i < n; i++) {
a = (a + p[i]) % 65521u;
b = (b + a) % 65521u;
}
return (b << 16) | a;
}
int
krb_png_write(const char *path, const unsigned char *rgba, int w, int h)
{
static const unsigned char sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
unsigned char ihdr[13];
unsigned char tail[4];
size_t rawlen = (size_t)h * (1 + (size_t)w * 4);
unsigned char *raw;
unsigned char *z;
size_t zn = 0;
size_t off = 0;
size_t left;
const unsigned char *src;
FILE *f;
int row;
int ok = 0;
f = fopen(path, "wb");
if(f == NULL)
return -1;
raw = malloc(rawlen);
z = malloc(rawlen + (rawlen / 65535 + 1) * 5 + 16);
if(raw == NULL || z == NULL)
goto out;
for(row = 0; row < h; row++) {
raw[off++] = 0; /* filter: none */
memcpy(raw + off, rgba + (size_t)row * w * 4, (size_t)w * 4);
off += (size_t)w * 4;
}
z[zn++] = 0x78; /* zlib header, fastest */
z[zn++] = 0x01;
src = raw;
left = rawlen;
while(left > 0) {
size_t chunk = left > 65535 ? 65535 : left;
unsigned char bhdr[5];
bhdr[0] = (left - chunk == 0) ? 1 : 0; /* BFINAL on last block */
bhdr[1] = (unsigned char)(chunk & 0xff);
bhdr[2] = (unsigned char)(chunk >> 8);
bhdr[3] = (unsigned char)(~chunk & 0xff);
bhdr[4] = (unsigned char)((~chunk >> 8) & 0xff);
memcpy(z + zn, bhdr, 5);
zn += 5;
memcpy(z + zn, src, chunk);
zn += chunk;
src += chunk;
left -= chunk;
}
be32(tail, adler32_buf(raw, rawlen));
memcpy(z + zn, tail, 4);
zn += 4;
fwrite(sig, 1, 8, f);
be32(ihdr, (unsigned)w);
be32(ihdr + 4, (unsigned)h);
ihdr[8] = 8; /* bit depth */
ihdr[9] = 6; /* RGBA */
ihdr[10] = 0; /* deflate */
ihdr[11] = 0; /* filter */
ihdr[12] = 0; /* interlace */
png_chunk(f, "IHDR", ihdr, 13);
png_chunk(f, "IDAT", z, zn);
png_chunk(f, "IEND", NULL, 0);
ok = 1;
out:
free(raw);
free(z);
if(fclose(f) != 0)
ok = 0;
return ok ? 0 : -1;
}
-8
View File
@@ -1,8 +0,0 @@
#ifndef KRB_RUN_PNG_WRITE_H
#define KRB_RUN_PNG_WRITE_H
#include <stdio.h>
int krb_png_write(const char *path, const unsigned char *rgba, int w, int h);
#endif
-196
View File
@@ -1,196 +0,0 @@
/*
* krb-sdl — SDL2 desktop host for KRB cartridges (plan 11, phase 7).
*
* Same shape as the web host: the kry_sw rasterizer produces the frame,
* SDL2 owns the window, input, and presentation (streaming texture).
* This is the template for the Android EGL host.
*
* Usage: krb-sdl [--png out.png] [--w W] [--h H] file.krb
* --png renders exactly one frame, dumps it, and exits (for tests;
* runs fine under SDL_VIDEODRIVER=dummy).
*/
#include "krb.h"
#include "kry_sw.h"
#include "png_write.h"
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
const char *png_path = NULL;
const char *krb_path = NULL;
int w = 800;
int h = 600;
int i;
KrbImage img;
KrySw sw;
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *texture;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "--png") == 0 && i + 1 < argc)
png_path = argv[++i];
else if(strcmp(argv[i], "--w") == 0 && i + 1 < argc)
w = atoi(argv[++i]);
else if(strcmp(argv[i], "--h") == 0 && i + 1 < argc)
h = atoi(argv[++i]);
else if(argv[i][0] != '-' && krb_path == NULL)
krb_path = argv[i];
else {
fprintf(stderr,
"usage: krb-sdl [--png out.png] [--w W] [--h H]"
" file.krb\n");
return 2;
}
}
if(krb_path == NULL) {
fprintf(stderr, "krb-sdl: no cartridge given\n");
return 2;
}
memset(&img, 0, sizeof(img));
if(KrbLoadFile(&img, krb_path) != 0) {
fprintf(stderr, "krb-sdl: load failed: %s\n", krb_path);
return 1;
}
if(KrySwInit(&sw, NULL, w, h) != 0) {
fprintf(stderr, "krb-sdl: rasterizer init failed\n");
return 1;
}
{
const unsigned char *ad = NULL;
unsigned al = 0;
unsigned ak = 0;
if(KrbAssetFind(&img, "@atlas", &ad, &al, &ak, NULL, NULL) == 0 &&
ak == 1)
KrySwSetAtlas(&sw, ad, al);
}
KrbAutoMount(&img);
KryBackendSelect(KrySwBackend(&sw));
if(SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "krb-sdl: SDL_Init: %s\n", SDL_GetError());
return 1;
}
if(SDL_CreateWindowAndRenderer(w, h, SDL_WINDOW_RESIZABLE, &window,
&renderer) != 0) {
fprintf(stderr, "krb-sdl: window: %s\n", SDL_GetError());
return 1;
}
SDL_SetWindowTitle(window, "krb-sdl");
SDL_StartTextInput();
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32,
SDL_TEXTUREACCESS_STREAMING, w, h);
if(texture == NULL) {
fprintf(stderr, "krb-sdl: texture: %s\n", SDL_GetError());
return 1;
}
if(png_path != NULL) {
/* single deterministic frame for the exactness comparator */
KrySwAdvance(&sw, 1.0f / 60.0f);
KrbDraw(&img, 0, 0, w, h);
SDL_UpdateTexture(texture, NULL, sw.pixels, sw.stride);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
{
unsigned char *buf = malloc((size_t)w * h * 4);
SDL_Rect r = {0, 0, w, h};
int ok;
if(buf == NULL)
return 1;
ok = SDL_RenderReadPixels(renderer, &r,
SDL_PIXELFORMAT_RGBA32, buf,
w * 4) == 0;
if(ok)
ok = krb_png_write(png_path, buf, w, h) == 0;
free(buf);
if(!ok) {
fprintf(stderr, "krb-sdl: frame dump failed\n");
return 1;
}
}
printf("krb-sdl ok %s %dx%d\n", krb_path, w, h);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
KrbFree(&img);
KrySwFree(&sw);
return 0;
}
for(;;) {
SDL_Event ev;
int running = 1;
while(SDL_PollEvent(&ev)) {
if(ev.type == SDL_QUIT)
running = 0;
else if(ev.type == SDL_MOUSEMOTION)
KrySwMouse(&sw, ev.motion.x, ev.motion.y);
else if(ev.type == SDL_MOUSEBUTTONDOWN)
KrySwButtonDown(&sw, 0);
else if(ev.type == SDL_MOUSEBUTTONUP)
KrySwButtonUp(&sw, 0);
else if(ev.type == SDL_MOUSEWHEEL)
KrySwWheel(&sw, ev.wheel.y * 50);
else if(ev.type == SDL_TEXTINPUT)
KrySwText(&sw, (unsigned)(unsigned char)ev.text.text[0]);
else if(ev.type == SDL_KEYDOWN &&
ev.key.keysym.sym == SDLK_BACKSPACE)
KrySwText(&sw, 0x08);
}
if(!running)
break;
KrySwAdvance(&sw, 1.0f / 60.0f);
KrbDraw(&img, 0, 0, w, h);
if(SDL_UpdateTexture(texture, NULL, sw.pixels, sw.stride) != 0) {
fprintf(stderr, "krb-sdl: update: %s\n", SDL_GetError());
return 1;
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
if(png_path != NULL) {
/* Test mode: read back through the SDL renderer — the same
* pixels that reached the screen — and dump them. */
unsigned char *buf = malloc((size_t)w * h * 4);
SDL_Rect r = {0, 0, w, h};
int ok;
if(buf == NULL)
return 1;
ok = SDL_RenderReadPixels(renderer, &r,
SDL_PIXELFORMAT_RGBA32, buf,
w * 4) == 0;
if(ok)
ok = krb_png_write(png_path, buf, w, h) == 0;
free(buf);
if(!ok) {
fprintf(stderr, "krb-sdl: frame dump failed\n");
return 1;
}
break;
}
SDL_Delay(16);
}
printf("krb-sdl ok %s %dx%d\n", krb_path, w, h);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
KrbFree(&img);
KrySwFree(&sw);
return 0;
}
-113
View File
@@ -1,113 +0,0 @@
/*
* krb-web — native web host for KRB cartridges (plan 11, phase 3).
*
* Compiles the KRB runtime + kry_sw software rasterizer to wasm with
* emscripten. Pixel-identical to the native headless renderer: the frame
* is blitted into an ImageData every tick. Cartridge is preloaded at
* /app.krb (--preload-file); input comes from canvas events through the
* exported krb_web_mouse / krb_web_button.
*
* Build: make krb-web KRB=examples/02_buttons.kry
*/
#include "krb.h"
#include "kry_sw.h"
#include <emscripten.h>
#include <stdio.h>
#include <string.h>
#ifndef KRB_WEB_CARTRIDGE
#define KRB_WEB_CARTRIDGE "/app.krb"
#endif
static KrbImage g_img;
static KrySw g_sw;
static int g_running;
static void
frame(void)
{
KrySwAdvance(&g_sw, 1.0f / 60.0f);
KrbDraw(&g_img, 0, 0, g_sw.w, g_sw.h);
EM_ASM({
var ptr = $0;
var w = $1;
var h = $2;
var cv = Module.canvas;
var ctx = cv.getContext('2d');
if (!Module.krbImg || Module.krbImg.width !== w ||
Module.krbImg.height !== h)
Module.krbImg = ctx.createImageData(w, h);
Module.krbImg.data.set(HEAPU8.subarray(ptr, ptr + w * h * 4));
ctx.putImageData(Module.krbImg, 0, 0);
}, g_sw.pixels, g_sw.w, g_sw.h);
}
int
main(void)
{
/* The player waits for a cartridge: the shell writes the picked or
* dropped file to KRB_WEB_CARTRIDGE in MEMFS and calls krb_web_start. */
return 0;
}
int
krb_web_start(void)
{
memset(&g_img, 0, sizeof(g_img));
if(g_sw.pixels != NULL)
KrySwFree(&g_sw);
if(KrbLoadFile(&g_img, KRB_WEB_CARTRIDGE) != 0) {
fprintf(stderr, "krb-player: load failed: %s\n", KRB_WEB_CARTRIDGE);
return 1;
}
if(KrySwInit(&g_sw, NULL, 800, 600) != 0)
return 1;
KrbAutoMount(&g_img);
{
const unsigned char *ad = NULL;
unsigned al = 0;
unsigned ak = 0;
if(KrbAssetFind(&g_img, "@atlas", &ad, &al, &ak, NULL, NULL) == 0 &&
ak == 1)
KrySwSetAtlas(&g_sw, ad, al);
}
KryBackendSelect(KrySwBackend(&g_sw));
#ifdef KRB_WEB_ONESHOT
frame();
#else
if(!g_running)
emscripten_set_main_loop(frame, 0, 0);
g_running = 1;
#endif
return 0;
}
void
krb_web_mouse(int x, int y)
{
KrySwMouse(&g_sw, x, y);
}
void
krb_web_text(int cp)
{
KrySwText(&g_sw, (unsigned)cp);
}
void
krb_web_wheel(int dy)
{
KrySwWheel(&g_sw, dy);
}
void
krb_web_button(int button, int down)
{
if(down)
KrySwButtonDown(&g_sw, button);
else
KrySwButtonUp(&g_sw, button);
}
-43
View File
@@ -1,43 +0,0 @@
/* Pre-js for the KRB_WEB_ONESHOT node build: stubs a canvas whose 2D
* context records the blitted ImageData, so the wasm blit path can be
* byte-compared against the native kry_sw frame without a browser. */
var Module = {
printErr: function(t) { console.error(t); },
preRun: [function() {
var path = process.argv[2];
if (!path) {
console.error('node-capture: missing cartridge path');
process.exit(2);
}
var data = require('fs').readFileSync(path);
FS.writeFile('/app.krb', new Uint8Array(data));
}],
canvas: {
getContext: function() {
return {
createImageData: function(w, h) {
return { width: w, height: h,
data: new Uint8ClampedArray(w * h * 4) };
},
putImageData: function(img) {
if (globalThis.__krb_frame)
return;
globalThis.__krb_frame = Buffer.from(img.data);
require('fs').writeSync(1, globalThis.__krb_frame);
process.exit(0);
}
};
}
},
onRuntimeInitialized: function() {
var rc = Module._krb_web_start();
if (rc)
process.exit(rc);
},
onExit: function() {
if (!globalThis.__krb_frame) {
console.error('node-capture: no frame captured');
process.exit(1);
}
}
};
-104
View File
@@ -1,104 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>krb player</title>
<style>
html, body { margin: 0; height: 100%; background: #101014; color: #f0f0f2;
font: 14px system-ui, sans-serif; display: flex;
flex-direction: column; align-items: center;
justify-content: center; gap: 12px; }
canvas { image-rendering: pixelated; max-width: 96vw; max-height: 80vh; }
#drop { border: 1px dashed #8a8a93; border-radius: 8px; padding: 14px 22px;
cursor: pointer; }
#drop.hot { border-color: #f0f0f2; background: #1c1c22; }
</style>
</head>
<body>
<div id="drop">drop a .krb cartridge here, or click to pick one</div>
<input id="file" type="file" accept=".krb" hidden>
<canvas id="krb" width="800" height="600"></canvas>
<script>
var Module = {
canvas: document.getElementById('krb')
};
(function() {
const canvas = Module.canvas;
const drop = document.getElementById('drop');
const input = document.getElementById('file');
function start(file) {
file.arrayBuffer().then(function(buf) {
Module.FS.writeFile('/app.krb', new Uint8Array(buf));
drop.textContent = file.name + ' — drop another .krb to switch';
Module._krb_web_start();
});
}
drop.addEventListener('click', function() { input.click(); });
input.addEventListener('change', function() {
if (input.files.length > 0)
start(input.files[0]);
});
['dragover', 'dragenter'].forEach(function(ev) {
drop.addEventListener(ev, function(e) {
e.preventDefault();
drop.classList.add('hot');
});
});
['dragleave', 'drop'].forEach(function(ev) {
drop.addEventListener(ev, function(e) {
e.preventDefault();
drop.classList.remove('hot');
});
});
drop.addEventListener('drop', function(e) {
e.preventDefault();
if (e.dataTransfer.files.length > 0)
start(e.dataTransfer.files[0]);
});
function pos(e) {
const r = canvas.getBoundingClientRect();
return [Math.round((e.clientX - r.left) * canvas.width / r.width),
Math.round((e.clientY - r.top) * canvas.height / r.height)];
}
window.addEventListener('keydown', function(e) {
if (e.key === 'Backspace' && Module._krb_web_text) {
e.preventDefault();
Module._krb_web_text(8);
}
});
window.addEventListener('keypress', function(e) {
if (Module._krb_web_text && e.charCode > 31)
Module._krb_web_text(e.charCode);
});
canvas.addEventListener('wheel', function(e) {
e.preventDefault();
if (Module._krb_web_wheel)
Module._krb_web_wheel(Math.round(-e.deltaY / 2));
}, { passive: false });
canvas.addEventListener('mousemove', function(e) {
if (Module._krb_web_mouse) {
const p = pos(e);
Module._krb_web_mouse(p[0], p[1]);
}
});
canvas.addEventListener('mousedown', function(e) {
if (Module._krb_web_button) {
const p = pos(e);
Module._krb_web_mouse(p[0], p[1]);
Module._krb_web_button(0, 1);
}
});
canvas.addEventListener('mouseup', function(e) {
if (Module._krb_web_button) {
const p = pos(e);
Module._krb_web_mouse(p[0], p[1]);
Module._krb_web_button(0, 0);
}
});
})();
</script>
{{{ SCRIPT }}}
</body>
</html>
-593
View File
@@ -1,593 +0,0 @@
#include "kryon.h"
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#define KP_PATH_MAX 1024
typedef struct PreviewOptions {
const char *command;
const char *project;
const char *source;
const char *source_dir;
const char *out;
int width;
int height;
int count;
} PreviewOptions;
typedef struct PreviewSession {
void *dylib;
AppHost *host;
DestroyAppHostCallback destroy_host;
unsigned long generation;
} PreviewSession;
static void
usage(void)
{
fprintf(stderr,
"usage:\n"
" kryon-preview capture --project ROOT --source REL --output PNG [--width W --height H]\n"
" kryon-preview reload --project ROOT --source REL [--count N --width W --height H]\n"
" kryon-preview capture-all --project ROOT --source-dir DIR --out-dir DIR [--width W --height H]\n"
" kryon-preview cartridge --source FILE.kry|FILE.krb --output PNG [--project ROOT] [--width W --height H]\n");
}
static const char *
arg_value(int argc, char **argv, int *i)
{
if(*i + 1 >= argc)
return NULL;
(*i)++;
return argv[*i];
}
static int
parse_args(int argc, char **argv, PreviewOptions *opt)
{
memset(opt, 0, sizeof(*opt));
opt->width = 640;
opt->height = 480;
opt->count = 2;
if(argc < 2)
return 0;
opt->command = argv[1];
for(int i = 2; i < argc; i++) {
const char *value = NULL;
if(strcmp(argv[i], "--project") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->project = value;
} else if(strcmp(argv[i], "--source") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->source = value;
} else if(strcmp(argv[i], "--source-dir") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->source_dir = value;
} else if(strcmp(argv[i], "--output") == 0 ||
strcmp(argv[i], "--out-dir") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->out = value;
} else if(strcmp(argv[i], "--width") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->width = atoi(value);
} else if(strcmp(argv[i], "--height") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->height = atoi(value);
} else if(strcmp(argv[i], "--count") == 0) {
value = arg_value(argc, argv, &i);
if(value == NULL)
return 0;
opt->count = atoi(value);
} else {
return 0;
}
}
if(opt->width <= 0)
opt->width = 640;
if(opt->height <= 0)
opt->height = 480;
if(opt->count <= 0)
opt->count = 1;
if(strcmp(opt->command, "capture") == 0)
return opt->project != NULL && opt->source != NULL && opt->out != NULL;
if(strcmp(opt->command, "reload") == 0)
return opt->project != NULL && opt->source != NULL;
if(strcmp(opt->command, "capture-all") == 0)
return opt->project != NULL && opt->source_dir != NULL && opt->out != NULL;
if(strcmp(opt->command, "cartridge") == 0)
return opt->source != NULL && opt->out != NULL;
return 0;
}
static void
path_join(char *dst, size_t dst_size, const char *a, const char *b)
{
if(a == NULL || a[0] == '\0')
snprintf(dst, dst_size, "%s", b != NULL ? b : "");
else if(b == NULL || b[0] == '\0')
snprintf(dst, dst_size, "%s", a);
else
snprintf(dst, dst_size, "%s/%s", a, b);
}
static int
has_suffix(const char *path, const char *suffix)
{
size_t path_len = strlen(path);
size_t suffix_len = strlen(suffix);
return path_len >= suffix_len &&
strcmp(path + path_len - suffix_len, suffix) == 0;
}
static int
copy_file(const char *src, const char *dst)
{
FILE *in = fopen(src, "rb");
FILE *out;
char buf[16384];
size_t n;
if(in == NULL)
return 0;
out = fopen(dst, "wb");
if(out == NULL) {
fclose(in);
return 0;
}
while((n = fread(buf, 1, sizeof(buf), in)) > 0) {
if(fwrite(buf, 1, n, out) != n) {
fclose(out);
fclose(in);
return 0;
}
}
if(ferror(in)) {
fclose(out);
fclose(in);
return 0;
}
fclose(out);
fclose(in);
return 1;
}
static int
mkdir_p(const char *path)
{
char tmp[KP_PATH_MAX];
snprintf(tmp, sizeof(tmp), "%s", path);
for(char *p = tmp + 1; *p != '\0'; p++) {
if(*p != '/')
continue;
*p = '\0';
if(mkdir(tmp, 0755) != 0 && errno != EEXIST)
return 0;
*p = '/';
}
return mkdir(tmp, 0755) == 0 || errno == EEXIST;
}
static int
build_host(const char *project)
{
char command[KP_PATH_MAX * 4];
const char *kryon_dir = getenv("KRYON_DIR");
int rc;
if(kryon_dir == NULL || kryon_dir[0] == '\0')
kryon_dir = "/usr/home/wao/src/kryon";
snprintf(command, sizeof(command),
"cd '%s' && gmake kryon-host KRYON_DIR='%s' >/tmp/kryon-preview-build.log 2>&1",
project, kryon_dir);
rc = system(command);
return rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 0;
}
static void
preview_close(PreviewSession *session)
{
if(session->destroy_host != NULL && session->host != NULL)
session->destroy_host(session->host);
if(session->dylib != NULL)
kry_dylib_close(session->dylib);
session->dylib = NULL;
session->host = NULL;
session->destroy_host = NULL;
}
static int
preview_open(PreviewSession *session, const char *project)
{
char host_path[KP_PATH_MAX];
char copy_path[KP_PATH_MAX];
CreateAppHostCallback create_host;
preview_close(session);
if(!build_host(project)) {
fprintf(stderr, "kryon-preview: host build failed, see /tmp/kryon-preview-build.log\n");
return 0;
}
path_join(host_path, sizeof(host_path), project, "build/kryon/app_host.so");
snprintf(copy_path, sizeof(copy_path), "%s.preview.%lu.so", host_path,
++session->generation);
if(!copy_file(host_path, copy_path)) {
fprintf(stderr, "kryon-preview: could not copy %s\n", host_path);
return 0;
}
session->dylib = kry_dylib_load(copy_path);
if(session->dylib == NULL) {
fprintf(stderr, "kryon-preview: load failed: %s\n",
kry_dylib_error() != NULL ? kry_dylib_error() : copy_path);
return 0;
}
create_host = (CreateAppHostCallback)kry_dylib_sym(session->dylib,
"CreateAppHost");
session->destroy_host =
(DestroyAppHostCallback)kry_dylib_sym(session->dylib,
"DestroyAppHost");
if(create_host == NULL || session->destroy_host == NULL) {
fprintf(stderr, "kryon-preview: host missing app symbols\n");
preview_close(session);
return 0;
}
session->host = create_host(APP_HOST_ABI_VERSION, project);
if(session->host == NULL) {
fprintf(stderr, "kryon-preview: host rejected ABI %d\n",
APP_HOST_ABI_VERSION);
preview_close(session);
return 0;
}
return 1;
}
static int
capture_source(PreviewSession *session, const char *source, const char *out,
int width, int height)
{
RenderTexture2D target;
Image image;
int selected;
int saved;
selected = SetAppScreenBySourcePath(session->host, source);
if(!selected)
SetAppScreen(session->host, 0);
target = LoadRenderTexture(width, height);
BeginTextureMode(target);
ClearBackground(GetThemeBackground());
BeginUIFrame(width, height, 1.0f);
DrawAppScreen(session->host, (Rectangle){0, 0, (float)width, (float)height});
EndUIFrame();
EndTextureMode();
image = LoadImageFromTexture(target.texture);
UnloadRenderTexture(target);
if(image.data == NULL)
return 0;
ImageFlipVertical(&image);
saved = ExportImage(image, out);
UnloadImage(image);
if(!selected)
fprintf(stderr, "kryon-preview: %s delegates to app preview\n", source);
return saved;
}
static int
run_capture(const PreviewOptions *opt)
{
PreviewSession session = {0};
int ok;
if(!preview_open(&session, opt->project))
return 1;
ok = capture_source(&session, opt->source, opt->out,
opt->width, opt->height);
preview_close(&session);
return ok ? 0 : 1;
}
static int
run_reload(const PreviewOptions *opt)
{
PreviewSession session = {0};
for(int i = 0; i < opt->count; i++) {
if(!preview_open(&session, opt->project))
return 1;
if(!capture_source(&session, opt->source, "/tmp/kryon-preview-reload.png",
opt->width, opt->height)) {
preview_close(&session);
return 1;
}
}
preview_close(&session);
return 0;
}
static void
png_name(char *dst, size_t dst_size, const char *rel)
{
size_t n = 0;
for(const char *p = rel; *p != '\0' && n + 5 < dst_size; p++)
dst[n++] = (*p == '/' || *p == '.') ? '_' : *p;
memcpy(dst + n, ".png", 5);
}
static int
capture_all_dir(PreviewSession *session, const PreviewOptions *opt,
const char *rel_dir, int *total)
{
char abs_dir[KP_PATH_MAX];
DIR *dir;
struct dirent *entry;
int ok = 1;
path_join(abs_dir, sizeof(abs_dir), opt->project, rel_dir);
dir = opendir(abs_dir);
if(dir == NULL)
return 0;
while((entry = readdir(dir)) != NULL) {
char child_rel[KP_PATH_MAX];
char child_abs[KP_PATH_MAX];
struct stat st;
if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
path_join(child_rel, sizeof(child_rel), rel_dir, entry->d_name);
path_join(child_abs, sizeof(child_abs), opt->project, child_rel);
if(stat(child_abs, &st) != 0)
continue;
if(S_ISDIR(st.st_mode)) {
if(!capture_all_dir(session, opt, child_rel, total))
ok = 0;
} else if(S_ISREG(st.st_mode) && has_suffix(entry->d_name, ".kry")) {
char file[KP_PATH_MAX];
char out_path[KP_PATH_MAX];
png_name(file, sizeof(file), child_rel);
path_join(out_path, sizeof(out_path), opt->out, file);
(*total)++;
if(!capture_source(session, child_rel, out_path,
opt->width, opt->height)) {
fprintf(stderr, "kryon-preview: capture failed: %s\n", child_rel);
ok = 0;
}
}
}
closedir(dir);
return ok;
}
static int
run_capture_all(const PreviewOptions *opt)
{
PreviewSession session = {0};
int total = 0;
int ok;
if(!mkdir_p(opt->out))
return 1;
if(!preview_open(&session, opt->project))
return 1;
ok = capture_all_dir(&session, opt, opt->source_dir, &total);
preview_close(&session);
fprintf(stderr, "kryon-preview: captured=%d failed=%d\n", total, ok ? 0 : 1);
return ok ? 0 : 1;
}
static int
file_exists(const char *path)
{
struct stat st;
return path != NULL && stat(path, &st) == 0 && S_ISREG(st.st_mode);
}
static int
find_k2b(char *dst, size_t dst_size)
{
const char *kryon_dir = getenv("KRYON_DIR");
const char *path;
if(kryon_dir != NULL && kryon_dir[0] != '\0') {
snprintf(dst, dst_size, "%s/build/bin/k2b", kryon_dir);
if(file_exists(dst))
return 1;
snprintf(dst, dst_size, "%s/build/linux-x86_64/bin/k2b", kryon_dir);
if(file_exists(dst))
return 1;
}
if(file_exists("build/bin/k2b")) {
snprintf(dst, dst_size, "build/bin/k2b");
return 1;
}
if(file_exists("build/linux-x86_64/bin/k2b")) {
snprintf(dst, dst_size, "build/linux-x86_64/bin/k2b");
return 1;
}
path = getenv("PATH");
if(path != NULL) {
char buf[KP_PATH_MAX];
const char *start = path;
while(*start != '\0') {
const char *colon = strchr(start, ':');
size_t n = colon != NULL ? (size_t)(colon - start) : strlen(start);
if(n > 0 && n + 4 < sizeof(buf)) {
memcpy(buf, start, n);
buf[n] = '\0';
path_join(dst, dst_size, buf, "k2b");
if(file_exists(dst))
return 1;
}
if(colon == NULL)
break;
start = colon + 1;
}
}
return 0;
}
static int
compile_krb(const char *k2b, const char *project, const char *source,
char *out_krb, size_t out_size)
{
char command[KP_PATH_MAX * 4];
char out_dir[KP_PATH_MAX];
char rel[KP_PATH_MAX];
char src_abs[KP_PATH_MAX];
int rc;
snprintf(out_dir, sizeof(out_dir), "%s/kryon-preview-krb",
getenv("TMPDIR") != NULL ? getenv("TMPDIR") : "/tmp");
snprintf(rel, sizeof(rel), "%s", source);
if(has_suffix(rel, ".kry"))
rel[strlen(rel) - 4] = '\0';
path_join(out_krb, out_size, out_dir, rel);
{
size_t n = strlen(out_krb);
if(n + 5 < out_size)
memcpy(out_krb + n, ".krb", 5);
}
{
char parent[KP_PATH_MAX];
char *slash;
snprintf(parent, sizeof(parent), "%s", out_krb);
slash = strrchr(parent, '/');
if(slash != NULL) {
*slash = '\0';
if(!mkdir_p(parent))
return 0;
}
}
if(source[0] == '/')
snprintf(src_abs, sizeof(src_abs), "%s", source);
else
path_join(src_abs, sizeof(src_abs), project, source);
snprintf(command, sizeof(command),
"'%s' --no-main --root '%s' -o '%s' '%s'",
k2b, project, out_dir, src_abs);
rc = system(command);
if(!(rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 0))
return 0;
return file_exists(out_krb);
}
static int
capture_cartridge(const char *krb_path, const char *out, int width, int height)
{
KrbImage img;
RenderTexture2D target;
Image image;
int saved;
memset(&img, 0, sizeof(img));
if(KrbLoadFile(&img, krb_path) != 0) {
fprintf(stderr, "kryon-preview: could not load %s\n", krb_path);
return 0;
}
target = LoadRenderTexture(width, height);
BeginTextureMode(target);
ClearBackground(GetThemeBackground());
BeginUIFrame(width, height, 1.0f);
KrbDraw(&img, 0, 0, width, height);
EndUIFrame();
EndTextureMode();
KrbFree(&img);
image = LoadImageFromTexture(target.texture);
UnloadRenderTexture(target);
if(image.data == NULL)
return 0;
ImageFlipVertical(&image);
saved = ExportImage(image, out);
UnloadImage(image);
return saved;
}
static int
run_cartridge(const PreviewOptions *opt)
{
char krb_path[KP_PATH_MAX];
const char *source = opt->source;
if(has_suffix(source, ".krb")) {
if(source[0] == '/' || opt->project == NULL)
snprintf(krb_path, sizeof(krb_path), "%s", source);
else
path_join(krb_path, sizeof(krb_path), opt->project, source);
return capture_cartridge(krb_path, opt->out, opt->width, opt->height)
? 0
: 1;
}
if(has_suffix(source, ".kry")) {
char k2b[KP_PATH_MAX];
const char *project = opt->project != NULL ? opt->project : ".";
if(!find_k2b(k2b, sizeof(k2b))) {
fprintf(stderr, "kryon-preview: k2b not found for cartridge compile\n");
return 1;
}
if(!compile_krb(k2b, project, source, krb_path, sizeof(krb_path))) {
fprintf(stderr, "kryon-preview: k2b failed\n");
return 1;
}
return capture_cartridge(krb_path, opt->out, opt->width, opt->height)
? 0
: 1;
}
fprintf(stderr, "kryon-preview: cartridge source must be .kry or .krb\n");
return 1;
}
int
main(int argc, char **argv)
{
PreviewOptions opt;
int rc;
if(!parse_args(argc, argv, &opt)) {
usage();
return 2;
}
SetTraceLogLevel(LOG_WARNING);
SetConfigFlags(FLAG_WINDOW_HIDDEN);
InitWindow(opt.width, opt.height, "Kryon Preview");
SetTargetFPS(60);
InitUI(opt.width, opt.height, 1.0f);
SetCurrentTheme(THEME_MONO, 0);
setenv("KRYON_INSPECT", "1", 1);
if(strcmp(opt.command, "capture") == 0)
rc = run_capture(&opt);
else if(strcmp(opt.command, "reload") == 0)
rc = run_reload(&opt);
else if(strcmp(opt.command, "cartridge") == 0)
rc = run_cartridge(&opt);
else
rc = run_capture_all(&opt);
CloseWindow();
return rc;
}
-619
View File
@@ -1,619 +0,0 @@
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define KT_LINE_MAX 4096
#define KT_PATH_MAX 1024
#define KT_MAX_TESTS 512
typedef struct KTOptions {
int headless;
int snap;
int bless;
const char *files[KT_MAX_TESTS];
int file_count;
} KTOptions;
typedef struct KTRun {
const KTOptions *options;
const char *argv0;
char root[KT_PATH_MAX];
char clip[KT_LINE_MAX];
char target[16];
FILE *log;
pid_t visual_pid;
int steps;
int failures;
} KTRun;
static void
kt_usage(FILE *out)
{
fprintf(out,
"usage: kt [-headless] [-snap] [-bless] [tests/file.kt ...]\n");
fprintf(out,
"commands: target open tap type key see shot wait mkdir write append copy paste mv exists notexists contains\n");
fprintf(out, "without -headless, kt opens the target app by default; "
"'target none' runs headless\n");
}
static char *
kt_trim(char *s)
{
char *end;
while(*s != '\0' && isspace((unsigned char)*s))
s++;
end = s + strlen(s);
while(end > s && isspace((unsigned char)end[-1]))
*--end = '\0';
return s;
}
static int
kt_ends_with(const char *s, const char *suffix)
{
size_t n;
size_t m;
if(s == NULL || suffix == NULL)
return 0;
n = strlen(s);
m = strlen(suffix);
return n >= m && strcmp(s + n - m, suffix) == 0;
}
static int
kt_mkdir(const char *path)
{
if(mkdir(path, 0775) == 0)
return 1;
return errno == EEXIST;
}
static int
kt_join(char *out, size_t out_size, const char *a, const char *b)
{
if(a == NULL || a[0] == '\0')
a = ".";
if(b == NULL)
b = "";
return snprintf(out, out_size, "%s/%s", a, b) < (int)out_size;
}
static int
kt_parse_word(char **cursor, char *out, size_t out_size)
{
char *s = kt_trim(*cursor);
size_t n = 0;
if(*s == '\0')
return 0;
while(*s != '\0' && !isspace((unsigned char)*s)) {
if(n + 1 < out_size)
out[n++] = *s;
s++;
}
out[n] = '\0';
*cursor = s;
return n > 0;
}
static int
kt_parse_arg(char **cursor, char *out, size_t out_size, char *err,
size_t err_size)
{
char *s = kt_trim(*cursor);
size_t n = 0;
if(*s == '\0') {
snprintf(err, err_size, "missing argument");
return 0;
}
if(*s == '"') {
s++;
while(*s != '\0' && *s != '"') {
if(*s == '\\' && s[1] != '\0')
s++;
if(n + 1 < out_size)
out[n++] = *s;
s++;
}
if(*s != '"') {
snprintf(err, err_size, "unterminated string");
return 0;
}
s++;
if(*kt_trim(s) != '\0') {
snprintf(err, err_size, "unexpected trailing text");
return 0;
}
} else {
while(*s != '\0' && !isspace((unsigned char)*s)) {
if(n + 1 < out_size)
out[n++] = *s;
s++;
}
if(*kt_trim(s) != '\0') {
snprintf(err, err_size, "unexpected trailing text");
return 0;
}
}
out[n] = '\0';
*cursor = s;
return 1;
}
static int
kt_parse_tail(char **cursor, char *out, size_t out_size, char *err,
size_t err_size)
{
char *s = kt_trim(*cursor);
if(*s == '\0') {
snprintf(err, err_size, "missing argument");
return 0;
}
return kt_parse_arg(&s, out, out_size, err, err_size);
}
static int
kt_safe_relpath(const char *path)
{
const char *p;
if(path == NULL || path[0] == '\0' || path[0] == '/')
return 0;
for(p = path; *p != '\0'; p++) {
if((p == path || p[-1] == '/') && p[0] == '.' &&
p[1] == '.' && (p[2] == '/' || p[2] == '\0'))
return 0;
}
return 1;
}
static int
kt_project_path(KTRun *run, const char *rel, char *out, size_t out_size)
{
if(!kt_safe_relpath(rel))
return 0;
return kt_join(out, out_size, run->root, rel);
}
static int
kt_read_file(const char *path, char *out, size_t out_size)
{
FILE *f;
size_t n;
f = fopen(path, "rb");
if(f == NULL)
return 0;
n = fread(out, 1, out_size > 0 ? out_size - 1 : 0, f);
if(out_size > 0)
out[n] = '\0';
fclose(f);
return 1;
}
static int
kt_write_file(const char *path, const char *text, const char *mode)
{
FILE *f = fopen(path, mode);
if(f == NULL)
return 0;
if(text != NULL && fputs(text, f) == EOF) {
fclose(f);
return 0;
}
fclose(f);
return 1;
}
static void
kt_tool_path(char *out, size_t out_size, const char *argv0,
const char *tool)
{
const char *slash;
size_t dir_len;
if(argv0 == NULL)
argv0 = "";
slash = strrchr(argv0, '/');
if(slash == NULL) {
snprintf(out, out_size, "%s", tool);
return;
}
dir_len = (size_t)(slash - argv0);
if(dir_len + 1 + strlen(tool) + 1 > out_size) {
snprintf(out, out_size, "%s", tool);
return;
}
memcpy(out, argv0, dir_len);
out[dir_len] = '/';
snprintf(out + dir_len + 1, out_size - dir_len - 1, "%s", tool);
}
static int
kt_start_visual(KTRun *run)
{
char tool[KT_PATH_MAX];
if(run->options == NULL || run->options->headless)
return 1;
if(run->visual_pid > 0)
return 1;
if(strcmp(run->target, "none") == 0)
return 1;
kt_tool_path(tool, sizeof(tool), run->argv0, "kryon");
run->visual_pid = fork();
if(run->visual_pid < 0)
return 0;
if(run->visual_pid == 0) {
setenv("KRYON_PROJECT_ROOT", run->root, 1);
execl(tool, tool, "--project", run->root, "run", "native",
(char *)NULL);
execlp("kryon", "kryon", "--project", run->root, "run", "native",
(char *)NULL);
_exit(127);
}
usleep(800000);
return 1;
}
static void
kt_stop_visual(KTRun *run)
{
int status;
if(run->visual_pid <= 0)
return;
kill(run->visual_pid, SIGTERM);
waitpid(run->visual_pid, &status, 0);
run->visual_pid = 0;
}
static void
kt_visual_step_delay(KTRun *run)
{
if(run->options != NULL && !run->options->headless &&
run->visual_pid > 0)
usleep(180000);
}
static int
kt_open_log(KTRun *run)
{
char path[KT_PATH_MAX];
if(!kt_join(path, sizeof(path), run->root, "logs"))
return 0;
if(!kt_mkdir(path))
return 0;
if(!kt_join(path, sizeof(path), run->root, "logs/kt.log"))
return 0;
run->log = fopen(path, "a");
return run->log != NULL;
}
static void
kt_log(KTRun *run, const char *file, int line_no, const char *cmd,
const char *arg)
{
if(run->log == NULL)
return;
fprintf(run->log, "%s:%d: %s %s\n", file, line_no, cmd,
arg != NULL ? arg : "");
}
static int
kt_run_command(KTRun *run, const char *file, int line_no, char *line)
{
char *cursor = line;
char cmd[32];
char arg[KT_LINE_MAX];
char arg2[KT_LINE_MAX];
char err[128];
char path[KT_PATH_MAX];
char path2[KT_PATH_MAX];
char text[KT_LINE_MAX];
char snapshots[KT_PATH_MAX];
if(!kt_parse_word(&cursor, cmd, sizeof(cmd)))
return 1;
if(strcmp(cmd, "target") == 0 || strcmp(cmd, "open") == 0 ||
strcmp(cmd, "tap") == 0 ||
strcmp(cmd, "type") == 0 || strcmp(cmd, "key") == 0 ||
strcmp(cmd, "see") == 0 || strcmp(cmd, "shot") == 0 ||
strcmp(cmd, "wait") == 0 ||
strcmp(cmd, "copy") == 0 || strcmp(cmd, "exists") == 0 ||
strcmp(cmd, "notexists") == 0 || strcmp(cmd, "mkdir") == 0) {
if(!kt_parse_arg(&cursor, arg, sizeof(arg), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(strcmp(cmd, "target") == 0) {
if(strcmp(arg, "app") != 0 && strcmp(arg, "none") != 0) {
fprintf(stderr, "%s:%d: unknown target: %s\n", file, line_no,
arg);
return 0;
}
snprintf(run->target, sizeof(run->target), "%s", arg);
}
if(strcmp(cmd, "open") == 0) {
struct stat st;
if(stat(arg, &st) != 0 || !S_ISDIR(st.st_mode)) {
fprintf(stderr, "%s:%d: open target is not a directory: %s\n",
file, line_no, arg);
return 0;
}
snprintf(run->root, sizeof(run->root), "%s", arg);
if(run->log == NULL && !kt_open_log(run)) {
fprintf(stderr, "%s:%d: could not open logs/kt.log\n", file,
line_no);
return 0;
}
if(!kt_start_visual(run)) {
fprintf(stderr, "%s:%d: could not start Kryon visual runner\n",
file, line_no);
return 0;
}
}
if(strcmp(cmd, "shot") == 0) {
if(!kt_join(snapshots, sizeof(snapshots), run->root, "snapshots") ||
!kt_mkdir(snapshots)) {
fprintf(stderr, "%s:%d: could not create snapshots/\n", file,
line_no);
return 0;
}
}
if(strcmp(cmd, "copy") == 0)
snprintf(run->clip, sizeof(run->clip), "%s", arg);
if(strcmp(cmd, "wait") == 0) {
int ms = atoi(arg);
if(ms < 0)
ms = 0;
if(ms > 30000)
ms = 30000;
usleep((useconds_t)ms * 1000);
}
if(strcmp(cmd, "exists") == 0) {
struct stat st;
if(!kt_project_path(run, arg, path, sizeof(path)) ||
stat(path, &st) != 0) {
fprintf(stderr, "%s:%d: path does not exist: %s\n", file,
line_no, arg);
return 0;
}
}
if(strcmp(cmd, "notexists") == 0) {
struct stat st;
if(!kt_project_path(run, arg, path, sizeof(path)) ||
stat(path, &st) == 0) {
fprintf(stderr, "%s:%d: path exists: %s\n", file, line_no,
arg);
return 0;
}
}
if(strcmp(cmd, "mkdir") == 0) {
if(!kt_project_path(run, arg, path, sizeof(path)) ||
!kt_mkdir(path)) {
fprintf(stderr, "%s:%d: could not create directory: %s\n",
file, line_no, arg);
return 0;
}
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
if(strcmp(cmd, "write") == 0 || strcmp(cmd, "append") == 0 ||
strcmp(cmd, "contains") == 0) {
if(!kt_parse_word(&cursor, arg, sizeof(arg))) {
fprintf(stderr, "%s:%d: missing path\n", file, line_no);
return 0;
}
if(!kt_parse_tail(&cursor, arg2, sizeof(arg2), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(!kt_project_path(run, arg, path, sizeof(path))) {
fprintf(stderr, "%s:%d: unsafe path: %s\n", file, line_no, arg);
return 0;
}
if(strcmp(cmd, "contains") == 0) {
if(!kt_read_file(path, text, sizeof(text)) ||
strstr(text, arg2) == NULL) {
fprintf(stderr, "%s:%d: file does not contain text: %s\n",
file, line_no, arg);
return 0;
}
} else if(!kt_write_file(path, arg2,
strcmp(cmd, "append") == 0 ? "ab" : "wb")) {
fprintf(stderr, "%s:%d: could not write file: %s\n", file, line_no,
arg);
return 0;
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
if(strcmp(cmd, "paste") == 0) {
if(!kt_parse_arg(&cursor, arg, sizeof(arg), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(run->clip[0] == '\0') {
fprintf(stderr, "%s:%d: clipboard is empty\n", file, line_no);
return 0;
}
if(!kt_project_path(run, arg, path, sizeof(path)) ||
!kt_write_file(path, run->clip, "ab")) {
fprintf(stderr, "%s:%d: could not paste into file: %s\n", file,
line_no, arg);
return 0;
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
if(strcmp(cmd, "mv") == 0) {
if(!kt_parse_word(&cursor, arg, sizeof(arg))) {
fprintf(stderr, "%s:%d: missing source path\n", file, line_no);
return 0;
}
if(!kt_parse_tail(&cursor, arg2, sizeof(arg2), err, sizeof(err))) {
fprintf(stderr, "%s:%d: %s\n", file, line_no, err);
return 0;
}
if(!kt_project_path(run, arg, path, sizeof(path)) ||
!kt_project_path(run, arg2, path2, sizeof(path2)) ||
rename(path, path2) != 0) {
fprintf(stderr, "%s:%d: could not move %s to %s\n", file, line_no,
arg, arg2);
return 0;
}
kt_log(run, file, line_no, cmd, arg);
run->steps++;
kt_visual_step_delay(run);
return 1;
}
fprintf(stderr, "%s:%d: unknown command: %s\n", file, line_no, cmd);
return 0;
}
static int
kt_run_file(const KTOptions *options, const char *argv0, const char *path)
{
FILE *f;
KTRun run = {0};
char line[KT_LINE_MAX];
int line_no = 0;
int ok = 1;
run.options = options;
run.argv0 = argv0;
snprintf(run.root, sizeof(run.root), ".");
snprintf(run.target, sizeof(run.target), "app");
if(!kt_open_log(&run)) {
fprintf(stderr, "%s: could not open logs/kt.log\n", path);
return 0;
}
f = fopen(path, "r");
if(f == NULL) {
fprintf(stderr, "%s: %s\n", path, strerror(errno));
fclose(run.log);
return 0;
}
while(fgets(line, sizeof(line), f) != NULL) {
char *trimmed;
line_no++;
trimmed = kt_trim(line);
if(trimmed[0] == '\0' || trimmed[0] == '#')
continue;
if(!kt_run_command(&run, path, line_no, trimmed)) {
ok = 0;
run.failures++;
}
}
if(run.log != NULL) {
fprintf(run.log, "%s: %d steps, %d failures\n", path, run.steps,
run.failures);
fclose(run.log);
}
kt_stop_visual(&run);
fclose(f);
return ok;
}
static int
kt_compare_strings(const void *a, const void *b)
{
const char *const *sa = a;
const char *const *sb = b;
return strcmp(*sa, *sb);
}
static int
kt_discover_tests(KTOptions *options)
{
DIR *dir;
struct dirent *entry;
char *names[KT_MAX_TESTS];
int count = 0;
dir = opendir("tests");
if(dir == NULL)
return 0;
while((entry = readdir(dir)) != NULL && count < KT_MAX_TESTS) {
char path[KT_PATH_MAX];
if(!kt_ends_with(entry->d_name, ".kt"))
continue;
if(!kt_join(path, sizeof(path), "tests", entry->d_name))
continue;
names[count] = strdup(path);
if(names[count] != NULL)
count++;
}
closedir(dir);
qsort(names, (size_t)count, sizeof(names[0]), kt_compare_strings);
for(int i = 0; i < count; i++)
options->files[options->file_count++] = names[i];
return count > 0;
}
int
main(int argc, char **argv)
{
KTOptions options = {0};
int ok = 1;
for(int i = 1; i < argc; i++) {
if(strcmp(argv[i], "-headless") == 0) {
options.headless = 1;
} else if(strcmp(argv[i], "-snap") == 0) {
options.snap = 1;
} else if(strcmp(argv[i], "-bless") == 0) {
options.bless = 1;
} else if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
kt_usage(stdout);
return 0;
} else if(argv[i][0] == '-') {
kt_usage(stderr);
return 2;
} else if(options.file_count < KT_MAX_TESTS) {
options.files[options.file_count++] = argv[i];
} else {
fprintf(stderr, "kt: too many test files\n");
return 2;
}
}
if(options.file_count == 0 && !kt_discover_tests(&options)) {
fprintf(stderr, "kt: no tests supplied and no tests/*.kt found\n");
return 2;
}
for(int i = 0; i < options.file_count; i++) {
if(!kt_run_file(&options, argv[0], options.files[i]))
ok = 0;
}
return ok ? 0 : 1;
}
+19 -66
View File
@@ -1,39 +1,14 @@
# Kryon Agent Guide
This document is for agents and maintainers using Kryon inside applications. It
describes the behavior Kryon owns, what application code should keep, and how to
update downstream projects without editing vendored copies by hand.
This document is for agents and maintainers using Kryon inside applications such as
Inbe. It describes the behavior Kryon owns, what application code should keep, and
how to update downstream projects without editing vendored copies by hand.
## Role
Kryon is a small native UI runtime with a Kryon-owned clean app API.
The current default backend is raylib, but applications should not depend on
raylib directly. Applications should use Kryon for shared UI behavior instead
of duplicating pointer capture, modal backdrop, button, tab, scroll, text input,
theme, and DPI logic in each project.
See `docs/BOUNDARIES.md` for the architectural line between reusable Kryon
runtime behavior and downstream application behavior. See `docs/ARCHITECTURE.md`
for the current subsystem map.
Do not add compatibility wrappers or alias layers when the app API changes. Migrate
Kryon itself first, then update downstream apps to the
canonical names directly. Generated app code must use clean names such as
`BeginFrame`, `EndFrame`, `Background`, `Text`, `Rect`, `Button`, `TextField`,
`TextArea`, `Row`, `Column`, and `Picture`. Do not reintroduce duplicate public
widget names such as `WidgetText`, `UIText`, or `UITextNode` for the same
behavior. New public widget constructors must not use a `UI` prefix. If a stale
prefixed widget constructor still exists, migrate callers to the canonical
unprefixed widget name instead of adding another alias.
Do not add public picture/widget helpers with `DrawUI*`, `UIText*`, or reversed
UI-draw prefix names when the behavior belongs on the simple widget API. Extend
`PictureProps`, `ButtonProps`, or the relevant unprefixed widget props instead,
and leave no compatibility alias behind.
Kryon owns live preview rendering, preview PNG capture, and hot-reload
verification. Do not use Krait as the capture test harness for `.kry` files.
Use Kryon-owned tooling directly, for example `kryon-preview`, to prove that a
project source file renders, exports a PNG, and reloads safely.
Kryon is a small immediate-mode UI layer on top of raylib. Applications should use
Kryon for shared UI behavior instead of duplicating pointer capture, modal backdrop,
button, tab, scroll, text input, theme, and DPI logic in each project.
Keep application code focused on product state and domain behavior. Move repeated UI
interaction rules into Kryon when more than one screen or project needs them.
@@ -46,11 +21,6 @@ screen-space UI frame. If the application uses a transformed UI camera, call
invalid cameras before using them; a zero-initialized `Camera2D` is treated as
`GetUIDefaultCamera()` so pointer input does not silently break.
After drawing all widgets, call `EndUIFrame()` before the backend's
`EndFrame()`. The closing call draws deferred overlays such as dropdowns and
text-field context menus, then finalizes focus and inspection state. Applications
must not reproduce those overlay or finalization steps themselves.
Beginning a frame resets per-frame interaction state:
- input blocking
@@ -88,18 +58,18 @@ Use these APIs by responsibility:
Kryon modal helpers own backdrop capture:
- `UIActionModalNode`
- `UIModalNode`
- `UIModal3ButtonNode`
- `UIModalFrameNode`
- `DrawUIActionModal`
- `DrawUIModal`
- `DrawUIModal3Button`
- `DrawUIModalFrame`
When an application uses one of those helpers, it should not add separate outside-click
guards or duplicate backdrop blocking. The helper registers the modal bounds for the
current frame and the next frame.
Prefer `UIActionModalNode` for title, message, and action-button dialogs. It measures
Prefer `DrawUIActionModal` for title, message, and action-button dialogs. It measures
button labels, fits text inside buttons, and wraps actions into multiple rows when
localized labels do not fit. Prefer `UIModalFrameNode` for custom modal content.
localized labels do not fit. Prefer `DrawUIModalFrame` for custom modal content.
Use manual
`SetUIModalCapture` only for specialized overlays that cannot use the shared modal
frame.
@@ -118,8 +88,8 @@ button is clicked; Kryon should decide whether pointer input is captured.
## Custom Modal Pattern
```c
int modal_w = Scale(320);
int modal_h = Scale(240);
int modal_w = ScaleUIPx(320);
int modal_h = ScaleUIPx(240);
int modal_x = (view_width - modal_w) / 2;
int modal_y = (view_height - modal_h) / 2;
@@ -162,29 +132,14 @@ Kryon owns desktop file dialog backend selection. Applications should call
`LoadFileDialog`, `SaveFileDialog`, or `SelectFileDialogFolder` instead of invoking
desktop-specific picker commands directly.
The default backend order is XDG Desktop Portal, GTK, `zenity`, then `kdialog`,
then `yad`. For local diagnostics and packaging checks,
`KRYON_FILE_DIALOG_BACKEND` can be set to `auto`, `portal`, `gtk`, `zenity`,
`kdialog`, `yad`, or `none`.
The default backend order is `zenity`, then `kdialog`, then `yad`. For local
diagnostics and packaging checks, `KRYON_FILE_DIALOG_BACKEND` can be set to `auto`,
`zenity`, `kdialog`, `yad`, or `none`.
Do not add permanent app dependencies on an XFCE-specific picker. If a downstream app
needs different desktop behavior, add the backend support in Kryon first, then update
the downstream submodule pointer.
## Linux Desktop Metadata
Kryon owns the common Linux desktop package layout. Applications should expose
portable metadata in `project.kryon` or the matching Make variables (`APP_ID`,
`APP_TITLE`, `APP_SUMMARY`, `APP_CATEGORIES`, `APP_MIME_TYPES`,
`APP_URL_SCHEMES`, `APP_ICON`, `APP_DESKTOP_ID`, `APP_ICON_NAME`,
`APP_WM_CLASS`) and build it with `kryon package linux-desktop`. The target
stages the binary, `.desktop` entry, AppStream metainfo, hicolor icon, and
optional MIME package under one AppDir-style tree.
Application code should call `InitDesktopApp` once at startup when it needs
desktop identity, XDG config/data/cache directories, notification icon identity,
single-instance locking, or open-file/open-URL dispatch.
## Downstream Submodule Workflow
Applications should vendor Kryon as a git submodule. Do not edit
@@ -203,7 +158,5 @@ This keeps Kryon reusable and prevents project-local vendor edits from diverging
## Documentation Rules
Keep `docs/API.md` as the public API reference. Keep this guide as the operational
guidance for agents and maintainers. Keep `docs/BOUNDARIES.md` current with the
repo guardrails, and keep `docs/ARCHITECTURE.md` current when subsystems move.
Documentation in Kryon should describe current APIs, current behavior, and the
expected downstream workflow.
guidance for agents and maintainers. Documentation in Kryon should describe current
APIs, current behavior, and the expected downstream workflow.
+252 -1059
View File
File diff suppressed because it is too large. Load diff
+8 -19
View File
@@ -1,13 +1,9 @@
# Kryon App Build Plan
Kryon owns the repeatable build and packaging flow for every Kryon app. App
repositories provide app metadata, native sources, `.kry` sources, and assets.
Kryon provides the compiler, runtime, dependency builds, packaging helpers,
Krait preview hooks, and diagnostics through the `kryon` command.
Kryon also owns app-neutral framework primitives that repeatedly appear in
apps: measured form rows, safe-area content rectangles, route stacks, shell
layout, platform capability names, and persisted-setting normalization.
Goal: Kryon owns the repeatable build and packaging flow for every Kryon app.
App repositories should provide app metadata, native sources, `.kry` sources, and
assets. Kryon should provide the compiler, runtime, dependency builds, packaging
helpers, IDE preview hooks, and diagnostics.
## App Contract
@@ -27,13 +23,12 @@ should come from Kryon.
## Unified Commands
Kryon exposes one command surface for all apps:
Kryon should expose one command surface for all apps:
- `kryon build native`
- `kryon build web`
- `kryon build android-debug`
- `kryon build android-release`
- `kryon package linux-desktop`
- `kryon package linux`
- `kryon package appimage`
- `kryon package deb`
@@ -45,7 +40,7 @@ Kryon exposes one command surface for all apps:
- `kryon preview`
- `kryon test`
Makefiles in app repos are thin wrappers that call these commands.
Makefiles in app repos should become thin wrappers that call these commands.
## Build Ownership
@@ -72,25 +67,19 @@ Apps own:
- app metadata values in `project.kryon`
- optional platform-specific shims that cannot be generalized cleanly
Reusable behavior should move into Kryon only when it is app-neutral. Examples
that belong in Kryon are route-stack mechanics, form layout cursors,
safe-area-aware view measurement, capability checks, and setting clamps.
Product flows such as breathing-session behavior or password
generation stay in their app repositories.
## Migration Phases
1. Rename old build variables and paths from Flint to Kryon in every app.
`vendor/kryon` is the only runtime submodule path.
2. Keep app Makefiles working, but make them use `KRYON_DIR` and Kryon-owned
`mk/*.mk` includes exclusively.
3. Move repeated app Makefile logic into Kryon `mk/app.mk`,
3. Move repeated Makefile logic from Inbe into Kryon `mk/app.mk`,
`mk/android.mk`, `mk/web.mk`, and `mk/package-linux.mk`.
4. Add a Kryon CLI wrapper that reads `project.kryon` and invokes the shared
make fragments with normalized variables.
5. Convert app Makefiles to compatibility shims, then remove duplicated app-side
package/build rules.
6. Make Krait use the same build graph for preview/run so errors from manual
6. Make the IDE use the same build graph for preview/run so errors from manual
build, auto preview, and package targets use one diagnostic format.
7. Add template checks so new Kryon apps start with the unified layout.
-307
View File
@@ -1,307 +0,0 @@
# Kryon Architecture
Kryon is organized as a reusable runtime with a small set of public headers,
backend implementations, format/tooling paths, and conformance tests. The
runtime should expose primitives; downstream applications compose those
primitives into product behavior.
## Public API
Public headers live in `include/`. They define the app-facing Kryon surface:
window/runtime compatibility, UI widgets, platform services, formats, update,
sync, filesystem, desktop integration, and optional terminal primitives.
Public APIs should be named after the real domain concept. Do not add temporary
prefixes, compatibility aliases, or product-flavored names for new behavior.
The optional sync-node pool is local-first: paired LAN nodes rank ahead of
paired remote nodes, and a configured public node is the final fallback. Each
node has isolated bearer-token and clock-skew storage, so failing over cannot
send one node's credentials to another. Connectivity and authentication errors
advance to the next node; account, signing, and payload errors stop immediately.
Discovery may add candidates, but only explicit pairing grants trusted status.
## Runtime Implementation
Runtime code lives in `src/`. It owns widget behavior, rendering helpers,
platform adapters, serialization, sync/update primitives, and backend-specific
translation. Internal helpers should stay private to `src/` unless an unrelated
downstream application demonstrably needs the behavior.
### Widget lifecycle consolidation
Captured C retained paint includes blend state through the private
`ui_blend_internal.h` snapshot. OpenGL 3.3/GLES2 backend hooks preserve both
effective GPU factors/equations and rlgl's cached mode/custom configuration,
including changes awaiting activation. The hooks are injected into the build
copy by `prepare-raylib-source.sh`, not into the raylib submodule or public API.
Each captured node restores its declaration state for painting and restores the
caller's state afterward. The snapshot itself does not own render resources.
The private `ui_paint_layers.c` context now owns temporary C render textures,
collects mixed immediate/retained layers, and composites them in opening order.
Nested layers remain above subsequent parent paint; hidden parents suppress
descendants. Capture and composition restore drawing state, and texture resource
operations preserve the active framebuffer. Native `UIWindow` hosts lazily own
their context and handle its frame, composition and destruction. The private
active-window accessor exposes that owner to future composed widgets without
adding app-level lifecycle calls. Main UI frames own a separate lazy context:
`SetUIFrame` starts it, `EndUIFrame` composites it, and `CloseWindow` releases
its resources before graphics shutdown. The private frame accessor routes to
the active UIWindow when appropriate. Presenter readback preserves the calling
framebuffer. Layer scopes suspend the retained Row/Column path, keeping popup
children in the screen tree without consuming the owner's layout slots. Scope
exit checks balanced child layouts and restores the owner's path. Disabled
scopes likewise inherit the owner's state behind a protected local depth floor,
then restore the parent's scope on exit. Input clips and scroll depth are
isolated similarly, while modal capture stays active. The private C popup input
registry supplies nested branch capture to the shared hit-test path. Each paint
host owns its registry and advances, binds, retires and destroys it automatically.
Auxiliary frames switch to their own registry and restore the parent's binding
on completion; hiding a layer closes its input branch. Retained nodes snapshot
popup ownership for deferred hit testing and button hover/press state; snapshots
are kept with the committed tree while a replacement is declared. Closed,
missing, previous-frame or destroyed owners cannot receive those hits.
Deferred pointer-focus registration uses the same ownership snapshots without
reopening scopes, preserving modal, clip, disabled and inspection capture.
Retained hit testing and button hover/press state now use that same full capture
predicate, so modal blocking also prevents deferred click events.
The public `BeginCombo` / `EndCombo` / `CloseCombo` and `BeginPopup` /
`EndPopup` / `ClosePopup` scopes bind these paint, layout and input contexts for
arbitrary native children. `PopupTooltip` reuses that paint/layout scope while
intentionally skipping input ownership. `PopupModal` uses the same scope with a
full-view input/backdrop policy, and `PopupContext` uses it with right-release
activation over a retained trigger. Presentation variants remain flags on the
one popup implementation rather than parallel widget trees.
Modal outside releases remain non-dismissing. The input registry saves focus
when a top popup first opens, focuses its first eligible child, and restores the
parent or background after nested close, root close, or missing-owner retirement.
Long-lived drag values, sliders, splitters and table resizers store the same
persistent owner identity, allowing out-of-bounds continuation only while that
branch remains topmost and cancelling on dismissal or ownership changes.
C and Go now have a pointer-independent top-popup keyboard predicate. Closed
combos use it before keyboard opening, preventing a focused parent/background
combo from opening behind a child popup. Focus registrations now retain their
popup owner: C filters and deduplicates Tab destinations at focus finalization,
before releasing the host input binding; Go filters its current/previous-frame
focus order during traversal. Native tests cover forward/reverse wraparound,
parent/background exclusion and traversal after explicit dismissal. Go also
exercises actual editor Tab events. Native lifecycle tests cover automatic
first-child focus acquisition and parent/background restoration. Complete
keyboard routing remains unfinished. Generic accelerator dispatch is isolated
to the top live popup branch in C and Go, including immediate restoration when
an explicitly closed popup is next declared.
TextField/TextArea editing now also respects top-popup keyboard ownership in
both runtimes. C's immediate keyboard-enabled check uses the active scope;
retained editor routing uses its declaration snapshot after scopes close.
Tests cover blocked parent and eligible child typing, including immediate and
retained C paths. Immediate C TextArea skips painting without a graphics window.
Ordinary Go Button now registers focus, focuses on pointer activation and
handles Enter/Space and Tab. C's activation check also consults registered popup
ownership, including deferred button events. Unclaimed Go Tab events route at
frame end so a disabled, absent or blocked focus owner cannot swallow traversal.
Generated C/Go button tests cover Enter/Space, disabled rejection and Tab skipping
a disabled control; popup tests cover parent/child keyboard activation.
Missing C popup input owners are now retired before frame-end focus filtering,
not only during paint cleanup. Matching C/Go tests omit a child and then its
parent and verify that Tab reaches the surviving parent/background that frame.
Popup keyboard capture is remembered for the C host frame. Unhandled character
input and queued text-edit commands expire at frame end after such capture,
including same-frame dismissal, instead of leaking into an underlying editor
later. Tests cover injected/platform-queued text, queued Backspace/Enter and
fresh input after dismissal. Non-popup queue behavior is unchanged.
C retained IME commits now respect read-only editors, and popup-captured
composition events expire with other blocked text input. Preedit is cancelled
on focus loss, read-only transition or popup keyboard capture. Regression tests
cover cancellation and no commit replay after dismissal. Native Go now owns a
composition queue and per-editor preedit records. TextField/TextArea display
preedit separately from committed buffers and insert UTF-8 commits; focus loss,
removal, disabling and popup capture discard preedit. A native generated
composition fixture verifies non-mutating preedit, commit and cancellation in
C and Go. Device-level Go IME routing remains unfinished.
Native Go text props now carry ReadOnly, with mutation guards separate from
focus/selection/copy handling and read-only caret metadata. C retained editing
also guards ordinary typing, cut/paste and deletion, not just composition
commits. The generated composition fixture verifies read-only TextField and
TextArea buffers and copying in both native runtimes; Go tests cover preedit
cancellation, byte-for-byte buffer preservation and re-enabling without replay.
Native Go runtime creation now resolves Kryon's Noto Sans UI face from packaged,
development-tree, or standard system locations before falling back to the
minimal bitmap renderer. This matches the C host's default-font policy while
preserving explicit `RegisterUIFontData` / `UseUIFont` overrides.
Private paint scopes share a drawing-order guard across host contexts while
keeping texture ownership host-local. Token generations survive host destruction
and allocation reuse. Invalid closes are rejected before restoring drawing state.
C dropdown identity records now have stable dynamically allocated storage,
rather than a fixed 24-control array whose overflow reused the first control.
Frame-end overlay processing retires records for owners no longer declared.
C and Go tests declare 41 controls, open/select/reopen the first, and remove it
while checking independent selections and capture release. C dropdown storage
is still process-global; per-window ownership remains to be consolidated.
Options now use dynamically sized owned records and strings, removing the
128-option, 255-byte label and 31-byte font-name truncation limits. Unchanged
strings reuse their allocations; shrinking lists and retired controls release
their owned storage. Overlay painting visits visible rows only, and content
height saturates at the runtime's integer coordinate limit.
The private C `ui_scrollbar` helper handles interaction independently of window
painting. Dropdown overlays use base input capture so their own popup capture
does not block the thumb, while ordinary scrollbars retain full popup capture.
Dismissal and owner retirement cancel a dropdown's active scrollbar before its
offset storage is released. Scrollbar drags are distinct from popup content
drags and cannot select an option on release. The shared C scrollbar drag slot
is still process-global; this does not complete per-window input ownership.
Dropdowns process and paint the scrollbar after the panel background but before
emitting rows, so both use the updated offset in the drag frame. Row painting
is clipped to the content area, excluding popup padding and the scrollbar.
The C popup bounds helper and Go dropdown layout constrain horizontal placement
and width to the UI view. Hit testing, capture and painting share the popup
rectangle rather than assuming that its horizontal bounds match the owner.
The shared KIR parser lowers `.kry` `Disabled { when = condition ... }` blocks
to existing runtime calls and lexical cleanup. The same cleanup pass used for
`defer` closes the scope on normal exit, return, break and continue before any
backend emits code. The generated buttons parity fixture exercises those exits
and nested disabled inheritance in C, Go and JS; C++ syntax coverage checks the
same shared lowering. Native `Scroll` blocks use the same lexical cleanup and
existing `BeginScroll`/`EndScroll` operations. An optional block name binds the
returned content rectangle without leaking it beyond the block. Native generated
scroll parity covers nested clips/input and restoration after return, break and
continue. Native `Combo` and `Popup` blocks similarly lower caller-defined popup
contents to conditional begin calls plus cleanup-managed end calls, removing manual scope
bookkeeping from `.kry` sources while retaining the small runtime contract.
Other begin/end APIs have not all gained block syntax.
The C widget implementation is still being consolidated. Some constructors
submit retained paint, while others register generic nodes and draw immediately.
Do not treat the presence of a tree node as proof that a widget participates in
deferred painting.
`Button`, `SliderFloat`, `SliderInt`, `VSliderFloat`, `VSliderInt`, and `SliderAngle` resolve
their declaration bounds before handling input and submit typed paint data when
building a tree. The slider painters do not process input. Labels and formats
are copied into node-owned storage; value arrays remain caller-owned. Without
a tree, the same input and paint helpers run immediately. This preserves the
public API while removing the separate prefixed slider draw entry points.
Angle sliders retain the caller's radians pointer and convert to degrees only
within input or paint execution; no pointer to a temporary conversion survives
declaration.
`DragFloat` and `DragInt` follow the same split, including owned label/format
storage and resolved bounds. `DragFloatRange2` and `DragIntRange2` compose two
ordinary typed drag nodes inside a Row, plus retained Text for the label. Their
children preserve the existing input IDs and borrow the caller's endpoint
pointers; no range-specific renderer or prefixed drag draw entry point remains.
`Text(TextProps)` uses one typed retained text node with owned text, captured
font selection, and resolved bounds. Its painter measures intrinsic lines or
wraps bounded text, clips to positive bounds, and applies alignment, color, and
disabled presentation from the same property object. Headless declaration does
not invoke a graphics backend. There are no separate public colored, disabled,
wrapped, or in-rectangle text widget implementations.
The remaining families must migrate with evidence for layout, input timing,
paint order, disabled/clip scopes, and data lifetime. Captured render textures
remain private implementation machinery behind the public combo scope, not a
low-level public paint API or the completed widget architecture. Native Go keeps
its own implementation and must retain matching behavior through
generated-runtime parity coverage.
Numeric editor state uses collision chains keyed by numeric type, widget ID,
and component index,
with stable record addresses. A bucket is not a single replaceable editor slot:
distinct keys must preserve independent text, cursor, and focus. C and Go tests
cover 129 keys that share the C bucket index. Each component reserves three
separate numeric control IDs for its field, decrement, and increment controls;
vectors larger than 16 components do not alias neighboring numeric widgets.
Tests cover 396 component keys and the emitted IDs for a 17-component input
beside another input. C's process-wide numeric state still needs
per-window lifetime integration as numeric widgets are consolidated.
Numeric ID allocation is not yet a shared identity service for every widget
family or arbitrary application-supplied control IDs.
Numeric input wrappers resolve their bounds before invoking the editor and do
not retain pointers to stack-local props. Their increment/decrement controls
use standard `Button` submissions, so step handling is independent of graphics
availability and participates in retained painting and disabled scopes. C and
Go tests cover normal, fast, and disabled stepping inside Row layout. Numeric
text editing also runs without a graphics window and returns changes during
declaration. Its painter receives an owned display-text snapshot plus caret,
selection, scroll, style, and font information; retained painting does not
process editing input again. Disabled typing is discarded, not replayed on
re-enabling the field. The ordinary retained TextField input-routing path and
numeric editor input path are still separate; consolidation is not complete.
Native Go collects deferred popup paint in `go/kryon/paint_layers.go`, using
ordinary frame operations rather than dropdown-specific drawing records.
Dropdown placement lives in `dropdown_layout.go`; capture and painting share
the resulting constrained, optionally upward-facing rectangle. Popup rows use
the ordinary scroll container, with runtime-owned stable offset storage that
is released on dismissal or owner removal. Keyboard navigation reveals rows
without overriding wheel scrolling on idle frames; only visible rows are emitted.
Nested layers paint above their parents and restore the surrounding layout,
clip and disabled state. Existing dropdowns use this collector and the private
`popup_input.go` registry for scoped click ownership. That registry tracks
parent/child and sibling order, preserves capture before owner declaration in
the following frame, and removes descendants on closure or owner removal.
Native Go scroll scopes, lists, trees, source views and tables share a pointer
reachability check for wheel input, respecting popup ownership, disabled state
and parent clips. Generated C/Go tests verify that a background scroll scope
declared before an open combo cannot steal its wheel input.
Go drag-and-drop sources and targets also use that pointer check for starting
and accepting a drag; an already active source retains its payload when the
pointer leaves its original bounds. Rejected targets do not consume the release
or payload. Generated C/Go tests cover clipped sources/targets and copied data
lifetime across press and release.
The public arbitrary-content combo scope integrates these paint and input
registries in C and Go. Generated C/Go execution and k2cpp syntax coverage use
the same clean calls. Popup focus acquisition/restoration and active scalar,
slider, splitter and table-resize ownership are covered in both native runtimes;
device-level integration remains unfinished.
## Backends
Backend selection is controlled by `KRYON_BACKEND`. The default native backend
uses raylib through Kryon's compatibility surface. Other backends are expected
to implement Kryon behavior through the same public/runtime contracts, with
their support documented in `docs/BACKEND_CAPABILITIES.json`,
`docs/BACKENDS.md`, and `docs/FEATURE_MATRIX.md`.
## Formats And Tools
The `.kry`, KIR, generated C, generated Go, and KRB paths are Kryon-owned
tooling surfaces. Tool changes should update the matching specs, conformance
matrix data, examples or fixtures, and generated documentation when applicable.
## Examples And Fixtures
Examples under `examples/` should remain generic and readable. They demonstrate
Kryon capabilities, not downstream product screens. Exact rendering and parity
fixtures should be generic enough that they can run in any app-independent
Kryon build.
## Tests And Matrices
Kryon uses several test layers:
- boundary and naming checks for repository hygiene
- public API snapshot checks for app-facing identifier drift
- public header compile checks for app-facing include hygiene
- examples manifest checks for example inventory and exactness fixtures
- backend capability checks for backend inventory drift
- generated-file checks for docs, compatibility headers, icons, and matrices
- parser, runtime, sync, update, platform, and widget tests
- conformance and visual matrix checks across renderers and runtime paths
Use `make preflight` before committing focused Kryon changes. Use `make test`
for the broader local regression suite. Use `make test-asan` or
`make test-ubsan` for sanitizer-backed regression runs, and
`make release-preflight` before publishing release artifacts.
## Downstream Integration
Downstream applications vendor Kryon as a submodule. Permanent Kryon changes
must be made and committed in this repository first, then brought into apps by
updating the submodule pointer. Never edit a downstream `vendor/kryon` tree as
the source of a Kryon change.
-275
View File
@@ -1,275 +0,0 @@
# Kryon Backends
How the graphics/input backend is selected, what a backend must implement, and
how to add a new one. For the machine-readable backend inventory see
`docs/BACKEND_CAPABILITIES.json`; for the operational guide see
`docs/AGENTS.md`; for the public API see `docs/API.md`; for what runs where
see `docs/FEATURE_MATRIX.md`.
## The surface and how selection works
Kryon's public graphics/input API is `include/kryon_compat.generated.h`:
kryon owns the surface, and it currently tracks raylib's header verbatim so
raylib-style code compiles unchanged. A backend is a translation unit (or set
of them) that defines the surface's functions. No `raylib.h` include and no
raylib build path may appear in `include/`, `src/`, `examples/`, or `tests/`
(`make kryon-boundary-check`).
Backend selection is link-time, via the `KRYON_BACKEND` make variable:
- `raylib` (default) - generated forwarders (`build/generated/
kryon_raylib_wrappers.c`) call into raylib, which is compiled with every
symbol renamed `KryonRaylibBackend_*` (`build/generated/
raylib_backend_rename.h`, applied in `mk/raylib.mk`). Applications can never
bind raylib symbols directly.
- `null` - generated zero-return stubs (`build/generated/kryon_null_backend.c`)
so the library links and runs headless with no GPU or window. Injected input
(below) still works, which is what drives headless widget tests.
- `canvas` - HTML5 Canvas2D backend, no raylib (`src/backend/canvas_*.c`,
split by concern: window, input, draw, texture, text, os, audio).
Web-only (native sweeps of its sources compile to empty translation
units; a native canvas link fails at symbol resolution). Implements the
required surface through `EM_JS`: draws as canvas paths (rounded rects via
`roundRect` with an `arcTo` fallback, rings as filled even-odd annulus
segments, gradients carry both full colors), textures as offscreen canvases
(`putImageData`/`drawImage` are synchronous — no async ImageBitmap on the
draw path), full RGBA tinting through cached multiply + destination-in
composites per (texture, tint), text as glyph atlases rasterized from
`FontFace` data, and input via the `KryonBackendRaw_*` hooks fed by JS
event listeners. Audio uses WebAudio for decoded sound/music buffers,
scheduled PCM streams, stream callbacks, and stream/mixed processors on
Canvas-managed stream buffers; wave export writes synchronously to MEMFS.
Encoded loaders rely on browser `decodeAudioData`, so Canvas web links use
`-sASYNCIFY`, and playback still follows normal browser user-gesture
unlock rules. The app's `while (!WindowShouldClose())` loop works
because the build uses `-sASYNCIFY` and the frame end yields with
`emscripten_sleep`. The clipboard keeps a mirror of the last written text
(copy/paste round-trips in-app; the browser write is attempted
fire-and-forget — cross-app paste stays out of reach of the sync API).
`make canvas-test` builds a full app with this backend under emcc and
verifies the draw-call sequence in node (skips when emcc is absent); `make
canvas2d-parity-check` guards the no-WebGL 2D/browser subset, and `make
web-canvas-matrix-check` captures generated-C visual fixtures through the
same backend. `docs/CANVAS2D_PARITY.md` is the Canvas2D parity ledger.
The rendering has additionally been pixel-verified in a real browser page.
- `dom` - HTML/CSS DOM backend, no raylib (`src/backend/dom_*.c`). Web-only
and intended for app-style Kryon UI and Kryon-authored page surfaces rather
than games or pixel-perfect drawing. Kryon/app logic still runs as WASM; the
backend presents UI-oriented draw calls as absolutely positioned DOM nodes
with CSS colors, gradients, borders, rounded corners, clipping, transforms,
cursor state, and browser text. Page helpers attach semantic metadata so
headings can become `h1`-`h6`, links can become `a[href]`, pictures can
carry `alt`, page/section regions can become `main`/`section`, and document
title/description/canonical/theme-color plus browser routes can be controlled
from Kryon. Browser `popstate`/`hashchange` changes increment the route
version visible through `GetRouteVersion()`. The existing Kryon UI runtime remains responsible for
hit-testing, focus, text editing, dropdowns, scrolling, selection, and widget
state. Textures uploaded from RGBA pixels are presented as DOM image nodes;
render targets and unsupported raylib areas use conservative null-grade
behavior. `make dom-test` builds a small Emscripten app and verifies DOM node
output, semantic page metadata, texture image nodes, CSS gradients, browser
route helpers, and an injected widget click in Node against a minimal DOM
shim.
- `libdraw` - plan9port libdraw/devdraw backend, no raylib
(`src/backend/libdraw_*.c`). It keeps the same public surface as the other
backends: C apps still include `kryon.h` and call `InitWindow`,
`BeginDrawing`, `DrawRectangle`, `Button`, `TextField`, and the rest of
Kryon's normal API. Internally, the backend renders through `kry_sw` into an
RGBA buffer and presents it with libdraw, so the widget catalog shares the
same software drawing behavior as the KRB hosts. TTF/TrueType-outline font
data is rasterized into Kryon `Texture2D` atlases with `stb_truetype`
(header-only; no `libraylib` link). Plan9port owns the window, event,
keyboard, mouse, resize, and devdraw connection. Non-UI raylib areas such as
3D, shaders, gestures, and audio fall back to the generated weak null stubs
until a real libdraw implementation is added for them. `make libdraw-test`
builds and runs
a widget smoke app under plan9port devdraw (Xvfb when available),
pixel-verifies rounded widgets, thick lines, source-rectangle texture blits,
alpha blending, rotated texture blits, render textures, TTF glyph atlas
coverage, and screenshot export, and compiles/links a clean-surface C app
through plan9port `9c`/`9l`.
- `termi` - terminal-cell backend, no raylib (`src/backend/termi_*.c`). It
keeps the normal Kryon surface and widget API: apps still call
`InitWindow`, `BeginDrawing`, `DrawRectangle`, `Button`, `TextField`, and
`DrawUIText`-using widgets. The backend maps Kryon's pixel layout units onto
terminal cells (`TERMI_CELL_WIDTH` x `TERMI_CELL_HEIGHT`) and renders native
terminal primitives: rectangles become colored cell regions, rectangle
outlines become terminal line cells, and UI text goes through the native text
hook to real terminal text. PNG and other stb-supported images are decoded
into Kryon textures; texture draws render as a colored-cell fallback, and
sixel image data is emitted only when the terminal advertises sixel support
or `TERMI_SIXEL=1` is set (`TERMI_SIXEL=0` disables sixel explicitly). It uses the
generated weak null stubs for unsupported raylib compatibility areas such as
shaders and 3D. Input is read from the terminal in raw mode, including arrows,
basic mouse SGR events, and Ctrl-C as an application close request. `make
termi-test` builds a widget smoke app with `KRYON_BACKEND=termi`, runs it in
a pseudo-terminal, verifies alternate screen entry/exit, rendered widget text,
sixel texture output, and confirms Ctrl-C exits.
Exactly one backend TU is compiled into `libkryon.a` (root `Makefile`), and
`KRYON_BACKEND_LIBS`/`KRYON_BACKEND_LDLIBS` carry the backend's own link
inputs (only raylib needs `libraylib.a` and its SDL/GL system libs). The
downstream fragments (`mk/common.mk`, `mk/native.mk`, `mk/web.mk`) honor the
same variable, so `make KRYON_BACKEND=null` produces binaries with no raylib
in the link graph, `make KRYON_BACKEND=dom web` builds the DOM web backend,
`make KRYON_BACKEND=termi` links a terminal backend, and
`make KRYON_BACKEND=libdraw PLAN9PORT_DIR=/path/to/plan9port` links against
plan9port instead. The
cross-build dist targets (`dist-linux`, `dist-windows`, Android, and `make
dist-static`, whose pkg-config/cmake manifests hardcode raylib) are raylib-only
today.
## The shared input front-end
Input is not the backend's job beyond polling. `src/backend/kry_input.c`
defines the public input queries (`IsKeyPressed`, `IsKeyDown`,
`IsMouseButton*`, `GetMouse*`, `GetCharPressed`, `GetKeyPressed`, ...) once for
every backend, merging, in order:
1. synthetic input injection (`kry_inject.h` - headless tests and the
synthetic file system),
2. the keyboard enable/disable switch and keyboard platform callbacks
(`SetKeyboardInputEnabled`, `SetKeyPlatformCallbacks` - non-raylib key
sources such as an IME),
3. the modal input override (`BeginKryonInputOverride`/`EndKryonInputOverride`
- offscreen windows stealing the pointer),
4. the backend's raw poll, via the `KryonBackendRaw_*` hooks declared in
`include/kry_input.h`.
A backend implements only those raw hooks; it gets injection, overrides, and
platform-key routing for free. The generated raylib wrappers forward the
hooks; the generated null backend answers them with zeros.
## Shared surface functions
Pure-math surface symbols - `Fade`, `ColorLerp`, `CheckCollisionPointRec`,
`CheckCollisionRecs`, `GetWorldToScreen2D`, `GetScreenToWorld2D`,
`GetCodepointNext` - are backend-independent arithmetic (colors, rectangles,
the Camera2D transform, UTF-8 decoding) and are defined once for every
backend in `src/backend/kry_surface_math.c`. The generator skips them in both
generated files; a new backend implements none of them. Without this the null
backend's zero-return stubs would break pointer hit-testing, since
`ui_mouse_world()` transforms the mouse position through
`GetScreenToWorld2D` before any click test.
## What a backend must implement
The full surface is ~700 symbols, but kryon's own code, the tooling, and
generated `.kry` apps call a much smaller subset. `sh
tools/backend-required-symbols.sh` prints the exact list from current call
sites (~100 symbols); keep it in sync when adding surface usage. Grouped:
- **Window/frame**: `InitWindow`, `CloseWindow`, `WindowShouldClose`,
`IsWindowReady`, `SetConfigFlags`, `SetTargetFPS`, `SetWindowSize`,
`BeginDrawing`, `EndDrawing`, `GetScreenWidth/Height`, `GetFrameTime`,
`GetTime`, `GetWindowScaleDPI`, `SetTraceLogLevel`, `SetMouseCursor`.
- **Input**: the `KryonBackendRaw_*` hooks above only.
- **Drawing (immediate mode)**: `ClearBackground`, `DrawRectangle*`,
`DrawCircle*`, `DrawLine*`, `DrawRing`, `DrawTriangle`, `DrawTexture`,
`DrawTexturePro`, `DrawText` (default font), `BeginScissorMode`/
`EndScissorMode`, `BeginMode2D`/`EndMode2D` (scene camera). Callers assume
the backend batches internally (raylib/rlgl does); a backend without
batching is correct but slow.
- **Text**: `LoadFontFromMemory` (TTF with an explicit codepoint set),
`UnloadFont`, `GetFontDefault`, `GetGlyphInfo`, `GetGlyphAtlasRec`,
`GetGlyphIndex`, `SetTextureFilter` on the atlas. Layout, fallback, and
glyph blits are kryon's (`ui_text.c`, `ui_text_backend.h`); the backend
rasterizes glyphs into an atlas texture and reports metrics. `ui_text.c`
detects a backend that silently returns the default font as load failure.
- **Textures/images**: `LoadTexture`, `LoadTextureFromImage`,
`LoadImageFromMemory`, `UnloadTexture`, `UnloadImage`,
`LoadRenderTexture`, `BeginTextureMode`/`EndTextureMode`,
`LoadImageFromTexture`, `ImageFlipVertical`, `ExportImage` (screenshot and
`kryon-preview` PNG capture path), `GetImageColor`-class pixel access where
used.
- **Math/collision helpers**: `Fade`, `ColorLerp`, `CheckCollisionPointRec`,
`CheckCollisionRecs`, `GetWorldToScreen2D`, `GetScreenToWorld2D`,
`GetCodepointNext` already come from `src/backend/kry_surface_math.c`
(above). Only `TextFormat`/`TraceLog` remain backend-supplied (the null
backend implements them; raylib forwards).
- **OS services** (may be no-ops on a given platform): `GetClipboardText`/
`SetClipboardText`, `FileExists`, `DirectoryExists`, `GetDirectoryPath`,
`MakeDirectory`, `LoadFileData/Text`, `UnloadFileData/Text`, `OpenURL`.
- **Audio** (apps opt in; null-grade stubs are acceptable for UI-only
backends): `LoadSound`/`UnloadSound`/`PlaySound`, `SetSoundVolume/Pitch/Pan`,
music stream functions, and raw `AudioStream` update/playback functions.
Everything else on the surface (gestures, VR, ...) can be a zero-return
stub exactly like the generated null backend.
### 3D tier (camera, meshes, shaders, rlgl, math3d)
The surface carries a 3D tier for custom 3D pipelines such as voxel
renderers:
- **Camera and drawing**: `Camera3D` with `UpdateCamera(CAMERA_CUSTOM)`,
`BeginMode3D`/`EndMode3D`, `DrawCube*`, and the mesh path
`UploadMesh`/`DrawMesh`/`DrawMeshInstanced`/`UnloadMesh` with the raylib
`Mesh`/`Material` layouts, `LoadMaterialDefault`,
`SetMaterialTexture`, `UnloadMaterial`.
- **Custom shaders**: `LoadShader`/`LoadShaderFromMemory`,
`GetShaderLocation`, `SetShaderValue*`, `UnloadShader`, and the
`SHADER_LOC_*` constants.
- **Curated rlgl entry points** (`kryon_compat.generated.h` ends with
them): vertex array and vertex buffer upload/bind/draw
(`rlLoadVertexArray`, `rlLoadVertexBuffer(Element)`,
`rlUpdateVertexBuffer`, `rlSetVertexAttribute`,
`rlDrawVertexArray*`, the enable/disable family), shader uniforms
(`rlSetUniform`, `rlGetLocationUniform`, `rlSetUniformMatrix`),
matrix state (`rlGet/SetMatrixModelview/Projection/Transform`), and
cull/depth toggles, plus the `RL_*` GL constants they take. `RL_CALLOC`
and `RL_FREE` are not on the surface; use `MemAlloc`/`MemFree`.
- **Math3d**: `include/kry_math3d.generated.h` (included by `kryon.h`
right after the compat surface) provides raymath-style
`Vector2/3/4`, `Matrix`, and `Quaternion` arithmetic as static-inline
functions. Pure math with no state, so every backend gets it for free;
nothing to implement or stub.
The raylib backend implements the whole tier for real (rlgl is compiled
in, `RAYLIB_MODULE_MODELS=TRUE`, symbols renamed like the rest). Every
other backend provides the generated zero-return stubs, so 3D content
simply does not appear there; UI-only apps must not depend on it. Custom
shaders must target GLSL 100 / OpenGL ES 2 - the desktop raylib backend
runs GLES2, so `#version 330` desktop shaders do not compile.
## Struct-layout obligations
The surface passes `Font`, `Texture2D`, `Image`, `GlyphInfo`,
`RenderTexture2D`, `Camera2D`, `Rectangle`, `Vector2`, `Color` by value with
raylib's layouts, and kryon state stores them directly (font caches, frame
camera, icon atlases). A backend must fill those structs with its own objects
behind them. The standard pattern is a side table keyed by the integer
`Texture2D.id`/`Font.texture.id` mapping to native handles; ids must be
non-zero for loaded resources (0 means "invalid/default"). `src/ui/
ui_text_backend.c` is the only place that reads `Font` fields directly
(baseSize, glyphPadding, texture, readiness); respect those semantics.
## Adding a backend
1. Create `src/backend/<name>_backend.c` or `src/backend/<name>_*.c`
implementing the required subset
above under the surface's public names, plus the `KryonBackendRaw_*` hooks.
Everything not implemented should match the null backend's zero-return
behavior so the library still links.
2. Register it in the root `Makefile`'s `KRYON_BACKEND` block and in
`mk/common.mk` (backend TU + link inputs), mirroring the existing entries.
3. Prove it end-to-end: `make KRYON_BACKEND=<name> check`-style build of the
library, one example app, and a headless test slice. The `.krb` cartridge
interpreter (`src/krb/krb.c`) draws through the `KryBackend` vtable
(`include/kry_backend.h`) and is a quick way to smoke-test drawing without
the full UI stack.
4. Do not patch vendor code or add `#ifdef <backend>` branches to `src/`;
backend differences live behind the surface, `kry_input.h`, and
`kry_backend.h`.
## Checks
- `make kryon-boundary-check` - no `raylib.h` includes or raylib paths in
app-facing code.
- `make kryon-compat-check` - generated surface/rename/wrappers are in sync
with `vendor/raylib/src/raylib.h` and every raylib symbol has a rename plus
a public wrapper or `KryonBackendRaw_*` hook.
- `make libdraw-test` - plan9port/devdraw smoke for the libdraw surface backend
plus a `9c`/`9l` clean-public-surface compile/link check.
- `sh tools/backend-required-symbols.sh` - the live required-subset list a
backend must cover.
-60
View File
@@ -1,60 +0,0 @@
{
"schema": 1,
"source": "docs/BACKEND_CAPABILITIES.json",
"backends": [
{
"id": "raylib",
"label": "Desktop raylib",
"tier": "default",
"platforms": ["Linux", "FreeBSD", "macOS", "Windows"],
"surface": "full raylib compatibility through Kryon wrapper symbols, including the 3D tier (camera, meshes, custom shaders, curated rlgl entry points) and the static-inline math3d surface",
"status": "default",
"checks": ["make kryon-compat-check", "make raylib-matrix-check", "build/linux-x86_64/tests/raylib_compat_test"]
},
{
"id": "null",
"label": "Null headless",
"tier": "headless",
"platforms": ["hosted C"],
"surface": "generated zero-return stubs plus Kryon input injection",
"status": "test backend",
"checks": ["make KRYON_BACKEND=null all"]
},
{
"id": "canvas",
"label": "Web Canvas2D",
"tier": "web",
"platforms": ["Emscripten web"],
"surface": "Canvas2D and WebAudio implementation with null stubs for unsupported surface areas",
"status": "source-capture gated",
"checks": ["make canvas-test", "make canvas2d-parity-check", "make web-canvas-matrix-check"]
},
{
"id": "dom",
"label": "Web DOM",
"tier": "dom-page",
"platforms": ["Emscripten web"],
"surface": "HTML/CSS DOM UI presentation with semantic page metadata, native heading/link/image annotations, CSS gradients, RGBA image-node textures, browser route helpers with route-change versioning, and null stubs for unsupported surface areas",
"status": "smoke gated",
"checks": ["make dom-test"]
},
{
"id": "libdraw",
"label": "Plan 9 libdraw",
"tier": "desktop",
"platforms": ["plan9port/devdraw"],
"surface": "kry_sw software renderer presented through libdraw",
"status": "source-capture gated",
"checks": ["make libdraw-test", "make libdraw-matrix-check"]
},
{
"id": "termi",
"label": "Terminal cells",
"tier": "terminal",
"platforms": ["ANSI terminal"],
"surface": "terminal-cell drawing, raw terminal input, and null stubs for unsupported surface areas",
"status": "smoke gated",
"checks": ["make termi-test"]
}
]
}
-56
View File
@@ -1,56 +0,0 @@
# Kryon Boundaries
Kryon is a reusable UI runtime. It may contain generic runtime primitives,
generic examples, generic test fixtures, and documentation for integrating the
runtime into downstream applications. It must not contain product behavior,
branding, copy, assets, or fixtures from a downstream application.
## Belongs In Kryon
- reusable widgets, layout, text input, focus, theme, DPI, modal, scroll, and
input-capture behavior
- reusable renderer, backend, format, preview, packaging, update, sync, and
desktop primitives
- generic examples that demonstrate one Kryon feature at a time
- generic tests and fixtures that assert Kryon behavior across backends
- documentation for Kryon APIs, formats, backends, and downstream update flow
## Belongs In Applications
- product screens, routes, onboarding, workflows, and state machines
- product names, screenshots, icons, store metadata, app IDs, and domains
- app-specific copy, locale keys, settings semantics, and persistence policy
- business rules for sessions, habits, documents, projects, accounts, or other
product concepts
- downstream integration code that only one application needs
## Forbidden Downstream Terms
`make kryon-boundary-check` rejects known downstream product material. The hard
forbidden list lives in `tools/check-kryon-boundaries.sh`, which is excluded
from its own content scan so the banned terms do not appear elsewhere in this
repository. When another downstream product leaks into Kryon, remove the
material from Kryon and add that product term to the checker in the same
change.
## Runtime Primitive Test
Before adding a public API or example, ask whether another unrelated
application could use it without inheriting product assumptions. If the answer
is no, keep it in the downstream app. If the answer is yes, name it after the
domain concept directly and cover it with Kryon-owned tests.
## Generated And Showcase Material
Generated files should describe their generator and source inputs. Do not hand
edit generated outputs except to repair or replace the generator in the same
change.
Showcase material may reference external users of Kryon only when it is clearly
documentation about adoption, not an input fixture, public API example, or
runtime asset. Product examples used for rendering, parity, screenshots, or
coverage belong in the product repository.
Keep `examples/manifest.json` current when adding, removing, or renaming
examples. The manifest is the stable inventory for example metadata and curated
render-exact fixtures.
-55
View File
@@ -1,55 +0,0 @@
# Canvas2D Raylib Parity
Kryon's `canvas` backend is the no-WebGL web backend. It aims to run
raylib-style 2D/UI applications with the same public surface while leaving
non-2D raylib areas on generated weak null stubs.
The live required surface comes from:
```sh
sh tools/backend-required-symbols.sh
```
The no-WebGL 2D/browser subset is guarded by:
```sh
make canvas2d-parity-check
```
## Status Model
| Status | Meaning |
|---|---|
| `implemented` | Canvas2D has a real backend implementation. |
| `partial` | Implemented, but browser limits or known gaps remain. |
| `stub` | Provided by the generated weak null backend only. |
| `untested` | Implemented but not covered by `make canvas-test` yet. |
## 2D/UI Surface
| Area | Status | Notes |
|---|---|---|
| Window/frame lifecycle | `implemented` | `InitWindow`, frame timing, logical screen size, render size, title, cursor, and basic state flags. |
| HiDPI sizing | `implemented` | Main canvas uses logical coordinates over a `devicePixelRatio` backing store; render size reports backing pixels. |
| Keyboard/mouse/wheel | `implemented` | Includes key repeat, mouse buttons, pointer capture, mouse delta, and fractional wheel vectors. |
| Touch | `implemented` | Browser touch points map to raylib touch APIs and update mouse position from touch point 0. |
| Gamepad | `partial` | Standard browser Gamepad API buttons/axes are mapped; SDL mapping strings and vibration are no-ops. |
| Dropped files | `partial` | Browser drop events queue file paths and asynchronously write file contents into MEMFS. |
| Basic shapes | `implemented` | Pixels, lines, rectangles, rounded rectangles, circles, rings, triangles, fans, strips, and outlines. |
| Gradients | `implemented` | Vertical, horizontal, and four-corner rectangle gradients. |
| 2D camera/scissor | `implemented` | `BeginMode2D` and active scissor clipping use Canvas transforms/clips. |
| Textures | `implemented` | RGBA textures, render textures, tinting, alpha, rotation/origin, source rectangles, and negative-size flips. |
| Images/screenshots | `partial` | RGBA image load/export/screenshot and format validity are implemented; non-PNG decoders stay limited. |
| Fonts/text | `implemented` | FontFace-backed TTF loading, glyph atlas metrics, custom text drawing, codepoint drawing, and measurement. |
| Files/path helpers | `implemented` | MEMFS-backed load/save/path helpers and directory listing. |
| Clipboard | `partial` | Writes mirror locally and attempt browser clipboard writes; synchronous browser clipboard reads are unavailable. |
| Audio | `partial` | WebAudio sound/music/streams exist, with normal browser user-gesture unlock limits. |
## Explicit Non-Goals
| Area | Status | Notes |
|---|---|---|
| 3D cameras/models/meshes | `stub` | Requires WebGL or another renderer to match raylib. |
| Shaders/rlgl/render batches | `stub` | Canvas2D cannot faithfully expose shader or rlgl behavior. |
| VR/stereo rendering | `stub` | Out of scope for the no-WebGL backend. |
| Gesture recognizer | `stub` | Raw touch points are implemented; raylib gesture synthesis is still fallback. |
-410
View File
@@ -1,410 +0,0 @@
# Composed popup implementation requirements
Status: the public native `BeginCombo` / `EndCombo` / `CloseCombo` and generic
`BeginPopup` / `EndPopup` / `ClosePopup` scopes are implemented in C and Go,
with k2c, k2cpp and k2go generated coverage. The
remaining lifecycle and backend gaps below still apply. This is an
implementation checklist, not a completion claim or a restriction of the
native ImGui widget goal.
## Contract
Dear ImGui's [combo API](https://github.com/ocornut/imgui/blob/master/imgui.h)
explicitly separates the option-list convenience helper from a begin/end scope
whose contents and selection are caller-controlled. The upstream header was
checked on 2026-09-05. It also exposes popup alignment and height choices,
arrow/preview suppression, and fitting the width to the preview. Existing
Kryon option arrays do not establish support for that scope or those flags.
The same upstream header exposes arbitrary begin/end popup and tooltip scopes;
Kryon's generic popup scope now covers caller-defined non-modal popup contents,
non-input-capturing hover tooltips through `PopupTooltip`, and arbitrary modal
contents through `PopupModal`. `PopupContext` adds right-release activation over
an explicit trigger while retaining the same arbitrary-child scope and
caller-owned open state.
The clean native scope must accept ordinary native controls and nested layouts,
not a second set of popup-specific widget aliases. C, C++ codegen over C, and
native Go generated callers must share the same behavior. Selection and editing
remain in caller state. A successful begin must have one matching end; a closed
popup must not submit children.
## Verified architectural constraints
- `src/ui/ui.c:DrawUIFrameOverlays` runs dropdown, menu and text-context overlays
after ordinary UI content and resets the drawing clip first.
- `src/ui/ui_tree.c:EndTree` performs layout, input and painting after the app's
widget calls. A content scope must therefore survive beyond its lexical end
for retained painting and hit testing, without retaining borrowed props.
- Native controls also paint immediately. Reordering retained nodes alone is
insufficient: it would omit immediate controls from the popup paint layer.
- `src/ui/ui_window.c:BeginUIWindow` already enters a render texture before
`BeginUIFrame`; its end path calls `EndUIFrame` before ending that texture.
An overlay implementation must not restore the default framebuffer when the
destination is an existing UI-window target.
- `SaveUIFrameState` preserves UI camera/input state, not the active graphics
render target. It is not sufficient for nested paint-target restoration.
- Go now collects deferred `FrameOp` records in runtime-owned nested paint
layers. Existing option-list dropdowns and the public combo scope use that
collector and a private nested popup click-ownership registry. Scrollable
widgets gate wheel input through popup ownership and the active content clip;
drag values, sliders, splitters and table gestures retain their starting
popup owner across frames. C and Go accelerator dispatch is routed to the
active top popup branch; complete routing for every widget shortcut is not
implemented.
- C retained nodes now snapshot input clips and disabled scopes. Those snapshots
must also be respected when retained nodes are painted into a popup layer.
## Required implementation sequence
1. Implement internal per-window paint-layer capture/restoration. Verify an
existing offscreen target and nested layers before exposing a public scope.
The capture must include immediate drawing and subsequent retained painting.
Do not assume the destination is the main framebuffer.
Transparent capture must accumulate alpha with source factor one, separately
from RGB's source-alpha factor. Composite that premultiplied result without
multiplying RGB by alpha a second time. Restore the caller's blend mode and
custom factors, including around deferred retained painting.
2. Associate retained submissions with their layer and frame generation. Keep
child props/state ownership valid through deferred painting; do not keep
pointers to by-value props or temporary generated arrays after their lifetime.
3. Generalize Go's deferred popup records and both runtimes' pointer capture to
nested scopes. Preserve the parent's layout, clip, disabled state, focus and
paint destination on exit. Handle a missing owner and window destruction.
4. Add the clean combo scope and explicit close behavior in C and Go together,
then add k2c/k2cpp/k2go generated fixtures and output-scanner coverage.
5. Exercise the upstream presentation choices instead of assuming the presence
of an option-list helper covers them.
## Implemented prerequisite: nested raylib targets
The raylib-backed `BeginTextureMode` / `EndTextureMode` implementation now tracks
targets entered through Kryon's API and restores the parent target, its full
viewport, and the saved projection/modelview matrices. Tracking targets avoids
depending on `rlGetActiveFramebuffer`, which returns zero in the GLES2 build.
Every begin must be balanced with an end before closing the window.
`tests/texture_scope_test.c` verifies three nested offscreen targets with real
pixel readback, including drawing resumed under a translated camera. It also
opens a real `UIWindow`, nests two targets inside it, and checks the actual X11
presenter's texture readback for preserved background and subsequent drawing.
A test-only linker wrapper observes that readback without substituting a mock
or exposing the window's private target. This integration test requires the
raylib/X11 window path and a linker supporting `--wrap`.
Run it with `make texture-scope-test` on a display, or build the test binary and run it under
`KRYON_SHOT_ARM=1 xvfb-run -a` on headless Linux. Screenshot capture must be armed
to check the completed main framebuffer as well as the offscreen textures.
Retained nodes can now snapshot a borrowed paint destination selected by the
internal `ui_tree_set_paint_target` hook. Each captured node also records the
projection and modelview active at declaration. A private frame-local table
shares consecutive identical snapshots; ordinary nodes only carry a zero index.
`DrawTree` enters the captured target and restores those matrices for the node's
deferred painting, then returns to the caller's target and matrices. The hook
returns the previous destination for nested restoration, resets at `BeginTree`,
and forces repaint so clearing a captured texture does not lose unchanged nodes.
The texture must remain alive through `EndTree`; the hook neither allocates nor
owns it. Immediate drawing is still captured by the caller's texture scope.
The pixel test combines immediate drawing and retained `Rect` submissions,
including a nested destination and translated retained content before and after
that nested scope, followed by opaque ordinary retained content.
It composites the captured target last and checks both frames of an unchanged
tree. This proves that both kinds of paint reach the chosen destination, not
that a popup automatically owns or composites that destination.
This is not a complete paint-layer implementation. It does not restore
arbitrary custom viewports or raw framebuffer bindings, or provide per-window
popup ownership. Scope-level clip, shader, blend and input-state isolation
still need explicit handling in the future popup layer. The SDL and Win32
window presenters, final OS-window pixels, and per-window popup ownership have
not been verified by this test.
## Verified C translucent compositing prerequisite
`tests/texture_scope_test.c` now checks half-transparent immediate and retained
rectangles captured over transparent black. It verifies the captured RGBA values
and compares the composite over an opaque parent against direct source-over
drawing, pixel for pixel. The GLES2 test passes with separate RGB/alpha capture
factors and premultiplied compositing. The backend's ordinary alpha mode uses
one factor pair for both RGB and alpha, so it is not sufficient for transparent
layer capture: a source alpha of one half becomes approximately one quarter.
This test sets backend blend factors explicitly through a test-only declaration;
it does not add a public low-level API or implement automatic layer ownership.
Retained target captures now also snapshot blend state and restore it for each
captured node, then restore the caller's blend state. The test ends the capture
blend scope before `EndTree`, activates a different caller blend configuration,
and configures another pending set of custom factors. It checks exact restoration
of both active GPU state and pending renderer configuration after deferred paint.
Kryon's build-preparation hook compiles private helpers inside the copied rlgl
implementation; the raylib submodule and public generated APIs are unchanged.
This implementation covers the OpenGL 3.3/GLES2 paths, with real pixel evidence
for GLES2. The future owned layer still needs scope-level blend restoration and
automatic composition, plus the remaining resource/window ownership work.
## Implemented prerequisite: private C owned paint layers
`src/ui/ui_paint_layers.c` owns render textures in an explicit host context.
Opening a layer reserves its order and captures immediate drawing plus retained
submissions into the same texture. Nested layers composite above the parent's
later drawing. The context reuses textures, replaces them when dimensions change,
and releases unused entries after the frame is composited. Hiding a parent
suppresses its descendants; a frame without an owner emits none of its old paint.
Capture establishes separate source-over alpha factors. End restores the prior
target, clip and blend state; composition uses premultiplied alpha and restores
the caller's matrices, clip and blend configuration. Resource allocation and
destruction also preserve the active framebuffer, since the backend's texture
helpers bind and unbind framebuffers internally. The host must finish retained
painting before compositing or destroying the context. Scope tokens check frame
generation and last-opened/first-closed order across all active host contexts,
before touching backend state. Generations are allocated across context lifetimes
so a destroyed host's token cannot become valid if its memory address is reused.
Unix subprocess regressions require rejection of null, stale, double-close,
destroyed-host and cross-host out-of-order tokens; valid nested scopes continue
through the real framebuffer checks.
The real framebuffer test covers translucent immediate content, retained content
above later opaque main content, child-over-parent ordering, hidden parents,
missing owners, and resumed drawing under a transformed camera and clip. This
is exposed through the public combo scope. C layer scopes suspend the
owner's retained layout path through `ui_tree_layout_suspend` and restore it on
exit. Popup nodes stay attached to the screen root in the same retained tree,
but do not consume parent Row/Column slots. Declaration-generation and balanced
child-layout checks reject ending a layer after changing its tree or leaving a
child layout open. A headless node/position regression and real pixels verify
an independent popup Column origin and the resumed parent Row's next position.
C layers also isolate disabled-scope depth while inheriting the parent's disabled
state. An internal floor prevents a child's `EndDisabled` from unwinding its
parent. Ending the layer requires balanced child disabled scopes, then restores
the parent's depth and disabled origin. Headless tests cover enabled/disabled
parents and nested scopes; the framebuffer test checks inheritance across host
contexts and rejects an unclosed disabled child scope. C layer scopes now also
suspend input clips and scroll-scope depth, leaving modal/input capture intact.
Their child scroll scopes must balance before exit restores the owner's clips.
Ordinary button regressions verify interaction outside the owner's viewport,
restored background clipping and rejection by a modal capture. Real pixels
verify mixed popup content escaping a 1x1 scrolling owner; invalid-scope tests
reject an unclosed child scroll. Complete shortcut routing and shader isolation
remain work.
The private C `ui_popup_input.c` registry now tracks persistent popup bounds,
parentage and branch ordering in explicit contexts. The shared input-capture
path consults its bound context, allowing ordinary controls to participate.
Records preserve capture before the next frame's owner declaration; closing a
parent disables descendants, and frame completion retires missing owners.
Headless button tests cover background controls before/after the owner, a child
receiving input instead of its parent, child dismissal, context rebinding,
missing owners and reordered sibling branches. Go's corresponding popup tests
remain a regression gate. C paint hosts now own their input registries: starting
a host frame advances and binds its registry, composition retires missing owners
and restores the previous binding, and destruction releases the registry.
Auxiliary windows establish their own context even before declaring a layer
when a parent context is bound. Hiding a layer closes its matching input branch.
The graphical test checks capture before redeclaration, auxiliary isolation,
parent restoration and missing-owner retirement. Retained nodes now keep private
declaration-time input snapshots, separate from paint snapshots, for deferred
hit testing and button hover/press state. Routing does not reopen lexical scopes.
The committed tree keeps its snapshots while a replacement is being declared;
registry generation/liveness checks reject old and destroyed owners. Headless
tests cover child precedence over later parent/background declarations and
dismissal restoring the parent then background. Deferred pointer-focus
registration now uses the same snapshots, retaining modal, clip, disabled and
inspection gates. A button regression clears immediate focus before the deferred
pass and verifies child focus versus modal blocking after both scopes close.
It also checks deferred click events. The test initially reproduced a click
leaking through modal capture; hit testing and hover/press state now consult the
same full capture predicate as pointer-focus registration. The public combo
scope uses this ownership registry. Persistent active-gesture ownership is
covered below.
C and Go now select the top live popup branch for keyboard eligibility without
testing pointer coordinates. Closed combos consult this check before accepting
keyboard opening. Matching native tests cover a focused combo in the parent
versus the top child, and keyboard eligibility after child and branch dismissal.
This check does not cover every shortcut path or establish complete keyboard
ownership.
TextField/TextArea editing now consults top-popup keyboard ownership in both
native runtimes. C's immediate keyboard-enabled query is scope-aware; retained
editors resolve their saved input owner and reject closed/stale owners before
editing. Matching typing tests cover blocked parent and eligible child editors,
with both immediate and deferred C variants. Immediate C TextArea skips paint
when no graphics window exists, matching TextField's headless editing support.
Complete widget-specific shortcut coverage and replay for every dismissal
ordering still require dedicated integration and tests.
The canonical `AcceleratorPressed` / `DispatchAccelerators` surface now exists
in native C and Go. It inherits disabled state and only accepts a chord in the
top live popup branch. Generated k2c/k2cpp/k2go parity queues Ctrl+C with an
open popup, verifies that only the popup command fires, closes the popup, and
verifies that background routing resumes on the next declaration. C
`BeginPopup` now retires an explicitly closed or outside-dismissed input owner
before returning, rather than leaving keyboard capture until frame cleanup.
This establishes generic accelerator ownership and explicit-close replay, not
all widget-specific shortcuts or cross-window routing.
Collapsible/tree-header directional navigation now resolves its registered
popup focus owner before handling arrows in C and Go. Native and generated
tests cover a focused background header blocked by an open popup, an eligible
header inside that popup, and restored background navigation after close.
Selectable-text copy also consults top-popup keyboard ownership in both
runtimes; Go's native regression covers blocked background and eligible popup
copy paths. C uses the same scope-aware keyboard predicate as accelerators.
Focus registrations now retain popup ownership separately from the lexical
scope. C stores frame-local registrations in the host input registry and
filters/deduplicates Tab destinations before releasing the host binding. Go
keeps ownership alongside current/previous-frame focus order and prunes removed
registrations at frame end. Matching tests cover forward/reverse wrapping,
parent/background exclusion, duplicate registrations and traversal after
explicit child/branch dismissal; Go additionally sends Tab through an editor.
Lifecycle tests in both runtimes verify that the first eligible child of a newly
opened top popup acquires focus, a nested close restores parent focus, and a
root close restores background focus. A complete cross-window keyboard lifecycle
is not established.
Ordinary Go Button now participates in focus order and handles Enter/Space and
Tab; unclaimed Tab events route at frame end after destination registration.
C's keyboard activation predicate checks the registered popup owner, so retained
button events work after lexical scopes close without activating the parent.
Matching popup tests cover Enter/Space in parent and child controls. The native
generated `buttons_layout.kry` runners additionally verify enabled/disabled
keyboard activation and Tab skipping a disabled button. Their shared JavaScript
comparison remains pointer-only for this fixture.
Missing C input owners are retired before focus finalization chooses a Tab
destination, while record/resource cleanup remains in its existing finish phase.
A regression reproduced focus being cleared when a missing child still blocked
its surviving parent. Matching native tests now omit the child and then parent
across frames and verify same-frame traversal to the parent and background.
Separate lifecycle regressions verify automatic background-focus restoration
when a popup owner disappears without a navigation event.
Text input lifetime now has dismissal regressions. C reproduced blocked text
reappearing in the underlying editor after a popup closed. The host registry
remembers keyboard capture for the frame, and EndUIFrame expires leftover native
characters and queued text-edit commands before releasing that binding. The
marker survives same-frame dismissal and resets at the next host frame; ordinary
non-popup queue behavior is unchanged. Tests cover immediate TextField/TextArea,
injected and platform-queued characters, queued Backspace/Enter for TextField,
and fresh input after dismissal. Go's frame cleanup passes the matching text
test. IME composition and Android device delivery are not established here.
C retained composition now has focused regressions. Popup-captured composition
events expire at frame end alongside other unhandled text, preventing delayed
commit after dismissal. Commits cannot mutate read-only TextField/TextArea
buffers. Preedit is cancelled when the retained editor loses focus, becomes
read-only or is blocked by popup keyboard ownership; tests check cancellation
events and no revival after re-enabling. Immediate C composition and device-level
IME delivery remain unfinished.
Native Go now has runtime-local composition queues and per-editor preedit state.
TextField/TextArea display preedit without mutating caller buffers, and commits
use UTF-8 insertion/cursor handling. Tests cover queue isolation and limits,
multi-frame preedit, commits, cancellation, removed/disabled/unfocused editors,
and popup dismissal without replay. The native generated `composition.kry`
fixture verifies non-mutating preedit, UTF-8 commit and cancellation through C
and Go; the JavaScript runner does not execute it. Go OS-window event delivery,
detailed preedit cursor/selection rendering and C TextArea preedit rendering
are still incomplete.
Read-only editing now has matching native generated coverage. The composition
fixture declares read-only TextField and TextArea in C and Go, checks copying,
and rejects ordinary text, cut/paste, deletion and IME commits. Go props carry
ReadOnly through editing and frame metadata; focused read-only controls keep
their focus styling without an insertion caret. C retained mutation paths also
honor read_only. Go tests check preedit cancellation and no rejected-input replay
when the editor becomes editable again.
The same framebuffer test interleaves two host contexts using the same owner ID,
resizes one context from 32 to 64 pixels, reuses the other context's resources,
and destroys one while the other destination is active. It verifies both hosts'
immediate/retained pixels and subsequent drawing. The real X11 `UIWindow`
presenter readback now also checks an owned layer composited over later opaque
retained content. Native `UIWindow` implementations lazily own their layer context:
begin starts its frame, end composites before presentation, and close destroys
it. Closing the active window first finishes its frame. The private accessor
returns no context outside an active window; callers no longer manage its
frame/composition/destruction. Four presenter readbacks cover consecutive frames,
an omitted owner and closing an active frame. X11 runtime and SDL compile checks
pass; Win32 runtime behavior remains unverified. This does not isolate C widget
or input state.
The main UI frame now lazily owns a separate context through the same private
frame accessor. `SetUIFrame` starts its layer frame and `EndUIFrame` composites
it; `CloseWindow` releases its textures before closing the graphics context.
UIWindow frames route to their own owner and do not end the main context. The
pixel test covers main-frame immediate/retained content, a missing owner,
interleaving an auxiliary window, and closing/reopening the graphics context.
Presenter texture readback preserves its caller's framebuffer, so interleaving
an auxiliary presentation does not redirect the main frame's later composition.
Callers of private internals still must balance layer scopes and finish retained
painting before host finalization. The public combo scope owns that balancing
for ordinary callers and rejects an unmatched `EndCombo`.
## Implemented prerequisite: native Go nested paint collection
`go/kryon/paint_layers.go` replaces the dropdown-specific paint map with an
ordered collection of ordinary `FrameOp` layers. A layer reserves its position
when opened, so nested popup paint follows all parent paint, including parent
widgets declared after the nested scope. Independent later layers paint last.
Layer scopes isolate layout and scrolling clips, inherit disabled content, and
restore the parent's layout, clip and disabled stack on exit. Their tokens are
runtime- and frame-specific and enforce last-opened/first-closed order.
The frame-end visibility predicate suppresses a closed or missing owner and
all of its descendants. Beginning a new frame discards previous paint records.
Existing dropdowns submit through this collector and retain their own input
and dismissal implementation. `paint_layers_test.go` verifies nested and
sibling order with software-rendered pixels, parent layout/clip restoration,
disabled-state inheritance/restoration, removed-parent suppression, frame
reset, and rejection of foreign, stale and unbalanced scope tokens. The native
Go suite and generated-runtime parity fixture for the existing dropdown path
remain regression gates.
The public Go combo scope now builds on this collector. Native tests cover
ordinary buttons, checkboxes, editable fields and nested layouts, including
nested dismissal, missing owners, layout restoration and presentation flags.
The shared `.kry` fixture is executed through generated C and Go and is also
syntax-checked through k2cpp.
`go/kryon/popup_input.go` separately generalizes click ownership. Its persistent
runtime-local registry preserves capture before the owner is declared on the
next frame. Input scopes restore the active parent, and overlap priority follows
whole popup branches rather than map iteration or leaf timestamps. Closing a
parent removes descendants; a missing owner is pruned at frame end. Ordinary
button tests cover nested overlap, child closure, background controls before
and after the owner, sibling reordering, owner removal, and runtime isolation.
Existing dropdown click consumers use this registry. Scroll scopes, list boxes,
trees, source views and tables also use its ownership check for wheel input,
alongside disabled-state and clip checks. Unit tests verify that each family
rejects covered background scrolling while allowing its popup-owned counterpart
to scroll. Generated native C/Go regression coverage opens a combo over an
earlier scroll scope and checks that the latter's offset remains unchanged on
wheel input. Go drag-and-drop start/accept paths now also respect popup and clip
ownership; tests verify that rejected background targets leave the release and
copied payload available to the popup target. Drag values, sliders, splitters
and table column resizers now store persistent popup owner identity in C and Go.
Native tests verify out-of-bounds continuation for the owning branch, preemption
of a background drag by a new popup, and cancellation on owner dismissal before
a background control with matching identity can mutate. Composed dismissal
covers explicit close, Escape, outside pointer release and owner removal; popup
focus restoration covers both explicit dismissal and owner removal.
## Acceptance evidence
| Case | Required evidence |
|---|---|
| Mixed contents | Generated button, checkbox, editable field and nested Row with independent caller state |
| Layer order | C and Go pixel checks with opaque content drawn after the combo owner |
| Existing render target | Native C offscreen/UI-window test proving the parent target and later drawing are preserved |
| Nested popup | One level closes without corrupting the parent's capture, layout or destination |
| Scrolling owner | Popup escapes the owner's clip while ordinary owner content remains clipped |
| Pointer ownership | Background controls declared both before and after the owner cannot steal popup input |
| Active gestures | Generated C/Go popup drag continues outside its bounds and cancels before same-ID background reuse; k2cpp compiles the same fixture |
| Editing lifecycle | Focus, typing, disabling, re-enabling and no replay of discarded input |
| Dismissal | Escape, outside press, selection-close, missing owner and destroyed window |
| Presentation choices | Alignment, size policies, preview/arrow suppression and preview-fit width |
Headless state tests cannot prove paint-target restoration or layering. Existing
string-list popup tests remain regressions but cannot replace these checks.
-275
View File
@@ -1,275 +0,0 @@
<!DOCTYPE html>
<!-- Generated by scripts/feature-matrix-html.py. DO NOT EDIT MANUALLY. -->
<html><head><meta charset="utf-8">
<title>Kryon Feature Matrix</title>
<style>
body{font-family:system-ui,sans-serif;max-width:1100px;margin:2rem auto;padding:0 1rem;color:#1a1a1a;background:#fafafa}
h1{border-bottom:3px solid #333;padding-bottom:.4rem} h2{margin-top:2.2rem;border-bottom:1px solid #ccc;padding-bottom:.25rem}
h3{margin-top:1.6rem;color:#333}
table{border-collapse:collapse;margin:1rem 0;font-size:.92rem;width:100%}
th,td{border:1px solid #bbb;padding:.42rem .6rem;text-align:left;vertical-align:top}
th{background:#2b2b2b;color:#fff;position:sticky;top:0}
tr:nth-child(even) td{background:#f2f2f2}
td.ok{background:#d9f2dd !important} td.part{background:#fdeebc !important}
td.no{background:#fbd5d2 !important} td.na{background:#e8e8e8 !important;color:#888}
code{background:#eee;padding:.08rem .3rem;border-radius:3px;font-size:.85em}
pre{background:#222;color:#ddd;padding:1rem;border-radius:6px;overflow-x:auto}
li{margin:.25rem 0}
</style></head><body>
<h1>Kryon Feature Matrix</h1>
<p>What every widget and feature supports, per compile target and per renderer backend. For how backends are selected and implemented see <code>docs/BACKENDS.md</code>; for the cartridge binary format see <code>docs/KRB_FORMAT.md</code>; for the language see <code>docs/KRY_LANGUAGE_SPEC.md</code>. Keep this file current with the code, and regenerate the browsable view after every change: <code>python3 scripts/feature-matrix-html.py</code> writes <code>docs/FEATURE_MATRIX.html</code>.</p>
<p>Legend: ✅ available · ◐ partial (reason given) · ✗ not available · — not applicable. <b>C</b> is the <code>libkryon.a</code> C API; <b>k2c</b> is what <code>.kry</code> reaches through the C compiler — always equal to C, because the language is C-close and every library call is a legal statement (the widget-statement whitelist below only adds sugar). The other compilers lower subsets, which is where the columns diverge.</p>
<h2>The pipeline</h2>
<pre>.kry source
│ shared frontend: cmd/kir/kir_parse.c -&gt; KirProgram
├── k2c -&gt; .c/.h + kryon_project.c/.h -&gt; cc + libkryon.a -&gt; native C app
├── k2cpp -&gt; .cpp/.hpp + kryon_project.c/.h (extern &quot;C&quot; decls; same lowering as k2c)
├── k2go -&gt; .go (kryon.&lt;Widget&gt; calls) -&gt; go build + go/kryon -&gt; Go app
├── k2js -&gt; .js (web runtime calls) -&gt; browser/Node ESM -&gt; Web app
├── k2b -&gt; .krb (+ .krb.c/.krb host) -&gt; KrbLoad/KrbExec on any KryBackend
└── k2kir -&gt; .kir (text IR dump; debugging, tests, Krait)</pre>
<table>
<tr><th>Target</th><th>Producer</th><th>Runtime</th><th>Status</th></tr>
<tr><td class="">C</td><td class=""><code>k2c</code></td><td class=""><code>cc</code> + <code>libkryon.a</code> (raylib/null/canvas/libdraw surface backend)</td><td class="">Most complete path; production use</td></tr>
<tr><td class="">C++</td><td class=""><code>k2cpp</code></td><td class=""><code>c++</code> + <code>libkryon.a</code>; C++ codegen with C linkage, same lowering as <code>k2c</code></td><td class="">Parity port of the <code>k2c</code> backend</td></tr>
<tr><td class="">Go</td><td class=""><code>k2go</code></td><td class=""><code>go/kryon</code> native Go package, no cgo</td><td class="">Declarative subset; executable CI gate</td></tr>
<tr><td class="">JS/Web</td><td class=""><code>k2js</code></td><td class=""><code>web/kryon-runtime.js</code> ESM recorder/presenter</td><td class="">Syntax, Node recorder snapshots, and generated runtime state parity gated</td></tr>
<tr><td class="">KRB cartridge</td><td class=""><code>k2b</code></td><td class=""><code>src/krb/krb.c</code> via the <code>KryBackend</code> vtable</td><td class="">Format v2; byte-exact across engines; CI-gated</td></tr>
<tr><td class="">KIR</td><td class=""><code>k2kir</code></td><td class="">— (inspection artifact)</td><td class="">Debugging/tooling only</td></tr>
</table>
<p>Two backend tiers exist (see <code>docs/BACKENDS.md</code>):</p>
<ul>
<li><b>Tier A — surface backends</b>: implement the ~700-symbol raylib-compatible</li>
</ul>
<p>surface (<code>include/kryon_compat.generated.h</code>), selected at <b>link</b> time via <code>KRYON_BACKEND=raylib|null|canvas|libdraw</code>. The whole widget catalog runs on these.</p>
<ul>
<li><b>Tier B — cartridge hosts</b>: implement the ~20-function <code>KryBackend</code> vtable</li>
</ul>
<p>(<code>include/kry_backend.h</code>), selected at <b>runtime</b>. Only the KRB widget subset runs on these.</p>
<h2>Widget statement whitelist (<code>.kry</code> frontend)</h2>
<p><code>parse_widget_statement</code> (<code>cmd/kir/kir_parse.c</code>) recognizes 102 widget names. <code>k2c</code> compiles any library call regardless (plain call statement); <code>k2cpp</code> shares that lowering (C++ output, C linkage); <code>k2go</code> lowers the full whitelist onto its <code>Runtime</code> interface (except <code>Canvas</code>, below); <code>k2js</code> records whitelisted standalone widget calls as browser-loadable runtime operations; and <code>k2b</code> lowers a subset of it:</p>
<p>`Background Text LabelText BulletText ValueBool ValueInt ValueUInt ValueFloat Paragraph TextLines Rect Line Bevel Icon Picture ImageWithBg ImageButton Button Selectable CheckboxFlags SmallButton InvisibleButton ArrowButton Bullet Separator SeparatorText ColorEdit3 ColorEdit4 ColorPicker3 ColorPicker4 ColorButton Tooltip IconButton Href TextField TextArea Dropdown Slider Toggle Checkbox Radio Progress Spinbox Combobox Screen Column Row Stack End Scroll PlotLines PlotHistogram DragFloat DragInt DragFloatRange2 DragIntRange2 SliderFloat SliderInt VSliderFloat VSliderInt SliderAngle InputFloat InputInt InputDouble Canvas BeginDisabled EndDisabled Modal ActionModal MessageDialog ConfirmDialog PromptDialog TitleBar MenuBar PopupMenu ContextMenu TabBar BottomNav TopNav Toolbar ShowToast ShowToastFor LabelFrame Notebook PanedView Collapsible ListBox TreeView SourceView TableView ColorPicker TabItemButton ClosableTabBar DragDropSource DragDropTarget MultiSelectList CanvasGrid SelectableText`</p>
<p>(<code>Canvas</code> is whitelisted but no <code>Canvas(...)</code> widget exists — examples call <code>BeginCanvas</code> directly. Scroll coverage uses the C <code>BeginUIScrollContainer</code> / <code>EndUIScrollContainer</code> API.)</p>
<h2>Widget matrix</h2>
<p>The upstream widget-family crosswalk and its remaining semantic gaps are kept in [<code>IMGUI_WIDGET_COVERAGE.md</code>](IMGUI_WIDGET_COVERAGE.md).</p>
<p>Columns: <b>C</b> = the C API · <b>k2c</b> = <code>.kry</code>→C codegen (always equal to C) · <b>k2cpp</b> = <code>.kry</code>→C++ codegen (mirrors <code>k2c</code>) · <b>k2go</b> = <code>.kry</code>→Go codegen (pure Go importing <code>go/kryon</code> as <code>kryon</code> and calling <code>kryon.&lt;Widget&gt;</code>) · <b>Go</b> = hand-written Go via the <code>go/kryon</code> package API · <b>KRB</b> = lowered into a cartridge by <code>k2b</code>.</p>
<p>Retained-tree caveat that applies to the whole C column: <code>#ui</code> lowering records ~29 widget kinds, while the retained painter covers BACKGROUND, TEXT, RECT, LINE, BUTTON, TEXT_FIELD, TEXT_AREA, SLIDER, TOGGLE, and CHECKBOX. It routes retained interaction for BUTTON, TEXT_FIELD, TEXT_AREA, SLIDER, TOGGLE, and CHECKBOX; every other kind renders through its immediate-mode call during the declaration pass (<code>src/ui/ui_tree.c</code>).</p>
<h3>UI/Display</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Background</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Background</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Text</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Text</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Text properties (bounds, wrap, clip, color, alignment, disabled)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Text(TextProps)</code></td><td class="ok">✅</td></tr>
<tr><td class="">Label/value and bullet text</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Value helpers (bool, int, unsigned, float)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Paragraph (rich text + inline icons)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Paragraph</code></td><td class="no">✗</td></tr>
<tr><td class="">TextLines</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TextLines</code></td><td class="no">✗</td></tr>
<tr><td class="">Rect</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ (+ <code>RectGradientH</code>)</td><td class="part">◐ <code>DrawRectangle*</code> primitives</td><td class="ok">✅ node</td></tr>
<tr><td class="">Line</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>DrawLine</code></td><td class="ok">✅</td></tr>
<tr><td class="">Bevel</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Bevel</code></td><td class="ok">✅</td></tr>
<tr><td class="">Icon sheets (MingCute UI plus 6 full-color families)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ (by icon type)</td><td class="ok">✅ <code>Icon</code></td><td class="no">✗</td></tr>
<tr><td class="">Image/Picture</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>kryon.Picture(kryon.PictureProps)</code></td><td class="ok">✅ <code>kryon.Picture</code></td><td class="ok">✅ node (embedded asset or PNG)</td></tr>
<tr><td class="">ImageWithBg / ImageButton</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">PlotLines / PlotHistogram</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>PlotLines</code> / <code>PlotHistogram</code></td><td class="no">✗</td></tr>
</table>
<h3>UI/Input</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Button (ButtonProps)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>kryon.Button(kryon.ButtonProps)</code> / <code>kryon.Button(&quot;Save&quot;)</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Selectable / CheckboxFlags</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Legacy positional buttons</td><td class="ok">✅ low-level only</td><td class="ok">✅ only for existing C callers</td><td class="ok">✅ only for existing C callers</td><td class="no">✗ use <code>kryon.Button(kryon.ButtonProps)</code></td><td class="no">✗ generated Go uses <code>kryon.Button</code></td><td class="part">◐ BUTTON style byte</td></tr>
<tr><td class="">IconButton / PaddedIconBtn</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>IconButton</code> only</td><td class="part">◐ <code>IconButton</code> only</td><td class="no">✗</td></tr>
<tr><td class="">InfoButton</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Href (TextLink / TextLinkOpenURL)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Href</code></td><td class="no">✗</td></tr>
<tr><td class="">IconLink</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">TextField</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>kryon.TextField(kryon.TextFieldProps)</code> / <code>kryon.TextField(&quot;Name&quot;, &amp;value)</code></td><td class="ok">✅ TEXTINPUT node</td></tr>
<tr><td class="">Read-only text</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ via <code>Text</code></td><td class="ok">✅ <code>Text(TextProps)</code></td><td class="no">✗</td></tr>
<tr><td class="">TextArea (selection, syntax highlight)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>NewTextArea</code>/<code>TextArea</code></td><td class="no">✗</td></tr>
<tr><td class="">Dropdown / DropdownOptions</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Dropdown</code> (rich option arrays are native C only)</td><td class="ok">✅ <code>Dropdown</code></td><td class="ok">✅ DROPDOWN control</td></tr>
<tr><td class="">Slider</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Slider</code>/<code>Slider</code></td><td class="ok">✅ SLIDER control</td></tr>
<tr><td class="">Vertical sliders</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>VSliderFloat</code> / <code>VSliderInt</code></td><td class="ok">✅</td><td class="ok">✅ VSLIDER control</td></tr>
<tr><td class="">Toggle (switch)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Toggle</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Checkbox (+ disabled)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Checkbox</code></td><td class="ok">✅ node</td></tr>
<tr><td class="">Radio</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Radio</code></td><td class="ok">✅ <code>KRB_CTRL_RADIO</code></td></tr>
<tr><td class="">Progress</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Progress</code></td><td class="ok">✅ <code>KRB_CTRL_PROGRESS</code></td></tr>
<tr><td class="">Spinbox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Spinbox</code></td><td class="ok">✅ SPINBOX control</td></tr>
<tr><td class="">Combobox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Combobox</code></td><td class="ok">✅ COMBOBOX control (renders like the dropdown, mirroring the C widget)</td></tr>
<tr><td class="">ColorPicker (RGB sliders)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>ColorPicker</code></td><td class="no">✗</td></tr>
<tr><td class="">DragFloat / DragInt (scalar and N-component)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">DragFloatRange2 / DragIntRange2 (ordered endpoints)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">SliderFloat / SliderInt / VSliderFloat / VSliderInt / SliderAngle</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">InputFloat / InputInt / InputDouble (scalar and N-component)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">SmallButton / InvisibleButton / ArrowButton / Bullet / Separator</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">SeparatorText</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">ColorEdit3 / ColorEdit4 / ColorPicker3 / ColorPicker4 / ColorButton</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
</table>
<h3>UI/Layout</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Column / Row / Stack (flex-like)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ all three</td><td class="ok">✅ all three</td><td class="ok">✅ structural no-ops (node table is the tree)</td></tr>
<tr><td class="">Group</td><td class="ok">✅ (lowers to Stack)</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ via Column</td><td class="ok">✅ via Stack</td><td class="ok">✅</td></tr>
<tr><td class="">Scroll container</td><td class="ok">✅ <code>BeginScroll</code>/<code>EndScroll</code></td><td class="ok">✅ C API</td><td class="ok">✅ C API</td><td class="ok">✅ generated wheel/drag/nested-child tests</td><td class="ok">✅ wheel scrolling, scrollbar dragging, and nested clipping via <code>BeginScroll</code>/<code>EndScroll</code></td><td class="ok">✅ SCROLL node</td></tr>
<tr><td class="">Separator</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td></tr>
<tr><td class="">LabelFrame</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>LabelFrame</code></td><td class="ok">✅ rect/text lowering</td></tr>
<tr><td class="">Notebook (tabs)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Notebook</code></td><td class="no">✗</td></tr>
<tr><td class="">PanedView (splitter)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>PanedView</code></td><td class="no">✗</td></tr>
<tr><td class="">Collapsible</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Collapsible</code></td><td class="no">✗</td></tr>
<tr><td class="">Tk pack/grid helpers (<code>FramePack</code>, <code>GridCell</code>, <code>Place</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">UIForm cursor (<code>UIForm*</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Canvas (pan/zoom, hit-test, grid)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Begin/EndCanvas</code></td><td class="ok">✅ <code>Begin/EndCanvas</code>+hit-test</td><td class="no">✗</td></tr>
</table>
<h3>UI/Collections</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">ListBox (+ disabled)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>ListBox</code></td><td class="no">✗</td></tr>
<tr><td class="">TreeView (+ disabled) / CascadingTreeView</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>TreeView</code></td><td class="part">◐ <code>TreeView</code></td><td class="no">✗</td></tr>
<tr><td class="">SourceView (code + line numbers)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>SourceView</code></td><td class="no">✗</td></tr>
<tr><td class="">TableView (resizing, frozen rows, sort direction, cell colors, column visibility/order, focus/keyboard/clipboard, disabled)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TableView</code></td><td class="no">✗</td></tr>
<tr><td class="">CanvasGrid</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>CanvasGrid</code></td><td class="no">✗</td></tr>
<tr><td class="">SelectableText</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>SelectableText</code></td><td class="no">✗</td></tr>
<tr><td class="">MultiSelectList (focus, keyboard navigation, Ctrl/Shift range selection)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Nested disabled scope</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>BeginDisabled</code> / <code>EndDisabled</code></td><td class="no">✗</td></tr>
</table>
<h3>UI/Navigation</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">MenuBar / PopupMenu / ContextMenu</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ (<code>MenuBar</code>, nested items, retained right-click context state)</td><td class="no">✗</td></tr>
<tr><td class="">Popup scope (ordinary, hover-tooltip, modal arbitrary native content)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">TabBar</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>TabBar</code></td><td class="no">✗</td></tr>
<tr><td class="">TabItemButton / closable tab items</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Typed drag-and-drop source / target</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">SubtabBar / PaneTabBar (dock zones)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">BottomNav (+ config modal)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>BottomNav</code></td><td class="part">◐ <code>NavButton</code> lowers to a BUTTON</td></tr>
<tr><td class="">TopNav / Toolbar / ToolbarHeader</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>TopNav</code>/<code>Toolbar</code> only</td><td class="ok">✅ <code>TopNav</code>/<code>Toolbar</code></td><td class="no">✗</td></tr>
<tr><td class="">TitleBar family</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>TitleBar</code> only</td><td class="ok">✅ <code>TitleBar</code></td><td class="no">✗</td></tr>
</table>
<h3>UI/Overlays</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">ActionModal / Modal / Modal3Button / ModalFrame</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ <code>Modal</code> only</td><td class="part">◐ <code>Modal</code> only</td><td class="no">✗</td></tr>
<tr><td class="">MessageDialog / ConfirmDialog / PromptDialog</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">Toast</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>ShowToast(For)</code></td><td class="ok">✅ <code>ShowToast(For)</code></td><td class="no">✗</td></tr>
<tr><td class="">GuideOverlay / TutorialImage(Placeholder)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">TransitionFade / Focus ring</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="part">◐ <code>AnimNode</code> + <code>TIME</code> opcode drive animation</td></tr>
<tr><td class="">ThemeSettings / ThemeSwitcher / ThemePicker</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="part">◐ theme-control methods only</td><td class="part">◐ <code>SetCurrentTheme</code>/<code>SetThemeStyle</code> (control only)</td><td class="no">✗</td></tr>
<tr><td class="">FocusDebugOverlay</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">InfoRows / OverlayButton / IconSliderPopup</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>UI/Composite And App Framework</h3>
<table>
<tr><th>Widget</th><th>C</th><th>k2c</th><th>k2cpp</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">LabelTextField / SectionLabel</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">CheckboxRow / SpinboxRow / ButtonRow / BottomIconRow</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">BottomNavConfig</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">SidebarAccountHeader / ProfilePicturePicker</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Reorder (drag handle + placeholder)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">ImageBox</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Route stack / shell measurement</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Capabilities / safe content rect</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Setting normalization helpers</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>Game2D (scene tree, <code>src/scene/</code>)</h3>
<table>
<tr><th>Node</th><th>C</th><th>✅</th><th>✅</th><th>k2go</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Scene / Node2D / Camera2D</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Sprite2D / AnimatedSprite2D / TileMap / TileLayer / Light2D</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">CollisionShape2D / Area2D / Body2D (box2d)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Timer / AudioSource / AnimationPlayer</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Signals (<code>KrySignal</code>) / keyframe animation</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
</table>
<h3>KRB cartridge vocabulary (no C widget equivalent)</h3>
<table>
<tr><th>Item</th><th>Notes</th></tr>
<tr><td class="">DATA node</td><td class="">state-field mount read/written by bytecode</td></tr>
<tr><td class="">CIRCLE / RING nodes</td><td class="">lowered from <code>DrawCircleV</code> / <code>DrawRing</code> calls</td></tr>
<tr><td class=""><code>NavButton</code></td><td class=""><code>k2b</code>-only lowering; becomes a BUTTON with <code>KRB_FLAG_NAV</code></td></tr>
<tr><td class=""><code>AnimNode</code></td><td class=""><code>k2b</code>-only; animated node driven by <code>TIME</code></td></tr>
<tr><td class="">v2 logic bytecode</td><td class="">stack machine, node mutation, if-guards over node ranges</td></tr>
<tr><td class="">Host capabilities</td><td class="">imported storage/http/audio/notify calls (<code>krb_caps.c</code>)</td></tr>
</table>
<h2>Cross-cutting features</h2>
<table>
<tr><th>Feature</th><th>C</th><th>Go</th><th>KRB</th></tr>
<tr><td class="">Theming</td><td class="ok">✅ 6 palettes × light/dark INI, scopes, vars, runtime loader</td><td class="ok">✅ <code>SetCurrentTheme</code>/<code>SetThemeDarkMode</code>/<code>GetTheme*</code></td><td class="part">◐ theme color slots (<code>KrySwSetTheme</code>); light/dark env knobs on hosts</td></tr>
<tr><td class="">Style tokens</td><td class="ok">✅ radius/border/shadow/bevel; RETRO, MATERIAL, SYSTEM styles</td><td class="ok">✅ <code>Get/SetUIStyleTokens</code></td><td class="no">✗</td></tr>
<tr><td class="">Animation</td><td class="ok">✅ transitions (smoothstep), ripple, keyframe scene anims</td><td class="no">✗</td><td class="part">◐ <code>AnimNode</code> + <code>TIME</code> opcode</td></tr>
<tr><td class="">Text/fonts</td><td class="part">◐ multi-font registry, per-codepoint fallback, italic synthesis, wrap, selectable text, Android/browser IME preedit+commit; no shaping/bidi</td><td class="ok">✅ <code>RegisterUIFont(Data)</code>, <code>Push/Pop/UseUIFont</code>, input queue</td><td class="part">◐ font8x8 default, or pre-baked KFA1 glyph atlas; no TTF rasterization</td></tr>
<tr><td class="">DPI/scaling</td><td class="ok">✅ viewport-derived scale, <code>Scale</code></td><td class="ok">✅ <code>Scale</code>, <code>GetWindowScaleDPI</code></td><td class="part">◐ per-mille UI scale (<code>KRB_RUN_UI_SCALE</code>)</td></tr>
<tr><td class="">Clipping</td><td class="ok">✅ 16-deep scissor stack + input clip stack</td><td class="ok">✅ <code>Begin/EndScissorMode</code></td><td class="ok">✅ 16-deep <code>clip_push/pop</code> in <code>kry_sw</code></td></tr>
<tr><td class="">Z-order/popups</td><td class="ok">✅ overlay paint pass, modal capture, input-capture stack</td><td class="part">◐ dropdown popups internal to <code>Dropdown</code></td><td class="part">◐ dropdown menus handled by the engine</td></tr>
<tr><td class="">Input</td><td class="ok">✅ unified front-end, pointer gestures/ownership, keyboard focus + Tab + accelerators, clipboard, backend-neutral IME composition; no gamepad nav</td><td class="ok">✅ native host key/mouse/text queues</td><td class="part">◐ vtable: mouse, press, wheel, text-key queue</td></tr>
<tr><td class="">Accessibility</td><td class="part">◐ retained accessibility snapshots + host sink + DOM ARIA bridge; native screen-reader bridge pending</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">i18n</td><td class="ok">✅ locale strings + CJK font switching; no RTL</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Multi-window</td><td class="ok">✅ <code>OpenUIWindow</code> (X11 dlopen / SDL)</td><td class="no">✗</td><td class="na">— single framebuffer</td></tr>
<tr><td class="">3D rendering</td><td class="ok">✅ camera + mesh/shader tier incl. curated rlgl entry points and raymath-style math3d (GLSL 100); raylib backend implements it, others stub it</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">State/data binding</td><td class="ok">✅ retained event queue; scene signals</td><td class="ok">✅ <code>#ui</code> functions + retained events</td><td class="ok">✅ field mounts (<code>KrbMount*</code>) + bytecode</td></tr>
<tr><td class="">Dialogs/platform</td><td class="ok">✅ file dialogs (web/portal/gtk/zenity/kdialog/yad), XDG paths, desktop metadata packaging, single-instance lock, tray, notifications (Android/web/Linux)</td><td class="ok">✅ tray + notify polling</td><td class="part">◐ host capability imports (storage/http/audio/notify)</td></tr>
<tr><td class="">Debug tooling</td><td class="ok">✅ widget inspector, node registry + snippets</td><td class="no">✗</td><td class="part">◐ <code>KryBackendRec</code> call-stream recording</td></tr>
</table>
<h2>Renderer backends</h2>
<h3>Tier A — surface backends (link-time, <code>KRYON_BACKEND</code>)</h3>
<table>
<tr><th>Backend</th><th>Graphics API</th><th>Platforms</th><th>CI</th><th>Notes</th></tr>
<tr><td class=""><code>raylib</code> (default)</td><td class="">OpenGL ES 2.0 over SDL2</td><td class="">Linux, FreeBSD</td><td class="ok">✅ <code>ci.yml</code> (Linux + FreeBSD)</td><td class="">Default everywhere; dist/static SDK targets; implements the full 3D tier (camera/mesh/shader + rlgl entry points)</td></tr>
<tr><td class=""><code>raylib</code> web</td><td class="">WebGL (ES2) over GLFW3</td><td class="">Emscripten</td><td class="ok">✅ web/app builds</td><td class=""><code>mk/web.mk</code>; present shim for WebKitGTK</td></tr>
<tr><td class=""><code>raylib</code> windows <code>opengl</code></td><td class="">OpenGL 2.1</td><td class="">Windows (mingw)</td><td class="ok">✅ release builds</td><td class="">Default Windows flavor</td></tr>
<tr><td class=""><code>raylib</code> windows <code>rlsw</code></td><td class="">raylib software renderer (no GPU)</td><td class="">Windows</td><td class="ok">✅ release builds</td><td class=""><code>WINDOWS_RENDERERS</code> second flavor</td></tr>
<tr><td class=""><code>raylib</code> windows RGFW rule</td><td class="">GL 1.1 immediate mode</td><td class="">Windows</td><td class="no">✗ opt-in make rule</td><td class=""><code>KRYON_RAYLIB_WINDOWS_RULE</code></td></tr>
<tr><td class=""><code>raylib</code> android</td><td class="">GLES via NDK <code>NativeActivity</code></td><td class="">Android (downstream Gradle)</td><td class="no">✗ downstream apps</td><td class=""><code>mk/android.mk</code></td></tr>
<tr><td class=""><code>null</code></td><td class="">none (zero-return stubs)</td><td class="">all</td><td class="no">✗ (used by local headless tests)</td><td class="">Injected input still works</td></tr>
<tr><td class=""><code>canvas</code></td><td class="">HTML5 Canvas2D via <code>EM_JS</code> (ASYNCIFY loop)</td><td class="">Emscripten</td><td class="ok">✅ <code>make canvas-test</code>, <code>make canvas2d-parity-check</code>, <code>make web-canvas-matrix-check</code></td><td class="">No raylib/WebGL; HiDPI Canvas2D, 2D raylib aliases, touch/gamepad/drop-file hooks, glyph atlases, textures/render textures/tinting, WebAudio, and weak stubs for non-2D raylib areas</td></tr>
<tr><td class=""><code>libdraw</code></td><td class=""><code>kry_sw</code> RGBA8 presented through plan9port libdraw/devdraw</td><td class="">plan9port on Unix/X11</td><td class="ok">✅ <code>make libdraw-test</code> (devdraw smoke + <code>9c</code>/<code>9l</code> clean-surface check)</td><td class="">No libraylib; widgets/drawing/screenshots through software backend; TTF/TrueType-outline glyph atlases via <code>stb_truetype</code>; rounded controls, alpha/tint texture blits, rotation, render textures, plan9port input/resize; non-UI raylib areas use weak null stubs</td></tr>
</table>
<h3>Tier B — cartridge hosts (<code>KryBackend</code> vtable, runtime selection)</h3>
<table>
<tr><th>Host</th><th>Rendering</th><th>Input</th><th>Textures</th><th>Text</th><th>CI</th><th>Notes</th></tr>
<tr><td class=""><code>KryBackendDraw</code></td><td class="">raylib surface</td><td class="">raylib</td><td class="ok">✅</td><td class="">full font stack</td><td class="ok">✅</td><td class="">Auto-installed via constructor; hooks cartridge audio; runs inside raylib apps and <code>kryon-preview</code></td></tr>
<tr><td class=""><code>kry_sw</code></td><td class="">software RGBA8 rasterizer</td><td class="">injected (<code>KrySwMouse</code> etc.)</td><td class="ok">✅ + PNG decode</td><td class="">font8x8 or KFA1 atlas</td><td class="ok">✅</td><td class="">No GPU/libc deps; <code>KrySwToRGB565</code> for embedded panels; one-shot dirty-rect tracking</td></tr>
<tr><td class=""><code>krb-run</code></td><td class=""><code>kry_sw</code> headless</td><td class="">injected</td><td class="ok">✅</td><td class="">via <code>kry_sw</code></td><td class="ok">✅ linux/windows/macos</td><td class="">PNG dump + <code>KryBackendRec</code> call log; conformance host</td></tr>
<tr><td class=""><code>krb-sdl</code></td><td class=""><code>kry_sw</code> → SDL2 streaming texture</td><td class="">SDL2</td><td class="ok">✅</td><td class="">via <code>kry_sw</code></td><td class="ok">✅</td><td class="">Template for the planned Android EGL host</td></tr>
<tr><td class=""><code>krb-web</code></td><td class=""><code>kry_sw</code> → wasm, Canvas2D <code>putImageData</code></td><td class="">JS bridge exports</td><td class="ok">✅</td><td class="">via <code>kry_sw</code></td><td class="ok">✅ renderers.yml</td><td class="">Byte-identical to native; node-capture for tests</td></tr>
<tr><td class=""><code>KryBackendRec</code></td><td class="">wraps any backend</td><td class="">passthrough</td><td class="">passthrough</td><td class="">passthrough</td><td class="ok">✅ exactness job</td><td class="">Records the vtable call stream for cross-engine comparison</td></tr>
<tr><td class=""><code>KryBackendNull</code></td><td class="">stub vtable</td><td class="">none</td><td class="no">✗ (<code>texture_rgba</code> NULL)</td><td class="no">✗</td><td class="ok">✅ logic tests</td><td class="">Default until <code>KryBackendSelect</code></td></tr>
</table>
<h2>Known gaps</h2>
<ul>
<li>The <code>canvas</code> Tier A backend passes its node call-sequence gate and has</li>
</ul>
<p>been pixel-verified in a real browser page (rounded rects, annulus ring segments, dual-color gradients, and full RGBA texture tinting all check out). Remaining limits: cross-app clipboard paste is unreachable through the synchronous API (an in-app mirror handles round-trips), WebAudio playback depends on browser user-gesture unlock rules, and stream/mixed processors apply to Canvas-managed stream buffers, not decoded browser <code>AudioBuffer</code> playback that has already been handed to WebAudio.</p>
<ul>
<li>The <code>libdraw</code> Tier A backend passes the plan9port devdraw widget smoke and a</li>
</ul>
<p><code>9c</code>/<code>9l</code> clean-surface compile/link check. It is intended for C UI apps: windowing, input, resize, software drawing, widgets, rounded controls, thick lines, image loading, alpha/tint and source-rectangle texture blits, picture rotation, render textures, TTF/TrueType-outline glyph-atlas text, screenshots, files, and clipboard mirror are covered. Advanced raylib areas outside UI apps (3D, shaders, gestures, audio) are null-grade fallback.</p>
<ul>
<li><code>k2go</code> targets native Go: the <code>Runtime</code> interface covers the widget</li>
</ul>
<p>whitelist plus the generated-code widget families in <code>go/kryon</code> (controls, Props widgets, dialogs, canvas, Tk layout helpers, toasts, theme control), with <code>.kry</code> array declarations lowering to Go slices at the use site. Remaining boundaries: a forward <code>goto</code> over declarations is a loud Go compile error, <code>DropdownOptions</code>&#x27; rich option arrays are not expressible from <code>.kry</code>, and C pointer/<code>Texture2D</code> values cannot be written (icons pass by <code>UIIconType</code>, option lists as joined strings or <code>[N]string</code>).</p>
<ul>
<li><code>k2js</code> emits ESM for the web recorder runtime. `make</li>
</ul>
<p>k2js-runtime-snapshot-test` lowers every conformance source, imports the generated ESM in Node, runs <code>frame()</code>, and compares the recorded widget streams. <code>make generated-runtime-parity-test</code> also drives generated JS through the same state/input workflows as generated Go and C, then diffs the final state JSON. This is runtime state parity for the recorder surface, not browser pixel comparison.</p>
<ul>
<li><code>k2b</code> drops unsupported widget calls and reports them per file; the</li>
</ul>
<p>cartridge widget set remains smaller than the C catalog (see matrix). <code>Combobox</code> lowers to a <code>KRB_CTRL_COMBOBOX</code> control that renders like the dropdown, matching the C widget. <code>Progress</code> lowers to a read-only <code>KRB_CTRL_PROGRESS</code> control bound to an integer state field. <code>Radio</code> lowers to <code>KRB_CTRL_RADIO</code> for the common <code>selected == id</code> pattern and writes <code>id</code> into the mounted selection field on click. <code>LabelFrame</code> lowers to border rectangles plus title background/text nodes.</p>
<ul>
<li>Retained tree paints 10 node kinds and routes interaction for 6 (see caveat</li>
</ul>
<p>above the widget matrix).</p>
<ul>
<li>No text shaping yet: no HarfBuzz, ligatures, bidi, or RTL mirroring. Android</li>
</ul>
<p>and DOM text controls do have backend-neutral IME preedit/commit; gamepad UI navigation remains absent.</p>
<ul>
<li>Theme styles beyond RETRO/MATERIAL/SYSTEM (fluent/adwaita/liquid-glass</li>
</ul>
<p>labels in <code>ThemeSettingsProps</code>) fall back to SYSTEM tokens.</p>
<ul>
<li><code>kry_sw</code> tracks the dirty rectangle per call (<code>KrySwDirty</code> is one-shot);</li>
</ul>
<p>hosts that present full frames (<code>krb-sdl</code>, <code>krb-web</code>) do not use it yet.</p>
<ul>
<li>Plan 11 engines still to come: native Canvas2D fast path, Android EGL</li>
</ul>
<p>host, ESP32 RGB565 host. The Linux framebuffer host was removed again - raylib covers desktop presentation and the canvas backend covers native web, so it carried maintenance cost without a user.</p>
</body></html>
-330
View File
@@ -1,330 +0,0 @@
# Kryon Feature Matrix
What every widget and feature supports, per compile target and per renderer
backend. For how backends are selected and implemented see `docs/BACKENDS.md`;
for the cartridge binary format see `docs/KRB_FORMAT.md`; for the language see
`docs/KRY_LANGUAGE_SPEC.md`. Keep this file current with the code, and
regenerate the browsable view after every change:
`python3 scripts/feature-matrix-html.py` writes `docs/FEATURE_MATRIX.html`.
Legend: ✅ available · ◐ partial (reason given) · ✗ not available · — not
applicable. **C** is the `libkryon.a` C API; **k2c** is what `.kry` reaches
through the C compiler — always equal to C, because the language is C-close
and every library call is a legal statement (the widget-statement whitelist
below only adds sugar). The other compilers lower subsets, which is where
the columns diverge.
## The pipeline
```
.kry source
│ shared frontend: cmd/kir/kir_parse.c -> KirProgram
├── k2c -> .c/.h + kryon_project.c/.h -> cc + libkryon.a -> native C app
├── k2cpp -> .cpp/.hpp + kryon_project.c/.h (extern "C" decls; same lowering as k2c)
├── k2go -> .go (kryon.<Widget> calls) -> go build + go/kryon -> Go app
├── k2js -> .js (web runtime calls) -> browser/Node ESM -> Web app
├── k2b -> .krb (+ .krb.c/.krb host) -> KrbLoad/KrbExec on any KryBackend
└── k2kir -> .kir (text IR dump; debugging, tests, Krait)
```
| Target | Producer | Runtime | Status |
|---|---|---|---|
| C | `k2c` | `cc` + `libkryon.a` (raylib/null/canvas/libdraw surface backend) | Most complete path; production use |
| C++ | `k2cpp` | `c++` + `libkryon.a`; C++ codegen with C linkage, same lowering as `k2c` | Parity port of the `k2c` backend |
| Go | `k2go` | `go/kryon` native Go package, no cgo | Declarative subset; executable CI gate |
| JS/Web | `k2js` | `web/kryon-runtime.js` ESM recorder/presenter | Syntax, Node recorder snapshots, and generated runtime state parity gated |
| KRB cartridge | `k2b` | `src/krb/krb.c` via the `KryBackend` vtable | Format v2; byte-exact across engines; CI-gated |
| KIR | `k2kir` | — (inspection artifact) | Debugging/tooling only |
Two backend tiers exist (see `docs/BACKENDS.md`):
- **Tier A — surface backends**: implement the ~700-symbol raylib-compatible
surface (`include/kryon_compat.generated.h`), selected at **link** time via
`KRYON_BACKEND=raylib|null|canvas|libdraw`. The whole widget catalog runs on
these.
- **Tier B — cartridge hosts**: implement the ~20-function `KryBackend` vtable
(`include/kry_backend.h`), selected at **runtime**. Only the KRB widget
subset runs on these.
## Widget statement whitelist (`.kry` frontend)
`parse_widget_statement` (`cmd/kir/kir_parse.c`) recognizes 102 widget names.
`k2c` compiles any library call regardless (plain call statement); `k2cpp` shares that lowering (C++ output, C linkage); `k2go` lowers
the full whitelist onto its `Runtime` interface (except `Canvas`, below);
`k2js` records whitelisted standalone widget calls as browser-loadable runtime
operations; and `k2b` lowers a subset of it:
`Background Text LabelText BulletText ValueBool ValueInt ValueUInt ValueFloat Paragraph TextLines Rect Line Bevel Icon
Picture ImageWithBg ImageButton Button Selectable CheckboxFlags SmallButton InvisibleButton ArrowButton Bullet Separator SeparatorText ColorEdit3 ColorEdit4 ColorPicker3 ColorPicker4 ColorButton Tooltip IconButton Href TextField TextArea Dropdown Slider Toggle
Checkbox Radio Progress Spinbox Combobox Screen Column Row Stack End Scroll
PlotLines PlotHistogram DragFloat DragInt DragFloatRange2 DragIntRange2 SliderFloat SliderInt VSliderFloat VSliderInt SliderAngle InputFloat InputInt InputDouble
Canvas BeginDisabled EndDisabled Modal ActionModal MessageDialog ConfirmDialog PromptDialog TitleBar MenuBar PopupMenu ContextMenu
TabBar BottomNav TopNav Toolbar ShowToast ShowToastFor LabelFrame Notebook
PanedView Collapsible ListBox TreeView SourceView TableView ColorPicker TabItemButton ClosableTabBar DragDropSource DragDropTarget MultiSelectList
CanvasGrid SelectableText`
(`Canvas` is whitelisted but no `Canvas(...)` widget exists — examples call
`BeginCanvas` directly. Scroll coverage uses the C `BeginUIScrollContainer` /
`EndUIScrollContainer` API.)
## Widget matrix
The upstream widget-family crosswalk and its remaining semantic gaps are kept
in [`IMGUI_WIDGET_COVERAGE.md`](IMGUI_WIDGET_COVERAGE.md).
Columns: **C** = the C API · **k2c** = `.kry`→C codegen (always equal to C) · **k2cpp** = `.kry`→C++ codegen (mirrors `k2c`) · **k2go** = `.kry`→Go codegen
(pure Go importing `go/kryon` as `kryon` and calling `kryon.<Widget>`) · **Go** =
hand-written Go via the `go/kryon` package API · **KRB** = lowered into a
cartridge by `k2b`.
Retained-tree caveat that applies to the whole C column: `#ui` lowering
records ~29 widget kinds, while the retained painter covers BACKGROUND, TEXT,
RECT, LINE, BUTTON, TEXT_FIELD, TEXT_AREA, SLIDER, TOGGLE, and CHECKBOX. It
routes retained interaction for BUTTON, TEXT_FIELD, TEXT_AREA, SLIDER, TOGGLE,
and CHECKBOX;
every other kind renders through its immediate-mode call during the
declaration pass (`src/ui/ui_tree.c`).
### UI/Display
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Background | ✅ | ✅ | ✅ | ✅ | ✅ `Background` | ✅ node |
| Text | ✅ | ✅ | ✅ | ✅ | ✅ `Text` | ✅ node |
| Text properties (bounds, wrap, clip, color, alignment, disabled) | ✅ | ✅ | ✅ | ✅ | ✅ `Text(TextProps)` | ✅ |
| Label/value and bullet text | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Value helpers (bool, int, unsigned, float) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Paragraph (rich text + inline icons) | ✅ | ✅ | ✅ | ✅ | ✅ `Paragraph` | ✗ |
| TextLines | ✅ | ✅ | ✅ | ✅ | ✅ `TextLines` | ✗ |
| Rect | ✅ | ✅ | ✅ | ✅ (+ `RectGradientH`) | ◐ `DrawRectangle*` primitives | ✅ node |
| Line | ✅ | ✅ | ✅ | ✅ | ✅ `DrawLine` | ✅ |
| Bevel | ✅ | ✅ | ✅ | ✅ | ✅ `Bevel` | ✅ |
| Icon sheets (MingCute UI plus 6 full-color families) | ✅ | ✅ | ✅ | ✅ (by icon type) | ✅ `Icon` | ✗ |
| Image/Picture | ✅ | ✅ | ✅ | ✅ `kryon.Picture(kryon.PictureProps)` | ✅ `kryon.Picture` | ✅ node (embedded asset or PNG) |
| ImageWithBg / ImageButton | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| PlotLines / PlotHistogram | ✅ | ✅ | ✅ | ✅ | ✅ `PlotLines` / `PlotHistogram` | ✗ |
### UI/Input
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Button (ButtonProps) | ✅ | ✅ | ✅ | ✅ | ✅ `kryon.Button(kryon.ButtonProps)` / `kryon.Button("Save")` | ✅ node |
| Selectable / CheckboxFlags | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Legacy positional buttons | ✅ low-level only | ✅ only for existing C callers | ✅ only for existing C callers | ✗ use `kryon.Button(kryon.ButtonProps)` | ✗ generated Go uses `kryon.Button` | ◐ BUTTON style byte |
| IconButton / PaddedIconBtn | ✅ | ✅ | ✅ | ◐ `IconButton` only | ◐ `IconButton` only | ✗ |
| InfoButton | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Href (TextLink / TextLinkOpenURL) | ✅ | ✅ | ✅ | ✅ | ✅ `Href` | ✗ |
| IconLink | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| TextField | ✅ | ✅ | ✅ | ✅ | ✅ `kryon.TextField(kryon.TextFieldProps)` / `kryon.TextField("Name", &value)` | ✅ TEXTINPUT node |
| Read-only text | ✅ | ✅ | ✅ | ✅ via `Text` | ✅ `Text(TextProps)` | ✗ |
| TextArea (selection, syntax highlight) | ✅ | ✅ | ✅ | ✅ | ✅ `NewTextArea`/`TextArea` | ✗ |
| Dropdown / DropdownOptions | ✅ | ✅ | ✅ | ✅ `Dropdown` (rich option arrays are native C only) | ✅ `Dropdown` | ✅ DROPDOWN control |
| Slider | ✅ | ✅ | ✅ | ✅ | ✅ `Slider`/`Slider` | ✅ SLIDER control |
| Vertical sliders | ✅ | ✅ | ✅ | ✅ `VSliderFloat` / `VSliderInt` | ✅ | ✅ VSLIDER control |
| Toggle (switch) | ✅ | ✅ | ✅ | ✅ | ✅ `Toggle` | ✅ node |
| Checkbox (+ disabled) | ✅ | ✅ | ✅ | ✅ | ✅ `Checkbox` | ✅ node |
| Radio | ✅ | ✅ | ✅ | ✅ | ✅ `Radio` | ✅ `KRB_CTRL_RADIO` |
| Progress | ✅ | ✅ | ✅ | ✅ | ✅ `Progress` | ✅ `KRB_CTRL_PROGRESS` |
| Spinbox | ✅ | ✅ | ✅ | ✅ | ✅ `Spinbox` | ✅ SPINBOX control |
| Combobox | ✅ | ✅ | ✅ | ✅ | ✅ `Combobox` | ✅ COMBOBOX control (renders like the dropdown, mirroring the C widget) |
| ColorPicker (RGB sliders) | ✅ | ✅ | ✅ | ✅ | ✅ `ColorPicker` | ✗ |
| DragFloat / DragInt (scalar and N-component) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| DragFloatRange2 / DragIntRange2 (ordered endpoints) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| SliderFloat / SliderInt / VSliderFloat / VSliderInt / SliderAngle | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| InputFloat / InputInt / InputDouble (scalar and N-component) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| SmallButton / InvisibleButton / ArrowButton / Bullet / Separator | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| SeparatorText | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| ColorEdit3 / ColorEdit4 / ColorPicker3 / ColorPicker4 / ColorButton | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
### UI/Layout
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Column / Row / Stack (flex-like) | ✅ | ✅ | ✅ | ✅ all three | ✅ all three | ✅ structural no-ops (node table is the tree) |
| Group | ✅ (lowers to Stack) | ✅ | ✅ | ◐ via Column | ✅ via Stack | ✅ |
| Scroll container | ✅ `BeginScroll`/`EndScroll` | ✅ C API | ✅ C API | ✅ generated wheel/drag/nested-child tests | ✅ wheel scrolling, scrollbar dragging, and nested clipping via `BeginScroll`/`EndScroll` | ✅ SCROLL node |
| Separator | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| LabelFrame | ✅ | ✅ | ✅ | ✅ | ✅ `LabelFrame` | ✅ rect/text lowering |
| Notebook (tabs) | ✅ | ✅ | ✅ | ✅ | ✅ `Notebook` | ✗ |
| PanedView (splitter) | ✅ | ✅ | ✅ | ✅ | ✅ `PanedView` | ✗ |
| Collapsible | ✅ | ✅ | ✅ | ✅ | ✅ `Collapsible` | ✗ |
| Tk pack/grid helpers (`FramePack`, `GridCell`, `Place`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| UIForm cursor (`UIForm*`) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Canvas (pan/zoom, hit-test, grid) | ✅ | ✅ | ✅ | ✅ `Begin/EndCanvas` | ✅ `Begin/EndCanvas`+hit-test | ✗ |
### UI/Collections
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| ListBox (+ disabled) | ✅ | ✅ | ✅ | ✅ | ✅ `ListBox` | ✗ |
| TreeView (+ disabled) / CascadingTreeView | ✅ | ✅ | ✅ | ◐ `TreeView` | ◐ `TreeView` | ✗ |
| SourceView (code + line numbers) | ✅ | ✅ | ✅ | ✅ | ✅ `SourceView` | ✗ |
| TableView (resizing, frozen rows, sort direction, cell colors, column visibility/order, focus/keyboard/clipboard, disabled) | ✅ | ✅ | ✅ | ✅ | ✅ `TableView` | ✗ |
| CanvasGrid | ✅ | ✅ | ✅ | ✅ | ✅ `CanvasGrid` | ✗ |
| SelectableText | ✅ | ✅ | ✅ | ✅ | ✅ `SelectableText` | ✗ |
| MultiSelectList (focus, keyboard navigation, Ctrl/Shift range selection) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Nested disabled scope | ✅ | ✅ | ✅ | ✅ | ✅ `BeginDisabled` / `EndDisabled` | ✗ |
### UI/Navigation
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| MenuBar / PopupMenu / ContextMenu | ✅ | ✅ | ✅ | ✅ | ✅ (`MenuBar`, nested items, retained right-click context state) | ✗ |
| Popup scope (ordinary, hover-tooltip, modal arbitrary native content) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| TabBar | ✅ | ✅ | ✅ | ✅ | ✅ `TabBar` | ✗ |
| TabItemButton / closable tab items | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Typed drag-and-drop source / target | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| SubtabBar / PaneTabBar (dock zones) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| BottomNav (+ config modal) | ✅ | ✅ | ✅ | ✅ | ✅ `BottomNav` | ◐ `NavButton` lowers to a BUTTON |
| TopNav / Toolbar / ToolbarHeader | ✅ | ✅ | ✅ | ◐ `TopNav`/`Toolbar` only | ✅ `TopNav`/`Toolbar` | ✗ |
| TitleBar family | ✅ | ✅ | ✅ | ◐ `TitleBar` only | ✅ `TitleBar` | ✗ |
### UI/Overlays
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| ActionModal / Modal / Modal3Button / ModalFrame | ✅ | ✅ | ✅ | ◐ `Modal` only | ◐ `Modal` only | ✗ |
| MessageDialog / ConfirmDialog / PromptDialog | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| Toast | ✅ | ✅ | ✅ | ✅ `ShowToast(For)` | ✅ `ShowToast(For)` | ✗ |
| GuideOverlay / TutorialImage(Placeholder) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| TransitionFade / Focus ring | ✅ | ✅ | ✅ | ✗ | ✗ | ◐ `AnimNode` + `TIME` opcode drive animation |
| ThemeSettings / ThemeSwitcher / ThemePicker | ✅ | ✅ | ✅ | ◐ theme-control methods only | ◐ `SetCurrentTheme`/`SetThemeStyle` (control only) | ✗ |
| FocusDebugOverlay | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| InfoRows / OverlayButton / IconSliderPopup | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### UI/Composite And App Framework
| Widget | C | k2c | k2cpp | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| LabelTextField / SectionLabel | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| CheckboxRow / SpinboxRow / ButtonRow / BottomIconRow | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| BottomNavConfig | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| SidebarAccountHeader / ProfilePicturePicker | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Reorder (drag handle + placeholder) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| ImageBox | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Route stack / shell measurement | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Capabilities / safe content rect | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Setting normalization helpers | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### Game2D (scene tree, `src/scene/`)
| Node | C | ✅ | ✅ | k2go | Go | KRB |
|---|---|---|---|---|---|---|
| Scene / Node2D / Camera2D | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Sprite2D / AnimatedSprite2D / TileMap / TileLayer / Light2D | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| CollisionShape2D / Area2D / Body2D (box2d) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Timer / AudioSource / AnimationPlayer | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Signals (`KrySignal`) / keyframe animation | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
### KRB cartridge vocabulary (no C widget equivalent)
| Item | Notes |
|---|---|---|
| DATA node | state-field mount read/written by bytecode |
| CIRCLE / RING nodes | lowered from `DrawCircleV` / `DrawRing` calls |
| `NavButton` | `k2b`-only lowering; becomes a BUTTON with `KRB_FLAG_NAV` |
| `AnimNode` | `k2b`-only; animated node driven by `TIME` |
| v2 logic bytecode | stack machine, node mutation, if-guards over node ranges |
| Host capabilities | imported storage/http/audio/notify calls (`krb_caps.c`) |
## Cross-cutting features
| Feature | C | Go | KRB |
|---|---|---|---|---|
| Theming | ✅ 6 palettes × light/dark INI, scopes, vars, runtime loader | ✅ `SetCurrentTheme`/`SetThemeDarkMode`/`GetTheme*` | ◐ theme color slots (`KrySwSetTheme`); light/dark env knobs on hosts |
| Style tokens | ✅ radius/border/shadow/bevel; RETRO, MATERIAL, SYSTEM styles | ✅ `Get/SetUIStyleTokens` | ✗ |
| Animation | ✅ transitions (smoothstep), ripple, keyframe scene anims | ✗ | ◐ `AnimNode` + `TIME` opcode |
| Text/fonts | ◐ multi-font registry, per-codepoint fallback, italic synthesis, wrap, selectable text, Android/browser IME preedit+commit; no shaping/bidi | ✅ `RegisterUIFont(Data)`, `Push/Pop/UseUIFont`, input queue | ◐ font8x8 default, or pre-baked KFA1 glyph atlas; no TTF rasterization |
| DPI/scaling | ✅ viewport-derived scale, `Scale` | ✅ `Scale`, `GetWindowScaleDPI` | ◐ per-mille UI scale (`KRB_RUN_UI_SCALE`) |
| Clipping | ✅ 16-deep scissor stack + input clip stack | ✅ `Begin/EndScissorMode` | ✅ 16-deep `clip_push/pop` in `kry_sw` |
| Z-order/popups | ✅ overlay paint pass, modal capture, input-capture stack | ◐ dropdown popups internal to `Dropdown` | ◐ dropdown menus handled by the engine |
| Input | ✅ unified front-end, pointer gestures/ownership, keyboard focus + Tab + accelerators, clipboard, backend-neutral IME composition; no gamepad nav | ✅ native host key/mouse/text queues | ◐ vtable: mouse, press, wheel, text-key queue |
| Accessibility | ◐ retained accessibility snapshots + host sink + DOM ARIA bridge; native screen-reader bridge pending | ✗ | ✗ |
| i18n | ✅ locale strings + CJK font switching; no RTL | ✗ | ✗ |
| Multi-window | ✅ `OpenUIWindow` (X11 dlopen / SDL) | ✗ | — single framebuffer |
| 3D rendering | ✅ camera + mesh/shader tier incl. curated rlgl entry points and raymath-style math3d (GLSL 100); raylib backend implements it, others stub it | ✗ | ✗ |
| State/data binding | ✅ retained event queue; scene signals | ✅ `#ui` functions + retained events | ✅ field mounts (`KrbMount*`) + bytecode |
| Dialogs/platform | ✅ file dialogs (web/portal/gtk/zenity/kdialog/yad), XDG paths, desktop metadata packaging, single-instance lock, tray, notifications (Android/web/Linux) | ✅ tray + notify polling | ◐ host capability imports (storage/http/audio/notify) |
| Debug tooling | ✅ widget inspector, node registry + snippets | ✗ | ◐ `KryBackendRec` call-stream recording |
## Renderer backends
### Tier A — surface backends (link-time, `KRYON_BACKEND`)
| Backend | Graphics API | Platforms | CI | Notes |
|---|---|---|---|---|---|
| `raylib` (default) | OpenGL ES 2.0 over SDL2 | Linux, FreeBSD | ✅ `ci.yml` (Linux + FreeBSD) | Default everywhere; dist/static SDK targets; implements the full 3D tier (camera/mesh/shader + rlgl entry points) |
| `raylib` web | WebGL (ES2) over GLFW3 | Emscripten | ✅ web/app builds | `mk/web.mk`; present shim for WebKitGTK |
| `raylib` windows `opengl` | OpenGL 2.1 | Windows (mingw) | ✅ release builds | Default Windows flavor |
| `raylib` windows `rlsw` | raylib software renderer (no GPU) | Windows | ✅ release builds | `WINDOWS_RENDERERS` second flavor |
| `raylib` windows RGFW rule | GL 1.1 immediate mode | Windows | ✗ opt-in make rule | `KRYON_RAYLIB_WINDOWS_RULE` |
| `raylib` android | GLES via NDK `NativeActivity` | Android (downstream Gradle) | ✗ downstream apps | `mk/android.mk` |
| `null` | none (zero-return stubs) | all | ✗ (used by local headless tests) | Injected input still works |
| `canvas` | HTML5 Canvas2D via `EM_JS` (ASYNCIFY loop) | Emscripten | ✅ `make canvas-test`, `make canvas2d-parity-check`, `make web-canvas-matrix-check` | No raylib/WebGL; HiDPI Canvas2D, 2D raylib aliases, touch/gamepad/drop-file hooks, glyph atlases, textures/render textures/tinting, WebAudio, and weak stubs for non-2D raylib areas |
| `libdraw` | `kry_sw` RGBA8 presented through plan9port libdraw/devdraw | plan9port on Unix/X11 | ✅ `make libdraw-test` (devdraw smoke + `9c`/`9l` clean-surface check) | No libraylib; widgets/drawing/screenshots through software backend; TTF/TrueType-outline glyph atlases via `stb_truetype`; rounded controls, alpha/tint texture blits, rotation, render textures, plan9port input/resize; non-UI raylib areas use weak null stubs |
### Tier B — cartridge hosts (`KryBackend` vtable, runtime selection)
| Host | Rendering | Input | Textures | Text | CI | Notes |
|---|---|---|---|---|---|---|---|
| `KryBackendDraw` | raylib surface | raylib | ✅ | full font stack | ✅ | Auto-installed via constructor; hooks cartridge audio; runs inside raylib apps and `kryon-preview` |
| `kry_sw` | software RGBA8 rasterizer | injected (`KrySwMouse` etc.) | ✅ + PNG decode | font8x8 or KFA1 atlas | ✅ | No GPU/libc deps; `KrySwToRGB565` for embedded panels; one-shot dirty-rect tracking |
| `krb-run` | `kry_sw` headless | injected | ✅ | via `kry_sw` | ✅ linux/windows/macos | PNG dump + `KryBackendRec` call log; conformance host |
| `krb-sdl` | `kry_sw` → SDL2 streaming texture | SDL2 | ✅ | via `kry_sw` | ✅ | Template for the planned Android EGL host |
| `krb-web` | `kry_sw` → wasm, Canvas2D `putImageData` | JS bridge exports | ✅ | via `kry_sw` | ✅ renderers.yml | Byte-identical to native; node-capture for tests |
| `KryBackendRec` | wraps any backend | passthrough | passthrough | passthrough | ✅ exactness job | Records the vtable call stream for cross-engine comparison |
| `KryBackendNull` | stub vtable | none | ✗ (`texture_rgba` NULL) | ✗ | ✅ logic tests | Default until `KryBackendSelect` |
## Known gaps
- The `canvas` Tier A backend passes its node call-sequence gate and has
been pixel-verified in a real browser page (rounded rects, annulus ring
segments, dual-color gradients, and full RGBA texture tinting all check
out). Remaining limits: cross-app clipboard paste is unreachable through
the synchronous API (an in-app mirror handles round-trips), WebAudio
playback depends on browser user-gesture unlock rules, and stream/mixed
processors apply to Canvas-managed stream buffers, not decoded browser
`AudioBuffer` playback that has already been handed to WebAudio.
- The `libdraw` Tier A backend passes the plan9port devdraw widget smoke and a
`9c`/`9l` clean-surface compile/link check. It is intended for C UI apps:
windowing, input, resize, software drawing, widgets, rounded controls, thick
lines, image loading, alpha/tint and source-rectangle texture blits, picture
rotation, render textures, TTF/TrueType-outline glyph-atlas text,
screenshots, files, and clipboard mirror are covered. Advanced raylib areas
outside UI apps (3D, shaders, gestures, audio) are null-grade fallback.
- `k2go` targets native Go: the `Runtime` interface covers the widget
whitelist plus the generated-code widget families in `go/kryon` (controls,
Props widgets, dialogs, canvas, Tk layout helpers, toasts, theme control),
with `.kry` array declarations lowering to Go slices at the use site.
Remaining boundaries: a forward `goto` over declarations is a loud Go
compile error, `DropdownOptions`' rich option arrays are not expressible from
`.kry`, and C pointer/`Texture2D` values cannot be written (icons pass by
`UIIconType`, option lists as joined strings or `[N]string`).
- `k2js` emits ESM for the web recorder runtime. `make
k2js-runtime-snapshot-test` lowers every conformance source, imports the
generated ESM in Node, runs `frame()`, and compares the recorded widget
streams. `make generated-runtime-parity-test` also drives generated JS
through the same state/input workflows as generated Go and C, then diffs the
final state JSON. This is runtime state parity for the recorder surface, not
browser pixel comparison.
- `k2b` drops unsupported widget calls and reports them per file; the
cartridge widget set remains smaller than the C catalog (see matrix).
`Combobox` lowers to a `KRB_CTRL_COMBOBOX` control that renders like the
dropdown, matching the C widget. `Progress` lowers to a read-only
`KRB_CTRL_PROGRESS` control bound to an integer state field. `Radio` lowers
to `KRB_CTRL_RADIO` for the common `selected == id` pattern and writes `id`
into the mounted selection field on click. `LabelFrame` lowers to border
rectangles plus title background/text nodes.
- Retained tree paints 10 node kinds and routes interaction for 6 (see caveat
above the widget matrix).
- No text shaping yet: no HarfBuzz, ligatures, bidi, or RTL mirroring. Android
and DOM text controls do have backend-neutral IME preedit/commit; gamepad UI
navigation remains absent.
- Theme styles beyond RETRO/MATERIAL/SYSTEM (fluent/adwaita/liquid-glass
labels in `ThemeSettingsProps`) fall back to SYSTEM tokens.
- `kry_sw` tracks the dirty rectangle per call (`KrySwDirty` is one-shot);
hosts that present full frames (`krb-sdl`, `krb-web`) do not use it yet.
- Plan 11 engines still to come: native Canvas2D fast path, Android EGL
host, ESP32 RGB565 host. The Linux framebuffer host was removed again -
raylib covers desktop presentation and the canvas backend covers native
web, so it carried maintenance cost without a user.
-347
View File
@@ -1,347 +0,0 @@
# Dear ImGui widget coverage
This audit compares Kryon's clean native widget surface with Dear ImGui
`imgui.h` at commit
[`53d421955fdb658e75b039b8210841ad691dafd1`](https://github.com/ocornut/imgui/commit/53d421955fdb658e75b039b8210841ad691dafd1)
(`IMGUI_VERSION_NUM` 19295, `1.93.0 WIP`). It tracks widget behavior rather
than copying overload names: Kryon's counted value arrays cover the ImGui
`*2`, `*3`, `*4`, `Scalar`, and `ScalarN` fronts without adding aliases.
“Covered” in this family inventory means a native implementation exists; it is
not proof of every overload, flag, interaction or rendering detail. Full-goal
completion requires those semantics to be checked separately. In particular,
the [composed popup checklist](COMPOSED_POPUP_IMPLEMENTATION.md) records the
implemented combo scope and its remaining lifecycle/backend gaps.
| Dear ImGui widget family | Kryon native surface | Status |
|---|---|---|
| Text and value helpers | `Text(TextProps)`, `LabelText`, `BulletText`, `SeparatorText`, `Value*` | one canonical text widget owns bounds, wrapping, clipping, color, alignment, and disabled presentation |
| Buttons and boolean choices | `Button`, `SmallButton`, `InvisibleButton`, `ArrowButton`, `Toggle`, `Checkbox`, `CheckboxFlags`, `Radio`, `Bullet` | interactive controls share pointer focus, Tab traversal, Enter/Space activation, disabled gating, popup ownership, and focus presentation; `Bullet` is presentation-only |
| Progress and links | `Progress`, `Href` | covered; `Href` represents both clickable text and open-URL links |
| Images | `Picture`, `ImageWithBg`, `ImageButton` | covered; `ImageButton` shares ordinary focus and keyboard activation |
| Combo boxes | `Combobox`, `Dropdown`, `Selectable`, `BeginCombo` / `EndCombo` / `CloseCombo` | option-list helper plus a native arbitrary-child scope with explicit close and presentation flags |
| Drag values | `DragFloat`, `DragInt`, `DragFloatRange2`, `DragIntRange2` | covered, including counted N-component values, component focus/Tab traversal, Left/Right adjustment, Home/End bounds, and Shift/Alt step modifiers |
| Sliders | `SliderFloat`, `SliderInt`, `VSliderFloat`, `VSliderInt`, `SliderAngle` | counted N-component values, component focus, arrow/Home/End keyboard adjustment, and slow/fast modifiers are covered |
| Keyboard inputs | `TextField`, `TextArea`, `InputFloat`, `InputInt`, `InputDouble` | covered, including hints and counted N-component values |
| Color editors and pickers | `ColorEdit3`, `ColorEdit4`, `ColorPicker3`, `ColorPicker4`, `ColorButton` | covered; `ColorButton` shares ordinary focus and keyboard activation |
| Trees and collapsing headers | `TreeView`, `Collapsible` | `Collapsible` supports tree styling, depth indentation, leaves, selected/disabled state, optional close/visibility state, arbitrary nested children, keyboard expansion, and directional header/parent/child focus traversal |
| Selectables and multi-selection | `Selectable`, `MultiSelectList` | covered, including shared focus/Enter/Space activation, Tab traversal, arrow/Home/End navigation, and Ctrl/Shift range selection |
| List boxes | `ListBox`, `BeginListBox` / `EndListBox` | string-list helper with focus, arrow/Home/End navigation and selection-following scroll, plus a framed scrolling scope for arbitrary native children |
| Scrollable child content needed for composed lists and trees | `BeginScroll` / `EndScroll` | C/Go wheel scrolling, scrollbar dragging, and nested clipping implemented and exercised through generated native fixtures |
| Plots | `PlotLines`, `PlotHistogram` | covered |
| Menus | `MenuBar`, `PopupMenu`, `ContextMenu` | nested submenus plus focus, disabled/separator skipping, arrow/Home/End traversal, submenu entry/backout, activation, and Escape dismissal in native C and Go |
| Tooltips and popups | `PopupMenu`, `ContextMenu`, modal/dialog widgets, `BeginPopup` / `EndPopup` / `ClosePopup` with `PopupTooltip`, `PopupModal`, and `PopupContext` | arbitrary popup, hover-tooltip, modal, and right-click context contents are native through one scope |
| Tables | `TableView`, `BeginTableCell` / `EndTableCell` | row/cell model includes resizing, frozen rows, sorting, colors, visibility, ordering, slanted headers, focus/arrow/Tab navigation, activation, clipboard copy/paste targets, and scoped native child widgets in custom-cell mode |
| Tabs | `TabBar`, `BeginTabBar` / `BeginTabItem` / `EndTabItem` / `EndTabBar`, `ClosableTabBar`, `TabItemButton` | canonical tab sizing/scrolling, focus, disabled skipping, keyboard selection/close, popup ownership, close/middle/double-click signals, selected-tab reveal, and reorder reporting are covered; the scope submits arbitrary native children only for the selected item, and omitted scroll state is owned independently by stable tab-bar ID |
| Drag and drop | `DragDropSource`, `DragDropTarget` | covered with typed copied payloads |
| Disabled content | `BeginDisabled`, `EndDisabled`, per-widget `Disabled` fields | covered, including nested scopes |
Dear ImGui layout calls such as `SameLine`, `Spacing`, `Indent`, and groups are
represented by Kryon's retained `Row`, `Column`, `Stack`, and `Grid` layout
containers. They are not separate widget aliases. Window management, style
stacks, input queries, logging, clipping, and item-status queries are support
APIs rather than widget families and are outside this widget inventory.
## Composition verification
C and Go regressions declare 41 combo controls and verify independent identity,
selection and open-state capture. C no longer aliases the first control after
24 dropdown identities; missing owners' records are reclaimed at frame end.
C options and their copied labels/font names also use dynamically sized owned
storage. Native tests select option 130, beyond the former 128-option cap.
The C rendering test observes the real text renderer receiving a full owned
512-byte overlay label after its caller buffer has been overwritten; Go checks
the corresponding deferred text record. Visible-row painting avoids drawing
every option in a large list. The option-list helper's retained state is owned
per render host; native C tests open the same numeric widget ID in independent
stores and verify that popup visibility cannot cross windows. Arbitrary popup
composition uses the separate public combo scope.
Open native C/Go dropdowns support Up/Down, Home/End and Enter, keeping the
highlight separate from committed selection. Native tests navigate a 131-option
list, confirm with Enter, cancel with Escape and reopen. The C test also selects
the last option by pointer after End, verifying that keyboard navigation reveals
it in the constrained viewport. Generated C/Go checks exercise Home/End and
confirmation without prematurely changing selection, opening the control with
Space through its focus ID. Native unit tests cover opening focused positive-ID
controls with Enter, keypad Enter, Space and Down, without moving or committing
the selection, and reject opening under both property and scope disabling.
Go also checks the focused paint record and focus border. Popup keyboard-focus
isolation is covered separately across buttons, editors, choices, drags, lists,
tables, menus, tabs, collapsibles and generic accelerators; these tests still do
not prove every ImGui navigation semantic or widget-specific shortcut.
Native C and Go sliders now register each counted component as a focus target.
Left/Right adjust horizontal sliders, Up/Down adjust vertical sliders, Home/End
select the range limits, Alt slows adjustment, and Shift accelerates it. Pointer
presses focus the exact component, disabled sliders reject keys, popup ownership
gates keyboard input, and the focused component receives the ordinary focus
presentation. Matching native tests cover component Tab traversal and the
generated `plots.kry` fixture verifies horizontal float and vertical integer
adjustment through k2c and k2go.
Native Go now constrains and flips long dropdowns using the same placement
rules as C, reusing its ordinary scroll container for clipping, wheel input and
scrollbar interaction. A generated C/Go regression opens a 20-option control
near the bottom of the window, navigates to End and selects its revealed last
row by pointer above the control. Go unit tests also exercise 131 options in
both popup directions, retained wheel position, visible-row-only paint records,
and dismissal cleanup. This is vertical viewport coverage, not proof of every
popup placement policy, touch gesture or rendering backend.
The generated native fixture also drags the scrollbar to the last row and
releases over another row without selecting it, then selects the revealed last
row with a fresh click. C dropdown scrollbar input now runs headlessly and is
not blocked by its own popup capture. Native unit tests dismiss an active thumb
drag via Escape, disabling, and owner removal, checking release of drag state.
The real C framebuffer regression also drags a popup thumb, verifies the text
renderer receives the last row immediately, and compares that frame pixel for
pixel with the following stationary-pointer frame. This catches delayed row
painting independently of the headless selection checks.
Native C/Go also constrain popup width and horizontal position to the window.
Unit tests exercise partially off-screen owners at either edge and owners wider
than the window, including capture bounds and row selection. Generated native
parity selects a popup row shifted left from a right-edge owner. These checks
do not cover multi-monitor work areas or arbitrary popup placement flags.
For composed-popup painting, the C framebuffer regression verifies translucent
immediate and retained capture and compares premultiplied composition against
direct source-over drawing. This manually configured backend test establishes
the required alpha pipeline. Captured retained nodes now preserve declaration-time
blend state and restore the caller's active and pending custom blend settings
after painting, verified by the framebuffer test. The public combo scope uses
the C paint-layer context, which owns and
composites textures with scope-level drawing-state restoration. Real pixel tests
cover mixed translucent/retained content, nested ordering, hidden parents and
missing owners over an existing target. Native `UIWindow` now owns layer frame,
composition and destruction. Main UI frames now own a separate context with
automatic frame composition and pre-graphics-shutdown cleanup.
Additional framebuffer checks interleave independent contexts with identical
owner IDs, resize one, destroy the other while a destination is active, and
verify the real X11 UIWindow presenter's owned-layer pixels. These prove paint
resource isolation. The UIWindow presenter regression additionally exercises
automatic context management across consecutive frames, a missing owner and
closing an active frame. It does not prove isolation of the still-global C
widget/input state or Win32 runtime behavior.
The main-host framebuffer regression also checks a missing owner, interleaved
auxiliary presentation and graphics-context close/reopen. Auxiliary texture
readback no longer changes the main frame's active destination.
C paint layers now isolate the retained layout path. Headless node/position
checks and real pixels verify a popup's independent Column origin and that the
surrounding Row resumes at its next slot. Unclosed child layouts are rejected.
The public combo scope uses this isolation so its child layouts do not consume
the surrounding layout cursor.
C layer disabled scopes now inherit the parent's state without allowing child
scope endings to unwind the parent. Headless nested-scope tests and the real
layer test cover restoration, with invalid-scope checks for an unclosed child.
C layers also isolate input clips and scroll depth from the owner. Ordinary
button tests verify escaped clipping without bypassing modal capture, and real
pixels verify mixed content outside a 1x1 scrolling owner. Popup-to-background
and nested-popup input ownership now have a private C registry consulted by the
shared hit-test path. Ordinary button tests cover nested ownership, background
controls, dismissal, missing owners, context isolation and branch reordering.
Paint hosts now own and advance these registries automatically. The graphical
test checks capture before redeclaration, auxiliary-window isolation, parent
binding restoration and missing-owner retirement. Retained hit testing and
button hover/press state now use declaration-time popup ownership. Tests cover
child precedence over later parent/background nodes, dismissal restoring the
parent then background, pending-tree isolation and stale/destroyed registries.
Deferred pointer-focus registration also uses those snapshots; a test isolates
the deferred pass from immediate button focus and verifies modal blocking.
The same regression checks emitted click events: a blocked popup child emits
none, while an eligible child emits one. Deferred hit testing and hover/press
state share the complete capture predicate with focus registration.
Public composed-scope integration is covered. A newly opened top popup now
saves the displaced focus and gives focus to its first eligible child. Closing
a nested popup restores its parent's focus, while closing or omitting the root
owner restores the background focus. Active drag values, sliders, splitters and
table column resizing now retain the popup branch that started the gesture.
The same composed `Popup` scope now supports `PopupTooltip`: hover over an
explicit trigger submits arbitrary native child widgets into a non-input-capturing
overlay layer without an external `open` value. Matching C and Go unit tests
verify nested layout/child painting, disappearance outside the trigger and no
popup-input ownership. The generated C/Go composed fixture also verifies hover
visibility and that an underlying button still receives its click. The former
text-only `Tooltip` helper and `TooltipProps` surface were removed after all
maintained callers migrated, leaving one tooltip implementation.
`PopupModal` extends that same scope rather than adding a modal-specific child
API. It draws a full-view backdrop, keeps outside pointer input from reaching
background controls, preserves arbitrary nested children, and closes on Escape
or explicit caller action rather than an outside release. Matching native and
generated C/Go tests cover these semantics.
`PopupContext` extends the scope with a right-release trigger instead of adding
a context-only child API. The caller retains open state and stable panel bounds;
ordinary children, explicit close, outside dismissal, disabled rejection and
missing-owner cleanup remain shared with `Popup`. Matching native C/Go tests
and a generated k2c/k2cpp/k2go fixture cover the trigger and child lifecycle.
Matching C and Go tests now cover keyboard opening of a combo inside the top
popup versus a blocked parent, with popup bounds away from the combo to prove
the check is independent of pointer position. Child/branch dismissal restores
parent/background keyboard eligibility. This is not Tab trapping or general
button/editor keyboard isolation.
TextField and TextArea now gate editing by top-popup keyboard ownership in C
and Go. Native tests verify that typing leaves a focused parent editor unchanged
and edits an eligible child. C covers both immediate and deferred tree routing;
the immediate TextArea path now avoids renderer calls in headless tests.
All shortcuts and input replay across popup dismissal are not established by
these tests.
Generic native accelerators now have matching C and Go APIs and top-popup
ownership. Generated k2c/k2cpp/k2go coverage proves Ctrl+C dispatch inside the
active popup, suppression of the same background chord, and restoration after
the popup is explicitly closed. Widget-specific shortcut paths still require
their own ownership coverage.
Collapsible/tree-header arrows now have matching native and generated popup
ownership coverage, including background restoration after close.
Selectable-text copy is likewise ownership-gated in C and Go; native Go tests
cover both blocked background and eligible popup selection copies.
Table focus, display-order arrow and Tab/Shift+Tab navigation, Enter/F2 activation, Escape
clearing, and selection-following scroll now share a native C/Go contract.
Generated k2c and k2go fixtures exercise the same movement and activation, and
native popup tests prove that a focused table cannot consume keys owned by a
higher popup branch.
Cell, full-row, full-column, and override copying plus paste target reporting
now run through that same owned key path. Native C tests cover every copy shape,
and the shared generated fixture proves cell-copy and paste parity in k2c
and k2go.
Separate native Tab tests now cover ownership-filtered focus destinations,
forward/reverse wrapping, duplicate registrations and traversal after explicit
child/branch dismissal. Go tests exercise previous-frame order and real editor
Tab events. C finalizes focus while the host registry is still bound. Separate
native lifecycle tests cover first-child acquisition and restoration after
nested close, root close and missing-owner retirement. Full keyboard routing
remains work.
Ordinary Go Button now supports focus registration, pointer focus, Enter/Space
activation and Tab traversal. C keyboard activation consults popup ownership for
both immediate returns and deferred click events. Matching native popup tests
cover blocked parent versus eligible child activation. Generated C/Go checks
extend `buttons_layout.kry` coverage with Enter/Space, disabled activation
rejection and Tab skipping the disabled button; these additional assertions are
native-only and do not claim JavaScript keyboard coverage.
The same focusable-activation contract now backs native C and Go `Toggle`, `Checkbox`,
`CheckboxFlags`, `Radio`, `Selectable`, `InvisibleButton`, `ImageButton`, and
`ColorButton`, instead of duplicating key handling in each paint routine.
Direct runtime tests cover Enter/Space, Tab, disabled scopes, focus presentation,
and top-popup ownership. The generated `basic_controls.kry` fixture exercises
the canonical checkbox and props-based choice widgets through k2c and k2go;
JavaScript remains outside these added keyboard assertions.
Native missing-owner tests additionally omit the child and then the entire
branch across frames. C now retires missing input ownership before filtering
focus, matching Go's frame-end behavior; Tab reaches the surviving parent or
background in the same frame. Popup lifecycle tests separately verify automatic
restoration without a navigation event.
Text replay tests now span dismissal: focused parent TextField/TextArea controls
reject captured text, remain unchanged on the next frame without input, and
accept fresh text later. C covers both injected and platform-queued characters,
same-frame dismissal, and queued Backspace/Enter for TextField. Popup-captured
leftovers now expire at frame end. Go's existing frame cleanup passes the matching
text test. IME composition and device-level Android delivery remain unverified.
C retained IME now has separate regressions: blocked commits do not replay,
read-only TextField/TextArea reject commits, and TextField preedit cancels on
focus loss, a read-only transition or popup capture without revival. This does
not establish immediate C editor composition, native Go composition events or
device-level IME delivery.
Native Go now implements runtime-local composition events and per-editor
preedit for TextField/TextArea. Tests cover queue isolation/limits, preedit
persistence without buffer mutation, UTF-8 commit, cancellation, editor removal,
focus loss, disabling and popup dismissal. `composition.kry` is executed through
generated C and Go to verify preedit/commit/cancel behavior; it is not executed
by the JavaScript runner. OS-window Go IME delivery and detailed preedit
cursor/selection rendering remain unfinished.
Read-only TextField/TextArea behavior is now covered by the native generated
composition fixture: selection/copy remains usable while text, cut/paste,
deletion and IME commits cannot mutate buffers. C retained mutation paths now
enforce the property; Go text props expose ReadOnly and retain focus styling
while suppressing the insertion caret. Go tests cover preedit cancellation,
buffer preservation, rejected-input expiry and fresh editing after re-enabling.
Native C and Go list boxes now register with ordinary Tab focus, expose a
visible focus presentation, and move selection with Up/Down/Home/End while
keeping the selected row visible. Disabled and higher-popup-owned lists reject
the same keys. The shared generated list fixture exercises the navigation
contract through k2c and k2go without adding backend-specific widget aliases.
Native C and Go menus share one navigation model across menu bars, standalone
popup menus, context menus, and recursive submenus. Arrow, Home, End,
Enter/Space, and Escape navigation skips separators and disabled commands,
respects the active popup owner, and does not let passive pointer hover steal
keyboard focus. The generated menu fixture exercises nested activation through
k2c and k2go. C owns a recursive snapshot of deferred overlay items, so
generated frame-local menu arrays remain valid through end-of-frame painting.
`tests/parity/drag_drop.kry` is executed through generated C and Go. A clipped
source cannot activate, and a clipped target cannot consume the release before
an eligible target. Both runners mutate the source bytes after pressing and
check that the target receives the original copied payload. This native-only
fixture is not executed by the JavaScript runner. Go runtime tests additionally
exercise drag sources and targets beneath a popup, within its input scope, and
under disabled/clip restrictions, including rejection without losing the release
or payload. Separate native C/Go tests cover active drag values, sliders,
splitters and table resizing: an owned gesture follows the pointer beyond its
original bounds, a newly opened popup preempts a background gesture, and popup
dismissal cancels the gesture before a background widget can inherit it.
The composed-popup parity fixture drives that ownership lifecycle through
generated C and native Go, while k2cpp compiles the same `.kry` source against
the C runtime surface.
`tests/parity/scroll_content.kry` is driven through generated C and Go in the
parity harness. It checks wheel-driven offset changes, visible child clicks,
rejection of clipped child clicks, and parent input restoration. The generated
Go path also checks pixels below the viewport and outside the parent of a nested
container. Both generated native paths exercise nested child clicks, thumb
dragging, and the bottom scroll limit. A second region combines a checkbox,
editable text field, and button: the native runners verify independent state,
text editing, rejection of hidden button clicks, and activation after scrolling.
This demonstrates mixed-content composition using the general scroll scope,
with selection and editing delegated to its child widgets. The mixed-content
region now uses `BeginListBox`/`EndListBox`. This fixture is not executed by the
JavaScript runner. The same native fixture opens nested tree-style `Collapsible`
headers, activates an arbitrary button child, closes the root, rejects clicks on
the hidden child, and reopens with the nested open state preserved. Callers own
child layout; `Depth` indents the header hit and drawing bounds only.
The native runners also exercise Left/Right expansion and Enter/Space toggling
while preserving nested state. Directional tests move between headers and their
parent/child, including a leaf and a disabled header that navigation must skip.
The native fixture also selects a combo popup row outside the owner's scroll
viewport while a previously drawn button occupies the same bounds. Go pixel
coverage verifies that the deferred popup paints above later content, without
inheriting the owner's scroll clip. The separate composed-combo fixture covers
arbitrary native children. Native generated dismissal checks cover Escape and outside clicks,
unchanged selection, and restoration of underlying button interaction. Go also
tests closing when the option list becomes empty.
Generated C/Go tests also check that an earlier background scroll scope does
not change its offset on wheel input over an open combo popup. Native Go unit
tests cover the same ownership rule for scroll scopes, lists, trees, source
views and tables, including disabled and clipped content.
Generated native custom-cell tests place a button and checkbox in adjacent
cells, verify independent state and no table-selection interception, and reject
an oversized button's spill into its neighboring cell. Native scope tests cover
reordered columns, frozen-row clipping, and disabled-state restoration. Cell
widgets use explicit cell bounds. A generated nested `Row` test verifies two
buttons inside a cell, clipping against the adjacent checkbox, and restoration
of a surrounding `Column` cursor. C retained nodes preserve the scope clip for
deferred hit testing and painting; explicitly positioned children do not advance
the parent layout cursor, matching Go.
An editable field in a partially visible cell is also exercised through both
generated native paths: click focus, cursor movement, text entry, disabling
without accepting text, and editing again after re-enabling. C retains disabled
scope state through deferred tree input and paint.
Table header rotation uses slanted cells. Native generated tests check the
empty header wedge, height-dependent column hit tests, separator resizing, and
body-row selection with an 80-pixel header; Go pixel coverage checks rotated
label paint and clipping to the cell polygon. C uses scanline scissors for
slanted glyph clipping, while Go clips its software rasterization directly.
`header_angle` is in degrees, clamped to -89 through 89, with
non-finite values treated as zero. `header_height` defaults to 30 and cannot
reduce the header below that height.
Native C and Go now expose the missing composed tab contract through
`BeginTabBar`, `BeginTabItem`, `EndTabItem`, and `EndTabBar`. The bar delegates
all header interaction and painting to the canonical `TabBar`; the scope only
controls arbitrary child submission, so there is no second tab renderer.
Selection changes are written to caller state before item scopes are evaluated
in the same frame. Direct C and Go tests plus generated C, Go, and JavaScript
tests switch tabs by keyboard, activate overlapping child buttons, and verify
that only the selected item's child can receive input. Invalid bars do not open
a scope, and unbalanced item or bar endings are rejected.
-274
View File
@@ -1,274 +0,0 @@
# Kryon Cartridge Format (krb) — exact specification
A `.krb` file is Kryon's compact portable cartridge: everything a renderer
needs to draw and run a UI, in one little-endian, mmapable binary. This
document is normative. An implementation that follows it can parse and
render any cartridge without kryon source code.
`k2b` rejects calls outside the portable cartridge vocabulary by default, so
a successful build never silently changes application behavior. Projects that
intentionally produce a reduced cartridge may pass `--allow-unsupported`; the
compiler still lists every omitted call kind and count on standard error.
Reference implementation: `src/krb/krb.c` (runtime), `cmd/k2b` (compiler),
`include/krb.h` (constants). Reference renderers: `src/backend/kry_sw.c`
(software), `cmd/krb-run` (headless), `cmd/krb-web` (wasm), `cmd/krb-sdl`.
## 1. Encoding rules
- All multi-byte integers are **little-endian**, packed, no alignment
padding inside records.
- Strings are UTF-8, NUL-terminated, stored once in the string table;
every string reference elsewhere is a `u16` **byte offset** into it.
- Offsets into `prog[]` are `u32` **absolute** byte offsets from the start
of the program section.
- Colors are `u32` packed `0xRRGGBBAA`. Theme references: see §4.
## 2. File layout
One linear image, sections in this exact order, no gaps:
```
offset size section
0 32 header (28 used + 4 reserved)
H 28 × node_count nodes[]
N string_bytes strings[]
S prog_bytes prog[]
P 4 × import_count imports[] (u32 string offsets each)
I 24 × control_count controls[]
```
with `H = 32`, `N = H + 28 × node_count`, `S = N + string_bytes`,
`P = S + prog_bytes`, `I = P + 4 × import_count`. A loader MUST reject the
file when `file_size < I + 24 × control_count`.
## 3. Header (32 bytes)
| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | magic | `0x0042524B` — bytes `4B 52 42 00` (`"KRB\0"`) |
| 4 | 2 | version | `1` or `2` (see §7); a loader MUST reject other values |
| 6 | 2 | flags | reserved, MUST be 0 |
| 8 | 4 | node_count | number of node records |
| 12 | 4 | string_bytes | size of string table in bytes |
| 16 | 4 | prog_bytes | size of program section |
| 20 | 4 | import_count | number of host-import name offsets |
| 24 | 4 | control_count | number of control records |
| 28 | 4 | reserved | MUST be 0 |
Additional loader requirements: `string_bytes > 0` and the byte at string
offset `0` MUST be `0x00` (the empty string lives at offset 0).
## 4. Node record (28 bytes)
| Offset | Size | Field | Type | Meaning |
|---|---|---|---|---|
| 0 | 2 | id | u16 | node id (serial number; equals record index today) |
| 2 | 2 | parent | i16 | parent node index, `-1` = root |
| 4 | 2 | name_off | u16 | string offset (name / bound state path) |
| 6 | 1 | type | u8 | node type, §4.1 |
| 7 | 1 | flags | u8 | bit flags, §4.2 |
| 8 | 2 | bind_slot | u16 | import slot or control index; `0xFFFF` = none |
| 10 | 2 | x | i16 | x coordinate (meaning per type) |
| 12 | 2 | y | i16 | y coordinate |
| 14 | 2 | w | i16 | width / radius per type |
| 16 | 2 | h | i16 | height / inner radius per type |
| 18 | 4 | color | u32 | `0xRRGGBBAA` or theme reference |
| 22 | 2 | text_off | u16 | string offset (label / asset path / format) |
| 24 | 2 | font_size | u16 | pixels; `0` renders as 16 |
| 26 | 1 | style | u8 | per-type substyle |
| 27 | 1 | pad | u8 | reserved, MUST be 0 |
### 4.1 Node types
| Value | Name | x,y / w,h meaning | Drawn as |
|---|---|---|---|
| 0 | — | reserved | — |
| 1 | BACKGROUND | w,h = size (see §8) | filled rect, the screen backdrop |
| 2 | TEXT | x,y = top-left | text, `text_off` string, `font_size` |
| 3 | RECT | x,y,w,h = bounds | filled rect |
| 4 | BUTTON | bounds | filled rect + 1px border + centered label (`text_off`); import `bind_slot` fires on press-in-bounds. `style`: 0 primary (theme button color), 1 plain (theme surface), 2 danger (`0xB83B3BFF`) |
| 5 | DATA | — | not drawn; state-field metadata |
| 6 | PICTURE | bounds | texture; `text_off` = asset path, `color` = tint, `style` = fit (0 stretch, 1 contain, 2 cover) |
| 7 | CHECKBOX | box at bounds; label at `x+w+4` | cartridge-owned toggle on mount path `name_off`; flips value on press-in-bounds |
| 8 | TOGGLE | switch at bounds; label beside | same mount behavior as CHECKBOX |
| 9 | CONTROL | bounds = widget bounds | range widget; `bind_slot` indexes controls[] |
| 10 | CIRCLE | x,y = center; w = radius | filled circle |
| 11 | RING | x,y = center; w = outer, h = inner radius | annulus |
| 12 | SCROLL | bounds = viewport; `font_size` = content height; `name_off` = mount path of pixel offset | container: children (nodes with `parent` = this index) draw translated by `-offset` and clipped to the viewport; wheel over the viewport adjusts the mounted offset (clamped to `[0, content_h - h]`) |
### 4.2 Flags
| Bit | Mask | Name | Meaning |
|---|---|---|---|
| 0–1 | `0x03` | reserved | MUST be 0 |
| 2 | `0x04` | SCALE_X | x is in UI-scale units (multiply by backend scale) |
| 3 | `0x08` | SCALE_Y | same for y |
| 4 | `0x10` | SCALE_W | same for w |
| 5 | `0x20` | SCALE_H | same for h |
### 4.3 Colors and theme slots
A node `color` whose **top bit is set** (`color & 0x80000000 != 0`) is a
theme reference: `slot = color & 0x7FFFFFFF`; the renderer asks the host
backend for the slot color. Slots: `0` background, `1` text, `2` icon,
`3` surface, `4` button; other slot values resolve to the backend default.
**Consequence (deliberate v1 constraint):** any *literal* color with a red
channel ≥ `0x80` also has the top bit set and reads as a theme reference.
Literal cartridge colors MUST keep R < `0x80`; use a theme slot for bright
reds. (A future version may move the sentinel; until then this rule is
normative.)
## 5. String table
`string_bytes` bytes of concatenated NUL-terminated UTF-8 strings. Offset 0
is the empty string (the table starts with a `0x00` byte). A string
reference is valid iff `offset < string_bytes - 1` and the byte at
`offset` begins a complete string. Paths used as mount references (e.g.
`"counter"`, `"app/score"`) are plain strings compared exactly.
## 6. Imports
`import_count` × `u32` string offsets naming host functions (today: button
handlers). A node's `bind_slot` (when `< 0xFFFF`) selects the slot; the
host binds each slot with `KrbBind`/`KrbBindSlot`. A slot with no bound
function is skipped silently.
## 7. Control record (24 bytes)
Referenced by a CONTROL node's `bind_slot`.
| Offset | Size | Field | Type | Meaning |
|---|---|---|---|---|
| 0 | 1 | kind | u8 | 1 slider, 2 vslider, 3 spinbox, 4 dropdown, 5 combobox, 6 progress, 7 radio |
| 1 | 1 | option_count | u8 | dropdown/combobox option count, 0 otherwise |
| 2 | 2 | id | u16 | widget id |
| 4 | 4 | min | i32 | range minimum |
| 8 | 4 | max | i32 | range maximum |
| 12 | 4 | step | i32 | increment |
| 16 | 2 | value_off | u16 | string offset: mount path of the value |
| 18 | 2 | label_off | u16 | string offset: label |
| 20 | 2 | options_off | u16 | reserved, 0 |
| 22 | 2 | reserved | u16 | MUST be 0 |
Slider: held-drag maps the pointer position across the track to
`[min, max]`. Spinbox: click left/right half decrements/increments by
`step`, clamped to `[min, max]`. Dropdown (`kind 4`) and combobox (`kind 5`):
`options_off` points at `option_count` consecutive NUL-terminated option
strings; the bound `int` holds the selected index. Click toggles the popup;
clicking a row writes the index and closes. Progress (`kind 6`) reads the
bound `int`, clamps it to `[min, max]`, and draws a noninteractive filled bar
with optional `label_off` text. Radio (`kind 7`) reads the bound `int`, draws
selected when it equals `id`, and writes `id` on click.
## 8. Program and execution semantics
`prog[]` is a byte stream executed in order by `KrbExec` once per frame.
Opcodes:
| Op | Byte | Operands (in order) | Semantics |
|---|---|---|---|
| `OP_DRAW_TREE` | `0x01` | — | draw every node, in record order |
| `OP_CALL_HOST` | `0x02` | u8 slot | call host function bound to slot |
| `OP_SET_I32` | `0x03` | u16 path_off, i32 value | write mounted int |
| `OP_PUSH_CONST` | `0x10` | i32 | push immediate |
| `OP_PUSH_PATH` | `0x11` | u16 path_off | push mounted int at path (unmounted → 0) |
| `OP_POP_STORE` | `0x12` | u16 path_off | pop → write mounted int at path |
| `OP_ADD` | `0x13` | — | pop b, pop a, push `a + b` |
| `OP_SUB` | `0x14` | — | push `a - b` |
| `OP_MUL` | `0x15` | — | push `a * b` |
| `OP_DIV` | `0x16` | — | push `b == 0 ? 0 : a / b` (C division) |
| `OP_EQ`/`NE`/`LT`/`LE`/`GT`/`GE` | `0x17`–`0x1C` | — | pop b, pop a, push 1 or 0 |
| `OP_JMP` | `0x1D` | u32 addr | set program counter to `addr` |
| `OP_JZ` | `0x1E` | u32 addr | pop; if 0, set program counter to `addr` |
| `OP_TIME` | `0x1F` | — | push `(int)(host time in seconds × 1000)` |
| `OP_DRAW_NODE` | `0x20` | u16 node index | draw one node |
Rules:
- The VM stack is 16-deep int32 and persists across opcodes within one
`KrbExec` pass. Push on overflow or pop on underflow is an error
(execution fails).
- Jump targets are absolute offsets into `prog[]`; a target outside
`[0, prog_bytes]` makes the jump a no-op.
- Any other opcode byte is an error; execution stops.
- Drawing: node coordinates are relative to the current draw origin
(0,0 for a full-frame pass). A SCALE_* flag replaces the raw i16 with
`backend.scale_px(value)`. When `OP_DRAW_TREE` (or `OP_DRAW_NODE` on a
BACKGROUND node) executes, a BACKGROUND node's w/h are overridden with the
host screen size and its SCALE_W/H flags cleared.
- Interaction (BUTTON, CHECKBOX, TOGGLE, CONTROL) is evaluated at draw
time: "pointer pressed this frame" AND "pointer inside the node bounds"
(post-transform). Bounds are exclusive on the right/bottom edges.
### Versions
- **v1** — opcodes `0x01`–`0x03`, node types 1–9. Render-first.
- **v2** — adds opcodes `0x10`–`0x20` and node types 10–11. Loaders accept
both; compilers should emit 2.
### Asset section (v2)
When header offset 28 (`asset_bytes`) is nonzero, an asset section follows
`controls[]`: a `u32 asset_count`, then `asset_count` directory entries of
20 bytes, then the blobs. Entry: `path_off u32@0` (string table),
`data_off u32@4` (absolute file offset), `size u32@8`, `kind u16@12`
(0 = raw RGBA8 pixels, 1 = glyph atlas), `w u16@14`, `h u16@16`,
`reserved u16@18`. `asset_bytes` counts the whole section. A PICTURE node
whose path matches an embedded raw-RGBA asset is rendered from cartridge
pixels through the backend's optional `texture_rgba` (scaled, tinted);
non-embedded paths fall back to host texture loading. The conventional
name "@atlas" carries a KFA1 glyph atlas: `u32 "KFA1" | u16 size_count`,
then per size a 16-byte record (`px u16 | glyphs u16 | w u16 | h u16 |
table_off u32 | pixels_off u32`), then per-glyph 18-byte records
(`cp u32 | x,y,w,h u16 | xoff,yoff i16 | advance u16` in 1/256-px fixed point,
offsets into the
size's RGBA8 white-on-alpha bitmap). Engines with atlas support render
antialiased text with true advances; without it they fall back to their
built-in font.
## 9. Limits (current implementation)
256 nodes, 8 KiB strings, 32 imports, 128 controls, 32 host binds,
16 mount roots, 64 fields per mount, 16 MiB cartridge (raised from
64 KiB to fit embedded atlases and images).
## 10. Host surface (what a renderer must provide)
A renderer implements the `KryBackend` table (see `include/kry_backend.h`):
`clear`, `rect`, `text`, `measure_text`, `clip_push/pop`, `mouse`,
`mouse_down`, `mouse_pressed`, `width`, `height`, `time`, `scale_px`,
`theme_color`, `texture`, and optional `circle`/`ring` (v2 geometry; a
renderer may leave them NULL, in which case CIRCLE/RING nodes are no-ops).
Colors passed to the backend are already resolved literals. Assets are
referenced by path; loading and caching are host-owned.
## 11. C memory as files (mounts)
Hosts map live memory onto string paths:
```c
KrbField fields[] = {
{ "score", offsetof(App, score), KRB_I32, 4 },
{ "label", offsetof(App, label), KRB_CSTR, 16 },
{ NULL }
};
KrbMount(&img, "/app", app, fields);
KrbReadI32(&img, "/app/score", &n);
/* or a single field: */
KrbBindMem(&img, "counter", &counter, KRB_I32, 4);
```
Field kinds: `KRB_I32 1`, `KRB_U32 2`, `KRB_F32 3`, `KRB_BOOL 4`,
`KRB_CSTR 5`. Read/write is a typed memcpy. A TEXT node whose `name_off`
string equals a mounted path renders the live value; its `text_off` string
acts as a `printf` format when it contains `%`.
## 12. Tooling
- `k2b` compiles `.kry` → `.krb` (+ optional generated C host; `--no-main`
omits the host `main`). Unsupported `.kry` calls are dropped and reported.
- `krb-run` renders headless to PNG / a recorded call stream.
- `krb-web` / `krb-sdl` are full hosts; `tests/golden` + `tests/krb_engine_test.sh`
pin cross-engine byte-identical output.
+116
View File
@@ -0,0 +1,116 @@
# Kry Language
Kry is C-close app code for Kryon. `kc` emits readable `.c` and `.h` files
that are compiled by the normal C toolchain; there is no VM, runtime package
system, or hidden ownership model.
## Style
- Small files, clear names, and plain data flow.
- Explicit module prefixes for generated C symbols.
- Direct C-compatible pointers, field access, labels, and cleanup `goto`.
- Compile-time modules only.
- Raw C escape hatches only for platform or third-party edges.
## Declarations
```kry
#module "practice.session"
#output "session_impl"
#import "app.h"
#import <stddef.h>
#import "private_dep.h" #private
#pragma "GCC diagnostic push"
SessionTimer :: struct {
elapsed: float
running: bool
}
SessionMode :: enum {
SESSION_IDLE,
SESSION_ACTIVE,
}
#enum {
SESSION_FLAG_DIRTY = 1,
}
#enum #private {
SESSION_LOCAL_FLAG = 1,
}
TickCallback :: int (*)(float) #type
LocalSize :: unsigned long #type #private
session_count :: int #global #export
local_counter :: int = 7 #global
platform_ping :: (value: int, tag: const char*) -> int #extern
platform_log :: (level: int, text: const char*, ...) -> void #extern
win_entry :: (hwnd: void*) -> int #extern #storage "__declspec(dllimport)" #abi "__stdcall"
weak_hook :: () -> void #extern #attr "__attribute__((weak))"
session_update :: (app: InbeApp*, dt: float) -> int {
if !app->session.running {
return 0
}
result := breath_step(&app->breath, dt)
if result.done {
goto done
}
done:
return 1
}
session_entry :: (app: InbeApp*) #export {
session_update(app, 0.0f)
}
```
## Rules
- `#module "name"` sets the compile-time module name and generated C symbol
prefix. Dots become underscores.
- `#output "basename"` changes only the generated file basename.
- `#import "path.h"` emits a public include in the generated header.
- `#import <system.h>` and `#import "path.h" #private` emit source-only
includes.
- `alias :: #import "module/path"` imports another Kry module and binds a
compile-time alias for qualified calls.
- `name :: (...) -> Ret { ... }` defines a function. Inside a module, the
generated C symbol is module-prefixed by default.
- `#export` keeps the exact C ABI name and emits the declaration publicly.
- `#private` keeps a function or type alias source-local.
- `#global` creates a file-level variable; add `#export` for a public `extern`.
- `#extern` declares an external C function without defining it.
- External declarations accept precise interop tags when the platform ABI needs
them: `#storage "..."` before the return type, `#abi "..."` before the
function name, and `#attr "..."` after the parameter list.
- `...` is allowed as the final parameter of an external declaration.
- `#intrinsic "web"` emits a Kryon-owned platform wrapper for supported web
operations.
- `#pragma "text"` and `#error "message"` emit guarded C preprocessor
directives for compiler and platform integration.
Kry statements are deliberately minimal — declarations, assignments, calls,
and control flow. There are no widget keywords and no bespoke sugar verbs:
- `name := expr` for inferred locals.
- `name: Type = expr` or `name: Type` for typed locals.
- `name = expr` assignments (including compound `+=`, `%=`, `&=`, ...).
- plain function calls (any call used as a statement is a draw call and is
automatically wrapped with source-inspection metadata for click-to-source).
- `if`, `else if`, `else`, `while`, `for`, `switch`, `case`, `default`,
labels, `goto`, `break`, `continue`, `guard`, and `return`.
- `c line` for raw C glue and `unused expr` to silence unused-value warnings.
Widgets are ordinary library functions (WidgetText, WidgetRect, WidgetLine,
WidgetBackground, WidgetButton) declared in `ui_widgets.h`; the compiler
treats them exactly like any other call. Input handling is plain control
flow: `if (UIKeyPressed(KEY_A)) { ... }`, `if (UIKeyDown(KEY_A)) { ... }`.
Event-style blocks (`button ... {`, `on key ... {`, `event ... {`) and
arithmetic/declaration sugar (`advance x by N`, `clamp_min`, `c_rect`,
`texture`, `set_theme`) were removed in favor of their direct equivalents.
-309
View File
@@ -1,309 +0,0 @@
# Kry Language Specification
Kry language version: `0.2`
KIR version: `0.1`
This is the stable public contract for `.kry` source accepted by Kryon tools.
Kry is intentionally C-close: expressions and types stay familiar to C, while
the frontend owns declarations, compile-time guards, UI frame structure, and
KIR emission.
The required pipeline is:
```text
.kry -> KIR -> C
.kry -> KIR -> Go
.kry -> KIR -> JS
.kry -> KIR -> KRB
```
Backends may accept `.kry` directly as a CLI convenience, but they must behave
as if the source was first lowered into KIR. Unsupported behavior must be
diagnosed or represented honestly as unsupported KIR; it must not silently
change semantics.
## Compatibility
- Patch-level language changes may add diagnostics, new KIR metadata, or new
backend support for previously rejected forms.
- A minor language version bump is required when new source syntax becomes
documented as stable.
- A major language version bump is required if valid version `0.x` source would
be interpreted differently.
- Raw statement text remains part of KIR until structured expression lowering is
complete enough for every backend that needs it.
## Lexical Model
Kry source is line-oriented with C-like tokens inside expressions. Whitespace
separates declarations and statements but is otherwise not semantic except
inside strings and raw text.
```ebnf
identifier = letter , { letter | digit | "_" } ;
string = '"' , { character | escape } , '"' ;
integer = digit , { digit | "_" | "x" | "X" | "a".."f" | "A".."F" } ,
{ "u" | "U" | "l" | "L" } ;
type-text = C-compatible type text up to a grammar delimiter ;
expr-text = C-close expression text up to a statement/block delimiter ;
raw-c-text = text after the `c` statement marker ;
```
The frontend tokenizes expressions and parses them with C operator precedence.
Full C-close expression text is still preserved for backends. Unsupported forms
remain explicit `unknown` nodes; compound initializers retain their source text.
## Top-Level Grammar
```ebnf
source = { top-level-form } ;
top-level-form = module-decl
| output-decl
| import-decl
| pragma-decl
| error-decl
| assert-decl
| const-decl
| type-decl
| enum-decl
| state-block
| app-block
| function-decl
| guarded-top-level ;
module-decl = "#module" , string ;
output-decl = "#output" , string ;
import-decl = "#import" , ( string | "<" , text , ">" ) , [ "#private" ]
| identifier , "::" , "#import" , string ;
pragma-decl = "#pragma" , string ;
error-decl = "#error" , string ;
assert-decl = "#assert" , expr-text , [ "," , string ] ;
const-decl = identifier , "::" , const-expr ;
const-expr = "#defined" , "(" , identifier , ")"
| "#run" , integer-expr
| expr-text ;
type-decl = identifier , "::" , "struct" , "{" , { field-decl } , "}"
| identifier , "::" , type-text , "#type" , [ "#private" ] ;
field-decl = identifier , ":" , type-text , [ "=" , expr-text ] ;
enum-decl = identifier , "::" , "enum" , "{" , { enum-item } , "}"
| "#enum" , [ "#private" ] , "{" , { enum-item } , "}" ;
enum-item = identifier , [ "=" , expr-text ] ;
state-block = "state" , "{" , { field-decl } , "}" ;
app-block = "app" , string , "{" , { app-property } , "}" ;
app-property = "size" , integer , integer
| "fps" , integer
| "font" , identifier
| "theme" , identifier , identifier ;
function-decl = identifier , "::" , signature , modifiers , block ;
signature = "(" , [ params ] , ")" , [ "->" , type-text ] ;
params = param , { "," , param } ;
param = identifier , ":" , type-text ;
modifiers = { "#export" | "#private" | "#global" | "#extern" ,
[ string ] | "#intrinsic" , string | "#ui" | abi-tag } ;
abi-tag = "#storage" , string | "#abi" , string | "#attr" , string ;
```
## Statement Grammar
```ebnf
block = "{" , { statement } , "}" ;
statement = local-decl
| assignment
| ui-node
| call-statement
| if-statement
| while-statement
| for-statement
| switch-statement
| guard-statement
| defer-statement
| return-statement
| jump-statement
| label-statement
| raw-c-statement
| unused-statement
| guarded-statement ;
local-decl = identifier , ":=" , expr-text
| identifier , ":" , type-text , [ "=" , expr-text ] ;
assignment = expr-text , assignment-op , expr-text ;
assignment-op = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" ;
call-statement = identifier , "(" , [ expr-text ] , ")" ;
ui-node = layout-node | widget-props-node ;
layout-node = layout-widget , identifier , [ ":" ] , "{" ,
{ ui-prop | statement } , "}" ;
widget-props-node = props-widget , [ identifier ] , [ ":" ] , "{" ,
{ ui-prop } , "}" ;
ui-prop = identifier , "=" , expr-text ;
if-statement = "if" , expr-text , block ,
{ "else" , "if" , expr-text , block } ,
[ "else" , block ] ;
while-statement = "while" , expr-text , block ;
for-statement = "for" , expr-text , block ;
switch-statement= "switch" , expr-text , "{" ,
{ "case" , expr-text , ":" , { statement } } ,
[ "default" , ":" , { statement } ] , "}" ;
guard-statement = "guard" , expr-text , block ;
defer-statement = "defer" , statement ;
return-statement= "return" , [ expr-text ] ;
jump-statement = "goto" , identifier | "break" | "continue" ;
label-statement = identifier , ":" ;
raw-c-statement = "c" , raw-c-text ;
unused-statement= "unused" , expr-text ;
```
Plain call statements are UI declarations when they call Kryon widget/runtime
functions. Property-block widgets lower to the existing `WidgetProps` C-style
call shape, so `Button { label = "Save" ... }` is equivalent to
`Button((ButtonProps){.label = "Save", ...})`. Layout nodes (`Screen`,
`Column`, `Row`, `Stack`) still open retained UI scopes and therefore emit a
matching `End()`.
## Tooling
`k2c`, `k2cpp`, `k2go`, and `k2js` accept `--strict`. This enables the shared
scalar type checker before output generation. It checks lexical bindings,
duplicate local declarations, scalar operand compatibility, assignments,
function argument counts/types, return value types, and boolean conditions.
Unresolved names, opaque expressions, and unsupported statements are errors with
source locations. Accepted non-extern functions must use the shared scalar
emitter; strict mode cannot silently fall back to backend text interpretation.
It currently excludes UI calls, raw C, `for` headers, `switch`, pointer-sized
types, and aggregate/pointer expressions. It does not yet prove that every
control-flow path returns a value. Existing app builds may omit the flag while
these areas are being migrated.
The checker also annotates known expression types in ordinary builds, without
rejecting unresolved imported C/runtime symbols. KIR dumps expose these types.
`make language-test` runs expression-tree tests and executes matching numeric
and cleanup fixtures through C, C++, Go, and JavaScript, including arithmetic
traps and negative diagnostics. See [portable scalar programming](LANGUAGE_SCALARS.md)
for the exact numeric contract and build commands.
`kryon fmt [--check] file.kry...` formats Kry source with stable indentation
and simple spacing cleanup. `--check` exits non-zero when a file would change.
`kryon locale-check source.kry... -- locales/*.txt` validates `t("key")`
references against locale files that use `[key]` blocks. It reports missing
keys, unused keys, duplicate locale keys, and non-English locale entries that
copy the English text exactly.
## Compile-Time Forms
`#defined(SYMBOL)` expands to a preprocessor-style condition. It is useful for
guards and assertions that C should preserve.
`NAME :: #run INTEGER_EXPR` folds a small integer expression while parsing Kry.
It supports integer literals, parentheses, unary `!`, unary `+`, unary `-`,
arithmetic operators, relational operators, equality operators, `&&`, and `||`.
It is not a general compile-time function system.
`#assert CONDITION, "message"` records a KIR assertion. If the assertion is
unguarded, fully known, and false, the frontend fails immediately. C lowers
assertions to `#if` and `#error`. Go, JS, and KRB currently accept only
known-true assertions and reject guarded or unresolved assertions.
## Diagnostics
Diagnostics should include file and line whenever source spans are available.
Backends must reject unsupported compile-time behavior that could alter program
meaning. TODO comments in generated output are acceptable only for explicitly
best-effort backend areas and must be covered by conformance status.
## KIR Contract
KIR records modules, imports, defines, assertions, state fields, types,
functions, statements, and expression metadata. Statement records always keep
the normalized raw source text. Expression records currently cover:
| Kind | Meaning |
|---|---|
| `ident` | Simple identifier. |
| `int` | Integer literal text. |
| `float` | Floating-point literal text. |
| `string` | String literal text. |
| `call` | Call with child argument expressions; indirect calls also retain the callee expression. |
| `binary` | Top-level binary expression with operator, left child, and right child. |
| `unary` | Prefix unary expression with operator and right child. |
| `member` | `base.field` access with base expression and field name. |
| `pointer_member` | `base->field` access with base expression and field name. |
| `index` | `base[index]` access with base and index children. |
| `compound` | C-style compound literal text preserved as one expression. |
| `sizeof` | `sizeof(...)` expression metadata. |
| `char` | Character literal. |
| `cast` | Explicit C-style cast with target type and operand. |
| `conditional` | Condition, true arm, and false arm of `a ? b : c`. |
| `postfix` | Postfix increment or decrement. |
| `unknown` | Preserved expression text that the frontend did not structure yet. |
Backends may use raw statement text while structured expression KIR grows. They
must not require a second source-language path around KIR.
Declaration statements retain binding names and declared/inferred types.
Assignment statements retain separate destination and value expression roots.
Expressions include a resolved type when the scalar checker can establish it.
An empty type means unresolved; it must not be interpreted as a concrete type.
## Lexical Cleanup
`defer expression` or `defer assignment` registers a cleanup action in its
lexical block. Registered actions run in reverse order before leaving that
block, including `return`, `break`, and `continue`. A return expression is
evaluated exactly once into a temporary before cleanup begins. Deferred
expressions read their operands at cleanup time, not registration time.
Cleanup is lowered into ordinary KIR statements before backend emission. This
gives C, C++, Go, and JS the same normal-control-flow behavior; it does not use
Go's function-scoped `defer`. Cleanup does not run after process termination,
foreign exceptions, Go panics, or JS exceptions. Exceptional unwinding is not
yet part of this language contract.
Functions using cleanup currently reject raw C, conditional preprocessing,
`goto`, labels, and `guard` (use explicit `if`/`return`). A switch case must use an explicit nested block to register
cleanup. Declarations cannot shadow names referenced by active cleanup actions;
`for` headers cannot reuse those names. These forms require further binding and
control-flow lowering and are diagnosed instead of emitting incorrect cleanup.
## Backend Conformance
| Feature | KIR | C | Go | KRB |
|---|---|---|---|---|
| `.kry -> KIR` frontend | yes | source | source | source |
| Header imports | yes | yes | partial | partial |
| Module imports | yes | yes | partial | partial |
| State block | yes | yes | yes | yes |
| Structs and type aliases | yes | yes | partial | partial |
| Tagged extern declarations | yes | yes | host interface or direct Go package call | host/capability subset |
| `#defined` guards | yes | yes | partial | partial |
| `#run` integer constants | yes | yes | yes | yes |
| `#assert` | yes | `#if/#error` | known true only | known true only |
| Locals and assignments | yes | yes | yes | partial |
| Control flow | yes | yes | partial | partial |
| `defer` | shared lexical lowering | yes | yes | lowered subset; not behaviorally verified |
| Raw C lines | yes | yes | no | no |
| Structured scalar expression emission | yes | yes | yes | metadata only |
## Known Boundaries
- C is the broadest backend and the canonical ABI path.
- Go is a declarative app subset. Tagged extern targets that contain a full Go
import path, such as `github.com/example/app.Generate`, are imported and
called directly by generated Go; short targets such as `app.Generate` remain
host-interface methods. Explicit C ABI targets such as `#extern "c.abs"`
are rejected by Go with a source diagnostic. Generated Go never uses cgo;
provide a native Go package or host implementation instead.
- KRB is a portable cartridge subset with explicit host/capability boundaries.
- `defer` is a shared KIR transform; the restrictions above apply to every target.
- Raw C lines are not portable.
- Checked scalar functions emit directly from structured KIR in C/C++/Go/JS.
App, aggregate, and other unconverted bodies still use target-specific text
lowering outside strict mode. KRB has not adopted the scalar emitter.
- Kry is not yet a full C replacement. [Implementation status](LANGUAGE_IMPLEMENTATION.md)
lists the remaining type, memory, ABI, ownership, and compile-time work.
-76
View File
@@ -1,76 +0,0 @@
# C replacement implementation status
The requested goal is a systems language that replaces application C while
continuing to transpile through KIR to C, Go, JavaScript, and other targets.
That goal is **not complete**. This file records the implemented foundation and
the remaining work; the current contract remains `KRY_LANGUAGE_SPEC.md`.
## Implemented foundation
- Token-based expression trees with C precedence, casts, conditional
expressions, indirect calls, postfix operations, and chained indexing.
- Separate assignment destinations and declaration bindings in KIR.
- Shared scalar type annotation and opt-in strict checking before emission.
- Shared lexical cleanup lowering for normal block exits, returns, loop breaks,
and loop continuation. Return values are evaluated before cleanup.
- One structured statement emitter for checked scalar C/C++/Go/JS functions:
declarations, assignments, calls, conditionals, while loops, and early exits.
- Fixed-width integer arithmetic with wrapping overflow, exact JS BigInt i64/u64,
arithmetic signed shifts, and traps for invalid division, shifts, and casts.
- Left-to-right operand/argument evaluation and lazy logical/conditional arms.
- Explicit integer narrowing, numeric/boolean casts, and JS f32 rounding.
- Executable C/C++/Go/JS numeric and cleanup parity fixtures, arithmetic trap
checks, and negative source diagnostic tests.
- Removed duplicate backend cleanup implementations and the Go cgo generator.
Explicit C ABI imports now fail in Go; native host/package bindings remain.
- JS execution of module/host call statements, scalar while/switch control flow,
and increment/decrement statements.
- Go output omits its UI runtime import when generated code does not use it.
## Remaining: complete typed KIR
- Structured aggregate types/initializers, array and slice types, pointer and
function types, complete statement trees, and structured `for` clauses.
- Binding identities, hygienic lowering, import visibility, duplicate module
diagnostics, cross-module member resolution, and control-flow return analysis.
- Type checking for all constructs, complete literal/initializer validation, and
target capability checking. Scalar integer literal range checks and Go C-ABI
rejection exist; the current strict checker remains a scalar subset.
- Backend emission exclusively from checked KIR. Scalar functions use the shared
emitter; non-scalar bodies still interpret raw text outside strict mode.
The old paths cannot be removed until those callers have been migrated.
## Remaining: numeric and memory semantics
- Extend the [scalar numeric contract](LANGUAGE_SCALARS.md) to every expression,
including complex state/global initializers, aggregate copying, and all loops.
- Complete floating-point literal validation, IEEE exceptional-value behavior,
cross-target conversion rounding, and architecture coverage. Current tests
cover scalar f32 addition and selected conversions, not full IEEE conformance.
- Fixed arrays, bounds-checked slices, pointer-sized types, layout and alignment
rules, with execution tests across targets and architectures.
## Remaining: systems programming
- Explicit unsafe scopes, pointers/arithmetic, function pointers, untagged
unions, C-compatible layouts, volatile access, and atomics.
- Checked ABI imports/exports and target capability diagnostics. Native-only
operations must fail explicitly on targets without a representation.
- Freestanding compilation without an implicit UI runtime.
## Remaining: allocation and ownership
- Allocator interfaces, arenas, buffer/handle ownership rules, and slices.
- Cleanup binding identities instead of current shadowing restrictions.
- Defined exceptional unwinding and cleanup across foreign/runtime boundaries.
## Remaining: generics, modules, and compile-time execution
- Typed specialization of generic functions and aggregate types.
- Compile-time function evaluation beyond the existing integer `#run` evaluator.
- Explicit public module interfaces and reliable dependency ordering.
- Tagged unions with exhaustive matching, `Result`, and `Option`.
Each remaining feature needs execution fixtures on every supported backend and
negative tests for targets that cannot preserve its semantics. Generating target
syntax or adding a parser node is insufficient evidence of language support.
-103
View File
@@ -1,103 +0,0 @@
# Portable scalar programming
Checked scalar functions share one KIR emitter for C, C++, native Go, and
JavaScript. This is the tested portable core of Kry, not a complete systems
language. Use `--strict` to reject source outside that core.
```kry
step :: (value: i32) -> i32 {
return value + 1
}
third :: () -> u64 {
maximum: u64 = 18446744073709551615
return maximum / 3
}
```
`step(2147483647)` returns `-2147483648` on all four targets. `third()` returns
`6148914691236517205`; JavaScript represents this result as `6148914691236517205n`.
## Types and operations
| Kry type | C/C++ representation | Go representation | JavaScript representation |
|---|---|---|---|
| `i8`, `i16`, `i32`, `i64` | corresponding `intN_t` | corresponding `intN` | Number up to 32 bits; BigInt for 64 bits |
| `u8`, `u16`, `u32`, `u64` | corresponding `uintN_t` | corresponding `uintN` | Number up to 32 bits; BigInt for 64 bits |
| `f32` | `float` | `float32` | Number rounded with `Math.fround` |
| `f64` | `double` | `float64` | Number |
| `bool` | `bool` | `bool` | Boolean |
The familiar spellings `int`, `unsigned int`, `float`, `double`, and standard
fixed-width C typedefs are recognized. Prefer explicit widths in portable code.
Pointer-sized integers and C layout-dependent types are outside this core.
- Integer addition, subtraction, multiplication, negation, and narrowing wrap
modulo the destination width. Signed results use two's-complement values.
- Division truncates toward zero. Remainder has the dividend's sign. Signed
minimum divided by `-1` returns signed minimum; its remainder is zero.
- Signed right shift extends the sign bit. Left shift wraps to the operand width.
Negative shift counts and counts at least the width trap.
- Division or remainder by zero traps: C/C++ abort, Go panics, JS throws RangeError.
- Literal values must fit their contextual type. Use an explicit cast when
narrowing is intended. Integer-to-integer casts retain the low destination bits.
- Float-to-integer casts require a value in the destination range before
truncation: `[-2^(w-1), 2^(w-1))` for signed and `[0, 2^w)` for unsigned.
NaN, infinity, and values outside that interval trap. Accepted values truncate
toward zero.
- Numeric-to-boolean casts test against zero. Boolean-to-numeric casts yield 0 or 1.
Conditions and logical operators require booleans; there is no implicit truthiness.
- JS i64/u64 callers should pass BigInt. Safe integral Numbers are accepted;
unsafe or fractional Numbers are rejected. Integer parameters normalize to
their declared width, and boolean parameters require actual Booleans.
- f32 expression results and compound updates round to f32. Full IEEE exception,
literal-range, and conversion-rounding conformance is still unfinished.
## Evaluation and cleanup
Operands and call arguments evaluate from left to right, with each value captured
before evaluating the next expression. `x + x++`, with `x = 3`, produces 6.
`&&`, `||`, and `condition ? yes : no` evaluate only the selected operands.
Compound assignment captures the destination's previous value before its right
side runs.
`defer` runs when its lexical block exits, in reverse registration order. This
includes `return`, `break`, and `continue`. A return expression is evaluated and
saved before cleanup runs. The shared KIR pass expands cleanup once, before any
target emitter; there are no separate target defer implementations.
See the [language specification](KRY_LANGUAGE_SPEC.md) for cleanup restrictions.
Arithmetic traps do not promise cleanup or foreign-stack unwinding.
## Build and verify
Save the example as `numbers.kry`, then run from the repository root:
```sh
make k2c k2cpp k2go k2js
build/linux-x86_64/bin/k2c --strict --no-main -o /tmp/numbers-c numbers.kry
build/linux-x86_64/bin/k2cpp --strict --no-main -o /tmp/numbers-cpp numbers.kry
build/linux-x86_64/bin/k2go --strict --no-main -o /tmp/numbers-go numbers.kry
build/linux-x86_64/bin/k2js --strict --no-main -o /tmp/numbers-js numbers.kry
make language-test
```
Adjust `linux-x86_64` for your host build directory. C/C++ scalar translation units
need standard headers but no UI inspection header. Pure generated Go omits its
UI runtime import. JS output still includes its module/frame runtime scaffold;
fully freestanding JS modules remain work to do.
`language-test` compiles and runs the same fixture in all four target languages.
It covers cleanup, integer overflow, 64-bit exactness, signed division and shifts,
casts, f32 rounding, evaluation order, short-circuiting, and arithmetic traps.
## Current limits
The shared emitter handles scalar parameters, locals, returns, assignments,
function calls, nested blocks, if/else, while, break, continue, and unused values.
Strict mode rejects bodies outside this set instead of using text lowering.
Non-strict app code still uses target-specific lowering for unmigrated constructs.
Complex module initializers do not yet share the scalar expression emitter.
Arrays/slices, ownership and allocators, unsafe pointers, checked C layouts and
ABI exports, atomics, generic specialization, and compile-time functions still
need implementation. Track those gaps in [implementation status](LANGUAGE_IMPLEMENTATION.md).
File diff suppressed because it is too large. Load diff
-115
View File
@@ -1,115 +0,0 @@
# Runtime Parity
Generated by `tests/runtime_parity_test.sh`. Do not edit by hand.
| Method | Native Go (`go/kryon`) | Clean C entrypoint | Status |
|---|---|---|---|
| `ArrowButton` | `(ArrowButtonProps) (bool)` | `int ArrowButton(ArrowButtonProps button);` | ok |
| `Background` | `(Color)` | `void Background(Color color);` | ok |
| `BeginCombo` | `(ComboProps) (bool)` | `int BeginCombo(ComboProps combo);` | ok |
| `BeginDisabled` | `(bool)` | `void BeginDisabled(int disabled);` | ok |
| `BeginFrame` | `()` | `void BeginFrame(void);` | ok |
| `BeginListBox` | `(ListBoxProps) (Rectangle)` | `Rectangle BeginListBox(ListBoxProps list);` | ok |
| `BeginPopup` | `(PopupProps) (bool)` | `int BeginPopup(PopupProps popup);` | ok |
| `BeginScroll` | `(Rectangle, int32, *int32) (Rectangle)` | `Rectangle BeginScroll(Rectangle bounds, int content_height, int *scroll_offset);` | ok |
| `BeginTableCell` | `(TableViewProps, int32, int32) (Rectangle)` | `Rectangle BeginTableCell(TableViewProps table, int row, int column);` | ok |
| `Bevel` | `(x, y, w, h int32, light, dark Color)` | `void Bevel(int x, int y, int w, int h, Color light, Color dark);` | ok |
| `BottomNav` | `(props BottomNavProps)` | `BottomNavResult BottomNav(BottomNavProps nav);` | ok |
| `Bullet` | `(Rectangle)` | `void Bullet(Rectangle bounds);` | ok |
| `BulletText` | `(text string, bounds Rectangle, fontSize int32, color Color)` | `void BulletText(const char *text, Rectangle bounds, int font_size, Color color);` | ok |
| `Button` | `(ButtonProps) (bool)` | `int Button(ButtonProps button);` | ok |
| `CanvasGrid` | `(bounds Rectangle, step int32, color Color)` | `void CanvasGrid(Rectangle bounds, int step, Color color);` | ok |
| `Checkbox` | `(int32, int32, int32, string, *int32) (bool)` | `int Checkbox(int id, int x, int y, const char *label, int *value);` | ok |
| `CheckboxFlags` | `(CheckboxFlagsProps) (bool)` | `int CheckboxFlags(CheckboxFlagsProps checkbox);` | ok |
| `ClosableTabBar` | `(ClosableTabBarProps) (int32)` | `int ClosableTabBar(ClosableTabBarProps bar);` | ok |
| `CloseCombo` | `()` | `void CloseCombo(void);` | ok |
| `ClosePopup` | `()` | `void ClosePopup(void);` | ok |
| `Collapsible` | `(props CollapsibleProps) (int32)` | `int Collapsible(CollapsibleProps section);` | ok |
| `ColorButton` | `(ColorButtonProps) (bool)` | `int ColorButton(ColorButtonProps button);` | ok |
| `ColorEdit3` | `(ColorEditProps) (bool)` | `int ColorEdit3(ColorEditProps edit);` | ok |
| `ColorEdit4` | `(ColorEditProps) (bool)` | `int ColorEdit4(ColorEditProps edit);` | ok |
| `ColorPicker` | `(bounds Rectangle, color *Color) (bool)` | `int ColorPicker(Rectangle bounds, Color *color);` | ok |
| `ColorPicker3` | `(ColorEditProps) (bool)` | `int ColorPicker3(ColorEditProps picker);` | ok |
| `ColorPicker4` | `(ColorEditProps) (bool)` | `int ColorPicker4(ColorEditProps picker);` | ok |
| `Column` | `(ColumnProps)` | `NodeId Column(ColumnProps props);` | ok |
| `Combobox` | `(props ComboboxProps) (bool)` | `int Combobox(ComboboxProps combo);` | ok |
| `ConfirmDialog` | `(props ConfirmDialogProps) (int32)` | `int ConfirmDialog(ConfirmDialogProps dialog);` | ok |
| `ContextMenu` | `(props ContextMenuProps) (int32)` | `int ContextMenu(ContextMenuProps menu);` | ok |
| `DragDropSource` | `(DragDropSourceProps) (bool)` | `int DragDropSource(DragDropSourceProps source);` | ok |
| `DragDropTarget` | `(DragDropTargetProps) (bool)` | `int DragDropTarget(DragDropTargetProps target);` | ok |
| `DragFloat` | `(DragFloatProps) (bool)` | `int DragFloat(DragFloatProps drag);` | ok |
| `DragFloatRange2` | `(DragFloatRange2Props) (bool)` | `int DragFloatRange2(DragFloatRange2Props drag);` | ok |
| `DragInt` | `(DragIntProps) (bool)` | `int DragInt(DragIntProps drag);` | ok |
| `DragIntRange2` | `(DragIntRange2Props) (bool)` | `int DragIntRange2(DragIntRange2Props drag);` | ok |
| `Dropdown` | `(id, x, y, w, h int32, options any, rest ...any) (bool)` | `int Dropdown(int id, int x, int y, int w, int h, const char **options, int option_count, int *selected_index);` | ok |
| `EndCombo` | `()` | `void EndCombo(void);` | ok |
| `EndDisabled` | `()` | `void EndDisabled(void);` | ok |
| `EndFrame` | `()` | `void EndFrame(void);` | ok |
| `EndListBox` | `()` | `void EndListBox(void);` | ok |
| `EndPopup` | `()` | `void EndPopup(void);` | ok |
| `EndScroll` | `()` | `void EndScroll(void);` | ok |
| `EndTableCell` | `()` | `void EndTableCell(void);` | ok |
| `Href` | `(props HrefProps) (bool)` | `int Href(HrefProps link);` | ok |
| `Icon` | `(id, x, y, size int32, iconType int32, tint Color)` | `void Icon(int id, int x, int y, int size, UIIconType icon, Color tint);` | ok |
| `IconButton` | `(props IconButtonProps) (bool)` | `int IconButton(IconButtonProps button);` | ok |
| `ImageButton` | `(ImageButtonProps) (bool)` | `int ImageButton(ImageButtonProps image);` | ok |
| `ImageWithBg` | `(ImageWithBgProps)` | `void ImageWithBg(ImageWithBgProps image);` | ok |
| `InputDouble` | `(InputDoubleProps) (bool)` | `int InputDouble(InputDoubleProps input);` | ok |
| `InputFloat` | `(InputFloatProps) (bool)` | `int InputFloat(InputFloatProps input);` | ok |
| `InputInt` | `(InputIntProps) (bool)` | `int InputInt(InputIntProps input);` | ok |
| `InvisibleButton` | `(InvisibleButtonProps) (bool)` | `int InvisibleButton(InvisibleButtonProps button);` | ok |
| `LabelFrame` | `(props LabelFrameProps)` | `void LabelFrame(LabelFrameProps frame);` | ok |
| `LabelText` | `(label, value string, bounds Rectangle, fontSize int32, color Color)` | `void LabelText(const char *label, const char *value, Rectangle bounds, int font_size, Color color);` | ok |
| `Line` | `(int32, int32, int32, int32, Color)` | `void Line(int x1, int y1, int x2, int y2, Color color);` | ok |
| `ListBox` | `(props ListBoxProps) (int32)` | `int ListBox(ListBoxProps list);` | ok |
| `MenuBar` | `(id int32, bounds Rectangle, menus []Menu, openIndex *int32) (MenuBarResult)` | `MenuBarResult MenuBar(int id, Rectangle bounds, const Menu *menus, int menu_count, int *open_index);` | ok |
| `MessageDialog` | `(props MessageDialogProps) (int32)` | `int MessageDialog(MessageDialogProps dialog);` | ok |
| `Modal` | `(title, message, cancelBtn, confirmBtn string) (int)` | `int Modal(const char *title, const char *message, const char *cancel_btn, const char *confirm_btn);` | ok |
| `MultiSelectList` | `(MultiSelectListProps) (int32)` | `int MultiSelectList(MultiSelectListProps list);` | ok |
| `Notebook` | `(props NotebookProps) (int32)` | `int Notebook(NotebookProps notebook);` | ok |
| `PanedView` | `(props PanedViewProps) (int32)` | `int PanedView(PanedViewProps panes);` | ok |
| `Paragraph` | `(spec ParagraphSpec, x int32, y *int32)` | `void Paragraph(ParagraphSpec paragraph, int x, int *y);` | ok |
| `Picture` | `(props PictureProps)` | `void Picture(PictureProps picture);` | ok |
| `PlotHistogram` | `(PlotProps)` | `void PlotHistogram(PlotProps plot);` | ok |
| `PlotLines` | `(PlotProps)` | `void PlotLines(PlotProps plot);` | ok |
| `PopupMenu` | `(id, x, y int32, items []MenuItem, itemCount int32) (int32)` | `int PopupMenu(int id, int x, int y, const MenuItem *items, int item_count);` | ok |
| `Progress` | `(ProgressBarProps)` | `void Progress(ProgressBarProps progress);` | ok |
| `Radio` | `(props RadioButtonProps) (int32)` | `int Radio(RadioButtonProps radio);` | ok |
| `Rect` | `(int32, int32, int32, int32, Color, ...Color)` | `void Rect(int x, int y, int w, int h, Color fill, Color border);` | ok |
| `Row` | `(ColumnProps)` | `NodeId Row(RowProps props);` | ok |
| `Selectable` | `(SelectableProps) (bool)` | `int Selectable(SelectableProps selectable);` | ok |
| `Separator` | `(Rectangle, int32)` | `void Separator(Rectangle bounds, int vertical);` | ok |
| `SeparatorText` | `(SeparatorTextProps)` | `void SeparatorText(SeparatorTextProps separator);` | ok |
| `Slider` | `(id, x, y, w int32, label string, min, max int32, value *int32, rest ...any) (bool)` | `int Slider(int id, int x, int y, int w, const char *label, int min, int max, int *value, const char *suffix, const char *value_text_override);` | ok |
| `SliderAngle` | `(SliderAngleProps) (bool)` | `int SliderAngle(SliderAngleProps slider);` | ok |
| `SliderFloat` | `(SliderFloatProps) (bool)` | `int SliderFloat(SliderFloatProps slider);` | ok |
| `SliderInt` | `(SliderIntProps) (bool)` | `int SliderInt(SliderIntProps slider);` | ok |
| `SmallButton` | `(ButtonProps) (bool)` | `int SmallButton(ButtonProps button);` | ok |
| `SourceView` | `(props SourceViewProps) (int32)` | `int SourceView(SourceViewProps source);` | ok |
| `Spinbox` | `(props SpinboxProps) (bool)` | `int Spinbox(SpinboxProps spinbox);` | ok |
| `Stack` | `(ColumnProps)` | `NodeId Stack(ColumnProps props);` | ok |
| `TabItemButton` | `(TabItemButtonProps) (bool)` | `int TabItemButton(TabItemButtonProps button);` | ok |
| `TableView` | `(props TableViewProps) (int32)` | `int TableView(TableViewProps table);` | ok |
| `Text` | `(TextProps)` | `void Text(TextProps text);` | ok |
| `TextArea` | `(props TextAreaProps) (bool)` | `int TextArea(TextAreaProps area);` | ok |
| `TextField` | `(TextFieldProps)` | `int TextField(TextFieldProps field);` | ok |
| `TextLines` | `(lines any, count int32, x int32, y *int32, font, lineH int32, color Color)` | `void TextLines(const char **lines, int count, int x, int *y, int font, int line_h, Color color);` | ok |
| `TitleBar` | `(title string, height int32)` | `void TitleBar(const char *title, int height);` | ok |
| `Toggle` | `(id, x, y, w, h int32, value *int32, offLabel, onLabel string) (bool)` | `int Toggle(int id, int x, int y, int w, int h, int *value, const char *off_label, const char *on_label);` | ok |
| `Toolbar` | `(props ToolbarProps) (ToolbarResult)` | `ToolbarResult Toolbar(ToolbarProps toolbar);` | ok |
| `TopNav` | `(props TopNavProps)` | `TopNavResult TopNav(TopNavProps nav);` | ok |
| `TreeView` | `(props TreeViewProps) (int32)` | `int TreeView(TreeViewProps tree);` | ok |
| `VSliderFloat` | `(SliderFloatProps) (bool)` | `int VSliderFloat(SliderFloatProps slider);` | ok |
| `VSliderInt` | `(SliderIntProps) (bool)` | `int VSliderInt(SliderIntProps slider);` | ok |
| `ValueBool` | `(prefix string, value bool, bounds Rectangle, fontSize int32, color Color)` | `void ValueBool(const char *prefix, int value, Rectangle bounds, int font_size, Color color);` | ok |
| `ValueFloat` | `(prefix string, value float32, format string, bounds Rectangle, fontSize int32, color Color)` | `void ValueFloat(const char *prefix, float value, const char *format, Rectangle bounds, int font_size, Color color);` | ok |
| `ValueInt` | `(prefix string, value int32, bounds Rectangle, fontSize int32, color Color)` | `void ValueInt(const char *prefix, int value, Rectangle bounds, int font_size, Color color);` | ok |
| `ValueUInt` | `(prefix string, value uint32, bounds Rectangle, fontSize int32, color Color)` | `void ValueUInt(const char *prefix, unsigned int value, Rectangle bounds, int font_size, Color color);` | ok |
## Generated Runtime Semantics
`tests/generated_runtime_parity_test.sh` transpiles the fixtures in `tests/parity/` through k2go, k2c, and k2js, rejects blocked generated output, drives all three generated runtimes through text editing, click-to-focus, focus traversal, selection replacement, secure clipboard copy, buttons, rows, columns, text areas, controls, list boxes, tables, and long-running text input with per-character cursor movement and Tab traversal, asserts generated Go emits renderable native frame operations without leaking secure text, renders those operations into visible pure-Go images, then diffs the final state JSON.
## Native Host Text Input
`go/kryon` tests run the native `Host` through thousands of text-input frames with cursor navigation on every typed character, Tab traversal between fields, stable frame operation counts, and bounded focus/selection bookkeeping.
-50
View File
@@ -1,50 +0,0 @@
# Widget Conformance
Kryon widgets must be tested at the runtime boundary, not only inside downstream
apps. Each widget family should have the same coverage shape:
1. Direct Go runtime tests in `go/kryon/*_test.go`.
These drive public widget APIs with `QueueTap`, `QueueText`, `QueueKey`,
focus, selection, and frame rendering. They catch native Go runtime bugs.
2. Generated runtime parity in `tests/generated_runtime_parity_test.sh`.
Fixtures in `tests/parity/*.kry` are lowered to Go, C, and JS, driven
through the same workflow, rendered where the target has a renderer in the
harness, and compared by final state JSON.
3. Backend or platform translation tests.
Backend event adapters must translate native events into the same public
input queue contracts. Example: `window_linux_test.go` verifies X11 keysyms
for printable text, Backspace, Enter, and shortcuts.
4. Performance harnesses for hot widgets.
Text input has `make perf-text-input`, which validates generated lowering and
measures retained-core C typing, backspace, selection replacement, tab
traversal, idle frames, and random-focus precision.
Required workflow coverage for editable widgets:
- click/tap focus
- focus switch between multiple fields
- printable text insertion
- Backspace and Delete
- Enter/commit
- Tab and Shift-Tab traversal
- selection replacement
- clipboard copy/cut/paste where supported
- secure text rendering does not leak plaintext
- Unicode cursor movement and deletion
- stable frame operation counts under long input
Required workflow coverage for collection widgets:
- single click selection
- double-click activation
- keyboard navigation
- scrolling
- context/right-click selection where supported
- selected item/cell rendering without unintended row or panel highlights
New widgets are not complete until their direct runtime test, generated parity
fixture or explicit unsupported note, backend event coverage where relevant, and
benchmark coverage for hot paths are present.
-5
View File
@@ -1,5 +0,0 @@
/*
Cache-Control: public, max-age=0, must-revalidate
/showcase-data.json
Cache-Control: public, max-age=0, must-revalidate
+21 -57
View File
@@ -6,69 +6,33 @@
<title>Kryon API Reference</title>
<meta name="description" content="Kryon runtime and UI API reference rendered from the canonical markdown documentation.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="icon" type="image/png" sizes="16x16" href="icons/kryon.png">
<link rel="apple-touch-icon" href="icons/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="index.html">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="api.html">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<div class="content">
<header class="hero compact">
<img class="hero-icon" src="icons/kryon.png" width="96" height="96" alt="Kryon">
<h1>API</h1>
<p class="tagline">Runtime and widget reference</p>
</header>
<main class="wrap api-reference" style="padding: 32px 20px 60px;">
<p class="section-eyebrow">Reference</p>
<h1 style="margin-top: 0; font-size: 28px; border-bottom: 1px solid var(--line); padding-bottom: 10px;">API</h1>
<p class="section-lead" style="margin-bottom: 28px;">Runtime and widget surface, rendered from the canonical <code>docs/API.md</code>.</p>
<nav class="site-nav" aria-label="Primary">
<a href="index.html">Home</a>
<a href="index.html#features">Features</a>
<a href="index.html#start">Start</a>
<a href="api.html">API</a>
</nav>
<main class="api-reference">
{{ API_BODY }}
</main>
<footer>
<div class="footer-inner">
<div class="footer-brand">
<img src="icons/proj/kryon.png" alt="Kryon" width="20" height="20">
<span>KRYON</span>
</div>
<div class="footer-cols">
<div class="footer-col">
<h4>Kryon</h4>
<ul>
<li><a href="index.html#features">Features</a></li>
<li><a href="index.html#platforms">Platforms</a></li>
<li><a href="api.html">API reference</a></li>
</ul>
</div>
<div class="footer-col">
<h4>Ecosystem</h4>
<ul>
<li><a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub ↗</a></li>
<li><a href="https://discord.gg/ep7gCWzHJD" target="_blank" rel="noopener">Discord ↗</a></li>
<li><a href="https://t.me/kryonlabs_com" target="_blank" rel="noopener">Telegram ↗</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</div>
</footer>
</main>
<footer>
<p>&copy; 2026 Kryon Labs | <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</footer>
</div>
<script src="highlight.js"></script>
</body>
</html>
-127
View File
@@ -1,127 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Benchmarks</title>
<meta name="description" content="Kryon compiler and runtime benchmark summaries generated from checked performance harnesses.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/benchmarks.html">
<meta property="og:title" content="Kryon Benchmarks">
<meta property="og:description" content="Text-input latency and lowering benchmark summaries for Kryon.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main>
<section class="doc-hero">
<p class="section-eyebrow">Runtime Evidence</p>
<h1>Benchmarks</h1>
<p class="section-lead">The text-input harnesses measure one full retained UI frame per interaction: declare, reconcile, layout, route, and update. Rendering is GPU-side and not included in headless timings.</p>
</section>
<section>
<p class="section-eyebrow">Text Input</p>
<h2>Latest Generated Results</h2>
<p>Generate this page's data with:</p>
<pre><code>make perf-text-input-site</code></pre>
<div class="table-wrap">
<table class="matrix-table" id="benchmark-table">
<thead>
<tr><th>Benchmark</th><th>Scenario</th><th>Samples</th><th>p50</th><th>p95</th><th>p99</th><th>Max</th><th>Notes</th></tr>
</thead>
<tbody>
<tr><td colspan="8">Loading <code>benchmarks.json</code>.</td></tr>
</tbody>
</table>
</div>
<p id="benchmark-meta"></p>
</section>
<section>
<p class="section-eyebrow">Contracts</p>
<h2>What The Harness Covers</h2>
<ul class="link-list">
<li><strong>Lowering:</strong> <code>perf-text-input</code> validates KIR, C, Go, JS, and KRB outputs for the same <code>.kry</code> source.</li>
<li><strong>Retained typing:</strong> <code>text_input_perf_test</code> checks repeated keystroke frames under the retained UI core.</li>
<li><strong>Precision path:</strong> <code>text_input_precision_test</code> focuses random fields, sends one character or backspace, and verifies the edited text after each frame.</li>
</ul>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="index.html">Home</a> &middot; <a href="language.html">Language</a> &middot; <a href="matrices.html">Matrices</a></p>
</div>
</footer>
<script src="highlight.js"></script>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
function fmt(v) {
return typeof v === "number" ? v.toFixed(3) + " us" : "";
}
fetch("benchmarks.json").then(function(r) {
if (!r.ok) throw new Error("missing benchmarks.json");
return r.json();
}).then(function(doc) {
var body = document.querySelector("#benchmark-table tbody");
var meta = document.getElementById("benchmark-meta");
body.innerHTML = "";
(doc.runs || []).forEach(function(run) {
var tr = document.createElement("tr");
var notes = [];
if (run.generated_contract) notes.push(run.generated_contract);
if (typeof run.mismatches === "number") notes.push("mismatches " + run.mismatches);
if (typeof run.focus_misses === "number") notes.push("focus misses " + run.focus_misses);
tr.innerHTML = "<td>" + (run.benchmark || "lowering") + "</td>" +
"<td>" + (run.scenario || run.generated_lowerings || "-") + "</td>" +
"<td>" + (run.samples || "-") + "</td>" +
"<td>" + fmt(run.p50_us) + "</td>" +
"<td>" + fmt(run.p95_us) + "</td>" +
"<td>" + fmt(run.p99_us) + "</td>" +
"<td>" + fmt(run.max_us) + "</td>" +
"<td>" + notes.join(", ") + "</td>";
body.appendChild(tr);
});
meta.textContent = doc.generated ? "Generated " + doc.generated + ". " + (doc.what || "") : "";
}).catch(function() {
var body = document.querySelector("#benchmark-table tbody");
body.innerHTML = "<tr><td colspan=\"8\">No generated benchmark data is checked in yet. Run <code>make perf-text-input-site</code> to create <code>docs/site/benchmarks.json</code>.</td></tr>";
});
})();
</script>
</body>
</html>
-149
View File
@@ -1,149 +0,0 @@
{
"generated": "2026-08-19T21:20:46.603953+00:00",
"what": "Text-input latency of the kryon retained core: one full declare/reconcile/layout/route/update frame per keystroke, so these are CPU-side microseconds - rendering is GPU-side and not included. Regenerate with: make perf-text-input-site",
"runs": [
{
"generated_lowerings": [
"kir",
"c",
"go",
"krb"
],
"generated_contract": "validated"
},
{
"runtime": "retained-core-c",
"scenario": "typing_burst",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 1.82,
"p95_us": 1.92,
"p99_us": 1.94,
"max_us": 8.62,
"mean_us": 1.73,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "backspace",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.47,
"p95_us": 0.53,
"p99_us": 0.71,
"max_us": 19.92,
"mean_us": 0.489,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "selection_replace",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.83,
"p95_us": 0.86,
"p99_us": 0.88,
"max_us": 7.3,
"mean_us": 0.835,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "tab_traversal",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.85,
"p95_us": 1.26,
"p99_us": 1.42,
"max_us": 16.5,
"mean_us": 0.897,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"scenario": "idle_frame",
"fields": 4,
"samples": 3000,
"warmup": 250,
"p50_us": 0.39,
"p95_us": 0.42,
"p99_us": 0.44,
"max_us": 0.66,
"mean_us": 0.395,
"full_frame_budget_us": 4000,
"input_budget_p99_us": 1000,
"node_delta": 0,
"mismatches": 0
},
{
"runtime": "retained-core-c",
"benchmark": "text-input-precision",
"scenario": "random_single_char",
"fields": 64,
"samples": 4000,
"warmup": 200,
"p50_us": 7.58,
"p95_us": 7.68,
"p99_us": 7.73,
"max_us": 19.89,
"mean_us": 7.524,
"chars_typed": 3734,
"backspaces": 466,
"focus_misses": 0,
"mismatches": 0,
"node_delta": 0
},
{
"runtime": "retained-core-c",
"benchmark": "text-input-precision",
"scenario": "random_single_char_long_text",
"fields": 64,
"samples": 4000,
"warmup": 200,
"p50_us": 8.29,
"p95_us": 8.44,
"p99_us": 8.58,
"max_us": 12.79,
"mean_us": 8.233,
"chars_typed": 3734,
"backspaces": 466,
"focus_misses": 0,
"mismatches": 0,
"node_delta": 0
},
{
"runtime": "retained-core-c",
"benchmark": "text-input-precision",
"scenario": "random_focus",
"fields": 64,
"samples": 4000,
"warmup": 200,
"p50_us": 7.83,
"p95_us": 7.93,
"p99_us": 7.96,
"max_us": 12.14,
"mean_us": 7.839,
"chars_typed": 0,
"backspaces": 0,
"focus_misses": 0,
"mismatches": 0,
"node_delta": 0
}
]
}
-228
View File
@@ -1,228 +0,0 @@
(function() {
var summary = document.querySelector("[data-conformance-summary]");
var pipelineBody = document.querySelector("[data-conformance-pipelines]");
var rendererBody = document.querySelector("[data-conformance-renderers]");
var rendererCheckBody = document.querySelector("[data-conformance-renderer-checks]");
var visualComparisonBody = document.querySelector("[data-conformance-visual-comparisons]");
var runtimeCheckBody = document.querySelector("[data-conformance-runtime-checks]");
var downstreamCheckBody = document.querySelector("[data-conformance-downstream-checks]");
var sourceHead = document.querySelector("[data-conformance-source-head]");
var sourceBody = document.querySelector("[data-conformance-sources]");
var search = document.querySelector("[data-conformance-search]");
var typeFilter = document.querySelector("[data-conformance-type]");
var widgetBody = document.querySelector("[data-conformance-widgets]");
if (!summary || !pipelineBody || !rendererBody || !sourceBody) {
return;
}
function escapeText(value) {
return String(value == null ? "" : value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function cell(status) {
var cls = status.status_class || "na";
var title = [status.evidence, status.scope].filter(Boolean).join(" | ");
return '<td class="' + escapeText(cls) + '" title="' + escapeText(title) + '">' +
escapeText(status.status || "unknown") + "</td>";
}
function evidence(items) {
if (Array.isArray(items)) {
return items.map(function(item) {
return "<code>" + escapeText(item) + "</code>";
}).join(", ");
}
return escapeText(items || "");
}
function renderSummary(data) {
var s = data.summary;
summary.innerHTML = [
["Sources", s.source_cases],
["Examples", s.examples],
["Parity Fixtures", s.parity_fixtures],
["Pipeline Cells", s.pipeline_cells],
["KRB RGB Visual", s.krb_rgb_visual_cases],
["KRB Byte Exact", s.krb_alpha_byte_exact_cases],
["Raylib C Capture", s.raylib_c_visual_cases + " / " + s.source_cases],
["Raylib C Gaps", s.raylib_c_visual_gaps],
["Canvas C Capture", s.web_canvas_c_visual_cases + " / " + s.source_cases],
["Canvas C Gaps", s.web_canvas_c_visual_gaps],
["Libdraw C Capture", s.libdraw_c_visual_cases + " / " + s.source_cases],
["Libdraw C Gaps", s.libdraw_c_visual_gaps],
["Exact Comparisons", s.visual_comparison_exact_rows + " / " + s.visual_comparison_rows],
["Pending Comparisons", s.visual_comparison_pending_rows],
["Renderer Cells", s.renderer_source_cells],
["Renderer OK Cells", s.renderer_source_ok_cells],
["Renderer Partial Cells", s.renderer_source_partial_cells],
["State Parity", s.semantic_parity_cases],
["Widgets Covered", s.widgets_detected + " / " + s.widgets_declared],
["Widgets Missing", s.widgets_missing]
].map(function(item) {
return '<div class="matrix-stat"><span>' + escapeText(item[0]) + "</span><strong>" + escapeText(item[1]) + "</strong></div>";
}).join("");
}
function renderPipelines(data) {
pipelineBody.innerHTML = data.pipelines.map(function(row) {
return "<tr><td><code>" + escapeText(row.id) + "</code></td><td>" + escapeText(row.label) + "</td>" +
cell(row) + "<td>" + evidence(row.evidence) + "</td></tr>";
}).join("");
}
function renderRenderers(data) {
rendererBody.innerHTML = data.renderers.map(function(row) {
return "<tr><td>" + escapeText(row.label) + "</td><td>" + escapeText(row.platform) + "</td><td>" +
escapeText(row.approach) + "</td>" + cell(row) + "<td>" + evidence(row.evidence) + "</td><td>" +
escapeText(row.scope || "") + "</td><td>" + escapeText(row.notes) + "</td></tr>";
}).join("");
}
function renderRendererChecks(data) {
renderCheckRows(rendererCheckBody, data.renderer_checks);
}
function renderVisualComparisons(data) {
if (!visualComparisonBody) {
return;
}
visualComparisonBody.innerHTML = (data.visual_comparisons || []).map(function(row) {
return "<tr><td>" + escapeText(row.label) + "</td><td>" + escapeText(row.mode) +
"</td>" + cell(row) + "<td>" + escapeText(row.compared) + " / " +
escapeText(row.source_cases) + "</td><td>" + escapeText(row.gap_cases) +
" " + escapeText(row.gap_label) + "</td><td>" + evidence(row.evidence) +
"</td><td>" + escapeText(row.scope) + "</td></tr>";
}).join("");
}
function renderCheckRows(body, rows) {
if (!body) {
return;
}
body.innerHTML = (rows || []).map(function(row) {
return "<tr><td>" + escapeText(row.label) + "</td><td><code>" +
escapeText(row.command) + "</code></td><td>" + escapeText(row.scope) + "</td></tr>";
}).join("");
}
function pipelineCells(row) {
return pipelineColumns(window.__kryonConformanceData || null).map(function(pipeline) {
var id = pipeline.id || pipeline;
return cell(row.pipelines[id] || {status: "missing", status_class: "no"});
}).join("");
}
function pipelineColumns(data) {
return data && data.pipelines
? data.pipelines
: [{id: "k2kir"}, {id: "k2c"}, {id: "k2go"}, {id: "k2js"}, {id: "k2b"}];
}
function sourceRendererColumns(data) {
return data.source_renderers || [
{id: "krb_rgb", label: "KRB RGB"},
{id: "krb_alpha", label: "KRB Alpha"},
{id: "libdraw_c", label: "Libdraw C"}
];
}
function renderSourceHead(data) {
if (!sourceHead) {
return;
}
var rendererHeaders = sourceRendererColumns(data).map(function(renderer) {
return '<th title="' + escapeText(renderer.scope || "") + '">' + escapeText(renderer.label) + "</th>";
}).join("");
var pipelineHeaders = pipelineColumns(data).map(function(pipeline) {
return "<th>" + escapeText(pipeline.id || pipeline) + "</th>";
}).join("");
window.__kryonConformanceData = data;
sourceHead.innerHTML = "<th>Source</th><th>Type</th>" + pipelineHeaders +
rendererHeaders + "<th>Widgets</th><th>State Evidence</th>";
}
function sourceRendererCells(data, row) {
var matrix = row.renderer_matrix || row.visuals || {};
return sourceRendererColumns(data).map(function(renderer) {
return cell(matrix[renderer.id] || {status: "missing", status_class: "no"});
}).join("");
}
function renderSources(data) {
var q = (search && search.value || "").trim().toLowerCase();
var type = typeFilter && typeFilter.value || "all";
var rows = data.cases.filter(function(row) {
if (type !== "all" && row.type !== type) {
return false;
}
if (!q) {
return true;
}
return (row.path + " " + row.label + " " + row.widgets.join(" ")).toLowerCase().indexOf(q) !== -1;
});
sourceBody.innerHTML = rows.map(function(row) {
var widgets = row.widgets.length ? row.widgets.map(function(widget) {
return '<span class="matrix-chip">' + escapeText(widget) + "</span>";
}).join("") : '<span class="matrix-muted">No widget calls detected</span>';
return "<tr><td><code>" + escapeText(row.path) + "</code><br><span class=\"matrix-muted\">" +
escapeText(row.label) + "</span></td><td>" + escapeText(row.type) + "</td>" +
pipelineCells(row) + sourceRendererCells(data, row) + "<td>" + widgets + "</td><td>" +
escapeText(row.semantic_evidence) + "</td></tr>";
}).join("");
}
function renderWidgets(data) {
if (!widgetBody) {
return;
}
var widgets = (data.widget_coverage || []).slice().sort(function(a, b) {
return a.status_class.localeCompare(b.status_class) ||
b.source_count - a.source_count ||
a.id.localeCompare(b.id);
});
widgetBody.innerHTML = widgets.map(function(widget) {
var sources = widget.sources.length ? widget.sources.map(function(source) {
return "<code>" + escapeText(source) + "</code>";
}).join(", ") : '<span class="matrix-muted">No .kry source</span>';
var semantic = widget.semantic_sources.length ? widget.semantic_sources.map(function(source) {
return "<code>" + escapeText(source) + "</code>";
}).join(", ") : '<span class="matrix-muted">Lowering/visual only</span>';
return "<tr><td>" + escapeText(widget.id) + "</td>" + cell(widget) +
"<td>" + escapeText(widget.source_count) + "</td><td>" + sources +
"</td><td>" + semantic + "</td></tr>";
}).join("");
}
fetch("conformance-matrix.json")
.then(function(response) {
if (!response.ok) {
throw new Error("matrix fetch failed");
}
return response.json();
})
.then(function(data) {
renderSummary(data);
renderPipelines(data);
renderRenderers(data);
renderRendererChecks(data);
renderVisualComparisons(data);
renderCheckRows(runtimeCheckBody, data.runtime_checks);
renderCheckRows(downstreamCheckBody, data.downstream_checks);
renderSourceHead(data);
renderSources(data);
renderWidgets(data);
if (search) {
search.addEventListener("input", function() { renderSources(data); });
}
if (typeFilter) {
typeFilter.addEventListener("change", function() { renderSources(data); });
}
})
.catch(function() {
summary.innerHTML = '<p class="section-lead">The generated conformance matrix could not be loaded.</p>';
});
})();
File diff suppressed because it is too large. Load diff
-141
View File
@@ -1,141 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Docs</title>
<meta name="description" content="Kryon documentation organized by language, framework, runtime, renderer, and target surface.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/docs.html">
<meta property="og:title" content="Kryon Docs">
<meta property="og:description" content="Documentation organized by language, framework, runtime, renderer, and target surface.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main id="top">
<section class="doc-hero">
<p class="section-eyebrow">Documentation</p>
<h1>Kryon docs by language and framework</h1>
<p class="section-lead">A focused map for the Kryon stack: source language, generated C, Go-facing helpers, KRB cartridges, renderer backends, and target surfaces.</p>
</section>
<section>
<div class="tabs" data-tabs>
<div class="tablist" role="tablist" aria-label="Kryon documentation sections">
<button type="button" role="tab" id="docs-tab-language" aria-selected="true" aria-controls="docs-panel-language">.kry language</button>
<button type="button" role="tab" id="docs-tab-c" aria-selected="false" aria-controls="docs-panel-c" tabindex="-1">C runtime</button>
<button type="button" role="tab" id="docs-tab-web" aria-selected="false" aria-controls="docs-panel-web" tabindex="-1">KRB artifacts</button>
<button type="button" role="tab" id="docs-tab-renderers" aria-selected="false" aria-controls="docs-panel-renderers" tabindex="-1">Renderers</button>
<button type="button" role="tab" id="docs-tab-platforms" aria-selected="false" aria-controls="docs-panel-platforms" tabindex="-1">Targets</button>
</div>
<div class="tabpanel is-active" id="docs-panel-language" role="tabpanel" aria-labelledby="docs-tab-language">
<h3>.kry language</h3>
<p>Source syntax, typed declarations, UI functions, KIR lowering, compile-time checks, and source-aware diagnostics.</p>
<ul class="link-list">
<li><strong><a href="language.html">Language reference</a></strong> — the primary .kry language documentation</li>
<li><strong><a href="live-examples.html">Live examples</a></strong> — browser-rendered example coverage</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-c" role="tabpanel" aria-labelledby="docs-tab-c" hidden>
<h3>C runtime</h3>
<p>Generated C, exported runtime symbols, widget APIs, app shell behavior, and source/runtime boundaries.</p>
<ul class="link-list">
<li><strong><a href="/api">API reference</a></strong> — generated API documentation from `docs/API.md`</li>
<li><strong><a href="matrices.html">Widget and compiler matrices</a></strong> — coverage status for UI and compiler surfaces</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-web" role="tabpanel" aria-labelledby="docs-tab-web" hidden>
<h3>KRB artifacts</h3>
<p>Portable KRB cartridges, preview tools, and runtime artifacts used by hosted builds.</p>
<ul class="link-list">
<li><strong><a href="ide.html">Playground</a></strong> — edit .kry and inspect browser output</li>
<li><strong><a href="benchmarks.html">Benchmarks</a></strong> — lowering and generated text-input performance data</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-renderers" role="tabpanel" aria-labelledby="docs-tab-renderers" hidden>
<h3>Renderers</h3>
<p>Backend capability coverage for native, browser, terminal, libdraw, KRB, and constrained host work.</p>
<ul class="link-list">
<li><strong><a href="renderers.html">Renderer matrices</a></strong> — current backend and host capability coverage</li>
<li><strong><a href="matrices.html">Feature matrices</a></strong> — language, widget, and runtime coverage</li>
</ul>
</div>
<div class="tabpanel" id="docs-panel-platforms" role="tabpanel" aria-labelledby="docs-tab-platforms" hidden>
<h3>Targets</h3>
<p>Desktop, mobile, FreeBSD, Plan 9, embedded, and microcontroller-facing runtime notes.</p>
<ul class="link-list">
<li><strong><a href="renderers.html">Renderer matrices</a></strong> — platform-specific backend capabilities</li>
<li><strong><a href="showcase.html">Showcase</a></strong> — real projects using Kryon</li>
</ul>
</div>
</div>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">Kryon source</a></p>
</div>
</footer>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
document.querySelectorAll("[data-tabs]").forEach(function(group) {
var tabs = group.querySelectorAll("[role=tab]");
tabs.forEach(function(tab) {
tab.addEventListener("click", function() {
tabs.forEach(function(t) {
var selected = t === tab;
t.setAttribute("aria-selected", selected ? "true" : "false");
t.tabIndex = selected ? 0 : -1;
});
group.querySelectorAll(".tabpanel").forEach(function(panel) {
var active = panel.id === tab.getAttribute("aria-controls");
panel.classList.toggle("is-active", active);
if (active) panel.removeAttribute("hidden");
else panel.setAttribute("hidden", "");
});
});
});
});
})();
</script>
</body>
</html>
+1 -1
View File
@@ -1,6 +1,6 @@
(function() {
var keywords = /\b(return|if|else|while|for|int|float|void|const|static|typedef|struct|enum|include|define|draw|native)\b|#\b(module|output|import|enum|global|export|private|extern|intrinsic|type)\b/g;
var types = /\b(Color|Rectangle|Texture2D|Camera2D|UIPanelFrame|Font)\b/g;
var types = /\b(Color|Rectangle|Texture2D|Camera2D|UIPanelFrame|UITextField|UILabelTextField|Font)\b/g;
var functions = /\b([A-Za-z_][A-Za-z0-9_]*)\s*(?=\()/g;
var strings = /("([^"\\]|\\.)*"|'([^'\\]|\\.)*')/g;
var comments = /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g;
-109
View File
@@ -1,109 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon Playground</title>
<meta name="description" content="Edit .kry files in the browser, compile with Kryon WASM tools, and preview the generated KRB cartridge from one place.">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body class="ide-page">
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="index.html">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="api.html">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main class="web-ide" data-kryon-web-ide>
<section class="ide-shell">
<div class="ide-toolbar">
<div>
<p class="section-eyebrow">Kryon Playground</p>
<h1>Write, compile, and preview .kry</h1>
</div>
<div class="ide-actions">
<button class="btn" type="button" data-action="load-sample">Sample</button>
<button class="btn btn-primary" type="button" data-action="compile">Run</button>
</div>
</div>
<div class="live-grid">
<aside class="ide-pane example-browser">
<div class="pane-title">
<span>Examples</span>
<span data-count>loading</span>
</div>
<div class="example-list" data-example-list></div>
</aside>
<div class="ide-pane source-pane">
<div class="pane-title">
<span data-source-title>app.kry</span>
<span data-status>Loading compiler...</span>
</div>
<textarea spellcheck="false" data-source>#import "kryon.h"
app "Kryon Web IDE" {
size 800 520
}
App :: () #ui {
Screen root: {
Background((Color){249, 246, 235, 255})
Rect(48, 42, 704, 390, (Color){255, 254, 249, 255})
Text((TextProps){.bounds={76,86,0,0}, .text="Hello from .kry", .font=Text24, .color=(Color){31,83,102,255}, .wrap=TextWrapNone})
Text((TextProps){.bounds={76,134,0,0}, .text="This page runs k2kir and k2b as WebAssembly, then renders the KRB cartridge.", .font=Text16, .color=(Color){42,59,64,255}, .wrap=TextWrapNone})
Rect(76, 188, 292, 80, (Color){35, 101, 125, 255})
Text((TextProps){.bounds={104,219,0,0}, .text="Portable preview", .font=Text20, .color=WHITE, .wrap=TextWrapNone})
Button((ButtonProps){.bounds = {76, 308, 184, 44}, .label = "Get started"})
}
}</textarea>
</div>
<div class="ide-pane preview-pane">
<div class="pane-title">
<span>KRB Preview (supported nodes)</span>
<span data-preview-status>waiting</span>
</div>
<canvas width="800" height="520" data-preview></canvas>
</div>
<div class="ide-pane artifact-pane">
<div class="artifact-tabs" role="tablist" aria-label="Generated artifacts">
<button type="button" class="is-active" data-tab="kry">.kry</button>
<button type="button" data-tab="kir">KIR</button>
<button type="button" data-tab="c">C</button>
<button type="button" data-tab="go">Go</button>
<button type="button" data-tab="js">JS</button>
<button type="button" data-tab="krb">KRB</button>
</div>
<pre class="artifact-output"><code data-artifact></code></pre>
</div>
</div>
</section>
</main>
<script src="ide-tools/k2kir.js"></script>
<script src="ide-tools/k2b.js"></script>
<script src="ide-tools/k2c.js"></script>
<script src="ide-tools/k2go.js"></script>
<script src="ide-tools/k2js.js"></script>
<script src="ide.js"></script>
</body>
</html>
-528
View File
@@ -1,528 +0,0 @@
(function() {
"use strict";
var source = document.querySelector("[data-source]");
var sourceTitle = document.querySelector("[data-source-title]");
var status = document.querySelector("[data-status]");
var previewStatus = document.querySelector("[data-preview-status]");
var canvas = document.querySelector("[data-preview]");
var artifact = document.querySelector("[data-artifact]");
var tabButtons = Array.prototype.slice.call(document.querySelectorAll("[data-tab]"));
var compileButton = document.querySelector("[data-action='compile']");
var sampleButton = document.querySelector("[data-action='load-sample']");
var list = document.querySelector("[data-example-list]");
var count = document.querySelector("[data-count]");
var menuToggle = document.querySelector(".menu-toggle");
var headerNav = document.getElementById("header-nav");
var k2kirMod = null;
var k2bMod = null;
var k2cMod = null;
var k2goMod = null;
var k2jsMod = null;
var activeTab = "kry";
var items = [];
var current = null;
var last = { kry: "", kir: "", krb: "", c: "", go: "", js: "", bytes: null };
var compileTimer = 0;
var sample = [
"#import \"kryon.h\"",
"",
"app \"Kryon Web IDE\" {",
" size 800 520",
"}",
"",
"App :: () #ui {",
" Screen root: {",
" Background((Color){249, 246, 235, 255})",
" Rect(48, 42, 704, 390, (Color){255, 254, 249, 255})",
" Text(\"Hello from .kry\", 76, 86, Text24, (Color){31, 83, 102, 255})",
" Text(\"This page runs k2kir and k2b as WebAssembly, then renders the KRB cartridge.\", 76, 134, Text16, (Color){42, 59, 64, 255})",
" Rect(76, 188, 292, 80, (Color){35, 101, 125, 255})",
" Text(\"Portable preview\", 104, 219, Text20, WHITE)",
" Button((ButtonProps){.bounds = {76, 308, 184, 44}, .label = \"Get started\"})",
" }",
"}"
].join("\n");
source.value = sample;
if (menuToggle && headerNav) {
menuToggle.addEventListener("click", function() {
var open = headerNav.classList.toggle("is-open");
menuToggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
function setStatus(text) {
if (status) status.textContent = text;
}
function setPreviewStatus(text) {
if (previewStatus) previewStatus.textContent = text;
}
function ensureDir(mod, path) {
var parts = path.split("/");
var cur = "";
for (var i = 0; i < parts.length; i++) {
if (!parts[i]) continue;
cur += "/" + parts[i];
try {
mod.FS.mkdir(cur);
} catch (e) {
if (!String(e).match(/File exists|ErrnoError/)) throw e;
}
}
}
function resetFs(mod) {
["/work", "/work/src", "/work/out"].forEach(function(path) {
try { mod.FS.rmdir(path); } catch (e) {}
});
ensureDir(mod, "/work/src");
ensureDir(mod, "/work/out");
}
function runTool(mod, args, reader) {
var rc;
if (!mod) return { ok: false, text: "Compiler module unavailable." };
try {
resetFs(mod);
mod.FS.writeFile("/work/src/app.kry", source.value);
rc = mod.callMain(args);
if (rc && rc !== 0) throw new Error("compiler exited with " + rc);
return reader(mod);
} catch (e) {
return { ok: false, text: String(e && e.stack ? e.stack : e) };
}
}
function readMaybe(mod, path, binary) {
try {
return mod.FS.readFile(path, binary ? { encoding: "binary" } : { encoding: "utf8" });
} catch (e) {
return binary ? new Uint8Array(0) : "";
}
}
function readFirst(mod, paths, binary) {
for (var i = 0; i < paths.length; i++) {
var value = readMaybe(mod, paths[i], binary);
if (binary ? value.length > 0 : value !== "") return value;
}
return binary ? new Uint8Array(0) : "";
}
function hex(bytes) {
var out = [];
for (var i = 0; i < bytes.length; i += 16) {
var line = ("00000000" + i.toString(16)).slice(-8) + " ";
for (var j = 0; j < 16; j++) {
line += i + j < bytes.length ? ("0" + bytes[i + j].toString(16)).slice(-2) + " " : " ";
}
out.push(line);
}
return out.join("\n");
}
function readU16(dv, off) {
return dv.getUint16(off, true);
}
function readI16(dv, off) {
return dv.getInt16(off, true);
}
function readU32(dv, off) {
return dv.getUint32(off, true);
}
function cstr(bytes, off, max) {
var end = off;
while (end < max && bytes[end] !== 0) end++;
return new TextDecoder().decode(bytes.slice(off, end));
}
function rgba(u32) {
if ((u32 & 0xffffff00) === 0x80000000) {
var slot = u32 & 0xff;
if (slot === 0) return "rgb(247,244,236)";
if (slot === 1) return "rgb(42,59,64)";
if (slot === 2) return "rgb(31,83,102)";
if (slot === 3) return "rgb(255,254,249)";
if (slot === 4) return "rgb(35,101,125)";
return "rgb(247,244,236)";
}
return "rgba(" + ((u32 >> 24) & 255) + "," + ((u32 >> 16) & 255) + "," + ((u32 >> 8) & 255) + "," + ((u32 & 255) / 255).toFixed(3) + ")";
}
function appSize() {
var m = source.value.match(/\bapp\b[\s\S]*?\{[\s\S]*?\bsize\s+([0-9]+)\s+([0-9]+)/);
var w = m ? parseInt(m[1], 10) : 800;
var h = m ? parseInt(m[2], 10) : 520;
if (!isFinite(w) || w <= 0) w = 800;
if (!isFinite(h) || h <= 0) h = 520;
return { width: Math.min(w, 4096), height: Math.min(h, 4096) };
}
function decodeKrb(bytes) {
if (!bytes || bytes.length < 32) throw new Error("KRB is empty");
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (readU32(dv, 0) !== 0x0042524b) throw new Error("KRB magic mismatch");
var nodeCount = readU32(dv, 8);
var stringBytes = readU32(dv, 12);
var nodeOff = 32;
var strOff = nodeOff + nodeCount * 28;
var nodes = [];
for (var i = 0; i < nodeCount; i++) {
var off = nodeOff + i * 28;
nodes.push({
id: readU16(dv, off),
parent: readI16(dv, off + 2),
name: cstr(bytes, strOff + readU16(dv, off + 4), strOff + stringBytes),
type: bytes[off + 6],
flags: bytes[off + 7],
bind: readU16(dv, off + 8),
x: readI16(dv, off + 10),
y: readI16(dv, off + 12),
w: readI16(dv, off + 14),
h: readI16(dv, off + 16),
color: readU32(dv, off + 18),
text: cstr(bytes, strOff + readU16(dv, off + 22), strOff + stringBytes),
font: readU16(dv, off + 24) || 16,
style: bytes[off + 26]
});
}
return nodes;
}
function coord(v, full, scaled) {
return scaled ? Math.round(full * v / 10000) : v;
}
function drawRound(ctx, x, y, w, h, r) {
r = Math.max(0, Math.min(r, w / 2, h / 2));
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function fitCanvas(size) {
if (canvas.width !== size.width) canvas.width = size.width;
if (canvas.height !== size.height) canvas.height = size.height;
canvas.style.aspectRatio = size.width + " / " + size.height;
canvas.style.setProperty("--preview-aspect", String(size.width / size.height));
}
function drawText(ctx, text, x, y, font, color) {
ctx.fillStyle = color;
ctx.font = "600 " + Math.max(8, font) + "px system-ui, -apple-system, sans-serif";
ctx.textBaseline = "top";
ctx.fillText(text || "", x, y);
}
function drawButton(ctx, n, x, y, w, h) {
var fill = n.style === 2 ? "rgb(184,59,59)" : (n.style === 0 ? "rgb(35,101,125)" : "rgb(255,254,249)");
var label = n.style === 0 || n.style === 2 ? "rgb(255,255,255)" : "rgb(42,59,64)";
ctx.fillStyle = fill;
drawRound(ctx, x, y, w, h, 4);
ctx.fill();
ctx.strokeStyle = "rgba(31,83,102,0.55)";
ctx.lineWidth = 1;
ctx.stroke();
ctx.font = "700 " + Math.max(8, n.font || 16) + "px system-ui, -apple-system, sans-serif";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = label;
ctx.fillText(n.text || n.name || "Button", x + w / 2, y + h / 2);
ctx.textAlign = "start";
ctx.textBaseline = "top";
}
function render(bytes) {
var size = appSize();
var nodes = decodeKrb(bytes);
var ctx = canvas.getContext("2d");
fitCanvas(size);
ctx.clearRect(0, 0, size.width, size.height);
ctx.fillStyle = "#f3f1ea";
ctx.fillRect(0, 0, size.width, size.height);
nodes.forEach(function(n) {
var x = coord(n.x, size.width, n.flags & 4);
var y = coord(n.y, size.height, n.flags & 8);
var w = coord(n.w, size.width, n.flags & 16);
var h = coord(n.h, size.height, n.flags & 32);
var color = rgba(n.color);
switch (n.type) {
case 1:
ctx.fillStyle = color;
ctx.fillRect(0, 0, w || size.width, h || size.height);
break;
case 2:
drawText(ctx, n.text, x, y, n.font || 16, color);
break;
case 3:
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
break;
case 4:
drawButton(ctx, n, x, y, w, h);
break;
case 7:
case 8:
case 13:
ctx.fillStyle = "rgb(255,254,249)";
ctx.fillRect(x, y, w, h);
ctx.strokeStyle = "rgba(31,83,102,0.55)";
ctx.strokeRect(x, y, w, h);
if (n.text) drawText(ctx, n.text, x + w + 6, y, n.font || 16, color);
break;
case 10:
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, Math.max(0, w), 0, Math.PI * 2);
ctx.fill();
break;
case 11:
ctx.strokeStyle = color;
ctx.lineWidth = Math.max(1, w - Math.max(0, h));
ctx.beginPath();
ctx.arc(x, y, Math.max(0, (w + h) / 2), 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 1;
break;
default:
break;
}
});
setPreviewStatus("canvas backend");
}
function showArtifact() {
artifact.textContent = last[activeTab] || "";
}
function compile() {
var passed = 0;
var failed = 0;
var result;
if (!k2kirMod || !k2bMod) return;
setStatus("compiling...");
last = { kry: source.value, kir: "", krb: "", c: "", go: "", js: "", bytes: null };
result = runTool(k2kirMod, ["--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/app.kir", "/work/out/src/app.kir"], false) };
});
if (result.ok && result.text) { last.kir = result.text; passed++; } else { last.kir = result.text || "KIR output unavailable."; failed++; }
result = runTool(k2cMod, ["--no-main", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
var files = [];
var appC = readFirst(mod, ["/work/out/src/app.c", "/work/out/app.c"], false);
var appH = readFirst(mod, ["/work/out/src/app.h", "/work/out/app.h"], false);
var projectC = readMaybe(mod, "/work/out/kryon_project.c", false);
if (appC) files.push("/* app.c */\n" + appC);
if (appH) files.push("/* app.h */\n" + appH);
if (projectC) files.push("/* kryon_project.c */\n" + projectC);
return { ok: files.length > 0, text: files.join("\n\n") || "C output unavailable." };
});
if (result.ok) { last.c = result.text; passed++; } else { last.c = result.text; failed++; }
result = runTool(k2goMod, ["--no-main", "--pkg", "kryexample", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/app.go", "/work/out/src/app.go"], false) };
});
if (result.ok && result.text) { last.go = result.text; passed++; } else { last.go = result.text || "Go output unavailable."; failed++; }
result = runTool(k2jsMod, ["--no-main", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
return { ok: true, text: readFirst(mod, ["/work/out/app.js", "/work/out/src/app.js"], false) };
});
if (result.ok && result.text) { last.js = result.text; passed++; } else { last.js = result.text || "JS output unavailable."; failed++; }
result = runTool(k2bMod, ["--allow-unsupported", "--no-main", "--root", "/work", "-o", "/work/out", "/work/src/app.kry"], function(mod) {
var bytes = readFirst(mod, ["/work/out/app.krb", "/work/out/src/app.krb"], true);
return { ok: bytes.length > 0, bytes: bytes, text: "KRB bytes: " + bytes.length + "\n\n" + hex(bytes) };
});
if (result.ok) {
last.bytes = result.bytes;
last.krb = result.text;
passed++;
try {
render(last.bytes);
if (current) setPreviewStatus("best-effort KRB subset");
} catch (e) {
setPreviewStatus(String(e && e.message ? e.message : e).slice(0, 80));
failed++;
}
} else {
last.krb = result.text || "KRB output unavailable.";
setPreviewStatus("no KRB preview");
failed++;
}
showArtifact();
setStatus(failed ? "compiled " + passed + "/5" : "compiled");
}
function scheduleCompile() {
window.clearTimeout(compileTimer);
compileTimer = window.setTimeout(compile, 260);
}
function markSelection(path) {
Array.prototype.slice.call(list.querySelectorAll("button")).forEach(function(btn) {
btn.classList.toggle("is-active", btn.getAttribute("data-path") === path);
});
}
function setScratch() {
current = null;
source.value = sample;
if (sourceTitle) sourceTitle.textContent = "app.kry";
markSelection("scratch");
if (window.history && window.history.replaceState)
window.history.replaceState({}, "", window.location.pathname);
}
function selectItem(item) {
current = item;
if (sourceTitle) sourceTitle.textContent = item.path;
markSelection(item.path);
setStatus("fetching source...");
if (window.history && window.history.replaceState)
window.history.replaceState({}, "", window.location.pathname + "?example=" + encodeURIComponent(item.id));
return fetch(item.url).then(function(res) {
if (!res.ok) throw new Error("Could not fetch " + item.url + ": " + res.status);
return res.text();
}).then(function(text) {
source.value = text;
});
}
function renderList() {
var heading = document.createElement("div");
var scratch = document.createElement("button");
list.innerHTML = "";
heading.className = "example-group";
heading.textContent = "Playground";
list.appendChild(heading);
scratch.type = "button";
scratch.textContent = "Scratch";
scratch.setAttribute("data-path", "scratch");
scratch.addEventListener("click", function() {
setScratch();
compile();
});
list.appendChild(scratch);
heading = document.createElement("div");
heading.className = "example-group";
heading.textContent = "Examples";
list.appendChild(heading);
items.forEach(function(item) {
var btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.title;
btn.setAttribute("data-path", item.path);
btn.addEventListener("click", function() {
selectItem(item).then(compile).catch(function(err) {
setStatus("source unavailable");
artifact.textContent = String(err);
});
});
list.appendChild(btn);
});
if (count) count.textContent = String(items.length);
}
function loadManifest() {
return fetch("examples-manifest.json").then(function(res) {
if (!res.ok) throw new Error("Could not load examples: " + res.status);
return res.json();
}).then(function(data) {
items = data.items || [];
renderList();
});
}
function loadInitialSource() {
var params = new URLSearchParams(window.location.search);
var wanted = params.get("example");
var src = params.get("src");
var item;
if (wanted) {
item = items.filter(function(entry) {
return entry.id === wanted || entry.path === wanted || entry.name === wanted;
})[0];
if (item) return selectItem(item);
}
if (!src) {
setScratch();
return Promise.resolve();
}
setStatus("fetching source...");
return fetch(src).then(function(res) {
if (!res.ok) throw new Error("Could not fetch " + src + ": " + res.status);
return res.text();
}).then(function(text) {
source.value = text;
}).catch(function(err) {
source.value = sample;
artifact.textContent = String(err);
});
}
function boot() {
if (typeof createK2irModule !== "function" || typeof createK2bModule !== "function" ||
typeof createK2cModule !== "function" || typeof createK2gModule !== "function" ||
typeof createK2jsModule !== "function") {
setStatus("compiler unavailable");
artifact.textContent = "The web compiler assets were not built.";
return;
}
Promise.all([
createK2irModule({ noInitialRun: true }),
createK2bModule({ noInitialRun: true }),
createK2cModule({ noInitialRun: true }),
createK2gModule({ noInitialRun: true }),
createK2jsModule({ noInitialRun: true }),
loadManifest()
]).then(function(mods) {
k2kirMod = mods[0];
k2bMod = mods[1];
k2cMod = mods[2];
k2goMod = mods[3];
k2jsMod = mods[4];
return loadInitialSource();
}).then(function() {
setStatus("ready");
compile();
}).catch(function(err) {
setStatus("error");
artifact.textContent = String(err && err.stack ? err.stack : err);
});
}
tabButtons.forEach(function(btn) {
btn.addEventListener("click", function() {
activeTab = btn.getAttribute("data-tab");
tabButtons.forEach(function(b) { b.classList.toggle("is-active", b === btn); });
showArtifact();
});
});
source.addEventListener("input", scheduleCompile);
compileButton.addEventListener("click", compile);
sampleButton.addEventListener("click", function() {
setScratch();
compile();
});
boot();
})();
+157 -155
View File
@@ -3,176 +3,178 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kryon</title>
<meta name="description" content="Kryon is a language, runtime, and native UI framework for small app development.">
<title>Kryon - Native Cross-Platform App and Game Development</title>
<meta name="description" content="Native cross-platform app and game development with .kry, human-readable C99 output, a full native widget toolkit, and an interactive AI-native IDE.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/">
<meta property="og:title" content="Kryon">
<meta property="og:description" content="A language, runtime, and native UI framework for small app development.">
<meta property="og:title" content="Kryon - Native Cross-Platform App and Game Development">
<meta property="og:description" content="Native cross-platform app and game development with .kry, human-readable C99 output, a full native widget toolkit, and an interactive AI-native IDE.">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://kryonlabs.com/">
<meta name="twitter:title" content="Kryon">
<meta name="twitter:description" content="A language, runtime, and native UI framework for small app development.">
<meta name="twitter:title" content="Kryon - Native Cross-Platform App and Game Development">
<meta name="twitter:description" content="Native cross-platform app and game development in .kry with readable C99 output.">
<meta name="twitter:site" content="@kryonlabs">
<meta name="twitter:creator" content="@kryonlabs">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="icon" type="image/png" sizes="16x16" href="icons/kryon.png">
<link rel="apple-touch-icon" href="icons/kryon.png">
<link rel="stylesheet" href="styles.css">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "SoftwareApplication",
"name": "Kryon",
"description": "Native declarative UI and app runtime. Write .kry, inspect KIR, ship readable C99 or portable KRB cartridges.",
"url": "https://kryonlabs.com",
"applicationCategory": "DeveloperApplication",
"operatingSystem": "Linux, Windows, macOS, Android, Browser, FreeBSD",
"offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"},
"author": {"@type": "Organization", "name": "Kryon Labs", "url": "https://kryonlabs.com"}
}
</script>
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
<a class="btn btn-primary" href="ide.html">Playground</a>
</nav>
</div>
</header>
<div class="content">
<header class="hero">
<img class="hero-icon" src="icons/kryon.png" width="128" height="128" alt="Kryon">
<h1>KRYON</h1>
<p class="tagline">Native cross-platform app and game development</p>
<p class="tagline-detail">Write .kry &bull; Translate to readable C99 &bull; Build visually with an AI-native IDE</p>
</header>
<main id="top">
<section class="hero lab-hero">
<div class="hero-inner">
<span class="hero-eyebrow"><span class="dot"></span>Language and native UI framework</span>
<img class="hero-icon" src="icons/proj/kryon.png" width="84" height="84" alt="Kryon">
<h1>Kryon</h1>
<p class="hero-sub">A compact app language, runtime, and renderer stack for building small native interfaces across desktop, web, and embedded targets.</p>
<div class="hero-cta">
<a class="btn btn-primary" href="docs.html">Read docs</a>
<a class="btn" href="showcase.html">Open showcase</a>
<nav class="site-nav" aria-label="Primary">
<a href="#about">About</a>
<a href="#goals">Goals</a>
<a href="#features">Features</a>
<a href="#philosophy">Philosophy</a>
<a href="#platforms">Platforms</a>
<a href="#start">Start</a>
<a href="api.html">API</a>
</nav>
<main>
<section id="about">
<h2>What is Kryon?</h2>
<p>Kryon is a native app and game development stack built around .kry source files, a small runtime, and clean translation to human-readable C99.</p>
<p>The Kryon IDE is built around the same source model: open a project or file path, edit .kry directly, see a live preview, and click a widget to jump back to the source line that generated it.</p>
</section>
<section id="goals">
<h2>Goals</h2>
<div class="goal-list">
<article class="goal">
<h3>Native Cross-Platform</h3>
<p>One source model for desktop, mobile, browser, and embedded targets, with platform behavior exposed as first-class Kryon features.</p>
</article>
<article class="goal">
<h3>Readable C99</h3>
<p>.kry translates to plain, inspectable C99 that can be built, debugged, and shipped by normal C toolchains.</p>
</article>
<article class="goal">
<h3>Full Native UI</h3>
<p>The widget toolkit should cover real product interfaces: layout, text, inputs, navigation, overlays, inspection, themes, and runtime assets.</p>
</article>
<article class="goal">
<h3>AI-Native IDE</h3>
<p>The IDE should make visual app and game development direct: live preview, source-aware inspection, diagnostics, and agent-assisted edits in one loop.</p>
</article>
</div>
</div>
</section>
</section>
<section class="replaces">
<div class="label">Development surface</div>
<div class="pills">
<span class="pill">.kry language</span>
<span class="pill">C runtime</span>
<span class="pill">KIR</span>
<span class="pill">KRB cartridges</span>
<span class="pill">renderer backends</span>
<span class="pill">app storage</span>
</div>
</section>
<section id="framework">
<p class="section-eyebrow">Framework</p>
<h2>Language, runtime, renderers</h2>
<p class="section-lead">Kryon keeps app code small while still exposing the lower-level surfaces needed for serious native development.</p>
<div class="why-grid">
<article class="why-card">
<h3><a href="language.html">Language</a></h3>
<p>Write declarative .kry interfaces, compile through KIR, and generate C, JavaScript, or portable runtime artifacts.</p>
</article>
<article class="why-card">
<h3><a href="docs.html">Framework docs</a></h3>
<p>Use the C runtime, app shell, storage, update, assets, windows, markdown, and automation APIs from one organized reference.</p>
</article>
<article class="why-card">
<h3><a href="renderers.html">Renderer backends</a></h3>
<p>Target raylib, Canvas, DOM, terminal cells, libdraw, and headless test backends from the same UI model.</p>
</article>
</div>
</section>
<section id="showcase">
<p class="section-eyebrow">Showcase</p>
<h2>Apps built with Kryon</h2>
<p class="section-lead">The homepage stays focused on Kryon itself. The showcase page is where first-party and community apps can be browsed with real screenshots and GitHub stars.</p>
<div class="hero-cta">
<a class="btn btn-primary" href="showcase.html">Browse showcase</a>
<a class="btn" href="https://github.com/kryonlabs/showcase/pulls/new?template=PULL_REQUEST_TEMPLATE.md" target="_blank" rel="noopener">Submit pull request</a>
</div>
</section>
<section id="links">
<p class="section-eyebrow">Development</p>
<h2>Source, docs, and related systems</h2>
<ul class="link-list">
<li><strong><a href="/api">API reference</a></strong> - generated C API documentation</li>
<li><strong><a href="ide.html">Playground</a></strong> - browser tools for trying Kryon source and artifacts</li>
<li><strong><a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">Kryon source</a></strong> - compiler, runtime, docs, and release history</li>
<li><strong><a href="https://daochi.net" target="_blank" rel="noopener">Daochi</a></strong> - independent sync project used by apps that opt into it</li>
</ul>
</section>
</main>
<footer>
<div class="footer-inner">
<div class="footer-brand">
<img src="icons/proj/kryon.png" alt="Kryon Labs" width="20" height="20">
<span>KRYON</span>
</div>
<div class="footer-cols">
<div class="footer-col">
<h4>Related</h4>
<ul>
<li><a href="https://daochi.net">Daochi</a></li>
<li><a href="https://taijios.net">TaijiOS</a></li>
<li><a href="https://krait.kryonlabs.com">Krait</a></li>
</ul>
<section id="features">
<h2>Core Features</h2>
<div class="grid">
<article class="feature">
<img src="icons/text.png" width="48" height="48" alt="">
<h3>Widget-Focused .kry</h3>
<p>Pages and reusable widgets stay in concise source files with explicit typed variables and direct compiler errors for unknown syntax.</p>
</article>
<article class="feature">
<img src="icons/c.png" width="48" height="48" alt="">
<h3>Clean C Output</h3>
<p>The compiler emits normal C and generated headers. Kry-to-Kry calls use compile-time modules, while C interop stays explicit.</p>
</article>
<article class="feature">
<img src="icons/globe.png" width="48" height="48" alt="">
<h3>Live Preview</h3>
<p>Hot reload rebuilds real .kry output, keeps the last good state during compilation, and shows diagnostics when the build fails.</p>
</article>
<article class="feature">
<img src="icons/wrench.png" width="48" height="48" alt="">
<h3>Source-Aware Inspection</h3>
<p>Preview widgets carry source metadata, so inspection clicks select the generated UI element and open the exact .kry line.</p>
</article>
</div>
<div class="footer-col">
<h4>Kryon</h4>
<ul>
<li><a href="docs.html">Docs</a></li>
<li><a href="language.html">Language</a></li>
<li><a href="matrices.html">Matrices</a></li>
<li><a href="renderers.html">Renderers</a></li>
<li><a href="/api">API reference</a></li>
</ul>
</div>
<div class="footer-col">
<h4>Community</h4>
<ul>
<li><a href="showcase.html">Showcase</a></li>
<li><a href="https://github.com/kryonlabs" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://t.me/kryonlabs_com" target="_blank" rel="noopener">Telegram</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</div>
</footer>
</section>
<section id="philosophy">
<h2>Philosophy</h2>
<ul class="philosophy-list">
<li><strong>Everything visible is a widget</strong> - source, bounds, state, and inspection all belong to the widget tree.</li>
<li><strong>Source stays primary</strong> - .kry files own screens and reusable UI pieces; C is the generated interop target.</li>
<li><strong>The IDE is source-aware</strong> - file browser, source editor, live preview, inspector, diagnostics, and search stay tied to .kry files.</li>
<li><strong>Default private API</strong> - only exported functions enter generated headers, keeping build boundaries small.</li>
<li><strong>Native first</strong> - direct C, raylib-style calls, and predictable runtime behavior across targets.</li>
</ul>
</section>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
<section id="platforms">
<h2>Platforms</h2>
<p>Kryon targets the same interface source at the environments apps actually ship to.</p>
<div class="platform-grid">
<article class="platform">
<img src="platforms/tux.png" width="32" height="32" alt="">
<h3>Linux</h3>
<p>Native desktop builds.</p>
</article>
<article class="platform">
<img src="platforms/win.png" width="32" height="32" alt="">
<h3>Windows</h3>
<p>Native desktop and WinINet assets.</p>
</article>
<article class="platform">
<img src="platforms/macos.png" width="32" height="32" alt="">
<h3>macOS</h3>
<p>Native desktop builds.</p>
</article>
<article class="platform">
<img src="platforms/droid.png" width="32" height="32" alt="">
<h3>Android</h3>
<p>Mobile runtime support.</p>
</article>
<article class="platform">
<img src="language/wasm.png" width="32" height="32" alt="">
<h3>Browser</h3>
<p>WebAssembly runtime and previews.</p>
</article>
<article class="platform">
<img src="platforms/freebsd.png" width="32" height="32" alt="">
<h3>FreeBSD</h3>
<p>Native desktop and embedded targets.</p>
</article>
</div>
</section>
})();
</script>
<section id="start">
<h2>Get Started</h2>
<p>Build the runtime and tools:</p>
<pre><code>git clone https://github.com/kryonlabs/kryon.git
cd kryon
make
make install</code></pre>
<p>A simple .kry shape:</p>
<pre><code>#import "kryon.h"
AppHome :: (app: InbeApp*) {
y: int = ScaleUIPx(24)
WidgetText("Inner Breeze", ScaleUIPx(20), y, UI_TEXT_24, GetThemeText())
app_draw_bottom_nav(app)
}</code></pre>
<p>Open a project or a single .kry file in the IDE:</p>
<pre><code>kryon .
kryon path/to/app.kry</code></pre>
</section>
<section id="docs">
<h2>Documentation</h2>
<ul class="link-list">
<li><a href="api.html">API reference</a> - runtime and widget surface</li>
<li><a href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">Source repository</a> - code, issues, and releases</li>
</ul>
</section>
</main>
<footer>
<p>&copy; 2026 Kryon Labs | <a href="https://waozi.xyz" target="_blank" rel="noopener">Made by Waozi</a></p>
</footer>
</div>
<script src="highlight.js"></script>
</body>
</html>
-199
View File
@@ -1,199 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kry Language Reference</title>
<meta name="description" content="Kry source language reference: declarations, statements, compile-time checks, KIR lowering, and backend behavior.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://kryonlabs.com/language.html">
<meta property="og:title" content="Kry Language Reference">
<meta property="og:description" content="The documented .kry to KIR to C, Go, JS, and KRB language contract.">
<meta name="theme-color" content="#f3f1ea">
<link rel="icon" type="image/png" sizes="16x16" href="icons/proj/kryon.png">
<link rel="apple-touch-icon" href="icons/proj/kryon.png">
<link rel="stylesheet" href="styles.css">
<script src="theme.js"></script>
</head>
<body>
<header class="site-header">
<div class="site-header-inner">
<a class="brand" href="/">
<img src="icons/proj/kryon.png" alt="Kryon" width="22" height="22">
<span>KRYON</span>
</a>
<button class="menu-toggle" type="button" aria-label="Open site menu" aria-expanded="false" aria-controls="header-nav">Menu</button>
<nav class="header-nav" id="header-nav" aria-label="Primary">
<a href="/">Home</a>
<a href="docs.html">Docs</a>
<a href="language.html">Language</a>
<a href="renderers.html">Renderers</a>
<a href="showcase.html">Showcase</a>
<a href="/api">API</a>
<a href="ide.html">Playground</a>
<a class="btn btn-primary" href="https://github.com/kryonlabs/kryon" target="_blank" rel="noopener">GitHub</a>
</nav>
</div>
</header>
<main>
<section class="doc-hero">
<p class="section-eyebrow">Kry Source Language</p>
<h1>Language Reference</h1>
<p class="section-lead">Kry is C-close application code for Kryon. This page mirrors the canonical source contract in <code>docs/KRY_LANGUAGE_SPEC.md</code>: source lowers into KIR first, then the same KIR can produce readable C, Go bindings, browser-loadable JS, or portable KRB cartridges.</p>
<pre><code>.kry -> KIR -> C
.kry -> KIR -> Go
.kry -> KIR -> JS
.kry -> KIR -> KRB</code></pre>
</section>
<section>
<p class="section-eyebrow">Contract</p>
<h2>What Kry Guarantees</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Rule</th><th>Meaning</th></tr></thead>
<tbody>
<tr><td>Single frontend</td><td><code>.kry</code> parses into KIR before every backend. Backend-specific behavior must be visible in KIR or reported as a diagnostic.</td></tr>
<tr><td>C-close expressions</td><td>Types, pointer expressions, calls, field access, and raw C escape lines stay familiar to C programmers.</td></tr>
<tr><td>Declarative UI shape</td><td><code>#ui</code> functions declare named node hierarchies; the runtime owns reconciliation, layout, input routing, focus, and update order.</td></tr>
<tr><td>Inspectable lowering</td><td><code>k2kir</code> prints imports, state, functions, statements, assertions, and simple structured expression trees for tooling.</td></tr>
<tr><td>Honest subsets</td><td>C is the full path. Go, JS, and KRB accept supported KIR and reject unsupported compile-time assertions instead of silently changing semantics.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Declarations</p>
<h2>Top-Level Forms</h2>
<pre><code>#import "kryon.h"
ui :: #import "src/ui/panel"
WEB :: #defined(PLATFORM_WEB)
ANSWER :: #run 6 * 7
#assert ANSWER == 42, "compile-time math failed"
state {
click_count: int = 0
}
Counter :: (viewport: Rectangle, app: App*) #ui {
Screen root: {
bounds = viewport
Column body: {
gap = 8
Text((TextProps){.text="Count", .font=Text16})
if Button((ButtonProps){.label = "Increment"}) {
app->click_count += 1
}
}
}
}</code></pre>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Form</th><th>Purpose</th></tr></thead>
<tbody>
<tr><td><code>#import "header.h"</code></td><td>Include a C header in generated native code.</td></tr>
<tr><td><code>name :: #import "module"</code></td><td>Import another Kry module.</td></tr>
<tr><td><code>name :: (...) -> Ret { ... }</code></td><td>Define a function. Module functions are source-prefixed in generated C unless exported.</td></tr>
<tr><td><code>name :: (...) #ui { ... }</code></td><td>Define a UI hierarchy function. Named nodes inside it get stable hierarchy paths.</td></tr>
<tr><td><code>#export</code>, <code>#private</code>, <code>#extern</code></td><td>Control ABI visibility and declarations that are implemented outside Kry.</td></tr>
<tr><td><code>#global</code></td><td>Create a file-level variable; combine with <code>#export</code> for public extern storage.</td></tr>
<tr><td><code>Type :: struct { ... }</code></td><td>Define a C-compatible struct type.</td></tr>
<tr><td><code>state { ... }</code></td><td>Declare persistent app state fields owned by the generated module.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">Statements</p>
<h2>Function Body Forms</h2>
<ul class="link-list">
<li><strong>Locals:</strong> <code>name := expr</code>, <code>name: Type = expr</code>, or <code>name: Type</code>.</li>
<li><strong>Assignments:</strong> <code>name = expr</code> and compound operators such as <code>+=</code>, <code>%=</code>, and <code>&=</code>.</li>
<li><strong>UI nodes:</strong> <code>Screen root: { ... }</code>, <code>Column body: { ... }</code>, <code>Row actions: { ... }</code>, and <code>Stack layer: { ... }</code> declare hierarchy nodes.</li>
<li><strong>Calls:</strong> plain call statements remain available for leaf widgets and utility calls inside UI or normal functions.</li>
<li><strong>Control flow:</strong> <code>if</code>, <code>else if</code>, <code>else</code>, <code>while</code>, <code>for</code>, <code>switch</code>, <code>case</code>, <code>default</code>, labels, <code>goto</code>, <code>break</code>, <code>continue</code>, <code>guard</code>, <code>defer</code>, and <code>return</code>.</li>
<li><strong>Interop:</strong> <code>c line</code> emits raw C glue, and <code>unused expr</code> silences unused-value warnings.</li>
</ul>
</section>
<section>
<p class="section-eyebrow">Compile Time</p>
<h2>Constants, Guards, And Assertions</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Feature</th><th>Status</th><th>Backend Behavior</th></tr></thead>
<tbody>
<tr><td><code>#defined(SYMBOL)</code></td><td class="ok">Available</td><td>Expands to a C preprocessor-style condition for guards and generated C.</td></tr>
<tr><td><code>NAME :: #run INTEGER_EXPR</code></td><td class="ok">Available</td><td>Evaluated by the Kry frontend as a small integer constant. It is not a general compile-time function system.</td></tr>
<tr><td><code>#assert CONDITION, "message"</code></td><td class="ok">Available</td><td>Ungarded constant-false assertions fail during Kry parsing. C emits <code>#if/#error</code>. Go, JS, and KRB require known true assertions.</td></tr>
<tr><td><code>#if</code>, <code>#else</code>, <code>#endif</code></td><td class="ok">Available</td><td>Retained in KIR as expanded guards so backends know the active platform conditions.</td></tr>
</tbody>
</table>
</div>
</section>
<section>
<p class="section-eyebrow">KIR</p>
<h2>Intermediate Representation</h2>
<p>KIR keeps raw source statement text for backend compatibility and adds structured metadata where the frontend can parse safely. Today that metadata covers simple identifiers, integer literals, string literals, calls, and binary expressions. More expression kinds can be added without changing the source pipeline.</p>
<pre><code>k2kir --root . -o build/ir src/app.kry
k2c --root . -o build/c src/app.kry
k2go --root . -o build/go src/app.kry
k2js --root . -o build/js src/app.kry
k2b --root . -o build/krb src/app.kry</code></pre>
</section>
<section>
<p class="section-eyebrow">Limits</p>
<h2>Known Language Boundaries</h2>
<ul class="link-list">
<li><strong>No hidden macro language:</strong> Kry keeps compile-time behavior small and explicit. <code>#run</code> currently folds integer expressions only.</li>
<li><strong>Backend subsets are real:</strong> C is broadest; Go, JS, and KRB intentionally support smaller surfaces and must diagnose unsupported KIR.</li>
<li><strong>Text system limits remain runtime limits:</strong> font fallback exists, but shaping, bidi, RTL mirroring, and IME preedit are not complete.</li>
<li><strong>KRB is portable by design:</strong> it carries a smaller widget and capability surface than native C.</li>
</ul>
</section>
<section>
<p class="section-eyebrow">Backend Contract</p>
<h2>Conformance Summary</h2>
<div class="table-wrap">
<table class="matrix-table">
<thead><tr><th>Feature</th><th>KIR</th><th>C</th><th>Go</th><th>JS</th><th>KRB</th></tr></thead>
<tbody>
<tr><td><code>#run</code> integer constants</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td></tr>
<tr><td><code>#assert</code></td><td class="ok">Yes</td><td class="ok"><code>#if/#error</code></td><td class="part">Known true only</td><td class="part">Known true only</td><td class="part">Known true only</td></tr>
<tr><td>State block</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td><td class="ok">Yes</td></tr>
<tr><td>Raw C lines</td><td class="ok">Preserved</td><td class="ok">Yes</td><td class="no">No</td><td class="no">No</td><td class="no">No</td></tr>
<tr><td>Structured expression metadata</td><td class="part">Partial</td><td class="part">Metadata</td><td class="part">Metadata</td><td class="part">Metadata</td><td class="part">Metadata</td></tr>
</tbody>
</table>
</div>
</section>
</main>
<footer>
<div class="footer-bottom">
<p>&copy; 2026 Kryon Labs &middot; <a href="index.html">Home</a> &middot; <a href="matrices.html">Matrices</a> &middot; <a href="renderers.html">Renderers</a></p>
</div>
</footer>
<script src="highlight.js"></script>
<script>
(function() {
var toggle = document.querySelector(".menu-toggle");
var nav = document.getElementById("header-nav");
if (toggle && nav) {
toggle.addEventListener("click", function() {
var open = nav.classList.toggle("is-open");
toggle.setAttribute("aria-expanded", open ? "true" : "false");
});
}
})();
</script>
</body>
</html>
Loaded 100 of 877 files, more files were not shown because too many files have changed in this diff. Show more