30 Commits

Author SHA1 Message Date
44ea1eebb0 style: auto-format example files with lux fmt
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-17 06:52:44 -05:00
7e76acab18 feat: rebuild website with full learning funnel
Website rebuilt from scratch based on analysis of 11 beloved language
websites (Elm, Zig, Gleam, Swift, Kotlin, Haskell, OCaml, Crystal, Roc,
Rust, Go).

New website structure:
- Homepage with hero, playground, three pillars, install guide
- Language Tour with interactive lessons (hello world, types, effects)
- Examples cookbook with categorized sidebar
- API documentation index
- Installation guide (Nix and source)
- Sleek/noble design (black/gold, serif typography)

Also includes:
- New stdlib/json.lux module for JSON serialization
- Enhanced stdlib/http.lux with middleware and routing
- New string functions (charAt, indexOf, lastIndexOf, repeat)
- LSP improvements (rename, signature help, formatting)
- Package manager transitive dependency resolution
- Updated documentation for effects and stdlib
- New showcase example (task_manager.lux)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 23:05:35 -05:00
b02807ebf4 feat: add property-based testing framework
Implements property-based testing infrastructure:

stdlib/testing.lux:
- Generators: genInt, genIntList, genString, genBool, etc.
- Shrinking helpers: shrinkInt, shrinkList, shrinkString
- Property helpers: isSorted, sameElements

examples/property_testing.lux:
- 10 property tests demonstrating the framework
- Tests for: involution, commutativity, associativity, identity
- 100 iterations per property with random inputs

docs/guide/14-property-testing.md:
- Complete guide to property-based testing
- Generator patterns and common properties
- Best practices and examples

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 04:39:50 -05:00
87c1fb1bbd feat: add PostgreSQL driver with Postgres effect
Implements full PostgreSQL support through the Postgres effect:
- connect(connStr): Connect to PostgreSQL database
- close(conn): Close connection
- execute(conn, sql): Execute INSERT/UPDATE/DELETE, return affected rows
- query(conn, sql): Execute SELECT, return all rows as records
- queryOne(conn, sql): Execute SELECT, return first row as Option
- beginTx(conn): Start transaction
- commit(conn): Commit transaction
- rollback(conn): Rollback transaction

Includes:
- Connection tracking with connection IDs
- Row mapping to Lux records with field access
- Transaction support
- Example: examples/postgres_demo.lux
- Documentation in docs/guide/11-databases.md

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 04:30:44 -05:00
204950357f feat: add HTTP framework with routing and JSON helpers
- Add stdlib/http.lux with:
  - Response builders (httpOk, httpNotFound, etc.)
  - Path pattern matching with parameter extraction
  - JSON construction helpers (jsonStr, jsonNum, jsonObj, etc.)
- Add examples/http_api.lux demonstrating a complete REST API
- Add examples/http_router.lux showing the routing pattern
- Update stdlib/lib.lux to include http module

The framework provides functional building blocks for web apps:
- Route matching: pathMatches("/users/:id", path)
- Path params: getPathSegment(path, 1)
- Response building: httpOk(jsonObj(...))

Note: Due to current type system limitations with type aliases
and function types, the framework uses inline types rather
than abstract Request/Response types.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 04:21:57 -05:00
26d340b5a3 chore: fix flake.nix rebuild detection
Better source change detection using find instead of single file check.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-15 03:54:36 -05:00
634f665b1b feat: add stdlib and browser examples
- stdlib/html.lux: Type-safe HTML construction
- stdlib/browser.lux: Browser utilities
- examples/web/: Counter app with DOM manipulation
- examples/counter.lux: Simple counter example

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-15 03:54:17 -05:00
bba94b534d feat: add FBIP debug counters to prove optimization effectiveness
Add runtime counters tracking FBIP reuse vs copy operations:
- lux_fbip_reuse_count: incremented when rc=1 allows in-place mutation
- lux_fbip_copy_count: incremented when rc>1 forces allocation

Output now shows both memory stats and FBIP stats:
  [RC] No leaks: 13 allocs, 13 frees
  [FBIP] 3 reuses, 0 copies

Rename test_no_fbip.lux to test_ownership_transfer.lux to better
reflect that ownership transfer enables FBIP even with aliases.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 14:52:35 -05:00
25a3adf4fc test: add RC stress tests with large lists
- stress_rc.lux: Single-owner chains testing FBIP optimization
- stress_shared_rc.lux: Shared-reference chains (rc>1) forcing copy path

Both process lists of 100, 200, 500, and 1000 elements with map/filter/reverse.
Verifies no memory leaks with large data sets.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 14:46:21 -05:00
771512a2ec test: add FBIP and RC verification test cases
Add test cases demonstrating FBIP (Functional But In-Place) optimization:
- test_fbip_clean.lux: Basic FBIP chain (map, filter, reverse)
- test_fbip_allocs.lux: Single-owner allocation test with range/map/filter/reverse
- test_no_fbip.lux: Demonstrates shared reference forcing rc>1 path
- test_rc_comparison.lux: Comparison of FBIP vs non-FBIP allocations

All tests verify no memory leaks with the RC system.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 14:44:53 -05:00
ee9acce6ec feat: add Test effect and native testing framework
- Add Test effect with operations: assert, assertEqual, assertNotEqual,
  assertTrue, assertFalse, fail
- Implement Test effect handlers in interpreter with TestResults tracking
- Add values_equal method for comparing Value types in tests
- Update lux test command to discover and run test_* functions
- Create example test files: test_math.lux, test_lists.lux
- Add TESTING_DESIGN.md documentation
- Fix AST mismatches in C backend and compiler.rs for compatibility

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 01:20:30 -05:00
f5fe7d5335 fix: fix examples to use working patterns
- behavioral.lux: use verifiable behavioral patterns (abs for idempotent)
- behavioral_types.lux: use simpler verified patterns, proper main invocation
- schema_evolution.lux: simplify to runtime schema ops, fix record access
- jit_test.lux: add proper main function with console output

All examples now parse and run correctly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 23:31:21 -05:00
cdc4f47272 fix: fix REST API and HTTP server examples
- Fix string interpolation issues: escape curly braces with \{ and \}
  since unescaped { triggers string interpolation
- Fix effectful function invocation: use "let _ = run main() with {}"
  instead of bare "main()" calls
- Use inline record types instead of type aliases (structural typing)
- Fix flake.nix to show build progress instead of suppressing output

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 23:11:51 -05:00
705bd57e81 docs: add demos and update documentation for new features
Documentation:
- Update IMPLEMENTATION_PLAN.md with current status (222 tests)
- Update feature comparison table (Schema Evolution, Behavioral Types: )
- Add HttpServer to built-in effects list
- Update OVERVIEW.md with working behavioral types examples

Demo Programs:
- examples/schema_evolution.lux - Version annotations, constraints, runtime ops
- examples/behavioral_types.lux - pure, deterministic, commutative, idempotent, total

Sample Project:
- projects/rest-api/ - Full REST API demo with:
  - Task CRUD endpoints
  - Pattern matching router
  - JSON serialization
  - Effect-tracked request handling

Tests:
- Add behavioral type tests (pure, deterministic, commutative, idempotent, total)
- 227 tests passing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 22:14:55 -05:00
086552b7a4 feat: add schema evolution type system integration and HTTP server effect
Schema Evolution:
- Preserve version info in type resolution (Type::Versioned)
- Track versioned type declarations in typechecker
- Detect version mismatches at compile time (@v1 vs @v2 errors)
- Support @v2+ (at least) and @latest version constraints
- Store migrations for future auto-migration support
- Fix let bindings to preserve declared type annotations

HTTP Server Effect:
- Add HttpServer effect with listen, accept, respond, respondWithHeaders, stop
- Implement blocking request handling via tiny_http
- Request record includes method, path, body, headers
- Add http_server.lux example with routing via pattern matching
- Add type-checking test for HttpServer effect

Tests: 222 passing (up from 217)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 22:06:31 -05:00
554a1e7c3e feat: expose JIT compiler via CLI command
Add `lux compile <file>` command that compiles and runs Lux code using
the Cranelift JIT compiler. Includes --benchmark flag for timing.

- Add compile_file() function in main.rs
- Add jit_test.lux example with fib(30) + factorial(10)
- Update VISION.md status

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 21:16:39 -05:00
ebc0bdb109 feat: improve error messages with context lines
- Show 2 lines of context before and after errors (dimmed)
- Fix guessing_game.lux to be non-interactive for testing
- Use binary search simulation to demonstrate game logic

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 18:13:57 -05:00
9ee7148d24 feat: add module import examples and standard library
Module system was already implemented - this adds examples and stdlib:

examples/modules/:
- math_utils.lux: Reusable math functions (square, cube, factorial)
- string_utils.lux: String utilities (repeat, exclaim, greet)
- main.lux: Basic module import example
- main_selective.lux: Selective imports {fn1, fn2}
- main_wildcard.lux: Wildcard imports (module.*)
- use_stdlib.lux: Using the standard library

std/:
- prelude.lux: Core utilities (identity, compose, flip, not, and, or)
- io.lux: I/O helpers (println, readLine, debug)
- option.lux: Option utilities (some, none, map, flatMap, filter)
- result.lux: Result utilities (ok, err, mapOk, mapErr)

Import syntax supports:
- import path/to/module       (access as module.fn)
- import path/to/module as x  (access as x.fn)
- import path/to/module.{a,b} (access as a, b directly)
- import path/to/module.*     (all exports directly)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 17:28:23 -05:00
0b5abece5f feat: add comprehensive example programs
Standard examples (examples/standard/):
- hello_world: Basic effect usage
- fizzbuzz: Classic programming exercise
- factorial: Recursive and tail-recursive versions
- primes: Prime number generation
- guessing_game: Interactive Random + Console effects
- stdlib_demo: Demonstrates List, String, Option, Math modules

Showcase examples (examples/showcase/):
- ask_pattern: Resumable effects for config/environment
- custom_logging: Custom effect with handler
- early_return: Fail effect for clean error handling
- effect_composition: Combining multiple effects
- higher_order: Closures and function composition
- pattern_matching: ADTs and exhaustive matching

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 17:25:04 -05:00
296686de17 feat: add HTTP client support
Add Http effect for making HTTP requests:
- Http.get(url) - GET request
- Http.post(url, body) - POST with string body
- Http.postJson(url, json) - POST with JSON body
- Http.put(url, body) - PUT request
- Http.delete(url) - DELETE request

Returns Result<HttpResponse, String> where HttpResponse contains
status code, body, and headers.

Includes reqwest dependency with blocking client, OpenSSL support
in flake.nix, and example at examples/http.lux demonstrating
API requests with JSON parsing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 16:30:48 -05:00
ef9746c2fe feat: add JSON parsing and manipulation support
Add comprehensive JSON support via the Json module:
- Parse JSON strings with Json.parse() returning Result<Json, String>
- Stringify with Json.stringify() and Json.prettyPrint()
- Extract values with Json.get(), getIndex(), asString(), asInt(), etc.
- Build JSON with constructors: Json.null(), bool(), int(), string(), array(), object()
- Query with Json.isNull() and Json.keys()

Includes example at examples/json.lux demonstrating building, parsing,
and extracting JSON data with file I/O integration.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 16:22:35 -05:00
b0f6756411 feat: add File and Process effects for real I/O
Adds two essential effects that enable Lux to interact with the system:

File effect:
- read(path) - Read file contents as string
- write(path, content) - Write string to file
- append(path, content) - Append to file
- exists(path) - Check if file/directory exists
- delete(path) - Delete a file
- readDir(path) - List directory contents
- isDir(path) - Check if path is directory
- mkdir(path) - Create directory (including parents)

Process effect:
- exec(cmd) - Run shell command, return stdout
- execStatus(cmd) - Run command, return exit code
- env(name) - Get environment variable (returns Option)
- args() - Get command line arguments
- exit(code) - Exit program with code
- cwd() - Get current working directory
- setCwd(path) - Change working directory

Also fixes formatter bug with empty handler blocks in `run ... with {}`.

These effects make Lux capable of writing real CLI tools and scripts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 16:09:20 -05:00
4eebaebb27 feat: implement Schema module for versioned types
Add Schema module with functions for creating and migrating versioned
values. This provides the runtime foundation for schema evolution.

Schema module functions:
- Schema.versioned(typeName, version, value) - create versioned value
- Schema.migrate(value, targetVersion) - migrate to new version
- Schema.getVersion(value) - get version number

Changes:
- Add Versioned, Migrate, GetVersion builtins to interpreter
- Add Schema module to global environment
- Add Schema module type to type environment
- Add 4 tests for schema operations
- Add examples/versioning.lux demonstrating usage

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:59:52 -05:00
9511957076 feat: implement resumable effect handlers
Add support for the `resume(value)` expression in effect handler
bodies. When resume is called, the value becomes the return value
of the effect operation, allowing handlers to provide values back
to the calling code.

Implementation:
- Add Resume(Value) variant to EvalResult
- Add in_handler_depth tracking to Interpreter
- Update Expr::Resume evaluation to return Resume when in handler
- Handle Resume results in handle_effect to use as return value
- Add 2 tests for resumable handlers

Example usage:
```lux
handler prettyLogger: Logger {
    fn log(level, msg) = {
        Console.print("[" + level + "] " + msg)
        resume(())  // Return Unit to the call site
    }
}
```

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:54:51 -05:00
52ad5f8781 feat: implement Random and Time built-in effects
Add Random and Time effects for random number generation and
time-based operations. These effects can be used in any
effectful code block.

Random effect operations:
- Random.int(min, max) - random integer in range [min, max]
- Random.float() - random float in range [0.0, 1.0)
- Random.bool() - random boolean

Time effect operations:
- Time.now() - current Unix timestamp in milliseconds
- Time.sleep(ms) - sleep for specified milliseconds

Changes:
- Add rand crate dependency
- Add Random and Time effect definitions to types.rs
- Add effects to built-in effects list in typechecker
- Implement effect handlers in interpreter
- Add 4 new tests for Random and Time effects
- Add examples/random.lux demonstrating usage

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:49:09 -05:00
c0ef71beb7 feat: implement built-in State, Reader, and Fail effects
Add runtime support for the State, Reader, and Fail effects that
were already defined in the type system. These effects can now be
used in effectful code blocks.

Changes:
- Add builtin_state and builtin_reader fields to Interpreter
- Implement State.get and State.put in handle_builtin_effect
- Implement Reader.ask in handle_builtin_effect
- Add Reader effect definition to types.rs
- Add Reader to built-in effects list in typechecker
- Add set_state/get_state/set_reader/get_reader methods
- Add 6 new tests for built-in effects
- Add examples/builtin_effects.lux demonstrating usage

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:46:13 -05:00
f670bd2659 feat: implement string interpolation
Add support for string interpolation with {expr} syntax:
  "Hello, {name}!" becomes "Hello, " + toString(name) + "!"

Lexer changes:
- Add StringPart enum (Literal/Expr) and InterpolatedString token
- Detect {expr} in strings and capture expression text
- Support escaped braces with \{ and \}

Parser changes:
- Add desugar_interpolated_string() to convert to concatenation
- Automatically wrap expressions in toString() calls

Interpreter changes:
- Fix toString() to not add quotes around strings

Tests added:
- 4 lexer tests for interpolation tokenization
- 4 integration tests for full interpolation pipeline

Add examples/interpolation.lux demonstrating:
- Variable interpolation
- Number interpolation (auto toString)
- Expression interpolation ({a + b})
- Escaped braces

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:30:37 -05:00
3734a17e5c feat: implement generic type parameters
Add full support for user-defined generic types and functions:

- Add type_params field to TypeChecker to track type parameters in scope
- Update resolve_type() to resolve type parameters to their bound variables
- Update function_type() to bind type parameters and return polymorphic TypeScheme
- Update type declaration handling for generic ADTs (e.g., Pair<A, B>)

Generic functions and types now work:
  fn identity<T>(x: T): T = x
  type Pair<A, B> = | MkPair(A, B)
  fn first<A, B>(p: Pair<A, B>): A = ...

Add examples/generics.lux demonstrating:
- Generic identity function
- Generic Pair type with first/second accessors
- Generic mapOption function

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:20:36 -05:00
15a820a467 fix: make all example programs work correctly
- Add string concatenation support to + operator in typechecker
- Register ADT constructors in both type environment and interpreter
- Bind handlers as values so they can be referenced in run...with
- Fix effect checking to use subset instead of exact match
- Add built-in effects (Console, Fail, State) to run block contexts
- Suppress dead code warnings in diagnostics, modules, parser

Update all example programs with:
- Expected output documented in comments
- Proper run...with statements to execute code

Add new example programs:
- behavioral.lux: pure, idempotent, deterministic, commutative functions
- pipelines.lux: pipe operator demonstrations
- statemachine.lux: ADT-based state machines
- tailcall.lux: tail call optimization examples
- traits.lux: type classes and pattern matching

Add documentation:
- docs/IMPLEMENTATION_PLAN.md: feature roadmap and status
- docs/PERFORMANCE_AND_TRADEOFFS.md: performance analysis

Add benchmarks for performance testing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:05:06 -05:00
15e5ccb064 init lux 2026-02-13 02:57:01 -05:00