### Run All Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/firstlang/README.md Iterates through all .fl files in the examples directory and executes them. ```bash for file in examples/*.fl; do echo "Running $file..." cargo run -- "$file" done ``` -------------------------------- ### Run all examples in a loop Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Shell loop to execute every .tl file in the examples directory. ```bash for file in examples/*.tl; do echo "=== $file ===" rustup run nightly cargo run --bin thirdlang -q -- "$file" done ``` -------------------------------- ### Install nightly Rust and LLVM Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/intro.md Required environment setup for projects utilizing JIT compilation. ```bash # Install nightly Rust rustup toolchain install nightly # Install LLVM (macOS) brew install llvm # Install LLVM (Debian/Ubuntu) - see https://apt.llvm.org/ ``` -------------------------------- ### Run Basics Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/firstlang/README.md Executes the basics example program demonstrating variables, functions, conditionals, and loops. ```bash cargo run -- examples/basics.fl ``` -------------------------------- ### Run individual example files Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Commands to execute specific example files from the thirdlang directory. ```bash cd thirdlang # Point: distance calculation rustup run nightly cargo run --bin thirdlang -- examples/point.tl # Counter: stateful object rustup run nightly cargo run --bin thirdlang -- examples/counter.tl # Destructor: cleanup demo rustup run nightly cargo run --bin thirdlang -- examples/destructor.tl # Linked node: object references rustup run nightly cargo run --bin thirdlang -- examples/linked_node.tl ``` -------------------------------- ### Run Factorial Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/firstlang/README.md Executes the factorial example program. ```bash cargo run -- examples/factorial.fl ``` -------------------------------- ### Fuzzing Setup: Cargo Fuzz Commands Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/testing.md Commands to install and initialize cargo-fuzz for fuzz testing. This includes installing the tool, initializing a fuzz target, and running the fuzz target. ```bash cargo install cargo-fuzz cargo fuzz init cargo fuzz run parse_fuzz ``` -------------------------------- ### Run VM Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/calculator/README.md Execute an example expression using the VM backend. Requires stable Rust and the 'vm' feature. ```bash cargo run --bin main --no-default-features --features vm examples/simple.calc ``` -------------------------------- ### Run Thirdlang Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/thirdlang/README.md Execute example programs using the cargo run command. ```bash # Point distance calculation rustup run nightly cargo run -- examples/point.tl # Output: 25 # Counter with increment rustup run nightly cargo run -- examples/counter.tl # Output: 18 # Destructor demonstration rustup run nightly cargo run -- examples/destructor.tl # Output: 1 # Multiple nodes rustup run nightly cargo run -- examples/linked_node.tl # Output: 60 ``` -------------------------------- ### Run Secondlang Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Commands to execute various example programs using the nightly Rust toolchain. ```bash rustup run nightly cargo run -- examples/fibonacci.sl ``` ```bash rustup run nightly cargo run -- examples/factorial.sl ``` ```bash rustup run nightly cargo run -- examples/inference.sl ``` ```bash rustup run nightly cargo run -- examples/basics.sl ``` ```bash for file in examples/*.sl; do echo "Running $file..." rustup run nightly cargo run -- "$file" done ``` -------------------------------- ### Install Secondlang Dependencies Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Commands to install the required Rust nightly toolchain and LLVM 20. ```bash # Install nightly Rust rustup toolchain install nightly # Install LLVM 20 # macOS: brew install llvm # Debian/Ubuntu: wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 20 ``` -------------------------------- ### Bytecode VM Opcodes Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/calculator/README.md Example bytecode sequence for the expression '1 + 2' in the stack-based VM. Demonstrates pushing constants and performing addition. ```text OpConstant(0) # Push 1 OpConstant(1) # Push 2 OpAdd # Pop 2, 1, push 3 ``` -------------------------------- ### Install Nightly Rust and Verify LLVM Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/intro.md Commands to set up the required Rust toolchain and verify the installed LLVM version. ```bash # Install nightly Rust rustup toolchain install nightly # Check LLVM version llvm-config --version ``` -------------------------------- ### Counter Class Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/codegen_classes.md A complete example demonstrating a class definition with a constructor and increment method, followed by instantiation and usage. ```text class Counter { count: int def __init__(self) { self.count = 0 } def increment(self) -> int { self.count = self.count + 1 return self.count } } c = new Counter() c.increment() ``` -------------------------------- ### Continuous Integration: Run Tests and Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/testing.md GitHub Actions workflow configuration to automatically run all tests (`cargo test --all`) and execute example programs (`cargo run -- examples/fibonacci.sl`) on every commit. ```yaml # .github/workflows/ci.yml - name: Run tests run: cargo test --all - name: Run examples run: | cargo run -- examples/fibonacci.sl cargo run -- examples/factorial.sl ``` -------------------------------- ### Install Nightly Rust Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Installs the nightly Rust toolchain, which is required for the Calculator JIT, Secondlang, and Thirdlang. ```bash rustup toolchain install nightly ``` -------------------------------- ### AOT Compilation Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Command-line example for Ahead-of-Time compilation using a custom compiler to produce a standalone executable. ```bash ./mycompiler program.tl -o program ./program # Run without compiler ``` -------------------------------- ### Install Rust using rustup Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Installs the Rust toolchain, including cargo, rustc, and rustup. This is required for the Calculator interpreter/VM and Firstlang. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Class implementation example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/transition_3_to_4.md Demonstrates the syntax for defining a class with fields, a constructor, and methods, alongside heap allocation and deallocation. ```text class Point { x: int # Fields - data stored in the object y: int def __init__(self, x: int, y: int) { # Constructor self.x = x self.y = y } def move(self, dx: int, dy: int) { # Method self.x = self.x + dx self.y = self.y + dy } } p = new Point(10, 20) # Heap allocation p.move(5, 5) # Method call delete p # Manual deallocation ``` -------------------------------- ### Example Object-Oriented Language Syntax Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/transition_3_to_4.md Demonstrates the syntax for class definition, instantiation, method invocation, and manual memory management. ```text class Counter { value: int def __init__(self, start: int) { self.value = start } def increment(self) -> int { self.value = self.value + 1 return self.value } def __del__(self) { # Cleanup when deleted } } c = new Counter(0) c.increment() # 1 c.increment() # 2 delete c ``` -------------------------------- ### Example Calculator Session Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/calculator/README.md Demonstrates typical interactions within the calculator's REPL, showing input expressions and their evaluated output. ```text Calculator prompt. Expressions are line evaluated. >> 1 + 2 3 >> -2 + 5 3 >> (10 - 3) + 5 12 >> -(5 - 2) -3 >> CTRL-C ``` -------------------------------- ### Execute Counter example via CLI Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Command to run the counter script using the thirdlang binary. ```bash rustup run nightly cargo run --bin thirdlang -- examples/counter.tl ``` -------------------------------- ### View Thirdlang program output Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Expected output after running the point example. ```text 25 ``` -------------------------------- ### Use After Free Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates undefined behavior resulting from accessing an object after it has been deleted. ```text p = new Point(1, 2) delete p p.x # BUG! Memory already freed ``` -------------------------------- ### OOP Feature Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/why_classes.md A summary of the syntax for supported object-oriented features. ```text class Point { ... } ``` ```text x: int ``` ```text def get_x(self) -> int ``` ```text def __init__(self, x: int) ``` ```text def __del__(self) ``` ```text new Point(1, 2) ``` ```text delete p ``` ```text p.x or self.x ``` ```text p.distance(other) ``` ```text other: Point ``` -------------------------------- ### Counter example output Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Expected output after running the counter script. ```text 18 ``` -------------------------------- ### Destructor example output Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Expected output after running the destructor script. ```text 1 ``` -------------------------------- ### Explicit Memory Management Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/why_classes.md Demonstrates manual allocation and deallocation of a Point object. ```text p = new Point(1, 2) # Allocate # ... use p ... delete p # Free (programmer's job) ``` -------------------------------- ### Install LLVM on Debian/Ubuntu Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Installs LLVM on Debian/Ubuntu systems. This is a dependency for nightly Rust features used in JIT compilation and advanced languages. ```bash # Debian/Ubuntu: ``` -------------------------------- ### Start Firstlang REPL Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Launch the Read-Eval-Print Loop (REPL) for the Firstlang interpreter. Ensure you are in the 'firstlang' directory. ```bash cd firstlang cargo run ``` -------------------------------- ### Debugger Usage Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Demonstrates basic debugger commands for setting breakpoints, running code, inspecting variables, and stepping through execution. ```plaintext (debug) break main.tl:10 (debug) run Breakpoint hit at main.tl:10 (debug) print x x = 42 (debug) step ``` -------------------------------- ### Define class method Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/codegen_classes.md Example of a method definition within a class. ```text class Point { def get_x(self) -> int { return self.x } } ``` -------------------------------- ### Integration Test Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Reference to an integration test file for verifying class functionality. ```rust {{#include ../../../thirdlang/tests/integration_tests.rs:test_simple_class}} ``` -------------------------------- ### Pass classes as parameters Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/intro.md Example of using a class type as a parameter in a method signature. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { self.x = x self.y = y } def distance_squared(self, other: Point) -> int { dx = other.x - self.x dy = other.y - self.y return dx * dx + dy * dy } } p1 = new Point(0, 0) p2 = new Point(3, 4) p1.distance_squared(p2) # returns 25 ``` -------------------------------- ### Execute Destructor example via CLI Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Command to run the destructor script using the thirdlang binary. ```bash rustup run nightly cargo run --bin thirdlang -- examples/destructor.tl ``` -------------------------------- ### Install LLVM on macOS Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Installs LLVM using Homebrew on macOS. This is a dependency for nightly Rust features used in JIT compilation and advanced languages. ```bash brew install llvm ``` -------------------------------- ### Define Class Size Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Example of a class structure and its memory footprint calculation. ```text class Point { x: int # 8 bytes (i64) y: int # 8 bytes (i64) } # Total: 16 bytes ``` -------------------------------- ### REPL Usage Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/firstlang/README.md Demonstrates variable assignment, function definition, and recursive function calls within the REPL. ```python >>> x = 10 >>> x + 5 15 >>> def double(n) { return n * 2 } >>> double(21) 42 >>> def fib(n) { ... if (n <= 1) { ... return n ... } else { ... return fib(n - 1) + fib(n - 2) ... } ... } >>> fib(10) 55 ``` -------------------------------- ### Full Fibonacci Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md A complete implementation of the Fibonacci sequence using type annotations. ```python def fibonacci(n: int) -> int { if (n <= 1) { return n } else { return fibonacci(n - 1) + fibonacci(n - 2) } } result = fibonacci(10) ``` -------------------------------- ### Type Inference Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Demonstration of local type inference with unification. ```python # All types are inferred automatically: def is_even(n: int) { return n % 2 == 0 # return type: bool (inferred) } x = 10 # int (inferred) result = is_even(x) # bool (inferred) ``` -------------------------------- ### Define a class with a constructor Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Example of a class definition in Thirdlang using the __init__ method to initialize fields. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { self.x = x self.y = y } } ``` -------------------------------- ### Example Class Definition Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/classes_syntax.md A sample class definition used to trace the parsing process. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { self.x = x self.y = y } def get_x(self) -> int { return self.x } } ``` -------------------------------- ### Run Thirdlang examples and tests Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/intro.md Use these commands to execute specific Thirdlang source files or run the full test suite using the nightly Rust toolchain. ```bash cd thirdlang # Run Point example rustup run nightly cargo run --bin thirdlang -- examples/point.tl # Run Counter example rustup run nightly cargo run --bin thirdlang -- examples/counter.tl # Run all tests rustup run nightly cargo test ``` -------------------------------- ### Type Annotations Syntax Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Examples of explicit type annotations for variables and functions. ```python # Variable with type x: int = 42 # Function with parameter and return types def add(a: int, b: int) -> int { return a + b } ``` -------------------------------- ### Validate constructor arguments Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Examples of valid and invalid constructor calls based on argument count and type matching. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { ... } } p = new Point(10, 20) # OK: 2 args match (int, int) q = new Point(10) # ERROR: expected 2 args, got 1 r = new Point(10, true) # ERROR: expected int, got bool ``` -------------------------------- ### Type Inference Syntax Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Examples demonstrating how the compiler infers types automatically. ```python # Type is inferred from the right-hand side x = 42 # inferred as int y = x + 10 # inferred as int flag = x > 0 # inferred as bool # Function with inferred return type def double(n: int) { return n * 2 # return type inferred as int } ``` -------------------------------- ### Generate unoptimized IR Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/optimization.md Command to generate the initial unoptimized IR for the counter example. ```bash cd thirdlang rustup run nightly cargo run -- --ir examples/counter.tl ``` -------------------------------- ### Run Calculator JIT Backend Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a simple calculator program using the Just-In-Time (JIT) compilation backend. Requires nightly Rust and LLVM installed. Ensure you are in the 'calculator' directory. ```bash rustup run nightly cargo run --bin main --no-default-features --features jit examples/simple.calc ``` -------------------------------- ### Double Free Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates undefined behavior resulting from attempting to delete the same object twice. ```text p = new Point(1, 2) delete p delete p # BUG! Already freed ``` -------------------------------- ### Code Formatting Command Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Example of using a command-line tool to automatically format code, similar to tools like rustfmt or prettier. ```bash ./myfmt program.tl # Like rustfmt or prettier ``` -------------------------------- ### Configure LLVM Prefix Environment Variable Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/intro.md Set the environment variable to point to the LLVM installation directory. ```bash export LLVM_SYS_201_PREFIX=/opt/homebrew/opt/llvm # macOS (Homebrew); adjust for your system ``` -------------------------------- ### Run Thirdlang Point Program Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a program demonstrating Point objects in Thirdlang. Requires nightly Rust and LLVM installed. ```bash rustup run nightly cargo run --bin thirdlang -- examples/point.tl ``` -------------------------------- ### Create a Closure with Environment Capture Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Example of a closure that captures its environment. Requires function types as first-class values and variable capturing. ```text def make_adder(n: int) -> (int) -> int { return def(x: int) -> int { return x + n } } add5 = make_adder(5) add5(10) # returns 15 ``` -------------------------------- ### Run Thirdlang Counter Program Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a program demonstrating Counter objects in Thirdlang. Requires nightly Rust and LLVM installed. ```bash rustup run nightly cargo run --bin thirdlang -- examples/counter.tl ``` -------------------------------- ### Run Secondlang Fibonacci Program Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a Fibonacci program using the Secondlang compiler with LLVM JIT. Requires nightly Rust and LLVM installed. ```bash rustup run nightly cargo run -- examples/fibonacci.sl ``` -------------------------------- ### Build and serve documentation Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Commands to preview or build the static site documentation using mdbook. ```bash cd book mdbook serve # Local preview at http://localhost:3000 mdbook build # Build static site ``` -------------------------------- ### Final Abstract Syntax Tree Structure Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/classes_syntax.md The resulting AST structure after parsing the Point class example. ```rust TopLevel::Class(ClassDef { name: "Point".to_string(), fields: vec![ FieldDef { name: "x".to_string(), ty: Type::Int }, FieldDef { name: "y".to_string(), ty: Type::Int }, ], methods: vec![ MethodDef { name: "__init__".to_string(), params: vec![ // Note: 'self' is NOT stored in params - it's implicit // Only the parameters AFTER self are stored ("x".to_string(), Type::Int), ("y".to_string(), Type::Int), ], return_type: Type::Unit, body: vec![/* assignments */], }, MethodDef { name: "get_x".to_string(), params: vec![], // No params after self return_type: Type::Int, body: vec![/* return self.x */], }, ], }) ``` -------------------------------- ### Define abs method for control flow example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/optimization.md A sample class method used to demonstrate control flow simplification. ```text class Number { value: int def abs(self) -> int { if (self.value < 0) { return 0 - self.value } else { return self.value } } } ``` -------------------------------- ### Rust Ownership Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Demonstrates Rust's ownership model where a variable is moved and can only be used by its new owner. The original variable becomes invalid after the move. ```rust p = new Point(1, 2) q = p # p is moved, can't use p anymore delete q # Only q can free ``` -------------------------------- ### Provide Helpful Error Messages with Hints Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Example of a detailed error message that includes a hint suggesting a possible correction. ```text Error: Cannot add int and bool --> example.tl:5:9 | 5 | x = 1 + true | ^^^^^^^^ | = hint: did you mean to compare? Try `1 == true` or `1 != true` ``` -------------------------------- ### LLVM JIT Generated IR Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/calculator/README.md Example of LLVM Intermediate Representation (IR) generated by the JIT compiler for a simple function. ```llvm define i32 @jit() { entry: ret i32 3 } ``` -------------------------------- ### Implement Interfaces/Traits in Rust Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Shows how to implement traits for polymorphism without inheritance. This example uses Rust's trait system. ```Rust trait Printable { def print(self) -> int } impl Printable for Point { def print(self) -> int { return self.x } } ``` -------------------------------- ### View Secondlang LLVM IR Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Generate and view the LLVM Intermediate Representation (IR) for a Secondlang Fibonacci program. Requires nightly Rust and LLVM installed. ```bash rustup run nightly cargo run -- --ir examples/fibonacci.sl ``` -------------------------------- ### Function Inlining Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Shows inlining optimization where a function call is replaced by the function's body. This can improve performance by reducing function call overhead. ```plaintext def square(x: int) -> int { return x * x } y = square(5) # Inline to: y = 5 * 5 ``` -------------------------------- ### Instantiate and use objects Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/intro.md Syntax for creating new objects, calling methods, and manually freeing memory. ```text c = new Counter() c.increment() # returns 1 c.increment() # returns 2 c.get() # returns 2 delete c # free memory ``` -------------------------------- ### Constructor parameter mapping Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Demonstrates how constructor parameters map to arguments provided during object instantiation. ```text def __init__(self, x: int, y: int) { ... } # ^^^^^^^^^^^^^ These become: p = new Point(10, 20) # ^^^^^^ Constructor arguments ``` -------------------------------- ### Define Constructor and Destructor Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/methods.md Shows the syntax for class initialization and cleanup methods. ```text def __init__(self, x: int) { self.x = x } ``` ```text def __del__(self) { # Cleanup code (if any) } ``` -------------------------------- ### Define class structure Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/codegen_classes.md Example of a high-level class definition. ```text class Point { x: int y: int } ``` -------------------------------- ### Clone the project repository Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/intro.md Use these commands to download the source code and navigate to the project directory. ```bash git clone https://github.com/ehsanmok/create-your-own-lang-with-rust cd create-your-own-lang-with-rust ``` -------------------------------- ### Algebraic Simplification Optimization Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Examples of algebraic simplifications performed by the compiler. ```python # Before: x + 0 # After: x # Before: x * 1 # After: x # Before: x - x # After: 0 ``` -------------------------------- ### Run Calculator and Firstlang projects Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/intro.md Execute the interpreter or VM modes for the calculator and run the Firstlang interpreter or REPL. ```bash # Calculator - interpreter mode cd calculator cargo run --bin main examples/simple.calc # Calculator - VM mode cargo run --bin main --features vm examples/simple.calc # Firstlang - interpreter cd firstlang cargo run -- examples/fibonacci.fl cargo run # REPL ``` -------------------------------- ### Run Calculator VM Backend Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a simple calculator program using the Virtual Machine (VM) backend. Ensure you are in the 'calculator' directory. ```bash cd calculator cargo run --bin main --no-default-features --features vm examples/simple.calc ``` -------------------------------- ### Heap Allocation in Thirdlang Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates manual heap allocation and deallocation using the new and delete keywords. ```text p = new Point(1, 2) # Allocate on heap # ... use p ... delete p # Must free manually! ``` -------------------------------- ### Run ThirdLang with Optimization CLI Flags Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/optimization.md Demonstrates various CLI commands to execute code with different optimization levels, custom pass pipelines, and IR inspection. ```bash # Run without optimization thirdlang examples/point.tl # Run with optimization thirdlang -O examples/point.tl # Run with custom passes thirdlang --passes "mem2reg,dce" examples/point.tl # Print unoptimized IR thirdlang --ir examples/point.tl # Print optimized IR thirdlang --ir -O examples/point.tl # Use LLVM's O2 pipeline thirdlang --passes "default" examples/point.tl ``` -------------------------------- ### Manage Object Lifecycle Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/thirdlang/README.md Demonstration of object creation, field access, method invocation, and manual deletion. ```python # Create object (calls __init__) p = new Point(3, 4) # Use object x = p.x # Field access d = p.distance_squared(other) # Method call # Delete object (calls __del__, then frees memory) delete p ``` -------------------------------- ### Implement Destructors Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Example of defining a __del__ method to handle object cleanup during deletion. ```text class Resource { id: int def __init__(self, id: int) { self.id = id } def __del__(self) { # Cleanup code here # (In a real language, might close files, release handles, etc.) } } r = new Resource(42) delete r # Calls __del__, then free() ``` -------------------------------- ### Constant Folding Optimization Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md Example of constant folding optimization performed at the AST level. ```python # Before: 1 + 2 * 3 # After: 7 ``` -------------------------------- ### Initialize fields within the constructor Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Shows the syntax for assigning parameter values to object fields using self. ```text def __init__(self, x: int, y: int) { self.x = x # Set the 'x' field to parameter 'x' self.y = y # Set the 'y' field to parameter 'y' } ``` -------------------------------- ### Configure inkwell dependency Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/intro.md Update the Cargo.toml file to match the installed LLVM version. ```toml inkwell = { version = "0.7", features = ["llvm20-1"] } ``` -------------------------------- ### Run Secondlang and Thirdlang projects Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/intro.md Execute the language projects using the nightly toolchain. ```bash # Secondlang cd secondlang rustup run nightly cargo run -- examples/fibonacci.sl rustup run nightly cargo run -- --ir examples/fibonacci.sl # view LLVM IR # Thirdlang cd thirdlang rustup run nightly cargo run --bin thirdlang -- examples/point.tl rustup run nightly cargo run --bin thirdlang -- examples/counter.tl ``` -------------------------------- ### Dangling Pointer Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates a dangling pointer issue where multiple variables reference memory that has been freed. ```text p = new Point(1, 2) q = p # Both point to same object delete p q.x # BUG! q is now dangling ``` -------------------------------- ### Memory Leak Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates a memory leak caused by failing to call delete on an allocated object. ```text def leak() { p = new Point(1, 2) # Oops, forgot delete p! } # Memory is lost forever ``` -------------------------------- ### Implement methods with parameters Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/methods.md Methods can accept additional parameters after self, including other class instances. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { self.x = x self.y = y } def distance_squared(self, other: Point) -> int { dx = other.x - self.x dy = other.y - self.y return dx * dx + dy * dy } def translate(self, dx: int, dy: int) { self.x = self.x + dx self.y = self.y + dy } } ``` -------------------------------- ### Example generated LLVM IR Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md The resulting LLVM IR code after compiling a new object expression. ```llvm ; new Point(10, 20) %size = call i64 @llvm.sizeof.s_Point() %raw = call ptr @malloc(i64 %size) call void @Point____init__(ptr %raw, i64 10, i64 20) ; %raw is now a pointer to an initialized Point ``` -------------------------------- ### Implement Array Assignment Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Demonstrates array creation and element assignment. Requires array syntax, type, bounds checking, and potentially dynamic resizing. ```text arr = [1, 2, 3] arr[0] = 10 ``` -------------------------------- ### Define and use a Counter class Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Demonstrates class instantiation, method calls, and state management. ```text class Counter { value: int def __init__(self, start: int) { self.value = start } def increment(self) -> int { self.value = self.value + 1 return self.value } def add(self, n: int) -> int { self.value = self.value + n return self.value } def get(self) -> int { return self.value } } c = new Counter(10) c.increment() # 11 c.increment() # 12 c.increment() # 13 c.add(5) # 18 c.get() # 18 - this is the return value ``` -------------------------------- ### Unsupported Language Features Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/transition_1_to_2.md Examples of syntax constructs that require stateful memory, which are not supported in a basic calculator. ```text x = 10 # No variables! if (x > 5) { } # No conditionals! def add(a, b) { return a + b } # No functions! ``` -------------------------------- ### Create an object with the new expression Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Syntax for instantiating an object using the new keyword. ```text p = new Point(10, 20) ``` -------------------------------- ### Build Thirdlang Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/thirdlang/README.md Commands to build the project using the Rust nightly toolchain. ```bash cd thirdlang rustup run nightly cargo build ``` -------------------------------- ### Class Definition and Allocation Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Defines a Point class with constructor and destructor, demonstrating object instantiation and manual deletion. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { self.x = x self.y = y } def __del__(self) { # Cleanup } } p = new Point(10, 20) delete p ``` -------------------------------- ### Validate method call type checking Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/methods.md Examples showing valid and invalid method calls based on type definitions. ```text class Point { x: int y: int def __init__(self, x: int, y: int) { ... } def distance_squared(self, other: Point) -> int { ... } } p1 = new Point(0, 0) p2 = new Point(3, 4) p1.distance_squared(p2) # OK: Point method, Point argument p1.distance_squared(5) # ERROR: expected Point, got int p1.nonexistent() # ERROR: method not found ``` -------------------------------- ### Manual Memory Cleanup Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates the standard pattern for allocating and explicitly freeing memory. ```text p = new Point(1, 2) # ... use p ... delete p # Always clean up ``` -------------------------------- ### Run All Tests Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/calculator/README.md Execute all tests for the interpreter and VM backends. Requires stable Rust. ```bash cargo test ``` -------------------------------- ### Define a typed Fibonacci function Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/transition_2_to_3.md Example of the Fibonacci algorithm using explicit type annotations and return types to enable JIT compilation. ```text def fib(n: int) -> int { if (n < 2) { return n } return fib(n - 1) + fib(n - 2) } fib(35) # Milliseconds instead of seconds! ``` -------------------------------- ### Run Calculator Interpreter Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a simple calculator program using the interpreter backend. Ensure you are in the 'calculator' directory. ```bash cd calculator cargo run --bin main examples/simple.calc ``` -------------------------------- ### Format Error Messages with Source Locations Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Example of an error message including source location (line and column) and highlighting the problematic code section. ```text Error at line 5, column 10: x = 1 + true ^^^^ expected int, got bool ``` -------------------------------- ### Implement Multi-Field Constructor Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Initializes multiple class fields using constructor parameters. ```text class Rectangle { x: int y: int width: int height: int def __init__(self, x: int, y: int, w: int, h: int) { self.x = x self.y = y self.width = w self.height = h } } r = new Rectangle(0, 0, 100, 50) ``` -------------------------------- ### Escape Analysis Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Illustrates escape analysis, a technique to determine if an object's lifetime is limited to a function's scope. If it doesn't escape, it can be stack-allocated. ```plaintext def foo() { p = new Point(1, 2) # Could be stack-allocated return p.x + p.y # p doesn't escape } ``` -------------------------------- ### Perform Computed Initialization Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Calculates field values based on constructor input parameters. ```text class Square { side: int area: int def __init__(self, side: int) { self.side = side self.area = side * side # Computed from input } } ``` -------------------------------- ### Dead Code Elimination Example Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Demonstrates dead code elimination, where code blocks that are provably unreachable (e.g., within an 'if (false)' condition) are removed. ```plaintext if (false) { # This entire block can be removed } ``` -------------------------------- ### Run full optimization pipeline Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/optimization.md Commands to run the full optimization pipeline using either the -O flag or explicit pass list. ```bash rustup run nightly cargo run -- --ir -O examples/counter.tl ``` ```bash rustup run nightly cargo run -- --ir --passes "mem2reg,instcombine,dce,simplifycfg" examples/counter.tl ``` -------------------------------- ### Constant Folding Examples Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Illustrates constant folding optimization where expressions with constant values are evaluated at compile time. This includes arithmetic operations and identity simplifications. ```plaintext x = 1 + 2 * 3 # Fold to x = 7 y = x + 0 # Fold to y = x z = x * 1 # Fold to z = x ``` -------------------------------- ### Demonstrate mem2reg optimization Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/optimization.md Shows the transformation of stack-allocated variables into SSA registers. ```llvm %x = alloca i64 store i64 42, ptr %x %val = load i64, ptr %x ``` ```llvm %val = 42 ``` -------------------------------- ### Stack Allocation in Secondlang Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/memory.md Demonstrates automatic stack-based memory management where variables are freed upon function exit. ```text def foo() { x = 10 # x is on the stack y = 20 # y is on the stack return x + y } # x, y automatically freed ``` -------------------------------- ### Run Firstlang Fibonacci Program Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/README.md Execute a Fibonacci program using the Firstlang interpreter. Ensure you are in the 'firstlang' directory. ```bash cd firstlang cargo run -- examples/fibonacci.fl ``` -------------------------------- ### Implement Basic Pattern Matching Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Demonstrates simple pattern matching on a value. This can be extended with destructuring. ```Rust match value { 0 => "zero", 1 => "one", n => "other" } ``` -------------------------------- ### Project Structure Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/firstlang/README.md Overview of the project directory layout. ```text firstlang/ ├── src/ │ ├── grammar.pest # PEG grammar definition │ ├── parser.rs # Parser (pest-generated) │ ├── ast.rs # Abstract Syntax Tree │ ├── interpreter.rs # Tree-walking interpreter │ └── main.rs # CLI and REPL ├── examples/ # Example programs │ ├── basics.fl │ ├── fibonacci.fl │ └── factorial.fl └── tests/ # Integration tests └── integration_tests.rs ``` -------------------------------- ### Implement Parameterless Constructor Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/constructors.md Defines a constructor that initializes fields without external arguments. ```text class Counter { count: int def __init__(self) { self.count = 0 } } c = new Counter() # No arguments ``` -------------------------------- ### Thirdlang CLI Options Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/thirdlang/README.md Command line interface usage for compilation, IR generation, and optimization passes. ```bash thirdlang # JIT compile and run thirdlang --ir # Print LLVM IR (unoptimized) thirdlang --ir -O # Print LLVM IR (optimized with default) thirdlang --ir --passes mem2reg,dce # Print IR with specific passes thirdlang -O # Run with default optimizations thirdlang --passes dce,instcombine # Run with custom passes thirdlang --ast # Print AST thirdlang --check # Type check only ``` -------------------------------- ### Execute Thirdlang program with JIT Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/codegen_classes.md Uses the LLVM JIT engine to compile and run the generated IR for Thirdlang programs. ```rust {{#include ../../../thirdlang/src/codegen.rs:jit_run}} ``` -------------------------------- ### Compare unoptimized and optimized LLVM IR Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Commands to generate and compare LLVM IR with and without optimization flags. ```bash # Unoptimized IR (verbose, many allocas) rustup run nightly cargo run --bin thirdlang -- --ir examples/point.tl # Optimized IR (clean, efficient) rustup run nightly cargo run --bin thirdlang -- --ir -O examples/point.tl ``` -------------------------------- ### REPL Interactive Programming Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/whats_next.md Shows a typical Read-Eval-Print Loop (REPL) session, demonstrating variable assignment, expression evaluation, and function definition and calls. ```plaintext > x = 10 > x + 5 15 > def double(n) { return n * 2 } > double(x) 20 ``` -------------------------------- ### Procedural data management without classes Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/intro.md Demonstrates the complexity of managing related variables and functions without object-oriented structures. ```text # Unrelated variables floating around point_x = 10 point_y = 20 point2_x = 30 point2_y = 40 def distance(x1, y1, x2, y2) -> int { dx = x2 - x1 dy = y2 - y1 return dx * dx + dy * dy } distance(point_x, point_y, point2_x, point2_y) ``` -------------------------------- ### Project Structure Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/secondlang/README.md The directory layout of the Secondlang project. ```text secondlang/ ├── src/ │ ├── grammar.pest # PEG grammar with types │ ├── parser.rs # Parser │ ├── ast.rs # Typed AST │ ├── types.rs # Type system │ ├── typeck.rs # Type checker/inference │ ├── visitor.rs # AST visitors (optimizations) │ ├── codegen.rs # LLVM IR code generation │ └── main.rs # CLI ├── examples/ # Example programs │ ├── basics.sl │ ├── fibonacci.sl │ ├── factorial.sl │ └── inference.sl └── tests/ # Integration tests └── integration_tests.rs ``` -------------------------------- ### Parentheses Syntax Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/calculator/README.md Shows how parentheses can be used for grouping expressions and controlling the order of operations. ```plaintext (1 + 2) # => 3 (10 - 3) + 5 # => 12 -(5 - 2) # => -3 ``` -------------------------------- ### Run Thirdlang with optimization passes Source: https://github.com/ehsanmok/create-your-own-lang-with-rust/blob/master/book/src/04_thirdlang/running.md Commands to execute Thirdlang programs using default optimizations, custom pass pipelines, or standard LLVM O2 optimization. ```bash # Default optimization (dce, mem2reg, instcombine, simplifycfg) rustup run nightly cargo run --bin thirdlang -- -O examples/point.tl # Custom pass pipeline rustup run nightly cargo run --bin thirdlang -- --passes "mem2reg,dce" examples/point.tl # LLVM's standard O2 optimization rustup run nightly cargo run --bin thirdlang -- --passes "default" examples/point.tl ```