Commit Graph

151 Commits

Author SHA1 Message Date
Michael Schimmel 580c0893c1 Update gemini.md 2026-02-28 14:45:06 +01:00
Michael Schimmel 58c5651b97 Refactor execute_trace to use run_debug
This commit refactors the `execute_trace` function to utilize the
`run_debug` method on the `Environment`. This simplifies the execution
flow and leverages existing functionality for tracing and error
handling.
2026-02-28 14:44:44 +01:00
Michael Schimmel 2cc47c557b Update benchmark results
This commit updates the benchmark results for various examples. The
benchmark times and repeat counts have been adjusted to reflect current
performance characteristics.
2026-02-28 14:27:54 +01:00
Michael Schimmel 0dfbda5e15 Refactor VM to use trait objects for closures
The `CallFrame` struct and various VM methods now use `Rc<dyn Object>`
to hold closures, allowing for more flexibility and avoiding unnecessary
cloning.

This change also addresses the performance concern regarding deep copies
of closures, preferring `Rc<dyn Trait>` with local `downcast_ref` where
appropriate.

Additionally, a documentation note has been added to `gemini.md`
regarding this performance preference in Rust.
2026-02-28 14:26:29 +01:00
Michael Schimmel 3daf8ef94d Fix: Clone closure directly for tail calls 2026-02-28 13:13:17 +01:00
Michael Schimmel 7126668934 Add prelude and while macro
This commit introduces a new prelude file that defines the `while` macro
and registers it during environment bootstrapping. The `again` macro has
been updated to accept multiple arguments for its recursive call, and
several examples have been adjusted to reflect this change.
Additionally, the `MacroRegistry` in the compiler is now cloneable and
can be moved out of the `MacroExpander`.
2026-02-28 12:41:19 +01:00
Michael Schimmel 83324a1892 feat: Document AST node structure across compiler stages
Add a new Markdown document detailing the AST node structure as it
evolves through the compiler's different stages. This includes a diagram
illustrating the data flow and relationships between the generic
`Node<K, T>` structure and its specialized forms (`UntypedNode`,
`BoundNode`, `TypedNode`, `AnalyzedNode`). The document explains the
`kind` and `ty` payloads for each stage and their significance.

Also removes a deleted file related to a previous optimization plan and
adds new files for future optimization plans.
2026-02-27 08:58:38 +01:00
Michael Schimmel e104e7f59b Add benchmark data to object_records.myc 2026-02-26 21:59:09 +01:00
Michael Schimmel 512193febc Add object-oriented records example 2026-02-26 21:54:26 +01:00
Michael Schimmel bf74795e01 Refactor: Implement Record Layouts and Optimized Field Access
Introduces a new `RecordLayout` system for efficient and type-safe
record handling.

Key changes:
- `RecordLayout` struct with `O(1)` field lookup using FMap
  optimization.
- Field accessors (`.name`) are now first-class callable values.
- Parser recognizes dot-prefixed identifiers as field accessors.
- Binder and TypeChecker handle field accessors.
- Optimizer transforms field accessor calls into specialized `GetField`
  nodes.
- VM executes `GetField` efficiently by directly accessing record
  values.
- Adds a new `records.myc` example showcasing record features.
- Improves comparison logic for records to use pointer equality for
  layout.
2026-02-26 21:38:20 +01:00
Michael Schimmel 2ad2eb5d43 Remove unused record destructuring tests
These tests were for record destructuring, which has been removed.
The code for record destructuring was also removed from the type checker
and types modules.
2026-02-26 10:58:46 +01:00
Michael Schimmel 81c805f07e Refactor optimizer utilities
Removes unused `flatten_tuple` function from optimizer utilities. The
functionality was moved to the `Folder` struct, making it more
contextually appropriate. This change streamlines the utility module and
improves code organization.
2026-02-25 21:26:12 +01:00
Michael Schimmel cf87bbeac5 Refactor tuple argument handling in inliner
Remove redundant tuple flattening logic in `map_params_to_args`. The
existing logic for iterating through tuple elements already correctly
handles nested tuples and records by recursively calling
`map_params_to_args`.
2026-02-25 21:19:12 +01:00
Michael Schimmel 42ad8455b0 Refactor tuple flattening in Specializer 2026-02-25 21:09:38 +01:00
Michael Schimmel 04f2203900 Refactor: Move utils to separate module
Moves `PathTracker` and `UsageInfo` to the `utils` module to improve
code organization.
2026-02-25 20:35:12 +01:00
Michael Schimmel cad0c03973 Refactor: Move inlining logic to Inliner struct
Introduces the `Inliner` struct to encapsulate logic related to value
and function inlining. This improves code organization and readability
within the optimizer engine.

Key changes include:
- Moving `is_inlinable_value` to the `Inliner` struct.
- Extracting beta-reduction preparation logic into
  `Inliner::prepare_beta_reduction`.
- Moving parameter slot collection to
  `Inliner::collect_parameter_slots`.
- Introducing `flatten_tuple` to a new `utils` module, used by both
  `Folder` and `Inliner`.
2026-02-25 20:07:37 +01:00
Michael Schimmel 7f64e7e6ea Refactor Optimizer to use Folder
Extract common AST manipulation and folding logic into a new Folder
struct. This improves code organization and reusability. The Optimizer
now delegates these tasks to the Folder.
2026-02-25 19:57:00 +01:00
Michael Schimmel d3d1497c02 Refactor: Move optimizer related types to dedicated module
This commit reorganizes the optimizer code by creating a new `optimizer`
module. The `Optimizer` struct and its related logic remain in
`optimizer/optimizer.rs`, while `SubstitutionMap` and `UsageInfo` are
moved to `optimizer/substitution_map.rs`.

This change improves code organization and makes it easier to manage the
optimizer's components.
2026-02-25 19:47:33 +01:00
Michael Schimmel c64902726b Refactor address types to use newtype wrappers
This commit introduces newtype wrappers for `LocalSlot`, `UpvalueIdx`,
and `GlobalIdx` to improve type safety and clarity. These wrappers
replace direct use of `u32` for indices, making the code more robust and
easier to understand.

The changes include:
- Defining `LocalSlot`, `UpvalueIdx`, and `GlobalIdx` structs.
- Implementing `Display` for these new types to provide user-friendly
  output.
- Updating the `Address` enum to use these new types.
- Modifying various compiler components (analyzer, binder, optimizer,
  type checker, environment, VM) to use the new types.
- Adjusting tests to accommodate the changes.
2026-02-25 18:24:26 +01:00
Michael Schimmel 11f6115fc1 Handle macro expansion in lambda collection
Recursively traverse through `BoundKind::Expansion` nodes when
collecting lambdas to ensure that macros correctly expanded into lambdas
are registered. This also updates assignments to global variables to
correctly track lambdas that have been assigned after macro expansion.

Added a new integration test to verify that macro-wrapped function calls
are correctly inlined and optimized, and that unused definitions are
removed by dead code elimination.
2026-02-25 13:47:50 +01:00
Michael Schimmel b12b85f54a Create optimizer_collision_repro.myc 2026-02-25 13:44:08 +01:00
Michael Schimmel 3ff7ba9d59 Refactor NodeIdentity to use unique IDs
The `NodeIdentity` struct has been refactored to use a unique `id` field
generated by an atomic counter. This ensures that each `NodeIdentity`
instance is distinct, even if it has the same `SourceLocation`. The
`location` field is now optional, allowing for anonymous nodes.

This change improves the reliability of identity comparisons and
provides a more robust way to manage AST node identities.
2026-02-25 13:43:57 +01:00
Michael Schimmel 7436edc9b5 Forgot to add captures.rs 2026-02-25 12:19:44 +01:00
Michael Schimmel 0371c21523 Refactor: Remove explicit upvalue analysis pass
The `UpvalueAnalyzer` pass is no longer necessary as the binder now
directly tracks captures. This commit removes the `UpvalueAnalyzer`
struct and associated logic from `src/ast/compiler/upvalues.rs`.

The `Binder::bind_root` function now returns the `captures` map, which
is then processed by a new `CapturePass` in `src/ast/environment.rs`
before type checking. This consolidates capture logic within the binder
and its subsequent processing steps.
2026-02-25 12:15:59 +01:00
Michael Schimmel 82daf03522 Refactor function compiler scope handling
Introduce a `ScopeKind` enum to distinguish between root and local
scopes.
This allows the `FunctionCompiler` to correctly handle global variable
declarations in the root scope and local variables in other scopes.
The `define_variable` method is introduced to encapsulate this logic.
2026-02-25 11:19:08 +01:00
Michael Schimmel d109cb2018 Refactor type checking for globals
Introduces a `global_types` field to `TypeContext` and updates the
`TypeChecker` to pass it down. This allows type checking to correctly
infer and set types for global variables, removing the previous
hardcoded `StaticType::Any` for global addresses.
2026-02-25 11:14:19 +01:00
Michael Schimmel 6034216524 Refactor AST inlining and global purity checks
Rename `ast_locals` to `ast_substitutions` for clarity.
Update `is_inlinable_value` to accept `Address` and check global purity
separately.
Simplify inlining logic in `optimize_node`.
2026-02-25 11:09:22 +01:00
Michael Schimmel 283cdf61a4 Refactor UsageInfo and SubstitutionMap
This commit refactors the `UsageInfo` struct to use a single
`HashSet<Address>` for both used and assigned addresses, simplifying the
logic. It also updates the `SubstitutionMap` to use a similar approach
for tracking assigned values.

Key changes include:
- `UsageInfo` now has `used` and `assigned` fields of type
  `HashSet<Address>`.
- `SubstitutionMap`'s `add_local`, `add_global`, `add_upvalue`,
  `remove_local`, `remove_global`, and `remove_upvalue` methods have
  been replaced with a generic `add_value` and `remove_value` that
  operate on `Address`.
- The `Optimizer`'s `collect_pattern_usage` and `visit_node` methods
  have been updated to use the new `UsageInfo` and `SubstitutionMap`
  APIs.
- `Get` and `Set` nodes now use `sub.map_address` to transform addresses
  based on the current substitution.
2026-02-25 10:57:58 +01:00
Michael Schimmel c256a8a992 Refactor: Use generic Define bound kind
This commit consolidates `DefLocal` and `DefGlobal` into a single
`Define` bound kind. This simplifies the AST and makes it more
consistent.

It also introduces `DeclarationKind` to differentiate between variable
and parameter definitions.
2026-02-25 10:45:36 +01:00
Michael Schimmel f995aaf81b Formatting 2026-02-25 09:59:23 +01:00
Michael Schimmel e07acc0208 Refactor optimizer to track upvalue usage
The `UsageInfo` struct has been updated to include tracking for
`used_upvalues` and `assigned_upvalues`. The `collect_usage` function
has been modified to handle these new fields when encountering
`Address::Upvalue`.

The `map_params_to_args` function now takes `body_usage` as an argument
to ensure that parameters assigned to or used in the body are correctly
substituted. A new helper function, `collect_parameter_slots_set`, has
been added to gather all parameter slots within a pattern.

The inlining logic in `Optimizer::inline_call` has been enhanced to
prevent inlining if a parameter is used or assigned in the function body
but cannot be substituted. This addresses a bug where aggressive
inlining could lead to incorrect code generation when parameters were
reassigned.

A new integration test, `test_closure_reassignment_optimization_bug`,
has been added to specifically target and verify the fix for this
inlining issue.
2026-02-24 12:53:06 +01:00
Michael Schimmel 2c652e0140 feat: Improve destructuring and function call type checking
Refine the type checker to correctly handle destructuring of various
collection types (tuples, vectors, matrices, lists, records).

Additionally, prevent implicit type coercion for function arguments,
ensuring that only tuples are passed to functions expecting tuple
arguments. This avoids unexpected behavior where vectors or matrices
might be treated as tuples.

Add a new example file demonstrating pattern matching and destructuring
rules.
2026-02-24 11:37:31 +01:00
Michael Schimmel 683d0f4dbe Simplify tuple flattening and destructuring
The `flatten_tuple` function was unnecessarily recursive. It can now
simply return the elements of the tuple directly. The VM's destructuring
logic has been updated to handle nested destructuring more efficiently.
A new integration test case for multi-level destructuring has been
added.
2026-02-24 10:10:47 +01:00
Michael Schimmel 6810d5fa9f Formatting 2026-02-24 08:51:51 +01:00
Michael Schimmel 51d83562de Refactor Destructure to handle assignments
Renames `DefDestructure` to `Destructure` to better reflect its use in
both definitions and assignments.
Introduces `bind_assign_pattern` to handle assignment destructuring in
the binder.
Adds `test_assign_destructuring` to verify assignment destructuring
functionality.
2026-02-24 08:51:24 +01:00
Michael Schimmel 2b0e7f49d7 Formatting 2026-02-24 08:41:18 +01:00
Michael Schimmel 252b725677 Add support for destructuring def
This commit introduces the `DefDestructure` bound kind and modifies the
binder, analyzer, type checker, and VM to support destructuring in `def`
statements. This allows for pattern matching on the right-hand side of a
`def` to bind multiple variables.

The parser has been updated to accept patterns in `def` statements. The
binder now handles `UntypedKind::Def` with a `target` pattern, rather
than a simple `name`. This enables destructuring.

The `Gemini.md` documentation has been updated to include a new rule for
incremental development.
2026-02-24 08:40:45 +01:00
Michael Schimmel eeb6621280 Formatting 2026-02-24 07:27:13 +01:00
Michael Schimmel 9b7ef5080c Create again.myc 2026-02-23 20:33:56 +01:00
Michael Schimmel 4905b08548 Add 'again' keyword for recursive calls
The `again` keyword is introduced to facilitate explicit recursive
function calls.
It is restricted to tail-call positions to prevent dead code and ensure
TCO
optimization. Type checking is enhanced to validate argument types
against
function parameters.
2026-02-23 20:33:50 +01:00
Michael Schimmel be7ce31408 Refactor VM evaluation for observer pattern
The `dispatch_eval` macro has been replaced with explicit
`eval_internal` and `eval_core` methods. This change aims to streamline
the evaluation process and better support the observer pattern by
providing clearer hooks for observing VM execution.
2026-02-23 18:10:20 +01:00
Michael Schimmel 229ca3eefa Add documentation for analysis metrics 2026-02-22 18:41:27 +01:00
Michael Schimmel 2e8d5284c2 Feat: Enable nested destructuring optimization
This commit introduces optimizations for nested destructuring, allowing
tuples and records to be flattened and matched directly against function
arguments. This significantly improves performance by enabling more
constant folding and reducing intermediate allocations.

The changes include:
- Modifying the `Binder` to correctly count nested parameters.
- Enhancing `flatten_tuple` in the `Optimizer` to handle records and NOP
  nodes.
- Updating `map_params_to_args` to recursively destructure nested
  compound arguments.
- Adding integration tests to verify the correctness of tuple-to-tuple
  and record-to-tuple destructuring optimizations.
2026-02-22 16:34:40 +01:00
Michael Schimmel c03b2af770 Update benchmark numbers in examples
This commit updates the benchmark numbers in various example files. The
changes reflect recent performance optimizations or adjustments to the
benchmarking environment.
2026-02-22 16:13:11 +01:00
Michael Schimmel 2fdeff1db4 Refactor: Analyze node purity and recursion
The Analyzer has been refactored to decorate `TypedNode`s with their
purity and recursion status. This involves creating a new `AnalyzedNode`
type and a `NodeMetrics` struct to hold this information. The `Analyzer`
now returns an `AnalyzedNode` instead of a separate `Analysis` struct.
This change lays the groundwork for future optimizations and analysis
passes.
2026-02-22 16:11:46 +01:00
Michael Schimmel 8f7947bde1 feat: Add AST analysis pass for purity and recursion
This commit introduces a new AST analysis pass that identifies function
purity and recursion. This information is then used by the optimizer and
specializer to make more informed decisions, particularly regarding
inlining.

The `Analyzer` struct and its associated `Analysis` struct are
responsible for traversing the AST and collecting this data.

Key changes include:
- A new `analyzer` module is added to `ast::compiler`.
- `Analyzer::analyze` performs a two-pass traversal to collect
  global-to-lambda mappings and then analyze purity and recursion.
- The `Optimizer` and `Specializer` are updated to accept and utilize
  the `Analysis` data.
- Recursion checks in `Optimizer` and `Specializer` are replaced with
  checks against the pre-computed `Analysis.is_recursive` set.
- The `Environment` now stores and passes the `Analysis` results to the
  compiler stages.
2026-02-22 15:00:20 +01:00
Michael Schimmel 5a017fb932 Update benchmark tests with filtering 2026-02-22 12:07:58 +01:00
Michael Schimmel cb94f20c0b Refactor native function registration and instantiation
Introduces `register_native` for direct registration of `NativeFunction`
and `register_native_fn` for convenience from closures. The
`Environment::run`
method is removed, and its functionality is now handled by
`Environment::instantiate`,
which packages the linked AST into an invokable `NativeFunction`. This
streamlines
the execution path and better separates compilation/linking from runtime
execution.
2026-02-22 11:56:46 +01:00
Michael Schimmel a726b79d8a Refactor Purity enum and NativeFunction struct
Move `Purity` enum definition from `optimizer.rs` to `types.rs` and
create a `NativeFunction` struct to hold the function and its purity.
Update `Value::Function` to store `Rc<NativeFunction>` and
`Value::make_function`
helper to simplify creation.

This change allows tracking the purity of native functions, which is
useful
for optimization and static analysis.
2026-02-22 10:50:37 +01:00
Michael Schimmel b54a449369 Update optimizer_purity.myc 2026-02-22 10:41:54 +01:00