diff --git a/postfix_lang_spec.md b/postfix_lang_spec.md deleted file mode 100644 index 3fe7d1d..0000000 --- a/postfix_lang_spec.md +++ /dev/null @@ -1,333 +0,0 @@ -# APEX Language Specification v0.1 -**Array-oriented Postfix Expression Language** - -## Design Philosophy - -APEX combines the clarity of postfix notation (RPL), the power of systems programming (C), and modern array-oriented programming (Uiua). The language uses strict postfix (RPN) syntax where all operators follow their operands, promoting a natural stack-based evaluation model. - ---- - -## Tier System - -### Tier 1: Foundation -Core stack operations, basic arithmetic, simple control flow - -### Tier 2: Structured Programming -Functions, arrays, complex data types, advanced control structures - -### Tier 3: Systems Programming -Memory management, pointers, foreign function interface, concurrency - ---- - -## Tier 1: Foundation - -### Stack Operations - -``` -dup - Duplicate top item: a → a a -drop - Remove top item: a → -swap - Swap top two items: a b → b a -over - Copy second item: a b → a b a -rot - Rotate three items: a b c → b c a -``` - -### Arithmetic Operators (Postfix) - -``` -+ - Addition: a b → (a+b) -- - Subtraction: a b → (a-b) -* - Multiplication: a b → (a*b) -/ - Division: a b → (a/b) -% - Modulo: a b → (a%b) -neg - Negate: a → (-a) -``` - -### Comparison Operators - -``` -= - Equal: a b → bool -< - Less than: a b → bool -> - Greater than: a b → bool -<= - Less or equal: a b → bool ->= - Greater or equal: a b → bool -!= - Not equal: a b → bool -``` - -### Logical Operators - -``` -and - Logical AND: a b → bool -or - Logical OR: a b → bool -not - Logical NOT: a → bool -``` - -### Basic Control Flow - -``` -[ condition ] [ true-branch ] if -[ condition ] [ true-branch ] [ false-branch ] ifelse -``` - -Example: -```apex -5 3 > [ "greater" ] [ "not greater" ] ifelse print -``` - -### Variables - -``` -var-name ! - Store to variable (pop from stack) -var-name @ - Load from variable (push to stack) -``` - -Example: -```apex -42 x ! # Store 42 to x -x @ 10 + # Load x, add 10 → 52 -``` - -### Comments - -``` -# Single line comment -(* Multi-line - comment *) -``` - ---- - -## Tier 2: Structured Programming - -### Functions - -Functions are defined with postfix syntax: - -``` -[ body ] function-name : -``` - -Example: -```apex -[ dup * ] square : # Define square function -5 square # Call: 5 → 25 -``` - -### Functions with Local Variables - -``` -[ arg1 arg2 | body ] function-name : -``` - -The `|` separator indicates parameter binding from stack: - -```apex -[ x y | x @ y @ + ] add : # Pop two values, bind to x and y -3 5 add # → 8 -``` - -### Recursion - -```apex -[ n | - n @ 1 <= - [ 1 ] - [ n @ n @ 1 - factorial * ] - ifelse -] factorial : - -5 factorial # → 120 -``` - -### Arrays (Uiua-inspired) - -``` -[ e1 e2 e3 ... ] - Array literal -length - Get array length: arr → n -@i - Index access: arr i → element -!i - Index store: arr i val → -range - Create range: n → [0..n-1] -each - Map function: arr [fn] → arr' -reduce - Fold: arr init [fn] → value -filter - Filter: arr [predicate] → arr' -``` - -Example: -```apex -[1 2 3 4 5] # Array on stack -[ 2 * ] each # → [2 4 6 8 10] - -10 range [ 2 % 0 = ] filter # Even numbers: [0 2 4 6 8] -``` - -### Loops - -``` -[ condition ] [ body ] while -n [ body ] times -``` - -Example: -```apex -0 i ! -[ i @ 10 < ] [ - i @ print - i @ 1 + i ! -] while - -5 [ "hello" print ] times # Print "hello" 5 times -``` - -### Structures (Records) - -``` -{ field1 field2 ... } struct-name struct -``` - -Example: -```apex -{ x y } Point struct - -3 4 Point.new p ! # Create Point(3, 4) -p @ .x # Access field x → 3 -p @ 5 .x! # Set field x to 5 -``` - ---- - -## Tier 3: Systems Programming - -### Memory Management - -``` -size alloc - Allocate memory: n → ptr -ptr free - Free memory -ptr @ peek - Read from pointer: ptr → value -ptr value ! poke - Write to pointer -sizeof - Size of type: type → n -``` - -### Pointers (C-inspired) - -``` -&var - Address of variable: → ptr -ptr * - Dereference: ptr → value -ptr n +ptr - Pointer arithmetic: ptr n → ptr' -``` - -Example: -```apex -42 x ! -&x # Get address of x -dup * # Dereference: → 42 -100 swap ! poke # Write 100 to that address -x @ # x now contains 100 -``` - -### Type System - -``` -:i32 :i64 :f32 :f64 - Numeric types -:bool :char - Basic types -:ptr - Pointer type -[ type ] :array - Array type -``` - -Example with type annotations: -```apex -[ x:i32 y:i32 | x @ y @ + ]:i32 add : -``` - -### Foreign Function Interface - -``` -"lib.so" import-lib -[ arg-types... ] ret-type "func_name" foreign -``` - -Example: -```apex -"libc.so.6" import-lib -[ :ptr ] :i32 "strlen" foreign strlen-ffi : - -"hello" strlen-ffi # Call C strlen -``` - -### Concurrency - -``` -[ body ] spawn - Spawn thread: → thread-id -thread-id join - Wait for thread -value channel.send - Send to channel -channel.recv - Receive from channel: → value -lock.acquire -lock.release -``` - -Example: -```apex -[ 1 100 range [ . ] each ] spawn worker ! -worker @ join -``` - -### System Calls - -``` -:read :write :open :close syscall -``` - ---- - -## Complete Example Program - -```apex -# Fibonacci sequence generator (Tier 2) - -[ n | - n @ 0 = - [ 0 ] - [ n @ 1 = - [ 1 ] - [ n @ 1 - fib n @ 2 - fib + ] - ifelse - ] - ifelse -] fib : - -# Calculate and print first 10 Fibonacci numbers -10 [ - dup fib print -] each - -# Array operations (Uiua-style) -[1 2 3 4 5] -[ dup * ] each # Square each: [1 4 9 16 25] -0 [ + ] reduce # Sum: 55 -print -``` - ---- - -## Syntax Summary - -### Key Principles - -1. **Postfix everywhere**: All operators come after operands -2. **Stack-based**: Implicit stack for data flow -3. **Brackets for grouping**: `[ ]` for code blocks and arrays -4. **Sigils for operations**: `!` for store, `@` for load, `.` for field access -5. **Natural composition**: Functions compose left-to-right - -### Operator Precedence - -None! Being postfix eliminates precedence issues. Evaluation is strictly left-to-right, consuming operands from the stack. - ---- - -## Implementation Notes - -- **Tier 1** can be implemented as a simple stack-based interpreter -- **Tier 2** requires a symbol table for functions and array support -- **Tier 3** needs memory management, type checking, and possibly compilation - -The tier system allows learners to master concepts progressively while enabling systems programming when needed. \ No newline at end of file diff --git a/stack_lang_spec (0.1).md b/stack_lang_spec (0.1).md deleted file mode 100644 index 4ceadeb..0000000 --- a/stack_lang_spec (0.1).md +++ /dev/null @@ -1,623 +0,0 @@ -# Stack Language Specification v0.1 - -## 1. Overview - -A statically-typed, stack-based language with postfix notation combining the execution model of HP's RPL, the type system of C and Rust, and modern array operations from Uiua. - -### Design Principles -- All operations are postfix (RPN) -- Stack-based execution (no local variables) -- Static typing with type inference -- Manual heap memory management -- C-like syntax style adapted to postfix notation -- Functions manipulate the stack directly - -## 2. Lexical Structure - -### 2.1 Comments -``` -// Single-line comment -``` - -### 2.2 Identifiers -- Start with letter or underscore: `[a-zA-Z_][a-zA-Z0-9_]*` -- Case-sensitive - -### 2.3 Literals - -**Integer Literals** -``` -42 // i32 (default) -42i64 // i64 -0xFF // hexadecimal -0b1010 // binary -``` - -**Floating Point Literals** -``` -3.14 // f64 (default) -3.14f32 // f32 -``` - -**String Literals** -``` -"hello world" -"escape sequences: \n \t \\ \"" -``` - -**Boolean Literals** -``` -true -false -``` - -**Array Literals** -``` -[1 2 3 4 5] // array of i32 -[1.0 2.0 3.0] // array of f64 -[[1 2] [3 4]] // 2D array -``` - -## 3. Type System - -### 3.1 Primitive Types -- `i8`, `i16`, `i32`, `i64` - Signed integers -- `u8`, `u16`, `u32`, `u64` - Unsigned integers -- `f32`, `f64` - Floating point -- `bool` - Boolean -- `char` - Single character (UTF-8) -- `ptr` - Raw pointer to type T - -### 3.2 Compound Types - -**Arrays** -``` -[T; N] // Fixed-size array -[T] // Dynamic array (heap-allocated) -``` - -**Structs** -``` -struct Point { - x: f64, - y: f64, -} -``` - -**Tagged Unions** -``` -union Result { - Ok(T), - Err(E), -} -``` - -### 3.3 Type Inference -Types are inferred where possible but can be explicitly annotated: -``` -42 :i64 // Annotate literal -x get :f32 // Annotate stack value -``` - -## 4. Stack Operations - -### 4.1 Stack Manipulation -``` -dup // ( a -- a a ) Duplicate top -drop // ( a -- ) Remove top -swap // ( a b -- b a ) Swap top two -over // ( a b -- a b a ) Copy second to top -rot // ( a b c -- b c a ) Rotate three items --rot // ( a b c -- c a b ) Rotate three items reverse -2dup // ( a b -- a b a b ) Duplicate top two -2drop // ( a b -- ) Drop top two -nip // ( a b -- b ) Drop second -tuck // ( a b -- b a b ) Copy top below second -``` - -### 4.2 Stack Inspection -``` -depth // ( -- n ) Push stack depth -pick // ( n -- x ) Copy nth item to top (0 = top) -roll // ( n -- ) Move nth item to top -``` - -## 5. Operators (Postfix) - -### 5.1 Arithmetic -``` -3 4 + // ( a b -- result ) Addition -10 3 - // Subtraction -5 6 * // Multiplication -20 4 / // Division -17 5 % // Modulo -2 8 ** // Exponentiation -``` - -### 5.2 Comparison -``` -5 3 > // Greater than -5 3 >= // Greater or equal -5 3 < // Less than -5 3 <= // Less or equal -5 5 == // Equal -5 3 != // Not equal -``` - -### 5.3 Logical -``` -true false && // Logical AND -true false || // Logical OR -true ! // Logical NOT -``` - -### 5.4 Bitwise -``` -0xFF 0x0F & // Bitwise AND -0xFF 0x0F | // Bitwise OR -0xFF 0x0F ^ // Bitwise XOR -0xFF ~ // Bitwise NOT -8 2 << // Left shift -8 2 >> // Right shift -``` - -## 6. Functions - -Functions consume arguments from the stack and push results to the stack. - -### 6.1 Function Definition -``` -fn add_point : (Point Point -- Point) { - // Stack: p1 p2 - swap .x get // p2.x - swap .x get // p1.x - + // sum_x - - swap .y get // p2.y - swap .y get // p1.y - + // sum_y - - Point::new // Create new Point -} -``` - -### 6.2 Function Signature -Format: `(input_types -- output_types)` -``` -fn square : (i32 -- i32) { - dup * -} - -fn divmod : (i32 i32 -- i32 i32) { - 2dup / -rot % -} - -fn no_op : (-- ) { - // Takes nothing, returns nothing -} -``` - -### 6.3 Generic Functions -``` -fn identity : (T -- T) { - // Simply returns the input -} - -fn swap_pair : (T U -- U T) { - swap -} -``` - -## 7. Control Flow - -### 7.1 Conditionals -``` -// if-then -condition if { - // Executed if true -} - -// if-then-else -x 0 > if { - // Positive -} else { - // Non-positive -} -``` - -### 7.2 Loops - -**While Loop** -``` -// While condition is true -{ condition } while { - // Loop body -} - -// Example: sum 1 to 10 -0 1 // sum counter -{ dup 10 <= } while { - 2dup + // Add counter to sum - swap 1 + swap // Increment counter -} -drop // Drop counter, leave sum -``` - -**For Loop (Range-based)** -``` -1 10 for i { - i print -} - -// Equivalent to: -1 10 range each { print } -``` - -### 7.3 Loop Control -``` -break // Exit loop -continue // Skip to next iteration -``` - -## 8. Memory Management - -### 8.1 Stack vs Heap -- Stack: Automatic, fixed-size types -- Heap: Manual, dynamic allocations - -### 8.2 Heap Operations -``` -// Allocate -Point::new heap_alloc // ( Point -- ptr ) - -// Dereference -ptr @ // ( ptr -- T ) - -// Store -value ptr ! // ( T ptr -- ) - -// Free -ptr free // ( ptr -- ) -``` - -### 8.3 Example -``` -// Create heap-allocated point -3.0 4.0 Point::new heap_alloc // ptr -dup .x get print // Print x (3.0) -free // Clean up -``` - -## 9. Data Structures - -### 9.1 Struct Definition and Usage -``` -struct Rectangle { - width: f64, - height: f64, -} - -// Constructor (auto-generated) -10.0 20.0 Rectangle::new // Create Rectangle - -// Field access (postfix) -rect .width get // Get width -rect .width 15.0 set // Set width - -// Method-like functions -fn Rectangle::area : (Rectangle -- f64) { - dup .width get - swap .height get - * -} - -// Usage -rect Rectangle::area // Calculate area -``` - -### 9.2 Tagged Unions -``` -union Option { - Some(T), - None, -} - -// Construction -42 Option::Some // Create Some(42) -Option::None // Create None - -// Pattern matching -value match { - Some(x) => { - x print - }, - None => { - "Nothing" print - }, -} -``` - -### 9.3 Enums -``` -enum Status { - Pending, - Active, - Complete, -} - -Status::Active // Create enum value -``` - -## 10. Traits - -Traits define shared behavior across types. - -### 10.1 Trait Definition -``` -trait Drawable { - fn draw : (Self -- ); -} - -trait Add { - fn add : (Self T -- Self); -} -``` - -### 10.2 Trait Implementation -``` -impl Drawable for Rectangle { - fn draw : (Rectangle -- ) { - "Drawing rectangle" print - dup .width get print - .height get print - } -} - -impl Add for Point { - fn add : (Point Point -- Point) { - // Implementation from earlier - swap .x get swap .x get + - swap .y get swap .y get + - Point::new - } -} -``` - -### 10.3 Trait Bounds -``` -fn draw_twice : (T -- ) { - dup draw - draw -} -``` - -## 11. Array Operations (Uiua-inspired) - -### 11.1 Basic Array Operations -``` -// Creation -[1 2 3 4 5] range // Create range array - -// Shape operations -arr shape // Get shape -arr [2 3] reshape // Reshape to 2x3 - -// Element access -arr 2 @ // Index access -arr [1 3] slice // Slice array -``` - -### 11.2 Array Combinators -``` -// Map -[1 2 3 4] { 2 * } map // [2 4 6 8] - -// Filter -[1 2 3 4 5] { 2 % 0 == } filter // [2 4] - -// Reduce -[1 2 3 4] 0 { + } reduce // 10 - -// Each (apply to each element) -[[1 2] [3 4]] { sum } each // [3 7] -``` - -### 11.3 Array Arithmetic -``` -[1 2 3] [4 5 6] .+ // Element-wise add: [5 7 9] -[1 2 3] [4 5 6] .* // Element-wise multiply: [4 10 18] -[1 2 3] 2 .* // Scalar multiply: [2 4 6] -``` - -### 11.4 Array Manipulation -``` -[1 2 3] [4 5 6] ++ // Concatenate: [1 2 3 4 5 6] -[1 2 3] reverse // [3 2 1] -[[1 2] [3 4]] transpose // [[1 3] [2 4]] -[1 2 3 4] 2 window // [[1 2] [2 3] [3 4]] -``` - -## 12. Eval Operator - -Execute code dynamically at runtime. - -``` -// Evaluate string as code -"2 3 +" eval // Pushes 5 - -// Build and execute code -"fn square : (i32 -- i32) { dup * }" eval -5 square // 25 - -// Dynamic dispatch -operation_name " get" ++ eval // Call function by name -``` - -**Security Note**: Eval should be used carefully as it can execute arbitrary code. - -## 13. Standard Library Concepts - -### 13.1 I/O -``` -"Hello" print // Print to stdout -"Enter name: " input // Read from stdin -"file.txt" read // Read file contents -"data" "file.txt" write // Write to file -``` - -### 13.2 String Operations -``` -"hello" " world" ++ // Concatenate: "hello world" -"hello" length // 5 -"hello" 1 3 substr // "el" -"a,b,c" "," split // ["a" "b" "c"] -["a" "b"] "," join // "a,b" -``` - -### 13.3 Type Conversion -``` -42 to_f64 // Convert i32 to f64 -"123" parse_i32 // Parse string to i32 -3.14 to_string // Convert to string -``` - -## 14. Example Programs - -### 14.1 Factorial -``` -fn factorial : (i32 -- i32) { - dup 1 <= if { - drop 1 - } else { - dup 1 - factorial * - } -} - -5 factorial print // 120 -``` - -### 14.2 FizzBuzz -``` -fn fizzbuzz : (i32 -- ) { - dup 15 % 0 == if { - drop "FizzBuzz" print - } else { - dup 3 % 0 == if { - drop "Fizz" print - } else { - dup 5 % 0 == if { - drop "Buzz" print - } else { - print - } - } - } -} - -1 100 for i { - i fizzbuzz -} -``` - -### 14.3 Using Structs and Traits -``` -struct Circle { - radius: f64, -} - -impl Drawable for Circle { - fn draw : (Circle -- ) { - "Circle with radius: " print - .radius get print - } -} - -fn Circle::area : (Circle -- f64) { - .radius get - 2.0 ** - 3.14159 * -} - -// Usage -5.0 Circle::new -dup draw // Draw the circle -Circle::area print // Print area -``` - -### 14.4 Array Processing -``` -// Sum of squares of even numbers from 1 to 10 -[1 2 3 4 5 6 7 8 9 10] -{ 2 % 0 == } filter // Keep even numbers -{ dup * } map // Square each -0 { + } reduce // Sum -print // 220 -``` - -## 15. Implementation Notes - -### 15.1 Type Checking -- Perform static type checking with full type inference -- Track stack types at compile time -- Ensure function signatures match actual stack effects - -### 15.2 Interpreter Design -- Value stack: runtime execution stack -- Type stack: compile-time type tracking -- Call stack: function call management -- Heap: global allocator - -### 15.3 Future Compilation -- Compile to bytecode for interpretation -- Potential LLVM backend for native compilation -- Stack optimization for register allocation - -## 16. Syntax Summary - -### Stack Manipulation -``` -dup drop swap over rot pick roll -``` - -### Arithmetic (postfix) -``` -a b + a b - a b * a b / a b % a b ** -``` - -### Comparison -``` -a b < a b > a b <= a b >= a b == a b != -``` - -### Control Flow -``` -cond if { ... } -cond if { ... } else { ... } -{ cond } while { ... } -start end for var { ... } -``` - -### Functions -``` -fn name : (inputs -- outputs) { body } -fn name : (T U -- U) { body } -``` - -### Memory -``` -value heap_alloc ptr @ value ptr ! ptr free -``` - -### Arrays -``` -[1 2 3] -arr { fn } map -arr { fn } filter -arr init { fn } reduce -``` - ---- - -**Version**: 0.1 -**Status**: Draft Specification -**License**: Define your license here \ No newline at end of file diff --git a/stack_lang_spec (0.2).md b/stack_lang_spec (0.2).md deleted file mode 100644 index 375bae4..0000000 --- a/stack_lang_spec (0.2).md +++ /dev/null @@ -1,778 +0,0 @@ -# Stack Language Specification v0.2 - -## 1. Overview - -A statically-typed, stack-based language with pure postfix notation combining the execution model of HP's RPL, the type system of C and Rust, and modern array operations from Uiua. - -### Design Principles -- **Everything is postfix** - no exceptions -- Stack-based execution (no local variables) -- Static typing with type inference -- Manual heap memory management -- Types define what things **are**, traits define how things **act** -- All constructs are implicitly generic - -## 2. Lexical Structure - -### 2.1 Comments -``` -// Single-line comment -``` - -### 2.2 Identifiers -- Start with letter or underscore: `[a-zA-Z_][a-zA-Z0-9_]*` -- Case-sensitive - -### 2.3 Literals - -**Integer Literals** -``` -42 // i32 (default) -42 i64 // Annotate as i64 -0xFF // hexadecimal -0b1010 // binary -``` - -**Floating Point Literals** -``` -3.14 // f64 (default) -3.14 f32 // Annotate as f32 -``` - -**String Literals** -``` -"hello world" -"escape sequences: \n \t \\ \"" -``` - -**Boolean Literals** -``` -true -false -``` - -**Array Literals** -``` -[1 2 3 4 5] // array of i32 -[1.0 2.0 3.0] // array of f64 -[[1 2] [3 4]] // 2D array -``` - -## 3. Type System - -### 3.1 Primitive Types -- `i8`, `i16`, `i32`, `i64` - Signed integers -- `u8`, `u16`, `u32`, `u64` - Unsigned integers -- `f32`, `f64` - Floating point -- `bool` - Boolean -- `char` - Single character (UTF-8) -- `ptr` - Raw pointer (generic over pointed type) - -### 3.2 Types vs Traits - -**Types** define the concrete structure and memory layout: -``` -Point struct // Point is a type -Rectangle struct // Rectangle is a type -``` - -**Traits** define behavioral contracts - how things act: -``` -Drawable trait // Drawable is a trait -Addable trait // Addable is a trait -``` - -**Key Distinction:** -- A value **has** a type (what it is structurally) -- A value **implements** a trait (how it behaves) -- Types are concrete; traits are interfaces -- Functions can be generic over both types and traits - -### 3.3 All Constructs are Generic - -Every function, struct, and union is implicitly generic. Constraints are specified via traits: - -``` -// Function generic over any type T -(T -- T) { dup * } square fn - -// Function requiring T to implement Addable trait -(T T -- T) Addable { + } add_two fn - -// Struct generic over field types -(T T --) { x: y: } Point struct - -// Union generic over variant types -(T --) { Some(T) None } Option union -``` - -## 4. Stack Operations - -### 4.1 Stack Manipulation -``` -dup // ( a -- a a ) Duplicate top -drop // ( a -- ) Remove top -swap // ( a b -- b a ) Swap top two -over // ( a b -- a b a ) Copy second to top -rot // ( a b c -- b c a ) Rotate three items --rot // ( a b c -- c a b ) Rotate three items reverse -2dup // ( a b -- a b a b ) Duplicate top two -2drop // ( a b -- ) Drop top two -nip // ( a b -- b ) Drop second -tuck // ( a b -- b a b ) Copy top below second -``` - -### 4.2 Stack Inspection -``` -depth // ( -- n ) Push stack depth -pick // ( n -- x ) Copy nth item to top (0 = top) -roll // ( n -- ) Move nth item to top -``` - -## 5. Operators (Postfix) - -### 5.1 Arithmetic -``` -3 4 + // ( a b -- result ) Addition -10 3 - // Subtraction -5 6 * // Multiplication -20 4 / // Division -17 5 % // Modulo -2 8 ** // Exponentiation -``` - -### 5.2 Comparison -``` -5 3 > // Greater than -5 3 >= // Greater or equal -5 3 < // Less than -5 3 <= // Less or equal -5 5 == // Equal -5 3 != // Not equal -``` - -### 5.3 Logical -``` -true false and // Logical AND -true false or // Logical OR -true not // Logical NOT -``` - -### 5.4 Bitwise -``` -0xFF 0x0F bitand // Bitwise AND -0xFF 0x0F bitor // Bitwise OR -0xFF 0x0F bitxor // Bitwise XOR -0xFF bitnot // Bitwise NOT -8 2 shl // Left shift -8 2 shr // Right shift -``` - -## 6. Functions (Postfix Definition) - -Functions are defined in postfix notation. The signature and body come before the name. - -### 6.1 Basic Function Definition - -**Syntax**: `(inputs -- outputs) { body } name fn` - -``` -// Define a square function -(i32 -- i32) { dup * } square fn - -// Use it -5 square // 25 - -// Multiple inputs and outputs -(i32 i32 -- i32 i32) { - 2dup / -rot % -} divmod fn - -10 3 divmod // 3 1 (quotient remainder) -``` - -### 6.2 Generic Functions with Trait Constraints - -**Syntax**: `(type_sig) trait_constraints { body } name fn` - -``` -// Generic identity - works with any type -(T -- T) {} identity fn - -// Requires T to be copyable -(T T -- T) Addable { - + -} add_values fn - -// Multiple trait constraints -(T U -- U T) Copyable Swappable { - swap -} swap_generic fn - -// Multiple type parameters with different traits -(T U -- T) Addable Numeric { - dup U as + -} add_converted fn -``` - -### 6.3 Function Examples - -``` -// No-op function -(-- ) {} noop fn - -// Factorial (recursive) -(i32 -- i32) { - dup 1 { drop 1 } { dup 1 - factorial * } <= if -} factorial fn - -// Constrained generic -(T -- T) Numeric { - dup 0 > { } { 0 T as - } if -} abs fn -``` - -## 7. Control Flow (Postfix) - -### 7.1 Conditionals - -**Syntax**: `condition { then-block } { else-block } if` - -``` -// if-then (else block is empty) -x 0 > { "positive" print } {} if - -// if-then-else -x 0 > - { "positive" print } - { "non-positive" print } -if - -// The condition comes first, then both blocks, then 'if' -a b > - { a } - { b } -if max set - -// Nested -x 0 > - { - y 0 > - { "both positive" print } - { "x positive, y not" print } - if - } - { "x not positive" print } -if -``` - -### 7.2 Loops - -**While Loop** - -**Syntax**: `{ condition-block } { body-block } while` - -``` -// Sum 1 to 10 -0 1 // sum counter - { dup 10 <= } // condition block - { // body block - 2dup + // Add counter to sum - swap 1 + swap // Increment counter - } -while -drop // Drop counter, leave sum - -// Infinite loop with break -{ true } { - // body - condition { break } {} if -} while -``` - -**For Loop** - -**Syntax**: `start end { body-with-counter } for` - -``` -// The loop variable is implicitly pushed to stack in each iteration -1 10 { - // Stack has loop counter on top - dup print -} for - -// More complex -1 100 { - dup fizzbuzz -} for -``` - -### 7.3 Loop Control -``` -break // Exit loop -continue // Skip to next iteration -``` - -### 7.4 Match/Pattern Matching - -**Syntax**: `value { pattern => block ... } match` - -``` -value { - Some(x) => { x print } - None => { "Nothing" print } -} match - -// With multiple patterns -status { - Pending => { "Waiting" print } - Active => { "Running" print } - Complete => { "Done" print } -} match -``` - -## 8. Data Structures (Postfix) - -### 8.1 Struct Definition - -**Syntax**: `(field_types -- ) { field_names } name struct` - -``` -// Define Point struct - generic over coordinate types -(T T --) { x: y: } Point struct - -// Use with specific types -3.0 4.0 Point // Creates Point with f64 fields -3 4 Point // Creates Point with i32 fields - -// More complex struct -(T U V --) { - width: - height: - depth: -} Box3D struct - -10.0 20.0 30.0 Box3D -``` - -### 8.2 Struct Field Access - -**Syntax (postfix)**: `struct field get` or `struct value field set` - -``` -point x get // Get x field -point 15.0 x set // Set x field to 15.0 - -// Chaining -point x get 2 * y get + // (point.x * 2) + point.y -``` - -### 8.3 Union Definition - -**Syntax**: `(variant_types -- ) { variants } name union` - -``` -// Option type - generic over T -(T --) { - Some(T) - None -} Option union - -// Result type - generic over T and E -(T E --) { - Ok(T) - Err(E) -} Result union - -// Create union values -42 Some // Creates Option::Some(42) -None // Creates Option::None -"success" Ok // Creates Result::Ok("success") -"error" Err // Creates Result::Err("error") -``` - -### 8.4 Enum Definition - -**Syntax**: `() { variants } name enum` - -``` -() { - Pending - Active - Complete -} Status enum - -// Usage -Pending // Creates Status::Pending -Active // Creates Status::Active -``` - -## 9. Traits (Postfix) - -### 9.1 Trait Definition - -**Syntax**: `{ function_signatures } name trait` - -``` -// Simple trait -{ - (Self -- ) draw: -} Drawable trait - -// Trait with multiple methods -{ - (Self Self -- Self) add: - (Self Self -- Self) sub: - (Self -- Self) neg: -} Numeric trait - -// Generic trait -{ - (Self T -- Self) append: - (Self -- T) pop: -} Container trait -``` - -### 9.2 Trait Implementation - -**Syntax**: `type { method_implementations } trait impl` - -``` -// Implement Drawable for Rectangle -Rectangle { - (Rectangle -- ) { - "Drawing rectangle" print - dup width get print - height get print - } draw: -} Drawable impl - -// Implement Numeric for Point -Point { - (Point Point -- Point) { - over x get over x get + - -rot y get swap y get + - Point - } add: - - (Point Point -- Point) { - over x get over x get - - -rot y get swap y get - - Point - } sub: - - (Point -- Point) { - dup x get 0 swap - x set - dup y get 0 swap - y set - } neg: -} Numeric impl -``` - -### 9.3 Using Traits in Functions - -``` -// Function requiring Drawable trait -(T -- ) Drawable { - draw -} draw_twice fn - -// Multiple trait requirements -(T -- T) Numeric Copyable { - dup abs swap dup * + -} complex_calc fn -``` - -## 10. Memory Management (Postfix) - -### 10.1 Heap Operations - -``` -// Allocate -3.0 4.0 Point alloc // ( Point -- ptr ) - -// Dereference -ptr deref // ( ptr -- T ) - -// Store (dereference and update) -new_value ptr store // ( T ptr -- ) - -// Free -ptr free // ( ptr -- ) -``` - -### 10.2 Example - -``` -// Create heap-allocated point -3.0 4.0 Point alloc // Returns ptr -dup x get print // Dereference and print x -free // Clean up -``` - -## 11. Array Operations (Postfix) - -### 11.1 Basic Array Operations - -``` -// Creation -1 10 range // Create range array [1..10] - -// Shape operations -arr shape // Get shape -arr 2 3 reshape // Reshape to 2x3 - -// Element access -arr 2 at // Index access -arr 1 3 slice // Slice array -``` - -### 11.2 Array Combinators - -``` -// Map - apply function to each element -[1 2 3 4] { 2 * } map // [2 4 6 8] - -// Filter - keep elements matching predicate -[1 2 3 4 5] { 2 % 0 == } filter // [2 4] - -// Reduce - fold with function -[1 2 3 4] 0 { + } reduce // 10 - -// Each - apply to each element (side effects) -[[1 2] [3 4]] { sum print } each -``` - -### 11.3 Array Arithmetic - -``` -[1 2 3] [4 5 6] +. // Element-wise add: [5 7 9] -[1 2 3] [4 5 6] *. // Element-wise multiply: [4 10 18] -[1 2 3] 2 *. // Scalar multiply: [2 4 6] -``` - -### 11.4 Array Manipulation - -``` -[1 2 3] [4 5 6] concat // Concatenate: [1 2 3 4 5 6] -[1 2 3] reverse // [3 2 1] -[[1 2] [3 4]] transpose // [[1 3] [2 4]] -[1 2 3 4] 2 window // [[1 2] [2 3] [3 4]] -``` - -## 12. Eval Operator (Postfix) - -Execute code dynamically at runtime. - -``` -// Evaluate string as code -"2 3 +" eval // Pushes 5 - -// Build and execute code -"(i32 -- i32) { dup * } square fn" eval -5 square // 25 - -// Dynamic dispatch -operation_name " get" concat eval -``` - -## 13. Standard Library Concepts - -### 13.1 I/O - -``` -"Hello" print // Print to stdout -"Enter name: " input // Read from stdin -"file.txt" read // Read file contents -"data" "file.txt" write // Write to file -``` - -### 13.2 String Operations - -``` -"hello" " world" concat // Concatenate: "hello world" -"hello" length // 5 -"hello" 1 3 substr // "el" -"a,b,c" "," split // ["a" "b" "c"] -["a" "b"] "," join // "a,b" -``` - -### 13.3 Type Conversion - -``` -42 f64 as // Convert i32 to f64 -"123" i32 parse // Parse string to i32 -3.14 str as // Convert to string -``` - -## 14. Complete Examples - -### 14.1 Factorial - -``` -(i32 -- i32) { - dup 1 - { drop 1 } - { dup 1 - factorial * } - <= if -} factorial fn - -5 factorial print // 120 -``` - -### 14.2 FizzBuzz - -``` -(i32 -- ) { - dup 15 % 0 == - { drop "FizzBuzz" print } - { - dup 3 % 0 == - { drop "Fizz" print } - { - dup 5 % 0 == - { drop "Buzz" print } - { print } - if - } - if - } - if -} fizzbuzz fn - -1 100 { fizzbuzz } for -``` - -### 14.3 Point with Traits - -``` -// Define Point struct -(T T --) { x: y: } Point struct - -// Define Drawable trait -{ (Self -- ) draw: } Drawable trait - -// Implement Drawable for Point -Point { - (Point -- ) { - "Point(" print - dup x get print - ", " print - y get print - ")" print - } draw: -} Drawable impl - -// Define distance function (requires Numeric) -(T T -- T) Numeric { - over x get over x get - dup * - swap y get swap y get - dup * - + sqrt -} distance fn - -// Usage -3.0 4.0 Point -5.0 12.0 Point -distance print // 13.0 -``` - -### 14.4 Generic Container - -``` -// Define a generic stack container -(T --) { - items: - size: -} Stack struct - -// Push function -(Stack T -- Stack) { - over items get swap concat - over size get 1 + - Stack -} stack_push fn - -// Pop function (returns Stack and popped value) -(Stack -- Stack T) { - dup items get - dup length 1 - - over length 1 - at // Get last item - -rot 0 swap 1 - slice // Remove last item - over size get 1 - - Stack - swap -} stack_pop fn - -// Usage -[] 0 Stack // Empty stack -42 stack_push -100 stack_push -stack_pop drop // Pop and discard value -``` - -### 14.5 Array Processing - -``` -// Sum of squares of even numbers from 1 to 10 -[1 2 3 4 5 6 7 8 9 10] - { 2 % 0 == } filter // Keep even numbers - { dup * } map // Square each - 0 { + } reduce // Sum -print // 220 - -// More complex: find max of absolute differences -[1 5 2 8 3] -[2 3 7 4 6] - { - abs } map2 // Element-wise abs difference - 0 { max } reduce // Find maximum -print // 4 -``` - -### 14.6 Result Type Usage - -``` -// Define Result union -(T E --) { Ok(T) Err(E) } Result union - -// Function that returns Result -(i32 i32 -- Result) { - dup 0 == - { drop "Division by zero" Err } - { / Ok } - if -} safe_div fn - -// Use it -10 2 safe_div { - Ok(x) => { x print } - Err(e) => { "Error: " print e print } -} match -``` - -## 15. Syntax Summary - -### Complete Grammar Patterns - -**Functions**: `(in -- out) constraints { body } name fn` - -**Structs**: `(types -- ) { fields: } name struct` - -**Unions**: `(types -- ) { Variant(T) ... } name union` - -**Enums**: `() { Variant ... } name enum` - -**Traits**: `{ (sig) method: ... } name trait` - -**Trait Impl**: `Type { (sig) { body } method: ... } Trait impl` - -**If**: `condition { then } { else } if` - -**While**: `{ condition } { body } while` - -**For**: `start end { body } for` - -**Match**: `value { pattern => block ... } match` - ---- - -**Version**: 0.2 -**Status**: Draft Specification - Pure Postfix Edition \ No newline at end of file diff --git a/stack_lang_spec_v03.md b/stack_lang_spec_v03.md deleted file mode 100644 index 207d027..0000000 --- a/stack_lang_spec_v03.md +++ /dev/null @@ -1,817 +0,0 @@ -# Stack Language Specification v0.3 - -## 1. Overview - -A statically-typed, stack-based language with pure postfix notation combining the execution model of HP's RPL, the type system of C and Rust, and modern array operations from Uiua. - -### Design Principles -- **Everything is postfix** - no exceptions -- Stack-based execution (no local variables) -- Static typing with type inference -- Manual heap memory management -- Types define what things **are**, traits define how things **act** -- All constructs are implicitly generic -- **Every operator is defined by a trait** - -## 2. Lexical Structure - -### 2.1 Comments -``` -// Single-line comment -``` - -### 2.2 Identifiers -- Start with letter or underscore: `[a-zA-Z_][a-zA-Z0-9_]*` -- Case-sensitive -- Trait names prefixed with `::` (e.g., `::Addable`, `::Number`) - -### 2.3 Literals - -**Integer Literals** -``` -42 // i32 (default) -42 i64 // Annotate as i64 -0xFF // hexadecimal -0b1010 // binary -``` - -**Floating Point Literals** -``` -3.14 // f64 (default) -3.14 f32 // Annotate as f32 -``` - -**String Literals** -``` -"hello world" -"escape sequences: \n \t \\ \"" -``` - -**Boolean Literals** -``` -true -false -``` - -**Array Literals** -``` -[1 2 3 4 5] // array of i32 -[1.0 2.0 3.0] // array of f64 -[[1 2] [3 4]] // 2D array -``` - -## 3. Type System - -### 3.1 Primitive Types -- `i8`, `i16`, `i32`, `i64` - Signed integers -- `u8`, `u16`, `u32`, `u64` - Unsigned integers -- `f32`, `f64` - Floating point -- `bool` - Boolean -- `char` - Single character (UTF-8) -- `ptr` - Raw pointer (generic over pointed type) - -### 3.2 Types vs Traits - -**Types** define the concrete structure and memory layout: -``` -Point struct // Point is a type -Rectangle struct // Rectangle is a type -``` - -**Traits** define behavioral contracts - how things act: -``` -::Drawable trait // Drawable is a trait -::Addable trait // Addable is a trait -``` - -**Key Distinction:** -- A value **has** a type (what it is structurally) -- A value **implements** a trait (how it behaves) -- Types are concrete; traits are interfaces -- Functions can be generic over both types and traits -- **Every operator must be backed by a trait** - -### 3.3 All Constructs are Generic - -Every function, struct, and union is implicitly generic. Constraints are specified via traits: - -``` -// Function generic over any type T -(T -- T) { dup * } square fn - -// Function requiring T to implement Addable trait -(T T -- T) ::Addable { + } add_two fn - -// Struct generic over field types -(T T --) { x: y: } Point struct - -// Union generic over variant types -(T --) { Some(T) None } Option union -``` - -## 4. Base Traits (Non-Exhaustive) - -### 4.1 Core Traits - -**::Pushable** - Can be pushed onto the stack -``` -{ (-- Self) push: } ::Pushable trait -``` - -**::ArrayOf** - Array container trait -``` -{ (-- ArrayOf[T]) create: (ArrayOf[T] i32 -- T) at: } ::ArrayOf trait -``` - -**::Addable** - Supports addition and subtraction -``` -{ (Self Self -- Self) +: (Self Self -- Self) -: } ::Addable trait -``` - -**::Number** - Numeric operations -``` -// Number inherits from multiple traits -[ ::Addable ::Multiplyable ::Comparable ] ::Number inher -``` - -**::String** - String operations -``` -{ (Self Self -- Self) concat: (Self -- i32) length: } ::String trait -``` - -**::Identifier** - Represents identifiers/symbols -``` -{ (-- TokenString) name: } ::Identifier trait -``` - -**::Trait** - Meta-trait for trait operations -``` -{ (TokenString Identifier --) trait: (Identifier TokenString Identifier --) impl: (ArrayOf[Identifier] Identifier --) inher: } ::Trait trait -``` - -### 4.2 Additional Core Traits - -**::Multiplyable** - Multiplication and division -``` -{ (Self Self -- Self) *: (Self Self -- Self) /: (Self Self -- Self) %: } ::Multiplyable trait -``` - -**::Comparable** - Comparison operations -``` -{ (Self Self -- bool) >: (Self Self -- bool) >=: (Self Self -- bool) <: (Self Self -- bool) <=: (Self Self -- bool) ==: (Self Self -- bool) !=: } ::Comparable trait -``` - -**::Logical** - Logical operations -``` -{ (Self Self -- Self) and: (Self Self -- Self) or: (Self -- Self) not: } ::Logical trait -``` - -**::Bitwise** - Bitwise operations -``` -{ (Self Self -- Self) bitand: (Self Self -- Self) bitor: (Self Self -- Self) bitxor: (Self -- Self) bitnot: (Self i32 -- Self) shl: (Self i32 -- Self) shr: } ::Bitwise trait -``` - -**::Exponentiable** - Exponentiation -``` -{ (Self Self -- Self) ^: } ::Exponentiable trait -``` - -## 5. Stack Operations - -### 5.1 Stack Manipulation - -All stack operations are backed by traits. - -``` -dup // ( a -- a a ) Duplicate top [::Duplicable] -drop // ( a -- ) Remove top [::Droppable] -swap // ( a b -- b a ) Swap top two [::Swappable] -over // ( a b -- a b a ) Copy second to top [::Overable] -rot // ( a b c -- b c a ) Rotate three items [::Rotatable] -``` - -### 5.2 Stack Inspection -``` -depth // ( -- n ) Push stack depth [::Inspectable] -pick // ( n -- x ) Copy nth item to top (0 = top) [::Pickable] -roll // ( n times -- ) Rotate n items, times times [::Rollable] -``` - -**Roll Examples:** -``` -// Stack: a b c d e -3 1 roll // Rotate top 3 items once: a b d e c -3 2 roll // Rotate top 3 items twice: a b e c d -5 1 roll // Rotate all 5 items once: b c d e a -``` - -## 6. Operators (Postfix) - -**Every operator is backed by a trait and must be implemented for types that use it.** - -### 6.1 Arithmetic (::Addable, ::Multiplyable, ::Exponentiable) - -``` -3 4 + // ( a b -- result ) Addition [::Addable] -10 3 - // Subtraction [::Addable] -5 6 * // Multiplication [::Multiplyable] -20 4 / // Division [::Multiplyable] -17 5 % // Modulo [::Multiplyable] -2 8 ^ // Exponentiation [::Exponentiable] -``` - -### 6.2 Comparison (::Comparable) -``` -5 3 > // Greater than [::Comparable] -5 3 >= // Greater or equal [::Comparable] -5 3 < // Less than [::Comparable] -5 3 <= // Less or equal [::Comparable] -5 5 == // Equal [::Comparable] -5 3 != // Not equal [::Comparable] -``` - -### 6.3 Logical (::Logical) -``` -true false and // Logical AND [::Logical] -true false or // Logical OR [::Logical] -true not // Logical NOT [::Logical] -``` - -### 6.4 Bitwise (::Bitwise) -``` -0xFF 0x0F bitand // Bitwise AND [::Bitwise] -0xFF 0x0F bitor // Bitwise OR [::Bitwise] -0xFF 0x0F bitxor // Bitwise XOR [::Bitwise] -0xFF bitnot // Bitwise NOT [::Bitwise] -8 2 shl // Left shift [::Bitwise] -8 2 shr // Right shift [::Bitwise] -``` - -## 7. Trait System - -### 7.1 Trait Definition - -**Syntax**: `{ function_signatures } ::name trait` - -``` -// Simple trait -{ - (Self -- ) draw: -} ::Drawable trait - -// Trait with multiple methods -{ - (Self Self -- Self) add: - (Self Self -- Self) sub: - (Self -- Self) neg: -} ::Numeric trait - -// The comprehensive Trait meta-trait -{ - (TokenString Identifier --) trait: - (Identifier TokenString Identifier --) impl: - (ArrayOf[Identifier] Identifier --) inher: -} ::Implementable trait -``` - -### 7.2 Trait Implementation - -**Syntax**: `::type { method_implementations } ::trait impl` - -``` -// Implement Addable for i32 -::i32 { - (Self Self -- Self) { - // Native addition implementation - } +: - - (Self Self -- Self) { - // Native subtraction implementation - } -: -} ::Addable impl - -// Implement Drawable for Rectangle -::Rectangle { - (Rectangle -- ) { - "Drawing rectangle" print - dup width get print - height get print - } draw: -} ::Drawable impl -``` - -### 7.3 Trait Inheritance - -**Syntax**: `[ ::trait1 ::trait2 ... ] ::derived_trait inher` - -``` -// Number inherits from Addable and Multiplyable -[ ::Addable ::Multiplyable ] ::Number inher - -// Numeric inherits from Number, Comparable, and Exponentiable -[ ::Number ::Comparable ::Exponentiable ] ::Numeric inher - -// Complex inheritance -[ ::Drawable ::Transformable ::Collidable ] ::GameObject inher -``` - -### 7.4 Using Traits in Functions - -``` -// Function requiring Drawable trait -(T -- ) ::Drawable { - draw -} draw_twice fn - -// Multiple trait requirements -(T -- T) ::Numeric ::Copyable { - dup abs swap dup * + -} complex_calc fn -``` - -## 8. Functions (Postfix Definition) - -Functions are defined in postfix notation. The signature and body come before the name. - -### 8.1 Basic Function Definition - -**Syntax**: `(inputs -- outputs) { body } name fn` - -``` -// Define a square function -(i32 -- i32) { dup * } square fn - -// Use it -5 square // 25 - -// Multiple inputs and outputs -(i32 i32 -- i32 i32) { - 2dup / swap % -} divmod fn - -10 3 divmod // 3 1 (quotient remainder) -``` - -### 8.2 Generic Functions with Trait Constraints - -**Syntax**: `(type_sig) ::trait_constraints { body } name fn` - -``` -// Generic identity - works with any type -(T -- T) {} identity fn - -// Requires T to be Addable -(T T -- T) ::Addable { - + -} add_values fn - -// Multiple trait constraints -(T U -- U T) ::Copyable ::Swappable { - swap -} swap_generic fn - -// Multiple type parameters with different traits -(T U -- T) ::Addable ::Numeric { - dup U as + -} add_converted fn -``` - -## 9. Control Flow (Postfix) - -### 9.1 Conditionals - -**Syntax**: `condition { then-block } { else-block } if` - -``` -// if-then (else block is empty) -x 0 > { "positive" print } {} if - -// if-then-else -x 0 > - { "positive" print } - { "non-positive" print } -if - -// The condition comes first, then both blocks, then 'if' -a b > - { a } - { b } -if max set - -// Nested -x 0 > - { - y 0 > - { "both positive" print } - { "x positive, y not" print } - if - } - { "x not positive" print } -if -``` - -### 9.2 Loops - -**While Loop** - -**Syntax**: `{ condition-block } { body-block } while` - -``` -// Sum 1 to 10 -0 1 // sum counter - { dup 10 <= } // condition block - { // body block - over over + // Add counter to sum - swap 1 + swap // Increment counter - } -while -drop // Drop counter, leave sum - -// Infinite loop with break -{ true } { - // body - condition { break } {} if -} while -``` - -**For Loop** - -**Syntax**: `start end { body-with-counter } for` - -``` -// The loop variable is implicitly pushed to stack in each iteration -1 10 { - // Stack has loop counter on top - dup print -} for - -// More complex -1 100 { - dup fizzbuzz -} for -``` - -### 9.3 Loop Control -``` -break // Exit loop -continue // Skip to next iteration -``` - -### 9.4 Match/Pattern Matching - -**Syntax**: `value { pattern => block ... } match` - -``` -value { - Some(x) => { x print } - None => { "Nothing" print } -} match - -// With multiple patterns -status { - Pending => { "Waiting" print } - Active => { "Running" print } - Complete => { "Done" print } -} match -``` - -## 10. Data Structures (Postfix) - -### 10.1 Struct Definition - -**Syntax**: `(field_types -- ) { field_names } name struct` - -``` -// Define Point struct - generic over coordinate types -(T T --) { x: y: } Point struct - -// Use with specific types -3.0 4.0 Point // Creates Point with f64 fields -3 4 Point // Creates Point with i32 fields - -// More complex struct -(T U V --) { - width: - height: - depth: -} Box3D struct - -10.0 20.0 30.0 Box3D -``` - -### 10.2 Struct Field Access - -**Syntax (postfix)**: `struct field get` or `struct value field set` - -``` -point x get // Get x field -point 15.0 x set // Set x field to 15.0 - -// Chaining -point x get 2 * y get + // (point.x * 2) + point.y -``` - -### 10.3 Union Definition - -**Syntax**: `(variant_types -- ) { variants } name union` - -``` -// Option type - generic over T -(T --) { - Some(T) - None -} Option union - -// Result type - generic over T and E -(T E --) { - Ok(T) - Err(E) -} Result union - -// Create union values -42 Some // Creates Option::Some(42) -None // Creates Option::None -"success" Ok // Creates Result::Ok("success") -"error" Err // Creates Result::Err("error") -``` - -### 10.4 Enum Definition - -**Syntax**: `() { variants } name enum` - -``` -() { - Pending - Active - Complete -} Status enum - -// Usage -Pending // Creates Status::Pending -Active // Creates Status::Active -``` - -## 11. Memory Management (Postfix) - -### 11.1 Heap Operations - -``` -// Allocate -3.0 4.0 Point alloc // ( Point -- ptr ) - -// Dereference -ptr deref // ( ptr -- T ) - -// Store (dereference and update) -new_value ptr store // ( T ptr -- ) - -// Free -ptr free // ( ptr -- ) -``` - -### 11.2 Example - -``` -// Create heap-allocated point -3.0 4.0 Point alloc // Returns ptr -dup x get print // Dereference and print x -free // Clean up -``` - -## 12. Array Operations (Postfix) - -### 12.1 Basic Array Operations - -``` -// Creation -1 10 range // Create range array [1..10] - -// Shape operations -arr shape // Get shape -arr 2 3 reshape // Reshape to 2x3 - -// Element access -arr 2 at // Index access -arr 1 3 slice // Slice array -``` - -### 12.2 Array Combinators - -``` -// Map - apply function to each element -[1 2 3 4] { 2 * } map // [2 4 6 8] - -// Filter - keep elements matching predicate -[1 2 3 4 5] { 2 % 0 == } filter // [2 4] - -// Reduce - fold with function -[1 2 3 4] 0 { + } reduce // 10 - -// Each - apply to each element (side effects) -[[1 2] [3 4]] { sum print } each -``` - -### 12.3 Array Arithmetic - -``` -[1 2 3] [4 5 6] +. // Element-wise add: [5 7 9] -[1 2 3] [4 5 6] *. // Element-wise multiply: [4 10 18] -[1 2 3] 2 *. // Scalar multiply: [2 4 6] -``` - -### 12.4 Array Manipulation - -``` -[1 2 3] [4 5 6] concat // Concatenate: [1 2 3 4 5 6] -[1 2 3] reverse // [3 2 1] -[[1 2] [3 4]] transpose // [[1 3] [2 4]] -[1 2 3 4] 2 window // [[1 2] [2 3] [3 4]] -``` - -## 13. Eval Operator (Postfix) - -Execute code dynamically at runtime. - -``` -// Evaluate string as code -"2 3 +" eval // Pushes 5 - -// Build and execute code -"(i32 -- i32) { dup * } square fn" eval -5 square // 25 - -// Dynamic dispatch -operation_name " get" concat eval -``` - -## 14. Standard Library Concepts - -### 14.1 I/O - -``` -"Hello" print // Print to stdout -"Enter name: " input // Read from stdin -"file.txt" read // Read file contents -"data" "file.txt" write // Write to file -``` - -### 14.2 String Operations - -``` -"hello" " world" concat // Concatenate: "hello world" -"hello" length // 5 -"hello" 1 3 substr // "el" -"a,b,c" "," split // ["a" "b" "c"] -["a" "b"] "," join // "a,b" -``` - -### 14.3 Type Conversion - -``` -42 f64 as // Convert i32 to f64 -"123" i32 parse // Parse string to i32 -3.14 str as // Convert to string -``` - -## 15. Complete Examples - -### 15.1 Trait Implementation Example - -``` -// Define the Addable trait -{ - (Self Self -- Self) +: - (Self Self -- Self) -: -} ::Addable trait - -// Implement for i32 -::i32 { - (Self Self -- Self) { - // Native addition - } +: - - (Self Self -- Self) { - // Native subtraction - } -: -} ::Addable impl - -// Implement for Point -::Point { - (Point Point -- Point) { - over x get over x get + - swap y get swap y get + - Point - } +: - - (Point Point -- Point) { - over x get over x get - - swap y get swap y get - - Point - } -: -} ::Addable impl -``` - -### 15.2 Trait Inheritance Example - -``` -// Define base traits -{ (Self Self -- Self) +: (Self Self -- Self) -: } ::Addable trait -{ (Self Self -- Self) *: (Self Self -- Self) /: } ::Multiplyable trait -{ (Self Self -- Self) ^: } ::Exponentiable trait - -// Number inherits from multiple traits -[ ::Addable ::Multiplyable ] ::Number inher - -// Numeric extends Number further -[ ::Number ::Exponentiable ] ::Numeric inher -``` - -### 15.3 Factorial - -``` -(i32 -- i32) { - dup 1 - { drop 1 } - { dup 1 - factorial * } - <= if -} factorial fn - -5 factorial print // 120 -``` - -### 15.4 FizzBuzz - -``` -(i32 -- ) { - dup 15 % 0 == - { drop "FizzBuzz" print } - { - dup 3 % 0 == - { drop "Fizz" print } - { - dup 5 % 0 == - { drop "Buzz" print } - { print } - if - } - if - } - if -} fizzbuzz fn - -1 100 { fizzbuzz } for -``` - -### 15.5 Using Roll - -``` -// Stack: 1 2 3 4 5 -3 1 roll // Rotate top 3 once: 1 2 4 5 3 -3 2 roll // Rotate top 3 twice: 1 2 5 3 4 - -// More complex example -10 20 30 40 50 -4 2 roll // Rotate top 4, twice: 10 30 40 50 20 -``` - -### 15.6 Array Processing - -``` -// Sum of squares of even numbers from 1 to 10 -[1 2 3 4 5 6 7 8 9 10] - { 2 % 0 == } filter // Keep even numbers - { dup * } map // Square each - 0 { + } reduce // Sum -print // 220 -``` - -## 16. Syntax Summary - -### Complete Grammar Patterns - -**Functions**: `(in -- out) ::constraints { body } name fn` - -**Structs**: `(types -- ) { fields: } name struct` - -**Unions**: `(types -- ) { Variant(T) ... } name union` - -**Enums**: `() { Variant ... } name enum` - -**Traits**: `{ (sig) method: ... } ::name trait` - -**Trait Impl**: `::Type { (sig) { body } method: ... } ::Trait impl` - -**Trait Inheritance**: `[ ::Trait1 ::Trait2 ] ::NewTrait inher` - -**If**: `condition { then } { else } if` - -**While**: `{ condition } { body } while` - -**For**: `start end { body } for` - -**Match**: `value { pattern => block ... } match` - ---- - -**Version**: 0.3 -**Status**: Draft Specification - Trait-Backed Operations Edition \ No newline at end of file diff --git a/stack_lang_spec_v04.md b/stack_lang_spec_v04.md deleted file mode 100644 index 8cb2f98..0000000 --- a/stack_lang_spec_v04.md +++ /dev/null @@ -1,1002 +0,0 @@ -# Stack Language Specification v0.4 - -## 1. Overview - -A statically-typed, stack-based language with pure postfix notation combining the execution model of HP's RPL, the type system of C and Rust, and modern array operations from Uiua. - -### Design Principles -- **Everything is postfix** - no exceptions -- Stack-based execution (no local variables) -- Static typing with type inference -- Manual heap memory management -- Types define what things **are**, traits define how things **act** -- All constructs are implicitly generic -- **Every operator is defined by a trait** - -## 2. Lexical Structure - -### 2.1 Comments -``` -// Single-line comment -``` - -### 2.2 Identifiers - -**Regular Identifiers** -- Start with letter or underscore: `[a-zA-Z_][a-zA-Z0-9_]*` -- Case-sensitive -- When encountered, identifiers are executed immediately - -**Identifier Literals** -- Prefix with `::` to push the identifier itself onto the stack instead of executing it -- Syntax: `::name` pushes the identifier `name` as a value -- Example: `::Addable` pushes the identifier `Addable` onto the stack -- Example: `::Point` pushes the identifier `Point` onto the stack - -### 2.3 Literals - -**Integer Literals** -``` -42 // i64 (default) -42:i32 // Annotate as i32 -0xFF // hexadecimal -0b1010 // binary -``` - -**Floating Point Literals** -``` -3.14 // f64 (default) -3.14:f32 // Annotate as f32 -``` - -**String Literals** -``` -"hello world" -"escape sequences: \n \t \\ \"" -``` - -> **TODO:** List all escape sequences. - -**Boolean Literals** -``` -true -false -``` - -**Array Literals** -``` -[1 2 3 4 5] // array of i32 -[1.0 2.0 3.0] // array of f64 -[[1 2] [3 4]] // 2D array -``` - -> **TODO:** Define Type Tuples: `(T T -- T)`. - -**Token Strings** -``` -{ code here } // TokenString - lexed but not parsed/executed -``` - -Token strings contain lexed tokens that are not parsed or executed until an operator causes them to be: -- `trait` operator parses the TokenString as a trait definition -- `fn` operator parses the TokenString as a function definition -- `impl` operator parses the TokenString as a trait implementation -- `eval` operator parses and executes the TokenString immediately - -Within TokenStrings, the `::` prefix may be used, though it's not strictly required since the context (trait definition or implementation, or function definition or eval) determines how identifiers are interpreted. - -> **TODO:** `::` should not be allowed for traits and implementations. - -> **TODO:** `if`, `while`, `match`, etc. also use Token Strings - -> **TODO: (FOR HUMAN)** Should `::` be required for identifier literals in functions? - -## 3. Type System - -### 3.1 Primitive Types -- `i8`, `i16`, `i32`, `i64` - Signed integers -- `u8`, `u16`, `u32`, `u64` - Unsigned integers -- `f32`, `f64` - Floating point -- `bool` - Boolean -- `char` - Single character (UTF-8) -- `ptr` - Raw pointer (generic over pointed type) - -### 3.2 Types vs Traits - -**Types** define the concrete structure and memory layout: -``` -Point struct // Point is a type -Rectangle struct // Rectangle is a type -``` - -**Traits** define behavioral contracts - how things act: -``` -{ ... } ::Addable trait // Addable is a trait -{ ... } ::Drawable trait // Drawable is a trait -``` - -**Key Distinction:** -- A value has a type (what it is structurally) -- A value implements a trait (how it behaves) -- Types are concrete; traits are interfaces -- Functions can be generic over traits -- Functions can have types and traits defined as return types -- Every operator must be backed by a trait - -### 3.3 All Constructs are Generic - -> **TODO:** Constructs are not all Generic. - -Every function, struct, and union is implicitly generic. Constraints are specified via traits: - -``` -// Function generic over any type T -(T -- T) { dup * } ::square fn - -// Struct generic over field types -(T T --) { x: y: } ::Point struct - -// Union generic over variant types -(T --) { Some(T) None } ::Option union -``` - -> **TODO:** `(T -- T) { dup * } ::square fn` would be illegal as the use of `*` requires `Multiplyable`. - -## 4. Trait System - -### 4.1 Standard Traits - -Traits define behavioral contracts. Every operator in the language is backed by one or more traits. - -**Stack Manipulation Traits** -``` -{ (-- Self) push: } ::Pushable trait -{ (Self -- Self Self) dup: } ::Duplicable trait -{ (Self -- ) drop: } ::Droppable trait -{ (Self Self -- Self Self) swap: } ::Swappable trait -{ (Self Self -- Self Self Self) over: } ::Overable trait -{ (Self Self Self -- Self Self Self) rot: } ::Rotatable trait -{ (Size -- Self) pick: } ::Pickable trait -{ (Size Size -- ) roll: } ::Rollable trait -{ (-- i64) depth: } ::Inspectable trait -``` - -> **TODO: (FOR HUMAN)** Can a type tuple have no parameters? - -> **TODO:** Stack manipulation should use one trait. - -> **TODO:** Add a `Size` trait that inherits from `Addable`, `Comparable`, and `Convertible`. - -**Arithmetic Traits** -``` -{ (Self Self -- Self) +: (Self Self -- Self) -: } ::Addable trait - -{ (Self Self -- Self) *: (Self Self -- Self) /: (Self Self -- Self) %: } ::Multiplyable trait - -{ (Self Self -- Self) ^: } ::Exponentiable trait - -{ (Self Self -- Self) logb: (Self -- Self) log: (Self -- Self) ln: } ::Logarithmic trait -``` - -**Comparison Traits** -``` -{ (Self Self -- bool) >: (Self Self -- bool) >=: (Self Self -- bool) <: (Self Self -- bool) <=: } ::Orderable trait - -{ (Self Self -- bool) ==: (Self Self -- bool) !=: } ::Equatable trait - -// Comparable combines ordering and equality -[ ::Orderable ::Equatable ] ::Comparable inher -{ } ::Comparable trait -``` - -**Logical Operations Traits** -``` -{ (Self -- bool) truthy: (Self Self -- Self) and: (Self Self -- Self) or: (Self -- Self) not: } ::Logical trait -``` - -**Bitwise Operations Traits** -``` -{ (Self Self -- Self) bitand: (Self Self -- Self) bitor: (Self Self -- Self) bitxor: (Self -- Self) bitnot: (Self Size -- Self) shl: (Self Size -- Self) shr: } ::Bitwise trait -``` - -**Container Traits** -``` -{ (Self -- i64) length: } ::Sized trait - -{ (Self Size -- T) at: } ::Selectable trait - -{ (Self Self -- Self) concat: } ::Concatenable trait - -{ (Self Size Size -- Self) slice: } ::Sliceable trait - -[ ::Sized ::Selectable ::Sliceable ] ::ArrayOf inher -{ } ::ArrayOf trait -``` - -**String Traits** -``` -[ ::Concatenable ] ::String inher -{ (Self Size Size -- Self) substr: (Self Self -- ArrayOf) split: } ::String trait -``` - -**Conversion Traits** -``` -{ (Self Type -- T) as: } ::Convertible trait - -{ (Self -- String) str: } ::Stringifiable trait - -{ (String -- Self) parse: } ::Parseable trait -``` - -> **TODO: (FOR HUMAN)** Type conversion may need to work a different way? - -**Numeric Composite Trait** - -The `Number` trait represents the full suite of numeric operations by inheriting from multiple traits: - -``` -[ Addable Multiplyable Exponentiable Comparable Logarithmic ] ::Number inher -{ } ::Number inher -``` - -**Meta-Traits** - -Traits for defining and working with traits themselves: - -``` -{ } ::Identifier trait - -{ (TokenString Identifier --) trait: (Identifier TokenString Identifier --) impl: (ArrayOf Identifier --) inher: } ::Implementable trait -``` - -> **TODO: (FOR HUMAN)** Can traits be completely empty (no inher and empty trait)? - -### 4.2 Trait Definition - -**Syntax**: `{ function_signatures } ::identifier trait` - -``` -// Using identifier literal -{ - (Self -- ) draw: -} ::Drawable trait - -// Trait with multiple methods -{ - (Self Self -- Self) add: - (Self Self -- Self) sub: - (Self -- Self) neg: -} ::Numeric trait - -// Generic trait -{ - (Self T -- Self) append: - (Self -- T) pop: -} ::Container trait -``` - -Within the TokenString (the `{ }` block), identifiers like `Self`, `add:`, `draw:` are part of the trait definition syntax. When referencing existing traits within the definition, you may use `::TraitName` for clarity, though the context makes it clear they are trait references. - -> **TODO:** Again, `::` should not be allowed in the Token String for traits and implementations. - -### 4.3 Trait Implementation - -**Syntax**: `identifier { method_implementations } ::identifier impl` - -``` -// Implement Addable for i32 -::Addable { - (Self Self -- Self) { - // Native addition implementation - } +: - - (Self Self -- Self) { - // Native subtraction implementation - } -: -} ::i32 impl - -// Implement Drawable for Rectangle -::Drawable { - (Self -- ) { - "Drawing rectangle" print - dup ::width get print - ::height get print - } draw: -} ::Rectangle impl -``` - -> **Note:** The following block has been human verified to be syntactically and logically correct. - -``` -// Implement Addable for Point -::Addable { - (Self Self -- Self) { - over ::x get over ::x get + - 3 pick ::y get 3 pick ::y get + - Point - } +: - - (Self Addable -- Self) { - over ::x get over + - 3 pick ::y get 3 pick + - Point - } +: - - (Addable Self -- Self) { - over over ::x get + - 3 pick 3 pick ::y get + - Point - } +: - - (Self Self -- Self) { - over ::x get over ::x get - - 3 pick ::y get 3 pick ::y get - - Point - } -: - - (Self Addable -- Self) { - over ::x get over - - 3 pick ::y get 3 pick - - Point - } -: -} ::Point impl - -// Implement Logical for everything -::Logical { - (Self -- bool) { true } truthy: - - (Self Self -- Self) { - over truthy { } { swap } if drop - } and: - - (Self Self -- Self) { - over truthy { swap } { } if drop - } or: -} ::Logical impl - -// Overload Logical for bool -::Logical { - (Self -- Self) { } truthy: -} ::bool impl - -// Overload Logical for Numeric -::Logical { - (Self -- bool) { 0 != } truthy: -} ::Number impl - -// Overload Logical for Option -::Logical { - (Self -- bool) { { Some(_) => { true } None => { false } } match } truthy: -} ::Option impl - -// Overload Logical for Result -::Logical { - (Self -- bool) { { Ok(_) => { true } Err(_) => { false } } match } truthy: -} ::Result impl -``` - -### 4.4 Trait Inheritance - -**Syntax**: `[ identifier_list ] identifier inher` - -> **TODO:** `inher` must be before `trait` and must have a `trait`. - -``` -// Number inherits from multiple arithmetic traits -[ ::Addable ::Multiplyable ] ::BasicNumber inher - -// Full Number inherits everything numeric -[ ::Addable ::Multiplyable ::Exponentiable ::Comparable ::Logarithmic ] ::Number inher - -// Complex inheritance -[ ::Drawable ::Transformable ::Collidable ] ::GameObject inher -``` - -### 4.5 Using Traits in Functions - -``` -// Function requiring Drawable trait -(Drawable -- ) { - draw -} ::draw_twice fn -``` - -## 5. Stack Operations - -### 5.1 Stack Manipulation - -All stack operations are backed by traits. - -``` -dup // ( a -- a a ) Duplicate top [Duplicable] -drop // ( a -- ) Remove top [Droppable] -swap // ( a b -- b a ) Swap top two [Swappable] -over // ( a b -- a b a ) Copy second to top [Overable] -rot // ( a b c -- b c a ) Rotate three items [Rotatable] -``` - -### 5.2 Stack Inspection -``` -depth // ( -- n ) Push stack depth [Inspectable] -pick // ( n -- x ) Copy nth item to top (0 = top) [Pickable] -roll // ( n times -- ) Rotate n items, times times [Rollable] -``` - -**Roll Examples:** -``` -// Stack: a b c d e -3 1 roll // Rotate top 3 items once: a b d e c -3 2 roll // Rotate top 3 items twice: a b e c d -5 1 roll // Rotate all 5 items once: b c d e a -4 3 roll // Rotate top 4 items three times: a d e c b -``` - -## 6. Operators (Postfix) - -**Every operator is backed by a trait and must be implemented for types that use it.** - -### 6.1 Arithmetic - -``` -3 4 + // ( a b -- result ) Addition [Addable] -10 3 - // Subtraction [Addable] -5 6 * // Multiplication [Multiplyable] -20 4 / // Division [Multiplyable] -17 5 % // Modulo [Multiplyable] -2 8 ^ // Exponentiation [Exponentiable] -100 log // Log base 10 [Logarithmic] -2.718 ln // Natural logarithm [Logarithmic] -``` - -### 6.2 Comparison - -``` -5 3 > // Greater than [Orderable] -5 3 >= // Greater or equal [Orderable] -5 3 < // Less than [Orderable] -5 3 <= // Less or equal [Orderable] -5 5 == // Equal [Equatable] -5 3 != // Not equal [Equatable] -``` - -### 6.3 Logical - -``` -true false and // Logical AND [Logical] -true false or // Logical OR [Logical] -true not // Logical NOT [Logical] -``` - -### 6.4 Bitwise - -``` -0xFF 0x0F bitand // Bitwise AND [Bitwise] -0xFF 0x0F bitor // Bitwise OR [Bitwise] -0xFF 0x0F bitxor // Bitwise XOR [Bitwise] -0xFF bitnot // Bitwise NOT [Bitwise] -8 2 shl // Left shift [Bitwise] -8 2 shr // Right shift [Bitwise] -``` - -## 7. Functions (Postfix Definition) - -Functions are defined in postfix notation. The signature and body come before the name. - -### 7.1 Basic Function Definition - -**Syntax**: `(inputs -- outputs) { body } name fn` - -``` -// Define a square function -(Number -- Number) { dup * } ::square fn - -// Use it -5 square // 25 - -// Multiple inputs and outputs -(Number Number -- Number Number) { - over over / swap % -} ::divmod fn - -10 3 divmod // 3 1 (quotient remainder) -``` - -### 7.2 Generic Functions with Trait Constraints - -**Syntax**: `(type_sig) { body } name fn` - -``` -// Generic identity - works with any type -(T -- T) { } ::identity fn - -// Requires Addable -(Addable Addable -- Addable) { - + -} ::add_values fn - -(Number -- Number) { - dup 0 > { } { 0 T as - } if -} ::abs fn -``` - -## 8. Control Flow (Postfix) - -### 8.1 Conditionals - -**Syntax**: `condition { then-block } { else-block } if` - -``` -// if-then (else block is empty) -x 0 > { "positive" print } {} if - -// if-then-else -x 0 > - { "positive" print } - { "non-positive" print } -if - -// The condition comes first, then both blocks, then 'if' -a b > - { a } - { b } -if - -// Nested -x 0 > - { - y 0 > - { "both positive" print } - { "x positive, y not" print } - if - } - { "x not positive" print } -if -``` - -### 8.2 Loops - -**While Loop** - -**Syntax**: `{ condition-block } { body-block } while` - -``` -// Sum 1 to 10 -0 1 // sum counter - { dup 10 <= } // condition block - { // body block - over over + // Add counter to sum - swap 1 + swap // Increment counter - } -while -drop // Drop counter, leave sum - -// Infinite loop with break -{ true } { - // body - condition { break } {} if -} while -``` - -**For Loop** - -**Syntax**: `start end { body-with-counter } for` - -``` -// The loop variable is implicitly pushed to stack in each iteration -1 10 { - // Stack has loop counter on top - dup print -} for - -// More complex -1 100 { - dup fizzbuzz -} for -``` - -### 8.3 Loop Control -``` -break // Exit loop -continue // Skip to next iteration -``` - -### 8.4 Match/Pattern Matching - -**Syntax**: `value { pattern => block ... } match` - -``` -value { - Some(x) => { x print } - None => { "Nothing" print } -} match - -// With multiple patterns -status { - Pending => { "Waiting" print } - Active => { "Running" print } - Complete => { "Done" print } -} match -``` - -## 9. Data Structures (Postfix) - -### 9.1 Struct Definition - -**Syntax**: `(field_types -- ) { field_names } name struct` - -``` -// Define Point struct - generic over coordinate types -(T T --) { x: y: } ::Point struct - -// Use with specific types -3.0 4.0 Point // Creates Point with f64 fields -3 4 Point // Creates Point with i64 fields - -// More complex struct -(T U V --) { - width: - height: - depth: -} ::Box3D struct - -10.0 20.0 30.0 Box3D -``` - -### 9.2 Struct Field Access - -**Syntax (postfix)**: `struct field get` or `struct value field set` - -``` -point ::x get // Get x field -point 15.0 ::x set // Set x field to 15.0 - -// Chaining -point ::x get 2 * over ::y get + // (point.x * 2) + point.y -``` - -### 9.3 Union Definition - -**Syntax**: `(variant_types -- ) { variants } name union` - -``` -// Option type - generic over T -(T --) { - Some(T) - None -} ::Option union - -// Result type - generic over T and E -(T E --) { - Ok(T) - Err(E) -} ::Result union - -// Create union values -42 Option::Some // Creates Option::Some(42) -Option::None // Creates Option::None -"success" Result::Ok // Creates Result::Ok("success") -"error" Result::Err // Creates Result::Err("error") -``` - -### 9.4 Enum Definition - -**Syntax**: `{ variants } name enum` - -``` -{ - Pending 1: // Normally starts at 0 - Active: // Defaults to 2 (one plus the last) - Complete 0: -} ::Status enum - -// Usage -Status::Pending // Creates Status::Pending -Status::Active // Creates Status::Active -``` - -## 10. Memory Management (Postfix) - -> **TODO: (FOR HUMAN)** Leave out or redo how memory management is done? - -### 10.1 Heap Operations - -``` -// Allocate -3.0 4.0 Point alloc // ( Point -- ptr ) - -// Dereference -ptr deref // ( ptr -- T ) - -// Store (dereference and update) -new_value ptr store // ( T ptr -- ) - -// Free -ptr free // ( ptr -- ) -``` - -### 10.2 Example - -``` -// Create heap-allocated point -3.0 4.0 Point alloc // Returns ptr -dup x get print // Dereference and print x -free // Clean up -``` - -## 11. Array Operations (Postfix) - -### 11.1 Basic Array Operations - -``` -// Creation -1 10 range // Create range array [1..10] - -// Shape operations -arr shape // Get shape -arr 2 3 reshape // Reshape to 2x3 - -// Element access -arr 2 at // Index access -arr 1 3 slice // Slice array -``` - -### 11.2 Array Combinators - -> **TODO:** Funcs don't parse, the `if`, `while`, etc. inside do. - -``` -// Map - apply function to each element -[1 2 3 4] { 2 * } map // [2 4 6 8] - -// Filter - keep elements matching predicate -[1 2 3 4 5] { 2 % 0 == } filter // [2 4] - -// Reduce - fold with function -[1 2 3 4] 0 { + } reduce // 10 - -// Each - apply to each element (side effects) -[[1 2] [3 4]] { sum print } each -``` - -### 11.3 Array Arithmetic - -``` -[1 2 3] [4 5 6] +. // Element-wise add: [5 7 9] -[1 2 3] [4 5 6] *. // Element-wise multiply: [4 10 18] -[1 2 3] 2 *. // Scalar multiply: [2 4 6] -``` - -### 11.4 Array Manipulation - -``` -[1 2 3] [4 5 6] concat // Concatenate: [1 2 3 4 5 6] -[1 2 3] reverse // [3 2 1] -[[1 2] [3 4]] transpose // [[1 3] [2 4]] -[1 2 3 4] 2 window // [[1 2] [2 3] [3 4]] -``` - -## 12. Eval Operator (Postfix) - -Execute code dynamically at runtime. - -``` -// Evaluate string as code -"2 3 +" eval // Pushes 5 - -// Build and execute code -"(i32 -- i32) { dup * } square fn" eval -5 square // 25 - -// Dynamic dispatch -operation_name " get" concat eval -``` - -## 13. Standard Library Concepts - -> **TODO: (FOR HUMAN)** How are imports done? Is everything automatically in scope? - -### 13.1 I/O - -``` -"Hello" print // Print to stdout -"Enter name: " input // Read from stdin -"file.txt" read // Read file contents -"data" "file.txt" write // Write to file -``` - -### 13.2 String Operations - -``` -"hello" " world" concat // Concatenate: "hello world" -"hello" length // 5 -"hello" 1 3 substr // "el" -"a,b,c" "," split // ["a" "b" "c"] -["a" "b"] "," join // "a,b" -``` - -### 13.3 Type Conversion - -> **TODO:** Again, conversions need to be re-done. - -``` -42 f64 as // Convert i32 to f64 -"123" i32 parse // Parse string to i32 -3.14 str as // Convert to string -``` - -## 14. Complete Examples - -> **TODO:** These need to be reviewed for correctness. - -### 14.1 Trait Implementation Example - -``` -// Define the Addable trait using identifier literal -{ - (Self Self -- Self) +: - (Self Self -- Self) -: -} ::Addable trait - -// Implement for i32 -::i32 { - (Self Self -- Self) { - // Native addition - } +: - - (Self Self -- Self) { - // Native subtraction - } -: -} ::Addable impl - -// Implement for Point -::Point { - (Point Point -- Point) { - over x get over x get + - swap y get swap y get + - Point - } +: - - (Point Point -- Point) { - over x get over x get - - swap y get swap y get - - Point - } -: -} ::Addable impl -``` - -### 14.2 Trait Inheritance Example - -``` -// Define base traits -{ (Self Self -- Self) +: (Self Self -- Self) -: } ::Addable trait -{ (Self Self -- Self) *: (Self Self -- Self) /: } ::Multiplyable trait -{ (Self Self -- Self) ^: } ::Exponentiable trait -{ (Self -- Self) log: } ::Logarithmic trait -{ (Self -- Self) ln: } ::NaturalLogarithmic trait - -// Number inherits from multiple traits -[ ::Addable ::Multiplyable ::Exponentiable ::Logarithmic ::NaturalLogarithmic ] ::Number inher -``` - -### 14.3 Logarithm Usage - -``` -// Calculate log base 10 -100 log print // 2.0 -1000 log print // 3.0 - -// Calculate natural logarithm -2.718 ln print // ~1.0 -7.389 ln print // ~2.0 - -// Combine with other operations -10 3 ^ log print // 3.0 (log of 1000) -``` - -### 14.4 Factorial - -``` -(i32 -- i32) { - dup 1 - { drop 1 } - { dup 1 - factorial * } - <= if -} factorial fn - -5 factorial print // 120 -``` - -### 14.5 FizzBuzz - -``` -(i32 -- ) { - dup 15 % 0 == - { drop "FizzBuzz" print } - { - dup 3 % 0 == - { drop "Fizz" print } - { - dup 5 % 0 == - { drop "Buzz" print } - { print } - if - } - if - } - if -} fizzbuzz fn - -1 100 { fizzbuzz } for -``` - -### 14.6 Using Roll - -``` -// Stack: 1 2 3 4 5 -3 1 roll // Rotate top 3 once: 1 2 4 5 3 -3 2 roll // Rotate top 3 twice: 1 2 5 3 4 - -// More complex example -10 20 30 40 50 -4 2 roll // Rotate top 4, twice: 10 30 40 50 20 -``` - -### 14.7 Array Processing - -``` -// Sum of squares of even numbers from 1 to 10 -[1 2 3 4 5 6 7 8 9 10] - { 2 % 0 == } filter // Keep even numbers - { dup * } map // Square each - 0 { + } reduce // Sum -print // 220 -``` - -### 14.8 Identifier Literals in Practice - -``` -// Push identifier literal to stack -::Point // Pushes identifier "Point" - -// Use with trait definition -{ (Self -- ) draw: } ::Drawable trait - -// Use with struct definition -(T T --) { x: y: } ::Point struct - -// Dynamic trait implementation -::MyType { ... } ::MyTrait impl -``` - -## 15. Syntax Summary - -### Complete Grammar Patterns - -**Functions**: `(in -- out) trait_constraints { body } name fn` - -**Structs**: `(types -- ) { fields: } name struct` - -**Unions**: `(types -- ) { Variant(T) ... } name union` - -**Enums**: `() { Variant ... } name enum` - -**Traits**: `{ (sig) method: ... } identifier trait` - -**Trait Impl**: `identifier { (sig) { body } method: ... } identifier impl` - -**Trait Inheritance**: `[ identifier_list ] identifier inher` - -**If**: `condition { then } { else } if` - -**While**: `{ condition } { body } while` - -**For**: `start end { body } for` - -**Match**: `value { pattern => block ... } match` - -**Identifier Literal**: `::name` pushes identifier instead of executing - ---- - -**Version**: 0.4 -**Status**: Draft Specification diff --git a/v0.3 ideas.md b/v0.3 ideas.md deleted file mode 100644 index ad6f561..0000000 --- a/v0.3 ideas.md +++ /dev/null @@ -1,25 +0,0 @@ -I have a few changes to this to make it match my vision more: -- Every operator defined should have a trait -- Remove `-rot`, `2dup`, `2drop`, `nip`, and `tuck` -- Make `roll` use the top two of the stack as the number of items to rotate and how many times to do so -- Make `rot` do what `roll` currently does -- Change `**` to `^` - -Base Traits (Non-Exhaustive): -- `Pushable` -- `ArrayOf` -- `Addable` -- `Number` -- `String` -- `Identifier` -- `Trait` - -Trait Examples: -- `{ (TokenString Identifier --) trait: (Identifier TokenString Identifier --) impl: (ArrayOf[Identifier] Identifier --) inher: } ::Implementable trait` -- `{ (Self Self -- Self) +: (Self Self -- Self) -: } ::Addable trait` - -Example Implementations: -- `::i32 { (Self Self -- Addable) { code } } ::Addable impl` - -Example Inheritance: -- `[ ::Addable ::Multiplyable ] ::Number inher`