Ctrl K
ComunidadGuías…

README.md

Rama main · réplica de lectura del repositorio original.

Archivo original ↗Preguntar a KiBot
# Kryndel

[![Go 1.27.1+](https://img.shields.io/badge/Go-1.27.1%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Kryndel is a small, statically checked language for developer tools and structured applications. The repository contains the compiler, checker, runtime, standard library wrappers, package tooling, and a self-contained command-line executable.

The implementation is written in Go and uses the standard library plus the Go modules listed in `go.mod` for host integrations. Source goes through lexing, parsing, module resolution, static checking, and runtime execution. Released binaries include their Go dependencies and do not need Go or another host-language runtime.

Native C AOT builds support Linux amd64/arm64 and Windows amd64. `--format=macho` adds Darwin amd64/arm64 using the matching native macOS `cc` or `clang`; Mach-O cross compilation is not configured. CI runs the toolchain and native AOT tests on Linux ARM64, macOS x64, and macOS ARM64.

## Quick start

A Go 1.27.1 or newer toolchain is needed when building from a checkout.

```bash
git clone https://github.com/Xyraniz/Kryndel.git
cd Kryndel
make

./tools/kry run examples/hello.kry
./tools/kry examples/hello.kry
./tools/kry check examples/control_flow.kry
./tools/kry build examples/hello.kry -o /tmp/hello.kexe
./tools/kry /tmp/hello.kexe
```

The direct file form is useful for desktop integrations. On Windows, the release installer associates `.kry` and `.kexe` with Kryndel for the current user. On Linux, `make install-association` installs a per-user desktop association.

## Commands

| Command | What it does |
| --- | --- |
| `kry check FILE` | Parses, resolves, and type-checks a source file or artifact without running user code. |
| `kry run FILE` | Checks and runs a `.kry` source file or `.kexe` artifact. |
| `kry debug FILE` | Runs in the interpreter with source breakpoints, stepping, a call stack, and visible variables. |
| `kry FILE.kry` | Runs a source file directly. This is the form used by file associations and double-click. |
| `kry build FILE` | Creates a deterministic `KRYNATIVE6` bundle with checked source and typed KIR. Native PE and ELF output is available for supported targets. |
| `kry build FILE --format=exe --target=windows-x64 --no-external-toolchain` | Builds a C-free Windows PE32+ executable for the direct PE subset. |
| `kry build FILE --format=pe-direct --target=windows-x64 --gui` | Marks the direct PE executable as a Windows GUI subsystem image; this selects the PE subsystem and does not add GUI toolkit APIs. |
| `kry fmt FILE` | Formats valid source with stable whitespace and indentation. |
| `kry lsp` | Serves editor diagnostics, navigation, hover, completion, and formatting over the Language Server Protocol on standard input/output. |
| `kry repl` | Starts the interactive evaluator. |
| `kry doctor` | Checks the executable, limits, standard library, and runtime capabilities. |
| `kry new PROJECT` / `kry init` | Creates a project layout and manifest. |
| `kry add` / `kry install` | Manages vendored package dependencies. |
| `kry test` | Runs `*_test.kry` cases under `tests/`; pass a `.kry` file or directory to select cases. |

Use `kry --help` for global limits, JSON diagnostics, restricted execution, emit options, registry commands, and package commands. `--restricted ROOT` confines Kryndel-managed filesystem access and denies unmediated host capabilities; it is not an operating system sandbox. See [system integration](docs/system.md#system-integration-guide).

See [debugger commands](docs/debugger.md) for interactive breakpoints, stepping, stack, and variable inspection.

Start a project and run its generated entry point:

```bash
kry new my-first-app
cd my-first-app
kry run main.kry
```

To try the compatible crypto package from the default registry, install it and replace `main.kry` with this example:

```bash
kry install crypto
```

```kryndel
import "crypto"

fn main() -> Nil {
    println(sha256_hex(string_to_bytes("hello from Kryndel")))
}
```

`kry install` creates a minimal manifest when the directory is new, writes the dependency to `kry.toml`, downloads and verifies the archive, copies it to `vendor/crypto`, and records the exact URL and SHA-256 in `kry.lock`. It never overwrites an existing `main.kry`. Set `KRY_REGISTRY` only when using a private mirror or a local registry; the public default is versioned in this repository.

## Language

Kryndel uses braces for blocks, explicit types at function boundaries, and immutable bindings by default.

```kryndel
fn factorial(n: Int) -> Int {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

let answer: Int = factorial(6)
println("factorial = " + str(answer))
```

The type system includes `Int`, `Float`, `Bool`, `String`, `Bytes`, arrays, maps, sets, structs, enums, `Option`, `Result`, channels, synchronized `Shared[T]` cells, `Actor[T]` mailboxes, threads, JSON, WebSockets, regexes, seeded random generators, SQLite databases, raw TCP/UDP sockets, and explicit FFI handles. It also supports deeply immutable compile-time `const`, private struct fields, signature-based overloads, and constrained generic functions (`Copy`, `Numeric`, and `Comparable`). Arithmetic is checked, conversions are explicit, and filesystem, network, process, graphics, camera, and concurrency operations stay behind typed builtins with bounded resources.

For concurrent workers, `TaskGroup` provides structured ownership, cancellation propagation, sibling cleanup, and deterministic group joins. Function overloads use statically checked multiple dispatch over all argument types; ambiguous calls are rejected at compile time.

Direct self-recursive calls in tail position use a runtime trampoline, allowing iterative algorithms written recursively without consuming one call-depth slot per iteration.

Kryndel has three build products: `kry run` interprets portable source; `kry build --format=kexe` writes a portable `KRYNATIVE6` bundle containing validated source and canonical typed KIR; and native formats emit machine code. The loader validates embedded KIR against the representation regenerated from those sources. `--format=elf` and `--format=exe` use the generated-C ahead-of-time backend by default. With `--target=windows-x64 --no-external-toolchain`, `--format=exe` selects the direct PE backend and emits machine code without C; `--format=pe-direct` requests that backend explicitly. Both direct PE routes support a documented subset and report unsupported source features before writing an executable. On the direct PE backend, `--gui` sets the Windows GUI subsystem field in the PE header; it does not provide GUI toolkit APIs. `--format=elf-direct` emits Linux amd64 machine code without C for its documented subset. Windows C AOT (`--format=exe` without the flag) still requires MinGW; Linux C AOT requires `cc`/`gcc`/`clang`. `--no-external-toolchain` rejects C formats without a direct target backend, and successful builds print the selected backend and toolchain dependency. `--format=c` emits C source without compiling it. For the Kryndel-authored compiler, `bash scripts/build-selfhost-pe.sh program.kry [program.exe]` runs the locked Stage 1 compiler ELF on Linux amd64/WSL and emits a Windows PE without Go, C, an assembler, or a linker. The generated-C AOT backend supports the TCP client builtins `tcp_connect`, `tcp_send`, `tcp_receive`, and `tcp_close`, plus SQLite `sqlite_open`, `sqlite_exec`, `sqlite_query`, and `sqlite_close`, on Linux amd64/arm64 and Windows amd64. SQLite dynamically loads a system runtime library; see [native backend limits](docs/native.md#sqlite-in-c-aot) for the library names and value limits. TCP listeners, UDP, HTTP/TLS, WebSockets, FFI, regex handles, camera/display APIs, geolocation, process enumeration, and Windows APIs remain unsupported in native backends. The direct ELF and PE backends reject TCP and SQLite builtins. Unsupported host integrations report an explicit builtin diagnostic instead of being silently degraded; the interpreter remains the complete host-integration backend.

Project dependencies are managed with `kry install PACKAGE` and removed with `kry uninstall PACKAGE [PACKAGE ...]`. Uninstall updates `kry.toml`, prunes `vendor/`, and rewrites `kry.lock` while retaining transitive packages still required by another direct dependency. The global download cache is intentionally preserved.

The public registry includes expanded `async`, `crypto`, and `fs` libraries plus the new `json` library. These expose cancellation-aware sleep and structured groups, SHA-256/HMAC/random bytes, sandboxed text/byte filesystem operations, and safe JSON parse/stringify helpers.

## Cryptography and executable protection

The cryptography library covers hashing (`crypto_sha256`, `crypto_sha512`, `crypto_sha384`, `crypto_sha1`, `crypto_md5`), message authentication (`crypto_hmac_sha256`), authenticated encryption (`crypto_aes_gcm_encrypt`/`crypto_aes_gcm_decrypt`), key derivation (`crypto_pbkdf2_sha256`, `crypto_hkdf_sha256`), constant-time comparison (`crypto_constant_time_equal`), byte-wise `crypto_xor`, and `base64url_encode`/`base64url_decode`. Every primitive is implemented in both the interpreter and the native C backend, verified against published vectors (RFC 5869, RFC 6070, NIST GCM), and held to byte-for-byte parity across the interpreter, the Linux ELF, and the Windows PE.

Built artifacts can be protected. `kry build --encrypt` wraps an artifact in the authenticated `KRYSEAL1` container — AES-256-GCM under a PBKDF2-HMAC-SHA-256 key derived from a passphrase — and the plaintext artifact never touches disk. A wrong passphrase, a truncated file, or any tampering fails the GCM tag check and is reported as a categorized artifact diagnostic. Supply the secret with `--passphrase` or `--passphrase-file`; running a sealed `.kexe` interactively prompts for it. `kry build --obfuscate` masks string literals in the native binary so a `strings` scan does not reveal messages or secrets, without changing observable output.

```sh
kry build app.kry --format=elf --encrypt --passphrase-file secret.txt --obfuscate
kry run app.kexe --passphrase-file secret.txt
```

## Python-style ergonomics

Functions may declare default parameter values, so callers can omit trailing arguments:

```kryndel
fn greet(name: String, greeting: String = "Hello") -> String {
    return greeting + ", " + name
}
println(greet("Ada"))          // Hello, Ada
println(greet("Ada", "Hi"))    // Hi, Ada
```

The checker rejects a required parameter that follows a defaulted one and a default value of the wrong type. New helpers close common Python gaps: `string_slice` and `array_slice_range` provide negative-index slicing with clamped bounds, `string_format` substitutes `{}` placeholders with `{{`/`}}` escapes, and `array_indices`/`array_zip` support enumeration and pairing. All are available in the interpreter and the native backend with verified parity.

Functions are collected before the top-level program runs, so a function can be called before its declaration in the source file. The checker still validates the whole program before execution.

## Modules and packages

Modules are resolved relative to the importing source file. The `.kry` extension is optional, paths cannot escape the module root, and only `pub` declarations are exported. Cycles, duplicate exports, unsafe paths, and invalid public types are rejected.

Projects use `kry.toml` and a lock file. Package archives are reproducible, dependency hashes are verified, and vendored sources go through the same parser and checker as local code.

## Runtime and safety

Kryndel uses a bounded runtime. Source size, artifact size, instruction count, wall-clock time, memory, output, network responses, process output, and collection sizes are limited. Threads and channels are shut down on normal exit and on failure. Process execution does not invoke a shell.

`check` runs before evaluation for `run`, `build`, and formatting. Diagnostics include stable categories and can be emitted as JSON with `--json`.

## Repository layout

| Path | Purpose |
| --- | --- |
| `cmd/kry` | CLI, REPL, formatter, and release entry point. |
| `cmd/kry-installer` | Windows installer with `.kry` and `.kexe` associations. |
| `internal/kry` | Lexer, parser, checker, IR, runtime, modules, artifacts, builtins, and package tooling. |
| `internal/platform` | Bounded camera and display capture with target-specific implementations. |
| `std/` | Typed standard-library wrappers. |
| `examples/` | Small programs covering the language and runtime features. |
| `tools/` | Repository launcher and desktop association installer. |
| `docs/` | Language, architecture, modules, diagnostics, testing, and platform notes. |

## Development

```bash
make test
make test-static
make test-race
make coverage
make check-docs
```

The test suite covers parsing, static errors, runtime behavior, modules, artifacts, concurrency cleanup, sandbox boundaries, diagnostics, native headers, package installation, and formatter stability.

## License

Kryndel is released under the [MIT License](LICENSE).