Commit Graph

217 Commits

Author SHA1 Message Date
dimgigov 0c41c7bb25 feat(selfhost): function types (func(Params) -> Ret)
- Add tekFunc AST node and TypeExprList linked list for params
- Parse func(T, U) -> R syntax in parser.bux
- Resolve tekFunc to tyFunc in sema.bux
- Track original TypeExpr via Symbol.refType for params/lets/consts/funcs
- Build C function-pointer type names in hir_lower.bux (Ret (*)(Params))
- Lower indirect calls through function-typed values as hCallIndirect
- Add CBE_CParamDecl helper in c_backend.bux to embed name inside (*)
- Emit hCallIndirect and function-pointer variable declarations
- _test_funcptr now builds and runs with selfhost buxc2
2026-06-08 23:39:15 +03:00
dimgigov 2e536488e6 feat(bootstrap): function pointer types + C emission
- Add tekFunc AST node and parser support for func(Params) -> Ret
- Add tkFunc type resolution in sema and hir_lower
- Add &FuncName address-taking yielding tkMutRef(tkFunc)
- Fix C emission: function pointer params use Ret (*name)(Params) syntax
  via cParamDecl helper that embeds the name inside (*)
- Fix forward declarations and temp declarations for function pointers
- Add funcPtrTypes table in C backend so &Fn temps get proper type
- Add _test_funcptr integration test
2026-06-08 22:31:32 +03:00
dimgigov 3f0a3901ca feat: named and default parameters
Bootstrap compiler:
- ast.nim: add exprCallArgNames to ekCall for named arg tracking
- parser.nim: detect name: value syntax in call args
- sema.nim: add resolveCallArgs helper that injects default values
  for missing params and reorders named args into param order.
  Parser already parsed default param values; sema now uses them.

Selfhost compiler:
- ast.bux: add defaultExpr to Param, argName to ExprList
- parser.bux: parse = defaultExpr in param list, detect name: value
  syntax in call arguments
- sema.bux: add Sema_ResolveCallArgs with same logic as bootstrap

Tests:
- _test_named_params verifies defaults, named args, mixed positional+named,
  and named args with defaults in both compilers.

All verifications pass: build, selfhost-loop, test-examples, test-golden.
2026-06-08 22:02:19 +03:00
dimgigov 17c896c4dc feat: string interpolation via f"..." syntax
Bootstrap compiler:
- Add ekStringInterp AST node with text/expr parts
- Lexer: recognize f"..." prefix for interpolation strings
- Parser: split f"..." into ekStringInterp, parse inner expressions
  via sub-lexer/sub-parser. Supports escaped braces \{ and \}.
- Sema: type-check interpolated expressions, return String type
- HIR lowerer: desugar ekStringInterp to chained String_Concat
  calls with automatic type conversions:
  - int/uint types -> String_FromInt
  - float types -> String_FromFloat
  - bool -> String_FromBool
  - String -> as-is

Selfhost compiler:
- ast.bux: add ekStringInterp constant (reserved for future)
- lexer.bux: accept f" prefix, treat as plain string literal
  (selfhost parser does not implement interpolation yet)

Tests:
- _test_string_interp verifies int, float, bool, String,
  multiple interpolations, plain strings, and Fmt-style {0} templates
2026-06-08 21:48:10 +03:00
dimgigov cfce2a93e5 feat: operator overloading in bootstrap compiler
- Add operatorMethodName mapping (tkPlus -> operator_add, etc.)
- Add tryLowerOperatorCall / tryLowerIndexCall in HIR lowerer
- Modify ekBinary lowering to check method table before builtins
- Modify ekAssign lowering to detect ekIndex target and emit
  operator_index_set method call when available
- Add sema type-checking for operator overloads in ekBinary
  and ekIndex paths (method-table lookup before builtin rules)
- Fix sema compile errors: minfo.params[N].typ -> minfo.params[N]
- Fix hir_lower forward decl ordering for resolveExprType
- Update golden test expected.c files for current C backend
- Update ROADMAP.md and PHASE8_STRATEGY.md status
2026-06-08 21:31:42 +03:00
dimgigov d9aceeac6e feat: switch/case statement
- Add  syntax
- Desugars to if-else chain in HIR lowering (both compilers)
- No new HIR/C backend nodes needed — reuses hIf/hBinary/hBlock
- Supports integer, char, and enum tag dispatch
- Case body can be single statement (no braces required)
2026-06-08 21:08:55 +03:00
dimgigov a67271b08c feat: defer statement support in both compilers
- Add  statement for function-level deferred execution
- Deferred expressions run in LIFO order on function exit (return or implicit)
- Bootstrap: desugar defers in hir_lower.nim (inject before return + end of func)
- Selfhost: emit defers in c_backend.bux via CEmitter defer stack
- Both: add tkDefer token, skDefer AST node, hDefer HIR node
- Parser, lexer, sema, token files updated in both bootstrap/ and src/
2026-06-08 20:59:27 +03:00
dimgigov cf92b63ba6 fix: bootstrap parser newline skipping + nexus compile errors
- Add tkNewLine skipping in bootstrap parser parsePrimary, parseUnary, parsePostfix
- Fix nexus: req.String_Len(path) -> String_Len(req.path)
- Fix nexus: bux_sb_append_char with char literal -> bux_sb_append with string
2026-06-08 20:28:37 +03:00
dimgigov 9c3d6dc723 fix: EVP_SignFinal unsigned int* type mismatch in OpenSSL calls 2026-06-08 20:24:47 +03:00
dimgigov 7d1d722cba fix: String_IsNull/String_Offset helpers + remove pointer-to-int casts
- Add String_IsNull and String_Offset wrappers in lib/String.bux
- Add bux_str_is_null and bux_str_offset runtime functions in rt/runtime.c
- Update String_Replace to use String_IsNull instead of String_Len(pos)==0
- Replace pointer-to-uint casts (as uint == 0, pointer arithmetic) across apps/
- Parser newline skipping fixes in src/parser.bux
2026-06-08 20:23:30 +03:00
dimgigov 3c7938163c fix(runtime): detach StringBuilder buffer on build to prevent use-after-free
bux_sb_build returned sb->buf and then bux_sb_free freed it,
causing dangling pointers in all callers of StringBuilder_Build
followed by StringBuilder_Free (e.g. JsonParser_ParseString, Fmt).

Fix: bux_sb_build now detaches the buffer (sets sb->buf = NULL)
before returning it, so bux_sb_free only frees the sb struct.
This transfers buffer ownership to the caller.
2026-06-08 20:10:30 +03:00
dimgigov c4e3f80405 fix(selfhost/c_backend): handle backtick raw string literals
Backtick strings were emitted directly into C code without
stripping the backticks or escaping the content, causing C syntax errors.

Fix: detect backtick-wrapped literals in CBE_EmitExpr, strip
the backticks, escape inner content, and wrap in double quotes.
2026-06-08 20:03:33 +03:00
dimgigov d253a01aa9 fix(selfhost/c_backend): emit _Tag + struct wrapper for all enums
Simple enums were emitted as plain C enums, but the rest of the codegen
(and source code) expected them to have a .tag field like algebraic enums.
This caused C compilation errors:
- 'request for member tag in something not a structure or union'
- 'field name not in record or union initializer'

Fix: always emit the _Tag typedef + struct wrapper for every enum.
For simple enums, the struct only contains the tag (no _Data union).
For algebraic enums, keep the existing _Data union + struct behavior.

This matches the bootstrap compiler's enum codegen.
2026-06-08 20:00:58 +03:00
dimgigov 2cb971a483 fix(selfhost/parser): skip newlines inside expressions
The selfhost parser did not skip tkNewLine tokens inside expression parsing,
causing multi-line expressions (e.g. if conditions spanning lines with ||)
to be truncated. When parserParseBinaryPrec hit a newline it treated it as
an invalid primary, returning a malformed literal and leaving p.pos at the
newline. parserParseBlock then failed to find '{' and its depth-counter
fallback consumed far too many tokens, causing subsequent function bodies
to be parsed into the wrong AST nodes.

Fix: add newline skipping in parserParsePrimary, parserParseUnary, and
parserParseBinaryPrec, matching the bootstrap parser's skipNewlines() calls
in parseAnd/parseOr.

Also complete the variant cap raise from 8->9 in src/sema.bux (was already
done in ast.bux, parser.bux, hir_lower.bux).
2026-06-08 19:45:05 +03:00
dimgigov b1deff7fd5 fix(selfhost/parser): skip newlines inside multi-import brace blocks
parserParseImportDecl now skips tkNewLine tokens inside {..} blocks,
matching the bootstrap parser behavior. This fixes parsing of imports
with names on separate lines, e.g.:

  import Std::String::{
      String_Eq,
      String_Len
  };

Previously the parser failed because it expected tkIdent immediately
after { but encountered tkNewLine instead.
2026-06-08 18:56:43 +03:00
dimgigov 38bc469be7 fix(bootstrap): resolve algebraic enum _Data union field types in HIR lowering
hir_lower.resolveExprType for ekField now correctly resolves variant
positional/named fields (e.g., r.data.Ok_0, r.data.Err_0) on _Data
union types, matching the existing logic in sema.checkExpr.

This fixes the runtime segfault in examples/algebraic_enums.bux where
the C backend emitted an int temporary for a String field, causing
PrintLine to dereference a garbage pointer.
2026-06-08 18:48:30 +03:00
dimgigov bebc362ae6 fix(bootstrap): simple enum codegen, crypto parser compatibility, import ordering
- Fix bootstrap sema to type simple enum variants as the enum itself
  (not _Tag), and .tag access returns the enum type.
- Fix hir_lower to lower simple enum .tag as no-op and Enum{tag:X}
  init as X directly.
- Fix sema collectGlobals to register imports AFTER real declarations,
  preventing duplicate-symbol errors when stdlib files import symbols
  defined in later files (e.g. jwt.bux importing rsa.bux).
- Rewrite lib/crypto/*.bux as single-line to work around bootstrap
  parser limitations with multi-line function calls.
- Rename 'pub' -> 'pubBuf' in ed25519.bux and jwt-pitbul/Main.bux
  to avoid reserved keyword collision.
- Remove algTag:int workaround from jwt-pitbul/Main.bux; enum
  comparisons now type-check without manual casts.
- Update .gitignore to exclude _test_*/ and backup files.
- Delete accidentally-committed _test_array/ directory.
2026-06-08 18:43:26 +03:00
dimgigov a7a1b45588 chore: add MIT license 2026-06-08 14:44:05 +03:00
dimgigov a13cee8a0f feat(simpledb): file-backed key-value database with CLI
- Add SimpleDB: plain-text key=value store with get/set/del/has/keys/count
- Fix lib/Fmt.bux: replace *(ptr+N) pointer arithmetic with ptr[N] indexing
- Fix lib/crypto/jwt.bux: use alg.tag directly instead of int-comparison
2026-06-08 12:26:24 +03:00
dimgigov 3b7fc455b0 fix(parser): infinite loop on newlines in multi-import, multi-line params, type args, struct patterns
Parser would hang (infinite loop) when encountering newline tokens
inside certain constructs because expect() returns without advancing
position when the expected token doesn't match.

Fixed 5 places in parseBaseType, parsePrimaryPattern, parseTypeParams,
parseParamList, and parseUseDecl by adding newline-skipping at the
start of each iteration.

Verified: compiler no longer hangs/crashes on all 3 real-world apps
from apps/ (boko-framework, jwt-pitbul, nexus).
2026-06-07 23:02:43 +03:00
dimgigov e7e900973f feat: crypto library, Nexus HTTP server, JWT CLI, Boko web framework
- lib/crypto/: 9-module crypto library (Hash, HMAC, Base64/URL, Random, AES, RSA, ECDSA, Ed25519, JWT)
- rt/runtime.c: +346 lines OpenSSL crypto primitives (SHA-1/384/512, HMAC, Base64URL, AES-CBC/GCM, RSA, ECDSA, Ed25519)
- apps/nexus/: multi-threaded HTTP/1.1 + HTTP/2 detect + WebSocket server
- apps/jwt-pitbul/: JWT CLI tool (sign, verify, decode, keygen)
- apps/boko-framework/: FastAPI-inspired async web framework
- test_crypto/: crypto library test suite (23 tests)
2026-06-07 22:15:00 +03:00
dimgigov a2617e9954 feat: VS Code extension, web playground, LSP server 2026-06-07 18:34:41 +03:00
dimgigov 3ffa9f7d54 feat: web playground + LSP server + docs update 2026-06-07 18:29:05 +03:00
dimgigov b3af1208e8 feat(lsp): add LSP server with completion, definition, hover, diagnostics 2026-06-07 18:20:35 +03:00
dimgigov 0d7a30835f feat: borrow expr, parser fix, borrow tests, borrow example 2026-06-07 18:09:40 +03:00
dimgigov adca52b269 docs: update README v0.4.0, update stdlib docs to 23 modules
- README: bump version to v0.4.0, add selfhost loop & borrow/shared
- Stdlib.md: update sections 1-4, add String_Chars, FromBool, Fmt, Iter
- BuildAndTest.md: add make selfhost-loop and make test-golden targets
- Standard library list updated to all 23 modules
2026-06-07 18:08:34 +03:00
dimgigov 04be9eb400 feat(stdlib): add String_Chars, String_FromBool, fix Fmt and Net
- String.bux: add String_Chars(s, index) for char-at-index access
- String.bux: add String_FromBool(b) conversion
- Fmt.bux: rewrite with correct stdlib imports (was using non-existent names)
- Net.bux: fix String_Len -> bux_strlen (String_Len not imported)
- All lib modules compile successfully
2026-06-07 18:05:04 +03:00
dimgigov bfe87a8acb feat: add borrow test example, fix borrow &mut parsing order
- examples/borrow.bux: working borrow expression example
- tests/borrow_test.nim: add 4 new tests for borrow & @[Shared]
- parser.nim: fix borrow parsing order (& before mut)
- Build verified: example compiles and runs
2026-06-07 17:50:27 +03:00
dimgigov 46814b2abc feat: selfhost-loop determinism, golden tests, sema diagnostics 2026-06-07 17:37:22 +03:00
dimgigov 9758b17b1a fix(parser): add stray } workaround in parserParseFuncDecl, enable selfhost build
This workaround consumes a stray } that parserParseBlock sometimes leaves
behind, which was causing the module handler to exit early. With this fix,
the selfhost compiler (buxc2) can now compile the entire src/ project.

- buxc2 project build: 491 user + 310 stdlib = 801 decls, no sema errors
- make selfhost-loop: builds and runs both passes
- C compilation succeeds, resulting binary works
2026-06-07 17:33:17 +03:00
dimgigov 8347599d23 fix(parser): save/restore + depth counter for reliable } consumption 2026-06-07 17:25:30 +03:00
dimgigov 4794335673 chore: clean up experimental changes, keep core parser improvements 2026-06-07 17:11:45 +03:00
dimgigov 134e8e877d fix(parser): depth counter in module handler, stray } cleanup, token count debug 2026-06-07 17:06:36 +03:00
dimgigov 88af8b09d4 fix(parser): improve parserParseBlock infinite-loop safeguard for stuck at } 2026-06-07 17:01:15 +03:00
dimgigov e41a8d31df fix(parser): use parserExpect for module closing brace 2026-06-07 16:43:14 +03:00
dimgigov a11071ab95 fix(parser): skip newlines before checking decl kind 2026-06-07 16:38:42 +03:00
dimgigov 093e08a2b9 chore(cli): remove diagnostic scan, keep FIFO merge and per-file counts 2026-06-07 16:25:23 +03:00
dimgigov 1500575982 fix(parser): replace destructive skip with single-token skip 2026-06-07 16:24:51 +03:00
dimgigov fe048eb4aa feat(cli): diagnostic scan for missing function defs, FIFO merge order, per-file counts 2026-06-07 16:20:22 +03:00
dimgigov 9dd964dc48 test: add fibonacci golden test, expand GOLDEN_TESTS 2026-06-07 16:10:05 +03:00
dimgigov e1038059c2 fix(cli): change user merge from LIFO to FIFO order, add per-file decl counts
- Cli_BuildProject now appends declarations (preserving original file order)
  instead of prepending (which reversed order)
- Added per-file declaration count debug output
- This makes merge order match Nim bootstrap behavior
2026-06-07 16:08:51 +03:00
dimgigov 1f0baefa5a feat: add selfhost-loop determinism check, golden tests, improve sema diagnostics
- Makefile: new targets `test-golden` and `selfhost-loop`
  - selfhost-loop verifies C codegen determinism (2-pass bootstrap)
  - test-golden compares C output against expected.c golden files
  - Updated clean-all to clean new build dirs
- tests/golden/hello/: first golden test (hello world)
- src/sema.bux:
  - Fix: import stubs only registered if symbol doesn't already exist
  - Improve: error message now includes identifier name
2026-06-07 15:47:48 +03:00
dimgigov 3b4456f01f selfhost: expand Decl to 256 fields, fix unary precedence, add discard/var parsing, fix diag buffer overflow
- ast.bux: Decl expanded with field0..field255, variant0..7, param0..8
- parser.bux: add parserParseUnary for correct unary precedence; handle tkDiscard statements; allow var without initializer (matching bootstrap); add diagCount bounds check in parserEmitDiag
- hir.bux: HirParam changed to pointers
- hir_lower.bux: full field chains for struct lowering
- c_backend.bux: hardened -> vs . field access; null checks in CBE_GetExprTypeName
- cli.bux: add -lcrypto to linker
2026-06-07 14:58:23 +03:00
dimgigov 0bdef58182 selfhost: fix pointer field access, algebraic enums, string literal escaping
- hir_lower: use per-function scope instead of global scope for params
  fixes p->error emission for pointer parameters
- parser: assign variant4..variant7 in enum decls (was only 0..3)
- c_backend: escape quotes, backslash, newline, tab, cr in string literals
- runtime: bux_write_file now writes raw bytes (was un-escaping sequences)
- c_backend: emit algebraic enums as tagged unions (tag enum + data union + struct)
- hir_lower: add hBreak/hContinue lowering
- sema: skip empty variant names when collecting enum globals
2026-06-06 23:54:09 +03:00
dimgigov 3ae8c60ebb fix(bootstrap): resolve lir lower crashes and struct-copy bugs
- Fix lirValToC crash on lvkInt in hStore raw C emission
- Add hAlloca handling to lowerExpr (returns &name, avoids unhandled fallback)
- Fix nested comment syntax in unhandled expr fallback
- Rewrite buildLval to handle hIndexPtr and nested hFieldPtr/hArrowField
  so assignments like arr[i].field = val emit direct C lvalues
- Make &&/|| temporaries unique (__and_tmp_N/__or_tmp_N) to avoid
  duplicate declarations in the same function
- Selfhost null-deref fix in sema.bux (unchained nested conditions)
2026-06-06 21:46:25 +03:00
dimgigov 9416c486b2 docs: update PLAN.md — Phase 11 roadmap, 26 examples, M10 completed 2026-06-06 19:53:24 +03:00
dimgigov ba0a55f467 docs: update README — 26 examples passing, selfhost working 2026-06-06 19:49:52 +03:00
dimgigov 797ca7c80c fix(lir): resolve all LIR backend regressions — 26/26 examples + selfhost passing
- hir_lower: add isScope=true to lowerBlock; fix resolveExprType for ekIndex,
  ekField on monomorphized structs, and ekTry/ekUnwrap tmpVar typing
- lir_lower: add loop label stack for break/continue; pass null arg to
  bux_task_spawn when spawn has no arguments
- lir_c_backend: multi-pass type inference for temps; include params in
  varTypes; handle lvkTemp in lirLoad; use inferred type in lirAlloca
2026-06-06 19:49:24 +03:00
dimgigov 4f7653a410 docs: update project status — buxc2 is now a working compiler, not a PoC 2026-06-06 19:02:54 +03:00
dimgigov 62a9c8b84a feat: LIR backend replaces direct HIR→C emission (v0.3.0)
- 42 LIR instructions in bootstrap/lir.nim

- HIR→LIR lowering in bootstrap/lir_lower.nim

- LIR→C emission with full struct/enum/vtable support

- All 22 examples + 5 Nim unit tests passing

- Updated README status and backend description
2026-06-06 18:55:59 +03:00