Редакция: 21.08.2026 Автор: Мищук А.Л. Время чтения: 5 мин ГОТОВО

Инструкция по добавлению нового слова в Forth на Rust

Создание примитивного слова HELLO в Forth-интерпретаторе

Концепция: Forth + Rust + AI

Архитектура

Архитектура строится вокруг инструментальной модульности — каждый компонент системы является словом Forth. Это не декларативное разделение (как в микросервисах), а реализованное на уровне языка: любая функция доступна для немедленного тестирования через единую консоль, что критически важно при работе с ИИ-агентами.

Ядро системы

Предельная декомпозиция через Forth-слова ограничивает контекст для AI — модель всегда работает над малым, чётко определённым компонентом. В связке с Rust это даёт «двойной контур безопасности»: AI генерирует код, Borrow Checker проверяет корректность работы с памятью, а Forth-консоль позволяет мгновенно валидировать поведение каждого слова в отдельности. Это делает команду, где часть разработчиков — ИИ-агенты, не просто возможной, а естественной и безопасной.

Почему это работает

Предельная декомпозиция через Forth-слова ограничивает контекст для AI — модель всегда работает над малым, чётко определённым компонентом. В связке с Rust это даёт "двойной контур безопасности": AI генерирует код, Borrow Checker проверяет корректность работы с памятью, а Forth-консоль позволяет мгновенно валидировать поведение каждого слова в отдельности. Это делает команду, где часть разработчиков — ИИ-агенты, не просто возможной, а естественной и безопасной.

ШАГ 1: Создать файл src/hello.rs

Создайте новый файл src/hello.rs со следующим содержимым:

Rust
// ═══════════════════════════════════════════════════════════════
// ФАЙЛ: src/hello.rs
// СОЗДАН: ИИ-ассистентом (Copilot)
// ДАТА: 2026-08-19
// НАЗНАЧЕНИЕ: Реализация слова HELLO для Forth на Rust
// ═══════════════════════════════════════════════════════════════

use crate::context::Context;
use crate::word::ForthFn;
use crate::dictionary::Dictionary;
use crate::core::advance_ip;

// ============================================================
// HELLO - ВЫВОД СТРОКИ "HELLO WORLD"
// ============================================================
//
// СИНТАКСИС:   hello
//
// АЛГОРИТМ:
//   1. Выводит строку "Hello World"
//   2. Продвигает IP — advance_ip(ctx);
//      (переход к следующей инструкции в векторе слова)
// ============================================================
pub fn word_hello(ctx: &mut Context) {
    ctx.append_output(b"Hello World");
    ctx.flush_output();
    advance_ip(ctx);  // ← ПРОДВИГАЕМ IP (переход к следующей инструкции)
}

// ============================================================
// РЕГИСТРАЦИЯ СЛОВ
// ============================================================
pub fn register_words(dictionary: &mut Dictionary) {
    macro_rules! add_word {
        ($dict:expr, $name:expr, $func:expr, $flags:expr) => {{
            let _word = $dict.add_primitive_word($name, $flags, $func as *const ForthFn);
        }};
    }
    
    add_word!(dictionary, b"hello", word_hello, 0);
}
Что делает этот код:
  • Заголовок файла — информация о файле: дата, автор, назначение
  • word_hello — основная функция, которая выводит строку "Hello World"
  • ctx.flush_output() — немедленный вывод в консоль
  • advance_ip(ctx) — продвигает указатель инструкций (переход к следующей инструкции в векторе слова)
  • register_words — регистрирует слово в словаре Forth-системы
  • Макрос add_word упрощает добавление новых слов

ШАГ 2: Объявить модуль в src/lib.rs

Откройте файл src/lib.rs и в начало файла, где объявляются все модули, добавьте:

Rust
pub mod hello;  // ← ДОБАВИТЬ ЭТУ СТРОКУ
Полный текст src/lib.rs с добавлением:
Rust
pub mod bump_allocator;
pub mod dictionary;
pub mod word;
pub mod context;
pub mod core;
pub mod arithmetic;
pub mod stack;
pub mod compiler;
pub mod interpreter;
pub mod console;
pub mod strings;
pub mod memory;
pub mod branch;
pub mod r#loop;
pub mod debug;
pub mod logic;
pub mod hello;  // ← ЭТА СТРОКА ДОБАВЛЕНА!

use std::sync::{Arc, Mutex};
use crate::context::Context;
use crate::dictionary::Dictionary;
use crate::core::register_words as core_register_words;
use crate::arithmetic::register_words as arithmetic_register_words;
use crate::stack::register_words as stack_register_words;
use crate::console::register_words as console_register_words;
use crate::strings::register_words as strings_register_words;
use crate::memory::register_words as memory_register_words;
use crate::branch::register_words as branch_register_words;
use crate::r#loop::register_words as loop_register_words;
use crate::debug::register_words as debug_register_words;
use crate::logic::register_words as logic_register_words;
use crate::hello::register_words as hello_register_words;  // ← ЭТА СТРОКА ДОБАВЛЕНА!

pub fn init_forth() -> Context {
    let primitive_size = 1024 * 1024;
    let compiled_size = 64 * 1024 * 1024;
    
    let mut dictionary = Dictionary::new(primitive_size, compiled_size);
    core_register_words(&mut dictionary);
    arithmetic_register_words(&mut dictionary);
    stack_register_words(&mut dictionary);
    console_register_words(&mut dictionary);
    strings_register_words(&mut dictionary);
    memory_register_words(&mut dictionary);
    branch_register_words(&mut dictionary);
    loop_register_words(&mut dictionary);
    debug_register_words(&mut dictionary);
    logic_register_words(&mut dictionary);
    hello_register_words(&mut dictionary);  // ← ЭТА СТРОКА ДОБАВЛЕНА!
    
    let shared_dict = Arc::new(Mutex::new(dictionary));
    let mut ctx = Context::new(shared_dict);
    
    ctx.return_stack.clear();
    ctx.data_stack.clear();
    ctx.compile_stack.clear();
    
    {
        let dict = ctx.dictionary.lock().unwrap();
        ctx.here = dict.compiled_allocator.get_start() as usize;
    }
    
    ctx
}

pub use context::Context as ForthContext;
pub use interpreter::Interpreter;
pub use console::run_console;
Что мы сделали в lib.rs:
  • Объявили модуль: pub mod hello;
  • Импортировали регистратор: use crate::hello::register_words as hello_register_words;
  • Зарегистрировали слова: hello_register_words(&mut dictionary);

ШАГ 3: Структура проекта

После выполнения всех шагов структура вашего проекта должна выглядеть следующим образом:

├── Cargo.lock
├── Cargo.toml
├── do_release.txt
├── forth.frt
├── src
│  ├── arithmetic.rs
│  ├── branch.rs
│  ├── bump_allocator.rs
│  ├── compiler.rs
│  ├── console.rs
│  ├── context.rs
│  ├── core.rs
│  ├── debug.rs
│  ├── dictionary.rs
│  ├── hello.rs ← НОВЫЙ ФАЙЛ (ШАГ 1)
│  ├── interpreter.rs
│  ├── lib.rs ← ИЗМЕНЁН (ШАГ 2)
│  ├── logic.rs
│  ├── loop.rs
│  ├── main.rs
│  ├── memory.rs
│  ├── stack.rs
│  ├── strings.rs
│  └── word.rs
└── ta

ИТОГ: Проверка работы

После выполнения всех шагов соберите и запустите проект:

bash
cargo build
cargo run

Результат:

терминал
developer@energy4all:~/projects/rust/forth$ cargo build
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s

developer@energy4all:~/projects/rust/forth$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
     Running `target/debug/forth`

Forth Interpreter v1.0
Loading file: forth.frt
---
Debug mode ON

=== Forth Console ===
Type Forth code or 'quit' to exit
Press Ctrl+C to exit
---
> hello
Hello World
>
УСПЕШНО! Слово hello работает в интерпретаторе. Поздравляем! Вы успешно добавили новое слово в Forth-систему на Rust. 🎉
Что дальше?
  • Добавьте другие слова: goodbye, greet
  • Создайте слово с параметрами: say "Hello"
  • Изучите другие модули: arithmetic.rs, memory.rs
  • Напишите свои Forth-программы в файле forth.frt