Commit Graph
45 Commits
Author SHA1 Message Date
waozi 2726d54f72 Advance Kry compile-time checks and expression KIR 2026-08-19 18:12:26 -03:00
waozi f2a48285c9 k2g: lower typed declarations, arrays, and goto/labels for real
Declarations no longer degrade to 'any': the declared type is split
from the initializer before translation, go_type skips leading
whitespace and normalizes 'char *' to 'char*', and array types
('[N] const char*', '[N] int') map to Go arrays. Composite-literal
initializers take the Go form 'var x = [N]T{...}'. goto and label
statements emit verbatim — 'name:' and 'goto name' are valid Go, and
a forward jump over declarations stays a loud compile error rather
than a silent TODO.

The shared frontend now classifies a bare 'name:' as KIR_STMT_LABEL
(previously the kind existed but was never produced; labels only
worked through the raw-text path).

Generated code may pass the C-shaped option list to Dropdown/TextLines
— a ';'-joined string, a []string, or a [N]string array — so array
declarations feed widgets directly; Dropdown also tolerates the C
option-count argument, which the Go side derives itself.
2026-08-18 16:27:02 -03:00
waozi 537912b0a6 k2g: host bridge, enums, switch and full for headers
k2g now compiles real declarative apps, not just the smoke subset:

- '#extern "pkg.Fn"' lowers to a generated <Guard>Host interface with a
  Set<Guard>Host setter; extern calls become host.Method(...) with numeric
  argument conversions so int/long/float widening always compiles. The Kir
  frontend keeps the quoted host symbol on KirFunction.extern_target.
- 'Name :: enum' lowers to untyped Go constants with C counter semantics
  (explicit literal resets the counter; explicit expressions chain +1), and
  bare member names rewrite to the qualified Go constant at every use site.
- switch bodies translate: case/default labels, including brace-open forms
  and same-line bodies; Go auto-break replaces C fallthrough by design.
- C-style three-clause for headers ('for int i = 0; i < n; i++') become
  Go for headers with typed initializers; Go-style headers pass through.
- 'guard cond' lowers to a plain if (the body is the exit path).
- Assignments lower as statements; '} else {' chains emit on one line.
- Extended C-to-Go type map (short/size_t/long long/unsigned variants,
  char** slices, [N]T arrays, T* pointers, const stripping) removes the
  any-fallback for real signatures.
- Output is flat: nested source trees no longer nest Go files into
  separate packages; duplicate basenames are rejected.

go/kryui grows the widget surface declarative apps need: TabBar (real
DrawUITabBar cgo wrapper with plain string labels), Rect, RectGradientH,
Line, Progress, Checkbox, Dropdown and screen-size getters on the k2g
Runtime interface, plus DropdownLabels for ';' option lists.

tests/k2g_syntax_test.sh now covers the whole subset and keeps the
compile-against-the-real-runtime gate; the full suite passes.
2026-08-17 21:34:07 -03:00
waozi bc0a3999d0 ui: enforce cross-lowering text input latency 2026-08-17 20:26:30 -03:00
waozi 3db6d5129c k2c: preserve anonymous enum declarations 2026-08-17 19:36:33 -03:00
waozi f8f5cd4c71 ui: add retained declarative tree and typed events 2026-08-17 18:55:05 -03:00
waozi 7bc838d67a k2ir: strip block comments while reading lines
A multi-line /* ... */ comment before a function silently dropped it from
the generated C: a line ending in the comment close tripped the trailing-
slash continuation rule and glued the comment onto the next function
header, whose name parse then found no leading identifier. Lines starting
with the comment open were likewise swallowed as lookahead continuations.

Strip C-style block comments in place as each line is read (string/char
literal aware, newlines preserved so spans stay honest, state carried
across lines for comments that span them).

Also fix the plain-#-comment catch-all, added recently, swallowing real
#module and #import directive lines - the k2ir test regressed to
'module main' with a missing header import. Directives now fall through
to their own branches.
2026-08-17 08:33:19 -03:00
waozi 37282eaf81 kir_parse: skip plain # comments in TOP mode
A top-level comment line fell through the TOP dispatch and was
treated as a declaration header, silently swallowing the following
state/app/frame blocks into a bogus construct (the screen then
compiled to zero nodes). #if/#else/#endif/#defined still pass through
the conditional-frame machinery.
2026-08-17 08:09:02 -03:00
waozi 14c8223acc k2c: fix one-line control blocks, char literals, and locals named c
Three parser defects that made k2c exit 0 while emitting broken C:

1. One-line control blocks ('if cond { body }', also while/for/switch/
   case/else/guard) glued the braces into the condition. The finalized
   logical line is now split into header/body/'}' and the parts re-enter
   the main loop through a FIFO that outranks the stashed lookahead
   (whose single slot the read-ahead would otherwise overwrite, losing
   source lines). The read-ahead is also skipped for queued parts and
   while a stash is pending.
2. Char literals containing structural characters ('"', '[', ']', '{',
   '}') toggled the string/bracket scanners and swallowed following
   lines; both brace scanners now skip char literals.
3. An assignment to a local named c was classified as a raw 'c <line>'
   escape and emitted without its trailing semicolon; assignment
   operators after the c token now fall through to the normal
   statement path.
2026-08-16 20:21:40 -03:00
waozi 96a30719ba kir: 'c:' is a typed decl, not the raw-C 'c' keyword
The ':' token boundary added for 'default:' made starts_word(s, "c")
match 'c: float = ...', sending typed declarations of variables named
'c' down the raw-passthrough branch and emitting invalid C.
2026-08-16 20:03:02 -03:00
waozi 62ce822082 k2c: fix braced and bare-default switch cases
Two parser gaps made switch all but unusable from Kry: (1) 'case X: {'
was not a header line, so the case body's braces were treated as
expression braces and glued onto the case text; (2) starts_word did not
accept ':' as a token boundary, so 'default:' fell through the case
classifier into the declaration branch and emitted 'default = {0}'.
Header classification now includes case/default (default may be followed
by ':'), and starts_word accepts a ':' boundary.
2026-08-16 19:52:47 -03:00
waozi f32d3e21ed k2c: join multi-line initializers on '::' global declarations
A logical line like 'palettes :: [3] Pal = {' was classified as a header
line (any line containing ' :: '), so its braces counted as block braces
and the multi-line initializer never joined; the global was then dropped
from the output while references to it still compiled, producing broken
C. Header forms ('name :: struct {', function/typedef/extern
declarations) never contain ' = ', so gating the ' :: ' header rule on
the absence of ' = ' routes initializer lines through expression-brace
continuation instead.
2026-08-16 19:45:54 -03:00
waozi 7ebedf9360 kir joiner: adjacent string literals on continuation lines join
A statement whose last token closes a string literal continued nowhere:
the trailing '"' is not a continuation operator, so every fragment of
the C adjacent-literal idiom ("..." \n "..." \n "...") was released
as its own orphan expression statement and the initializer kept only
its first fragment — SQL built that way prepared from a truncated
string and failed silently. The lookahead continuation now also joins a
line that opens a string literal when the statement so far ends with a
closing one, recomputed per joined fragment so chains work.
2026-08-14 19:53:41 -05:00
waozi 807e3fde58 kir joiner: '} #else_if COND {' region chains complete as statements
A chained region closer starts with '}', so the header-line word scan
saw nothing and the trailing '{' counted as an expression brace: the
line kept joining until braces balanced, swallowing the whole branch —
data_root's #if WEB/#else_if ANDROID/#else_if WIN32/#else chain lowered
to just the first region with no #endif, leaving desktop builds with an
empty data root and silently dead storage. Region braces after a '}' now
count as block braces (both FUNCTION-mode lowering and TOP-mode frames
already accept the optional leading '}'). Syntax test covers a full
chain: every branch, the expanded conditions, and the #endif.
2026-08-14 17:59:46 -05:00
waozi d5473a3233 k2c: guard statements, array params, alias-call stem matching, init rewrites
- 'guard cond' lowers to if(cond) { defers; return; } (legacy rule).
- '[N] T name' parameters emit C declarator order.
- Cross-module alias calls match the import's file-path target against
  the module source stem too — inbe imports name file paths
  ('src/screens/settings/settings_theme'), not dotted module names.
- Global initializers pass through rewrite_body2 (nil -> NULL, local
  function-name resolution) and KIR_TEXT_MAX grew to 4096 so joined
  multi-element initializers stop truncating mid-list.
2026-08-14 16:49:25 -05:00
waozi 76b21a607e kir joiner + k2c name-resolution fixes
- A trailing ':' (open ternary) continues the statement, matching the
  existing leading-':' rule — multi-line ternaries now join.
- A pending that is just '{' is a scope-open, not a compound-literal
  brace: the whole following block used to join into one statement
  ('{ labels: [7] const char* = {...} slot_w := ... for {...}').
- k2c bare-reference resolution never fires for 'name->'/'name.'
  accesses: 'habits->count' resolved the screen name 'habits' into
  'habits_kry_draw' whenever a module had a screen of that name.
2026-08-14 16:48:52 -05:00
waozi 1b9c9e4ed5 kir joiner: three continuation bugs
- The lookahead read raw fgets lines, so an appended continuation
  carried its newline into the joined statement text (ternary assigns
  emitted with an embedded '\n }').
- After appending a lookahead continuation the loop re-read the next
  physical line and appended it before re-deciding, swallowing the
  block-closing '}'. The lookahead now loops in place and stashes the
  first non-continuation line.
- Blank lookahead lines did not increment line_no, so every span after
  a blank under-counted (source line 9 reported as 7).
- Keyword headers require a following ' '/'('/'{': 'app->x = (T){...}'
  was treated as an app-block header, so its compound-literal brace
  counted as a block brace and the literal lost its closing '}'.
2026-08-14 16:48:52 -05:00
waozi 763adefcc2 kir: compute the body '#if' kind once — parse_cond_start strips the
trailing '{' in place, so the second parse in the emission branch saw no
brace and every body '#if' lowered to '#elif'.
2026-08-14 16:48:52 -05:00
waozi dc811b61c0 kir+k2c: '#if' regions lower to C preprocessor conditionals
Ports the legacy compile-conditional model onto Kir instead of skipping
unevaluated regions (which dropped '#if !WEB' desktop code inbe needs):

- kir_parse tracks a frame stack: '#if COND {', '} #else_if COND {',
  '#else'. Conditions expand through 'Name :: expr' constants ('WEB ::
  #defined(PLATFORM_WEB)' -> 'defined(PLATFORM_WEB)', '#defined' ->
  'defined'); unknown identifiers stay for the C preprocessor.
- Top-level captures inside a region are stamped with the combined
  guard (new 'guard' field on KirImport/KirGlobal/KirType/KirStateField/
  KirFunction); k2c wraps every stamped item in '#if cond / #endif' in
  both .h and .c. Body-level regions lower to raw #if/#elif/#else/
  #endif statements with their braces consumed.
- 'static'/'#private' globals no longer emit a header extern; the .c
  definition carries the 'static' prefix.
- 'name :: Type = init #global' splits type/init at ' = ' (the type
  previously swallowed the initializer); '#private' ::-globals capture
  as internal-linkage statics.
- Header emission order fixed: named enums and structs now precede the
  extern globals referencing them.
2026-08-14 16:48:52 -05:00
waozi db8ae1486e kir: parse K&R '} else {' as close + else re-open
The line-leading word scan saw only '}', so '} else {' failed the
header-line test: its trailing '{' counted as an expression brace and
the tokenizer kept accumulating until braces balanced, merging the else
and its whole body into one BLOCK_CLOSE. Even split correctly, FUNCTION
mode routed any '}'-leading line to a plain BLOCK_CLOSE, dropping the
else the k2c lowering expects as an IF starting with "else". Emit
BLOCK_CLOSE + IF("else ...") with net-zero depth, and teach the brace
classifier that '} else' braces are block braces. Allman else on its own
line already worked (and stays covered); k2c_syntax_test now covers the
K&R form whose else branches used to vanish silently.
2026-08-14 14:27:30 -05:00
waozi 501402bd71 kir: the '#if' region skip runs before import capture
The import branch was earlier in the dispatch than the conditional-skip
branch, so imports inside '#if MACRO {' blocks were captured anyway. Move
the skip to the top of the TOP-mode chain.
2026-08-14 14:07:03 -05:00
waozi 6db6f02b66 kir+k2c: top-level 'static name: T = init' globals; skip captures in unevaluated '#if MACRO {' blocks
'static tracks: [N] const T = {...}' (multi-line initializers arrive
joined) captures as an internal-linkage KirGlobal (KirModuleAddStatic) —
emitted with the 'static' prefix instead of extern. Top-level '#if MACRO {'
regions can't be resolved without build defines; like legacy's
undefined-macro-false case, their imports/globals are not captured (brace
tracked).
2026-08-14 14:02:41 -05:00
waozi aa27c7e07a kir+k2c: capture the 'args' header directive; C-style params pass through
'args <decl>' inside a screen ('args InbeApp *app') appends parameters to
the function signature (colon screens only, top level of the body).
convert_args now emits colon-less parts as-is (C-style 'InbeApp *app')
instead of dropping them.
2026-08-14 13:54:07 -05:00
waozi 44e969d284 kir+k2c: '#private' imports include in the .c only
required=0 marks '#import ... #private'; the header skips them and the
.c preamble includes them (implementation-only headers).
2026-08-14 13:39:28 -05:00
waozi 6db4f0eebc kir: ':=' classifies as DECL before the raw-'c' escape hatch
A variable named 'c' ('c := expr') was misclassified as raw C. ':=' wins.
2026-08-14 13:30:47 -05:00
waozi 3f4ee655b8 kir+k2c: named enums ('Name :: enum { ... }' -> typedef enum)
Parser captures ':: enum' bodies like structs (is_enum flag); lowering
emits 'typedef enum {...} Name;' with comma-terminated members.
2026-08-14 13:25:39 -05:00
waozi 15d1247b23 k2c: emit kryon_project.h/.c (app-host ABI) + main() from Kir
k2c_write_project runs after all files lower: kryon_project.h includes
every generated header; kryon_project.c auto-collects routes from public
screen-keyword functions (screen/preview/page/frame/scene/fn — the legacy
exact_name rule: colon helpers stay public-but-unrouted), emits
per-route wrappers dispatching on Rectangle/app-pointer/void args, the
route table, and CreateAppHost/DestroyAppHost over the weak
CreateApp/DestroyApp/ApplyRoute/BeginScreenDraw hooks. main() appends to
kryon_project.c from KirAppMeta (InitWindow/SetTargetFPS/InitUI/theme/
init-frame-shutdown hooks) unless --no-main.

Verified: a frame-app fixture emits a compiling project (main + route +
host ABI); the full krait corpus still compiles clean; make test green.
2026-08-14 13:04:54 -05:00
waozi e6e40d68be k2c: colon functions keep their bare C names; bare-ref resolution only in assignment-RHS
Legacy naming restored: 'Name :: (...) {' functions get the module prefix
but NO _kry_draw suffix (screens keep it) — krait's module.kry references
these exact names. Bare identifier resolution now fires only in '= name'
assignment-RHS position, so locals shadowing function names (strlen(name))
are never rewritten. All 9 krait .kry files (ide/* + modules/kryon) now
compile with zero errors through the pure Kir pipeline.
2026-08-14 08:55:15 -05:00
waozi 21e263c521 k2c: krait's full IDE corpus compiles — all 8 generated files, zero errors
- Typed-decl classification requires an identifier LHS (ternary fragments
  like '1 : 0' no longer misclassify as decls).
- Ternary else-branches (': value' leading lines) join via one-line
  read-ahead (lookahead stash).
- Typed decls convert array types to C declarator order with alias-stripped
  bases (temp buffers, no src==dst snprintf UB).

krait ide/*.kry -> C now syntax-checks clean across state/app/editor/
widgets/preview/console/problems/start_page. kryon make test green.
2026-08-14 08:43:18 -05:00
waozi 9f470e6a94 kir+k2c: typedefs with names, enum commas, type emission order, ternary/&& joins
- '#type' lines build real C declarators (name inserted after '(*' for
  function pointers) and are matched BEFORE the struct '::' catch-all that
  silently swallowed them.
- Enum members emitted with commas (newline-separated .kry members).
- Header emits typedefs, then enums, then structs (structs reference both).
- Ternary '?' and '&&'/'||' line continuations; pointer types ('char*') and
  '<header.h>' closes no longer join.
- Global array sizes strip interior aliases via the body rewriter
  ('[state.MAX]' -> '[MAX]').
2026-08-14 08:28:59 -05:00
waozi e491d932de kir+k2c: '#type' typedefs; angle-bracket includes don't join
'Name :: C-type #type' is captured as a #typedef KirType and emitted as
'typedef C-type;'. The '>' closing '#import <header.h>' no longer triggers
the operator continuation (space required before < and > too).
2026-08-14 08:06:21 -05:00
waozi 567245d415 kir: enum constants joined by comma-continuation close their enum
The operator continuation joins 'A, B, C, }' into one line; ENUM mode now
strips the trailing '}' and returns instead of waiting for a lone brace.
2026-08-14 08:01:22 -05:00
waozi b4469c12ba kir: fix duplicate anonymous enum (use int for enum_return) 2026-08-14 07:58:42 -05:00
waozi 895078118b kir: pointer types don't continue lines; #enum nests inside structs
'char*' ending a field line no longer joins the next line (trailing +,-,*,&
require a preceding space to be a continuation operator). #enum inside a
struct body is captured as its own enum and returns to the struct (mode
stack via enum_return).
2026-08-14 07:56:30 -05:00
waozi a25d72b15e kir+k2c: join operator continuations; alias-strip array sizes
Lines ending in a binary operator (&&, ||, +, -, *, /, %, =, <, >, comma)
now continue onto the next line (legacy line_needs_continuation), so
multi-line if conditions stay one statement. ++/-- are excluded. Global
array sizes with alias qualifiers (state.IDE_MAX_PANE_TABS) are stripped.
2026-08-14 07:53:44 -05:00
waozi e32ca8414a kir: '#'-directive lines are header lines (never join their braces)
'#enum {' starts with '#', so the first-word check found no keyword and its
'{' counted as an expression brace — the whole enum joined into one line and
was dropped. Any '#' prefixed logical line is now a header line.
2026-08-14 07:43:37 -05:00
waozi ef34928096 kir: join multi-line compound literals (expression braces)
The joiner only tracked ()/[] depth, so 'content := (Rectangle){ 0, ... }'
split at the '{' (paren depth 0) and the initializer lines became orphaned
statements. Now depth-0 braces on a logical line are classified: block
braces on control/header lines (if/else/while/for/switch/screen/:: /struct/
enum/state/app) end the line; expression braces elsewhere continue the join.
Compound-literal initializers now arrive as one statement.
2026-08-14 07:40:40 -05:00
waozi 4ab5b277aa kir+k2c: fix UB alias-strip (src==dst snprintf), emit #enum blocks
strip_alias_type(src==dst) is UB via snprintf overlap — it emptied every
struct field type ('left_width;' with no type). Route through a temp.
#enum { A, B } blocks are captured (ENUM mode) and emitted as C enums.
2026-08-14 07:34:55 -05:00
waozi 481913395f kir+k2c: struct fields converted to C declarators; '#' comments skipped in bodies
Struct fields ('name: [N] Type') now emit 'Type name[N];' with alias
stripping, instead of verbatim .kry text. '#' comment lines inside struct
and function bodies are skipped (directives are top-level only).
2026-08-14 07:30:19 -05:00
waozi edc6cb6269 kir+k2c: fix block-brace depth tracking + alias rewrite in body statements
Brace tracking: depth now counts NET braces at paren/bracket depth 0 only —
compound-literal braces inside calls (e.g. (Props){...}) no longer
mis-increment block depth, which previously ended function bodies early and
swallowed following top-level definitions.

Body rewrite: rewrite_nil became rewrite_body(m, ...) which additionally
strips 'alias.' qualifiers from identifiers when the alias is a module
import (state.IDE_PANE_LEFT -> IDE_PANE_LEFT), matching legacy
rewrite_kry_expr's alias rule.
2026-08-14 07:25:20 -05:00
waozi 90b6f7660d kir+k2c: struct types (Name :: struct), return types stop at '{'
KirType captures the struct body verbatim (TYPE mode in the parser); the
lowering emits typedef struct {...} Name; in the header. Return-type
extraction no longer swallows the opening brace of the function body.
2026-08-14 07:17:06 -05:00
waozi 7c8b79f151 kir+k2c: return types, #extern prototypes, #global vars, module prefixes, alias stripping
Frontend (kir_parse.c): extract '-> T' return types from function headers;
capture #extern (body-less prototypes stay TOP-mode); capture
'name :: Type #global' module globals (KirGlobal in kir.h/kir.c).

Lowering (k2c_lower.c): functions named <module>_<name>_kry_draw (module
dots->underscores); return types in prototypes + definitions; #extern
emitted as prototypes only; #global emitted as statics; alias-qualified
types ('st: state.IdeState*') stripped to bare C types when the alias is a
module import of the same module.

Verified: k2c_syntax_test green; k2ir shows module imports captured.
2026-08-14 07:11:27 -05:00
waozi 69eb7b3629 Extract Kir parser into shared kir_parse.c (prerequisite for k2c/k2b backends)
The .kry -> Kir parser is now a shared library (cmd/kir/kir_parse.c +
kir_parse.h) exposing kir_parse_file(path, root) -> KirProgram*. Both k2c
(the C backend) and k2b (the krb backend) can link it to share one frontend.

k2ir/main.c is now a thin wrapper: parse + KirProgramDump to a .kir file.
The output path uses the module's source_path to preserve directory structure.

k2ir_test passes; make test green. The k2c backend (Stage 2) can now link
kir_parse.c to get Kir input.
2026-08-13 22:07:11 -05:00
waozi 02c07c823e k2ir: parse app{} metadata (title/size/fps/theme/frame/init/scene/shutdown)
Add KirAppMeta to KirModule (has_app, title, dimensions, fps, theme,
dark_mode, font_examples, frame/init/scene/shutdown hooks). The k2ir frontend
gains an APP mode that parses the app{} block's properties, and the dump
prints the metadata. This is needed by the future k2c backend to generate
main() (hook-driven / scene-tree / single-screen variants).
2026-08-13 21:57:34 -05:00
waozi b3910fa403 Add initial KIR core 2026-08-13 11:17:39 -03:00