💻 Forth Fundamentals

🎯 What is Forth?

Forth is a stack-based, concatenative programming language created by Charles Moore in 1969. It is known for its simplicity, extensibility, and efficiency in embedded systems.

Key concept: Forth uses Reverse Polish Notation (RPN) and a data stack for all operations. Programs are built from small, reusable words (functions).

Deep Explanation

Forth is a unique language that combines a minimalist interpreter with a powerful extensibility mechanism. It is both a compiler and an interpreter, allowing interactive development and efficient compiled code.

Why it matters: Forth is still used in embedded systems, spacecraft, and real-time applications where efficiency and control are critical.

💻 Stack-Based📚 Concatenative📋 Extensible🔄 RPN
# Forth example (in Forth syntax, not Python) \ Hello World in Forth : hello ." Hello, World!" cr ; \ Simple math: 3 + 4 * 2 3 4 2 * + . \ Output: 11 \ Define a word to square a number : square dup * ; \ Use it 5 square . \ Output: 25 \ Control structure: factorial : factorial dup 1 > if dup 1 - recurse * else drop 1 then ;

📚 Stack-Based Paradigm

🎯 The Data Stack

Forth uses a Last-In-First-Out (LIFO) data stack for all operations. Words (functions) consume and produce values on the stack.

Stack Operations

Push: Numbers push themselves onto the stack. Pop: Operations consume values. Stack effect: Every word has a documented stack effect (e.g., "a b -- c" means consumes a and b, produces c).

Common operations: + (add), - (subtract), * (multiply), / (divide), dup (duplicate top), drop (remove top), swap (swap top two).

📚 LIFO📊 Stack Effect📋 Push/Pop🔄 Operations
# Stack operations in Forth \ Stack: [1, 2, 3] 3 2 1 \ Stack: [1, 2, 3] (top is 1) \ dup duplicates top dup \ Stack: [1, 2, 3, 3] \ drop removes top drop \ Stack: [1, 2, 3] \ swap swaps top two swap \ Stack: [1, 3, 2] \ over copies second from top over \ Stack: [1, 3, 2, 3] \ rot rotates top three (3 2 1 -> 2 1 3) rot \ Stack: [1, 3, 2, 3] (top is 3) \ 2dup duplicates top two 2dup \ Stack: [1, 3, 2, 3, 3, 2]

📋 Dictionary

🎯 The Forth Dictionary

The dictionary is Forth's central data structure. It stores all defined words (functions) and can be extended at runtime.

Dictionary Structure

Entries: Each word has a name and code pointer. Chaining: Entries are linked for lookup. Extensibility: New words can be added at any time. Search order: Dictionary is searched from newest to oldest.

Immediate words: Words that execute at compile time (e.g., IF, ELSE, THEN).

📋 Names📊 Pointers📋 Chaining🔄 Extensible
# Dictionary in Forth \ Define a new word : square dup * ; \ Word lookup (conceptual) \ find name "square" in dictionary \ returns code pointer to execute \ See all words (in Forth) words \ Dictionary entry structure (conceptual) \ { name, link, flags, code } \ Create vocabulary (namespace) vocabulary math also math \ Define words in vocabulary : squared dup * ; : cubed dup squared * ; \ Switch back to main vocabulary previous

📖 Defining Words

🎯 Creating New Words

Words in Forth are defined using colon definitions. The colon (:) starts a definition and semicolon (;) ends it.

Word Definition

Syntax: `: word-name definition ;`. Compilation: The definition is compiled into the dictionary. Execution: When called, the code is executed. Stack effect: Should be documented (e.g., `: avg ( a b -- avg ) + 2 / ;`).

Immediate words: Define words that execute at compile time using `IMMEDIATE`.

📖 Colon Def📊 Compilation📋 Stack Effect🔄 Immediate
# Defining words in Forth \ Simple word with documentation (stack effect) : square ( n -- n^2 ) dup * ; \ Multiple parameters : avg ( a b -- avg ) + 2 / ; \ Recursive word (using RECURSE) : factorial ( n -- n! ) dup 1 > if dup 1 - recurse * else drop 1 then ; \ Word with immediate execution : [if] immediate \ Compile-time conditional ; \ Defining a word that defines words : def-mult ( n -- ) create , does> @ * ; 3 def-mult triple 5 triple . \ 15

📦 Variables & Constants

🎯 Data Storage

Forth provides variables (mutable) and constants (immutable) for storing data. Variables allocate memory in the data space.

Storage Types

Variable: `variable name` creates a variable (initial value 0). Constant: `constant name` creates a constant with a value. Value: `value name` creates a value (like a variable but with setter).

Access: `@` reads, `!` writes, `?` prints a variable.

📦 Variable📊 Constant📋 Value🔄 @ and !
# Variables and constants in Forth \ Variable variable counter counter @ . \ Print current value (initially 0) 5 counter ! \ Store 5 in counter counter @ . \ Print 5 \ Constant 10 constant max-size max-size . \ Print 10 \ Value (with setter) 0 value counter2 counter2 . \ Print 0 5 to counter2 \ Set to 5 counter2 . \ Print 5 \ Arrays (allocated memory) create buffer 100 cells allot \ 100 cell array \ Access array elements 10 buffer 3 cells + ! \ Store 10 at index 3 buffer 3 cells + @ . \ Print 10

🔄 Control Structures

🎯 Flow Control

Forth has familiar control structures: IF-ELSE-THEN, BEGIN-UNTIL, DO-LOOP, BEGIN-WHILE-REPEAT.

Structure Details

IF: `condition if ... then` (or `else`). DO-LOOP: `limit start do ... loop` (with `i` for index). BEGIN-UNTIL: `begin ... condition until`. BEGIN-WHILE-REPEAT: `begin condition while ... repeat`.

EXIT: Exit from a definition early. LEAVE: Exit from a loop.

🔄 IF-THEN📊 DO-LOOP📋 BEGIN-UNTIL🔄 WHILE-REPEAT
# Control structures in Forth \ IF-ELSE-THEN : test ( n -- ) dup 0 > if ." Positive" cr else ." Non-positive" cr then drop ; \ DO-LOOP (from 1 to 10) : count-up 11 1 do i . cr loop ; \ BEGIN-UNTIL : count-down ( n -- ) begin dup . cr 1 - dup 0 = until drop ; \ BEGIN-WHILE-REPEAT : sum-to ( n -- sum ) 0 swap begin dup 0 > while over + swap 1 - repeat drop ; \ Nested loops : multiplication-table 1 10 do 1 10 do i j * . \ Note: Forth doesn't have nested loops with i,j easily loop loop ;

💾 Memory Management

🎯 Working with Memory

Forth provides direct memory access with words for reading and writing bytes, cells, and strings.

Memory Operations

Allocation: `allocate`, `free`, `resize`. Reading: `c@` (byte), `@` (cell). Writing: `c!` (byte), `!` (cell). String operations: `s"` (string literal), `count`, `type`.

Address arithmetic: `+`, `cell+`, `char+`.

💾 Allocation📊 Reading📋 Writing🔄 Address
# Memory operations in Forth \ Allocate memory 10 allocate throw \ Allocate 10 bytes dup 10 erase \ Clear memory \ Write and read bytes dup 'A' swap c! \ Store 'A' at address c@ . \ Print ASCII value \ Write and read cells create buffer 100 cells allot buffer 10 cells + 42 swap ! \ Store 42 at offset 10 buffer 10 cells + @ . \ Read back \ String operations s" Hello, World!" \ Push address and length type \ Print string \ Copy memory buffer buffer2 100 cells move \ Copy 100 cells \ Memory fill 0 buffer 50 cells fill \ Fill first 50 cells with 0

🔧 Compiler & Interpreter

🎯 Compilation Model

Forth is both a compiler and interpreter. Words can be compiled (colon definitions) or interpreted (immediate execution).

Compilation Process

Interpret mode: Words are executed immediately. Compile mode: Words are compiled into the dictionary. State: `[` enters interpret mode, `]` enters compile mode. Immediate words: Execute even in compile mode.

Metacompilation: Forth can compile itself (self-hosting).

🔧 Interpret📊 Compile📋 State🔄 Immediate
# Compiler/Interpreter in Forth \ Enter compile mode : define-word ['] literal , \ Compile literal ." Compiling" cr ; \ Enter interpret mode (inside compile) : compile-time-code [ ." This runs at compile time" cr ] ; \ Immediate word (executes at compile time) : immediate-word ." Compile-time" cr immediate ; \ Inline compilation : my-code [ 5 6 + ] literal \ Compile constant 11 . ; \ Prints 11 \ Postpone (defer compilation) : postpone-example postpone + \ Compiles + but doesn't execute ;

⚙️ Forth Assembly

🎯 Code Generation

Forth can generate native machine code for the target architecture, making it efficient for embedded systems.

Assembly Integration

Code words: `code` defines assembly routines. Registers: Access CPU registers. Labels: `label` for assembly labels. System specific: Assembly words are target-specific.

Performance: Assembly words are the fastest in Forth.

⚙️ Code Words📊 Registers📋 Labels🔄 Native
# Forth assembly (x86 example) \ Code word for fast addition (x86) code add-fast pop eax \ Pop parameter pop ebx \ Pop next parameter add eax, ebx \ Add push eax \ Push result next, \ Return to Forth interpreter \ Simple delay loop (for embedded) code delay-loop pop ecx \ Number of iterations delay: dec ecx jnz delay next, \ Inline assembly (conceptual) : fast-multiply [ assembler pop eax pop ebx imul eax, ebx push eax ] ;

🖥️ Embedded Systems

🎯 Forth in Embedded

Forth is widely used in embedded systems, microcontrollers, and aerospace applications due to its small footprint and efficiency.

Embedded Features

Small footprint: Forth kernels can be as small as 2-4 KB. Real-time: Deterministic execution. Interactive: Immediate testing and debugging. Portability: Easy to port to new architectures.

Examples: NASA's Deep Space 1, OpenFirmware, many industrial controllers.

🖥️ Small Footprint📊 Real-Time📋 Interactive🔄 Portable
# Embedded Forth example \ Forth for microcontrollers (conceptual) \ Set up microcontroller : init-mcu [ $02 $03 ] literal pins set \ Set pin directions [ $80 ] literal clock init \ Initialize clock ; \ Simple GPIO control : led-on [ $01 ] literal portb set \ Set pin high ; : led-off [ $00 ] literal portb set \ Set pin low ; \ ISR (Interrupt Service Routine) : timer-isr [ $01 ] literal tifr set \ Clear interrupt flag led-on 1000 ms delay led-off ; \ Complete embedded application : main init-mcu begin led-on 500 ms delay led-off 500 ms delay again ;

📊 Stack Operations

🎯 Core Stack Words

The stack is Forth's central feature. Stack manipulation words are essential for effective programming.

Stack Manipulation

dup: Duplicate top. drop: Remove top. swap: Swap top two. over: Copy second to top. rot: Rotate top three. -rot: Rotate opposite direction.

Pick: `pick` copies a deep stack element. Roll: `roll` moves deep element to top.

📊 Dup📋 Drop🔄 Swap📈 Over
# Stack operations examples \ Before: [1, 2, 3] (top is 3) dup \ [1, 2, 3, 3] drop \ [1, 2, 3] swap \ [1, 3, 2] over \ [1, 3, 2, 3] rot \ [1, 3, 2, 3] -> [1, 3, 3, 2] -rot \ [1, 3, 3, 2] -> [1, 3, 2, 3] 2dup \ [1, 3, 2, 3, 3, 2] 2drop \ [1, 3, 2, 3] 2swap \ [1, 3, 3, 2] \ Pick (n pick copies nth element) 3 pick \ Copies 3rd element (zero-indexed) \ Advanced stack words : nswap ( a b c -- b a c ) rot swap rot ; : ndup ( a b -- a b a b ) 2dup ;

🧠 Advanced Features

🎯 Advanced Forth Concepts

Advanced features include exception handling, multi-threading, and object-oriented Forth.

Advanced Techniques

Exception handling: `catch` and `throw` for error management. Multi-threading: Separate data stacks for each thread. OOP: Forth can implement OOP patterns (e.g., mini-OOF). Deferred words: Defer execution until runtime.

Interpreter extensions: Extend the interpreter with new syntax.

🧠 Catch/Throw📊 Threads📋 OOP🔄 Deferred
# Advanced Forth features \ Exception handling : safe-division ( a b -- result ) 2dup 0= if ." Division by zero error" cr drop drop 0 else / then ; \ With catch/throw : protected-div ['] / catch if ." Error in division" cr 0 then ; \ Deferred word defer print-message : set-message ( xt -- ) is print-message ; : hello-message ." Hello" cr ; : goodbye-message ." Goodbye" cr ; ' hello-message set-message print-message \ Prints "Hello" ' goodbye-message set-message print-message \ Prints "Goodbye" \ Multi-threading (conceptual) : worker begin work-task again ; : start-thread create-thread worker ;

💼 Applications

🎯 Where Forth is Used

Forth applications include embedded systems, spacecraft, financial systems, and boot firmware.

Application Domains

Spacecraft: NASA's Deep Space 1 used Forth. Boot firmware: OpenFirmware (IEEE 1275). Industrial control: Factory automation. Finance: High-frequency trading (rarely). Education: Teaching programming concepts.

Retrocomputing: Forth on vintage computers.

🚀 Space📊 Firmware📋 Industrial🔄 Education
# Application examples \ Spacecraft control (NASA DS1) : check-attitude read-gyro if adjust-thrusters then ; : attitude-control begin check-attitude 100 ms delay again ; \ OpenFirmware (boot firmware) : probe-device " /pci@0,0" find-device ." Found PCI device" cr ; : load-kernel " boot:kernel" load-file execute ; : boot probe-device load-kernel ; \ Industrial control : temperature-monitor read-temp dup 100 > if trigger-alarm then display-temp ;

🚀 Future Directions

🎯 Forth in Modern Contexts

Forth continues to evolve with web integration, modern hardware support, and new language features.

Future Trends

Web Forth: Forth running in browsers via WebAssembly. IoT: Forth for resource-constrained IoT devices. FPGA: Forth running on FPGAs. AI: Forth in specialized AI hardware.

Community: Active community maintaining modern Forth implementations.

🚀 Web📊 IoT📋 FPGA🔄 AI
# Future Forth applications \ WebAssembly Forth ( concept: Forth compiled to WASM ) ( Running in browser ) : web-button create-dom-element "button" set-onclick ." Clicked!" cr ; \ IoT Forth : iot-sensor read-sensor if send-to-cloud then ; \ FPGA Forth (hardware description) : fpga-adder create-module "adder" add-port "a" input add-port "b" input add-port "sum" output set-logic sum = a + b ; \ AI Forth (neural network in Forth) : neural-layer create-layer 128 inputs 64 outputs initialize-weights activation relu ;