Files
RustAst/examples/object_records.myc
T
Michael Schimmel beb693a068 Refactor: Implement block scoping and statement separation
This commit introduces fundamental changes to Myc's language structure
to enhance type safety and scoping clarity.

Key changes include:
- Introducing local scopes for `do` blocks.
- Separating statements (`def`, `assign`) from expressions, where
  statements now have no return value and are only allowed within
  blocks.
- A block now consists of multiple statements followed by a single final
  expression.
- Stricter validation rules are enforced, such as disallowing
  redefinition of local symbols in the same scope while allowing
  shadowing of outer symbols.
- Compiler errors are generated for statements used in expression
  contexts.

The implementation involved modifications to the AST, parser, binder
(scope-stack), and various compiler passes, along with VM runtime
optimizations.
2026-03-09 16:38:44 +01:00

52 lines
1.6 KiB
Plaintext

;; Benchmark: 1.4us
;; Benchmark-Repeat: 1473
;; Output: [150 130 "Insufficient funds" 130]
; ---------------------------------------------------------
; Object-Oriented Records Example
; ---------------------------------------------------------
; This showcase treats a record as an object by storing
; closures that capture private state.
(do
; A factory function (Constructor) for a BankAccount object
(def make-account (fn [initial-balance]
(do
; 'balance' is a captured parameter, acting as private state
(def balance initial-balance)
{
; Method: Get current balance
:balance (fn [] balance)
; Method: Deposit money
:deposit (fn [amount] (do (assign balance (+ balance amount)) balance))
; Method: Withdraw money with validation
:withdraw (fn [amount]
(if (>= balance amount)
(do (assign balance (- balance amount)) balance)
"Insufficient funds"))
}
)))
; 1. Create an instance
(def my-acc (make-account 100))
; 2. Call 'deposit' method
; Note the double parens: (.deposit my-acc) gets the function, then we call it
(def b1 ((.deposit my-acc) 50)) ; balance is now 150
; 3. Call 'withdraw' method
(def b2 ((.withdraw my-acc) 20)) ; balance is now 130
; 4. Call 'withdraw' with invalid amount
(def error-msg ((.withdraw my-acc) 1000))
; 5. Call 'balance' getter
(def final-balance ((.balance my-acc)))
; Return summary of operations
[b1 b2 error-msg final-balance]
)