Commit Graph

33 Commits

Author SHA1 Message Date
3ee3529ef6 feat: improve REPL with syntax highlighting and documentation
REPL improvements:
- Syntax highlighting for keywords (magenta), types (blue),
  strings (green), numbers (yellow), comments (gray)
- :doc command to show documentation for functions
- :browse command to list module exports
- Added docs for List, String, Option, Result, Console,
  Random, File, Http, Time, Sql, Postgres, Test modules

Example usage:
  lux> :doc List.map
  lux> :browse String
  lux> :doc fn

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 04:43:33 -05:00
3a46299404 feat: Elm-quality error messages with error codes
- Add ErrorCode enum with categorized codes (E01xx parse, E02xx type,
  E03xx name, E04xx effect, E05xx pattern, E06xx module, E07xx behavioral)
- Extend Diagnostic struct with error code, expected/actual types, and
  secondary spans
- Add format_type_diff() for visual type comparison in error messages
- Add help URLs linking to lux-lang.dev/errors/{code}
- Update typechecker, parser, and interpreter to use error codes
- Categorize errors with specific codes and helpful hints

Error messages now show:
- Error code in header: -- ERROR[E0301] ──
- Clear error category title
- Visual type diff for type mismatches
- Context-aware hints
- "Learn more" URL for documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-16 04:11:15 -05:00
ccd335c80f feat: improve CLI with auto-discovery and JS target
- Auto-discover .lux files for fmt and check commands
- Add --target js flag for JavaScript compilation
- Improve help text for new features

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-15 03:54:11 -05:00
10ff8dc6ad feat: add JavaScript backend for browser/Node.js compilation
Implement Phase 1 of the browser/frontend plan with a complete JS
code generator that compiles Lux programs to JavaScript:

- Basic types: Int, Float, Bool, String, Unit → JS primitives
- Functions and closures → native JS functions with closure capture
- Pattern matching → if/else chains with tag checks
- ADT definitions → tagged object constructors
- Built-in types (Option, Result) → Lux.Some/None/Ok/Err helpers
- Effects → handler objects passed as parameters
- List operations → Array methods (map, filter, reduce, etc.)
- Top-level let bindings and run expressions

CLI usage:
  lux compile app.lux --target js -o app.js
  lux compile app.lux --target js --run

Tested with factorial, datatypes, functional, tailcall, and hello
examples - all producing correct output when run in Node.js.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 21:22:43 -05:00
909dbf7a97 feat: add list support to C backend and improve compile workflow
C Backend Lists:
- Add LuxList type (dynamic array with void* boxing)
- Implement all 16 list operations: length, isEmpty, concat, reverse,
  range, take, drop, head, tail, get, map, filter, fold, find, any, all
- Higher-order operations generate inline loops with closure calls
- Fix unique variable names to prevent redefinition errors

Compile Command:
- `lux compile file.lux` now produces a binary (like rustc, go build)
- Add `--emit-c` flag to output C code instead
- Binary name derived from source filename (foo.lux -> ./foo)
- Clean up temp files after compilation

Documentation:
- Create docs/C_BACKEND.md with full strategy documentation
- Document compilation pipeline, runtime types, limitations
- Compare with Koka, Rust, Zig, Go, Nim, OCaml approaches
- Outline future roadmap (evidence passing, Perceus RC)
- Fix misleading doc comment (remove false Perceus claim)
- Update OVERVIEW.md and ROADMAP.md to reflect list completion

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 11:02:26 -05:00
67437b8273 feat: replace Cranelift JIT with C backend
Remove Cranelift JIT compiler and expose the existing C backend as the
compilation target. Generated C code can be compiled with GCC/Clang.

Changes:
- Remove cranelift-* dependencies from Cargo.toml
- Delete src/compiler.rs (565 lines of Cranelift code)
- Add compile_to_c() function with -o and --run flags
- Fix C backend name mangling (main -> main_lux) to avoid conflicts
- Update CLI help text and documentation

Usage:
  lux compile <file.lux>           # Output C to stdout
  lux compile <file.lux> -o out.c  # Write to file
  lux compile <file.lux> --run     # Compile and execute

C backend supports: functions, basic types, operators, if/then/else,
records, enums, Console.print. Future work: closures, lists, patterns.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 03:37:35 -05:00
c81349d82c fix: resolve all stress test bugs
- Record equality: add Record case to values_equal in interpreter
- Invalid escapes: error on unknown escape sequences in lexer
- Unknown effects: validate effect names in check_function with suggestions
- Circular types: add DFS cycle detection in check_type_cycles
- Parser: require | for enum variants, enabling proper type alias syntax

All 265 tests pass.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-14 02:45:52 -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
6ace4dea01 feat: add integration tests and lint script for examples
- Add 30 integration tests that verify all examples and projects
  parse and type-check correctly
- Add scripts/lint-examples.sh for quick pre-commit validation
- Tests will catch regressions like missing `run ... with {}` syntax
  or broken escape sequences

Run with: cargo test example_tests
Or quick check: ./scripts/lint-examples.sh

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 23:35:22 -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
d8e01fd174 feat: implement Cranelift JIT compiler for native code execution
Add a JIT compiler using Cranelift that compiles Lux functions to native
machine code. Achieves ~160x speedup over the tree-walking interpreter
(fib(30): 11.59ms JIT vs 1.87s interpreter).

Supports: arithmetic, comparisons, conditionals, let bindings, function
calls, and recursion. Compile time overhead is minimal (~500µs).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 17:11:19 -05:00
a037f5bd2f feat: implement package manager
Adds dependency management for Lux projects:
- `lux pkg install` - Install all dependencies from lux.toml
- `lux pkg add <pkg>` - Add a dependency (supports --git, --path)
- `lux pkg remove <pkg>` - Remove a dependency
- `lux pkg list` - List dependencies with install status
- `lux pkg update` - Update all dependencies
- `lux pkg clean` - Remove installed packages

Supports three dependency sources:
- Registry (placeholder for future package registry)
- Git repositories (with optional branch)
- Local file paths

Packages are installed to .lux_packages/ in the project root.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 10:44:49 -05:00
1c59fdd735 feat: implement interactive debugger
Adds a REPL-based debugger with:
- Breakpoint management (set/delete by line number)
- Single-step and continue execution modes
- Source code listing with breakpoint markers
- Expression evaluation in debug context
- Variable inspection and call stack display

Usage: lux debug <file.lux>

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 10:37:02 -05:00
f786d18182 feat: add devtools (tree-sitter, neovim, formatter, CLI commands)
- Add tree-sitter grammar for syntax highlighting
- Add Neovim plugin with syntax, LSP integration, and commands
- Add code formatter (lux fmt) with check mode
- Add CLI commands: fmt, check, test, watch, init
- Add project initialization with lux.toml template

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 10:30:13 -05:00
961a861822 feat: expand standard library with Math module and new functions
- Add Math module: abs, min, max, sqrt, pow, floor, ceil, round
- Add List functions: isEmpty, find, any, all, take, drop
- Add String functions: startsWith, endsWith, toUpper, toLower, substring
- Add 12 tests for new standard library functions

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 10:15:14 -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
62be78ff99 feat: implement better error messages with 'Did you mean?' suggestions
Add Levenshtein distance-based similarity matching for undefined
variables, unknown types, unknown effects, and unknown traits.
When a name is not found, the error now suggests similar names
within edit distance 2.

Changes:
- Add levenshtein_distance() function to diagnostics module
- Add find_similar_names() and format_did_you_mean() helpers
- Update typechecker to suggest similar names for:
  - Undefined variables
  - Unknown types
  - Unknown effects
  - Unknown traits
- Add 17 new tests for similarity matching

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 09:39:26 -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
20bf75a5f8 feat: implement LSP server for IDE integration
Add a Language Server Protocol (LSP) server to enable IDE integration.
The server provides:

- Real-time diagnostics (parse errors and type errors)
- Basic hover information
- Keyword completions (fn, let, if, match, type, effect, etc.)
- Go-to-definition stub (ready for implementation)

Usage: lux --lsp

The LSP server can be integrated with any editor that supports LSP,
including VS Code, Neovim, Emacs, and others.

Dependencies added:
- lsp-server 0.7
- lsp-types 0.94
- serde with derive feature
- serde_json

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 05:42:37 -05:00
3206aad653 feat: implement documentation comments
Add support for doc comments (/// syntax) that can be attached to
declarations for documentation purposes. The implementation:

- Adds DocComment token kind to lexer
- Recognizes /// as doc comment syntax (distinct from // regular comments)
- Parses consecutive doc comments and combines them into a single string
- Adds doc field to FunctionDecl, TypeDecl, LetDecl, EffectDecl, TraitDecl
- Passes doc comments through parser to declarations
- Multiple consecutive doc comment lines are joined with newlines

This enables documentation extraction and could be used for generating
API docs, IDE hover information, and REPL help.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 05:08:47 -05:00
6f860a435b feat: implement effect inference
Add automatic effect inference for functions and lambdas that don't
explicitly declare their effects. The implementation:

- Tracks inferred effects during type checking via `inferred_effects`
- Uses `inferring_effects` flag to switch between validation and inference
- Functions without explicit `with {Effects}` have their effects inferred
- Lambda expressions also support effect inference
- When effects are explicitly declared, validates that inferred effects
  are a subset of declared effects
- Pure functions are checked against both declared and inferred effects

This makes the effect system more ergonomic by not requiring explicit
effect annotations for every function while still maintaining safety.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 04:58:49 -05:00
05a85ea27f feat: implement type classes / traits
Add support for type classes (traits) with full parsing, type checking, and
validation. The implementation includes:

- Trait declarations: trait Show { fn show(x: T): String }
- Trait implementations: impl Show for Int { fn show(x: Int) = ... }
- Super traits: trait Ord: Eq { ... }
- Trait constraints in where clauses: where T: Show + Eq
- Type parameters on traits: trait Functor<F> { ... }
- Default method implementations
- Validation of required method implementations

This provides a foundation for ad-hoc polymorphism and enables
more expressive type-safe abstractions.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 04:51:06 -05:00
df5c0a1a32 feat: implement tail call optimization (TCO)
Add trampoline-based tail call optimization to prevent stack overflow
on deeply recursive tail-recursive functions. The implementation:

- Extends EvalResult with TailCall variant for deferred evaluation
- Adds trampoline loop in eval_expr() to handle tail calls iteratively
- Propagates tail position through If, Let, Match, and Block expressions
- Updates all builtin callbacks to handle tail calls via eval_call_to_value
- Includes tests for deep recursion (10000+ calls) and accumulator patterns

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 04:42:53 -05:00
052db9c88f Add enhanced REPL with rustyline
REPL improvements:
- Tab completion for keywords, commands, and user definitions
- Persistent history saved to ~/.lux_history
- Better line editing with Emacs keybindings
- Ctrl-C to cancel input, Ctrl-D to exit
- History search with Ctrl-R

New commands:
- :info <name> - Show type information for a binding
- :env - List user-defined bindings with types

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 04:32:52 -05:00
db516f5cff Add pattern match exhaustiveness checking
Implements the exhaustiveness algorithm to detect non-exhaustive pattern matches:
- Detects missing Bool patterns (true/false)
- Detects missing Option patterns (Some/None)
- Detects missing Result patterns (Ok/Err)
- Recognizes wildcards and variable patterns as catch-alls
- Warns about redundant patterns after catch-all patterns
- Integrates with the type checker to report errors

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 04:19:56 -05:00
d37f0fb096 Add Elm-style error diagnostics
Implement beautiful, informative error messages inspired by Elm:
- Rich diagnostic rendering with source code snippets
- Colored output with proper underlines showing error locations
- Categorized error titles (Type Mismatch, Unknown Name, etc.)
- Contextual hints and suggestions for common errors
- Support for type errors, runtime errors, and parse errors

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 04:01:49 -05:00
66132779cc Add behavioral types system
Implement behavioral properties for functions including:
- Property annotations: is pure, is total, is idempotent, is deterministic, is commutative
- Where clause constraints: where F is pure
- Result refinements: where result >= 0 (parsing only, not enforced)

Key changes:
- AST: BehavioralProperty enum, WhereClause enum, updated FunctionDecl
- Lexer: Added keywords (is, pure, total, idempotent, deterministic, commutative, where, assume)
- Parser: parse_behavioral_properties(), parse_where_clauses(), parse_single_property()
- Types: PropertySet for tracking function properties, updated Function type
- Typechecker: Verify pure functions don't have effects, validate where clause type params

Properties are informational/guarantees rather than type constraints - a pure
function can be used anywhere a function is expected. Property requirements
are meant to be enforced via where clauses (future work: call-site checking).

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