Skip to content

HypnoScript ist eine hypnotisch angehauchte Programmiersprache mit eigener Syntax (Focus { ... } Relax). Die komplette Laufzeitumgebung, der Compiler und die Kommandozeilen-Tools wurden aus C# nach Rust portiert und ab Version 1.0 ausschlieรŸlich in Rust weiterentwickelt.

License

Notifications You must be signed in to change notification settings

Kink-Development-Group/hyp-runtime

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

55 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

HypnoScript โ€“ Rust Implementation

HypnoScript is a hypnotically-inspired programming language with its own syntax (Focus { ... } Relax). The complete runtime environment, compiler, and command-line tools were ported from C# to Rust and are exclusively developed in Rust from version 1.0 onwards.


๐Ÿš€ Highlights

  • ๐Ÿฆ€ Pure Rust Codebase โ€“ fast builds, no .NET dependencies
  • ๐Ÿง  Complete Toolchain โ€“ Lexer, Parser, Type Checker, Interpreter, and multiple compiler backends
  • ๐ŸŽฏ Multiple Targets โ€“ Interpreter, WebAssembly (Text & Binary), Native Code (planned)
  • โšก Code Optimization โ€“ Constant Folding, Dead Code Elimination, CSE, LICM, Inlining
  • ๐Ÿงฐ 180+ Builtins โ€“ Math, Strings, Arrays, Hypnosis, Files, Time, System, Statistics, Hashing, Validation, Cryptography
  • ๐ŸŒ Multilingual โ€“ i18n support (EN, DE, FR, ES)
  • ๐Ÿ” Cryptography โ€“ SHA-256, SHA-512, MD5, Base64, UUID
  • ๐Ÿงฌ Functional Programming โ€“ map, filter, reduce, compose, pipe
  • ๐ŸŽญ Hypnotic Operators โ€“ 14 synonyms like youAreFeelingVerySleepy, lookAtTheWatch, underMyControl
  • ๐ŸŽฏ Pattern Matching โ€“ entrain/when/otherwise with Destructuring, Guards, and Type Patterns
  • ๐Ÿ”” Event-Driven โ€“ trigger for Callbacks and Event Handlers
  • ๐Ÿ’Ž Nullish Operators โ€“ lucidFallback (??) and dreamReach (?.) for safe null handling
  • ๐Ÿ›๏ธ OOP Support โ€“ Sessions with constructor, expose/conceal, dominant (static)
  • ๐Ÿ–ฅ๏ธ Extended CLI โ€“ run, lex, parse, check, compile-wasm, compile-native, optimize, builtins, version
  • โœ… Comprehensive Tests โ€“ 185+ tests across all compiler modules
  • ๐Ÿ“š Documentation โ€“ VitePress + extensive architecture docs + complete Rustdoc
  • ๐Ÿš€ Performance โ€“ Zero-cost abstractions, no garbage collector, optimized native code

๐Ÿ—๏ธ Workspace Architecture

hyp-runtime/
โ”œโ”€โ”€ Cargo.toml                    # Workspace configuration
โ”œโ”€โ”€ COMPILER_ARCHITECTURE.md      # Detailed compiler documentation
โ”œโ”€โ”€ hypnoscript-core/             # Type system & symbols (100%)
โ”œโ”€โ”€ hypnoscript-lexer-parser/     # Tokens, Lexer, AST, Parser (100%)
โ”œโ”€โ”€ hypnoscript-compiler/         # Compiler backend (100%)
โ”‚   โ”œโ”€โ”€ interpreter.rs            # โœ… Tree-walking interpreter
โ”‚   โ”œโ”€โ”€ type_checker.rs           # โœ… Static type checking
โ”‚   โ”œโ”€โ”€ wasm_codegen.rs           # โœ… WASM Text Format (.wat)
โ”‚   โ”œโ”€โ”€ wasm_binary.rs            # โœ… WASM Binary Format (.wasm)
โ”‚   โ”œโ”€โ”€ optimizer.rs              # โœ… Code optimizations
โ”‚   โ””โ”€โ”€ native_codegen.rs         # ๐Ÿšง Native compilation (LLVM)
โ”œโ”€โ”€ hypnoscript-runtime/          # 180+ builtin functions (100%)
โ””โ”€โ”€ hypnoscript-cli/              # Command-line interface (100%)

Documentation is available in hypnoscript-docs/ (Docusaurus).


โš™๏ธ Installation & Quick Start

Prerequisites

  • Rust 1.76+ (recommended) including cargo

Automatic Installer

curl -fsSL https://kink-development-group.github.io/hyp-runtime/install.sh | bash

The script automatically detects Linux/macOS, downloads the appropriate runtime from the current release, and updates existing installations. Important options: --prefix, --version, --check, --include-prerelease, --force, --uninstall.

Updates & Uninstallation

  • Check for updates: hypnoscript self-update --check displays available versions.
  • Update: hypnoscript self-update pulls the latest release version including sudo handling.
  • Force reinstallation: hypnoscript self-update --force runs the installer again.
  • Uninstall: curl -fsSL https://kink-development-group.github.io/hyp-runtime/install.sh | bash -s -- --uninstall removes binary and metadata.

Clone & Build Project

git clone https://github.com/Kink-Development-Group/hyp-runtime.git
cd hyp-runtime
cargo build --all --release

The CLI is created as two binaries: hypnoscript and hyp (short form). Both are identical and can be used interchangeably.

Run Program

# Both variants work
./target/release/hypnoscript exec program.hyp
./target/release/hyp exec program.hyp

Or during development:

cargo run -p hypnoscript-cli -- exec test_simple.hyp

Example Program

Focus {
    entrance {
        observe "Welcome to HypnoScript!";
    }

    induce x: number = 42;
    induce message: string = "Hello Trance";

    observe message;
    observe x;

    // Hypnotic operator synonym
    if (x yourEyesAreGettingHeavy 40) deepFocus {
        observe "X is greater than 40";
    }

    // Pattern matching with entrain
    induce result: string = entrain x {
        when 0 => "zero"
        when 42 => "answer to everything"
        when n if n > 100 => "large number"
        otherwise => "other"
    };
    observe result;

    // Nullish operators
    induce maybeNull: number? = null;
    induce defaulted: number = maybeNull lucidFallback 100;
    observe defaulted;  // 100

    // Trigger (event handler)
    trigger onComplete = suggestion() {
        observe "Task completed!";
    };
    onComplete();
} Relax

Detailed CLI Commands

Note: All commands can be executed with either hypnoscript or hyp.

# Execute program (Interpreter)
hypnoscript exec program.hyp
# or short:
hyp exec program.hyp

# Analysis tools
hypnoscript lex program.hyp          # Tokenization
hypnoscript parse program.hyp        # Display AST
hypnoscript check program.hyp        # Type checking

# Compilation
hypnoscript compile-wasm program.hyp              # WASM Text Format (.wat)
hypnoscript compile-wasm -b program.hyp           # WASM Binary Format (.wasm)
hypnoscript compile-native program.hyp            # Native binary (planned)
hypnoscript compile-native -t linux-x64 \
  --opt-level release program.hyp                 # With target platform

# Code optimization
hypnoscript optimize program.hyp --stats          # With statistics

# Package Manager
hypnoscript init                         # Initialize new project
hypnoscript init --template cli          # CLI project template
hypnoscript add package --version "^1.0.0"       # Add dependency
hypnoscript add pkg --version "^1.0.0" --dev     # Add dev dependency
hypnoscript remove package               # Remove dependency
hypnoscript install                      # Install all dependencies
hypnoscript list                         # List dependencies
hypnoscript run <script>                 # Run script from trance.json
hypnoscript validate                     # Validate trance.json

# Utilities
hypnoscript builtins                 # Builtin functions
hypnoscript version                  # Version
hypnoscript self-update              # Self-update

WASM Compilation in Detail

# Text format (readable, debugging-friendly)
hypnoscript compile-wasm script.hyp -o output.wat

# Binary format (compact, production-ready)
hypnoscript compile-wasm --binary script.hyp -o output.wasm

# Convert to complete WASM binary with wabt-tools
wat2wasm output.wat -o output.wasm

Native Compilation (Planned)

# For current platform
hypnoscript compile-native app.hyp

# Cross-compilation
hypnoscript compile-native -t windows-x64 app.hyp
hypnoscript compile-native -t macos-arm64 app.hyp
hypnoscript compile-native -t linux-x64 app.hyp

# With optimization
hypnoscript compile-native --opt-level release app.hyp

๐Ÿ“ฆ Package Manager

HypnoScript has a built-in package manager, similar to npm for JavaScript or Cargo for Rust. It uses trance.json as its manifest file.

Quick Start

# Initialize new project
hypnoscript init --name my-project --template cli
# Add dependencies
hypnoscript add hypnoscript-runtime --version โ€œ^1.0.0โ€
hypnoscript add @hypno/testing-lab --version โ€œ^0.3.0โ€ --dev
# Install dependencies
hypnoscript install
# List dependencies
hypnoscript list
# Run script
hypnoscript run test
# Validate manifest
hypnoscript validate

trance.json Manifest

The manifest uses hypnotic terminology:

  • ritualName: Package name (corresponds to name in npm)
  • mantra: Version (corresponds to version in npm)
  • intent: Project type (cli, library)
  • anchors: Production dependencies (corresponds to dependencies)
  • deepAnchors: Development dependencies (corresponds to devDependencies)
  • suggestions: Executable scripts (corresponds to scripts)
  • channels: Binary/CLI configuration
  • triggers: Lifecycle hooks

Example trance.json:

{
  โ€œritualNameโ€: โ€œmy-hypno-appโ€,
  โ€œmantraโ€: โ€œ1.0.0โ€,
  โ€œintentโ€: โ€œcliโ€,
  โ€œsuggestionsโ€: {
    โ€œfocusโ€: โ€œhypnoscript exec src/main.hypโ€,
    โ€œtestโ€: โ€œhypnoscript exec tests/test.hypโ€
  },
  โ€œanchorsโ€: {
    โ€œhypnoscript-runtimeโ€: โ€œ^1.0.0โ€
  }
}

Complete documentation: see PACKAGE_MANAGER.md


๐Ÿงช Tests & Quality Assurance

Run all tests:

cargo test --all

Test Coverage:

  • โœ… Lexer: 15+ tests
  • โœ… Parser: 20+ tests
  • โœ… Type Checker: 10+ tests
  • โœ… Interpreter: 12+ tests
  • โœ… WASM Generator: 4+ tests
  • โœ… Optimizer: 6+ tests
  • โœ… Native Generator: 5+ tests
  • โœ… Runtime Builtins: 30+ tests
  • โœ… Pattern Matching: Full coverage
  • โœ… Triggers: Full coverage
  • โœ… Nullish Operators: Full coverage

Total: 185+ tests (all passing)

Compiler Tests

# Compiler tests only
cargo test --package hypnoscript-compiler

# With detailed output
cargo test --package hypnoscript-compiler -- --nocapture

Code Quality

# Check formatting
cargo fmt --all -- --check

# Linting with Clippy
cargo clippy --all-targets --all-features

๐Ÿ“ฆ Builtin Functions (110+)

Mathematics (20+)

Sin, Cos, Tan, Sqrt, Pow, Log, Abs, Floor, Ceil, Round, Min, Max, Factorial, Gcd, Lcm, IsPrime, Fibonacci, Clamp

Strings (15+)

ToUpper, ToLower, Capitalize, TitleCase, IndexOf, Replace, Reverse, Split, Substring, Trim, Repeat, PadLeft, PadRight, StartsWith, EndsWith, Contains, Length, IsWhitespace

Arrays (15+)

ArrayLength, ArraySum, ArrayAverage, ArrayMin, ArrayMax, ArraySort, ArrayReverse, ArrayDistinct, ArrayFirst, ArrayLast, ArrayTake, ArraySkip, ArraySlice, ArrayJoin, ArrayCount, ArrayIndexOf, ArrayContains, ArrayIsEmpty, ArrayGet

Time/Date (15)

GetCurrentTime, GetCurrentDate, GetCurrentDateTime, FormatDateTime, GetYear, GetMonth, GetDay, GetHour, GetMinute, GetSecond, GetDayOfWeek, GetDayOfYear, IsLeapYear, GetDaysInMonth, CurrentDate, DaysInMonth

Validation (10)

IsValidEmail, IsValidUrl, IsValidPhoneNumber, IsAlphanumeric, IsAlphabetic, IsNumeric, IsLowercase, IsUppercase, IsInRange, MatchesPattern

File I/O (14)

ReadFile, WriteFile, AppendFile, FileExists, IsFile, IsDirectory, DeleteFile, CreateDirectory, ListDirectory, GetFileSize, CopyFile, RenameFile, GetFileExtension, GetFileName

Statistics (9)

CalculateMean, CalculateMedian, CalculateMode, CalculateStandardDeviation, CalculateVariance, CalculateRange, CalculatePercentile, CalculateCorrelation, LinearRegression, Mean, Variance

Hashing/Utilities (10)

HashString, HashNumber, AreAnagrams, IsPalindrome, CountOccurrences, RemoveDuplicates, UniqueCharacters, ReverseWords, TitleCase, SimpleRandom

System (12)

GetOperatingSystem, GetArchitecture, GetCpuCount, GetHostname, GetCurrentDirectory, GetHomeDirectory, GetTempDirectory, GetEnvVar, SetEnvVar, GetUsername, GetArgs, Exit

Hypnosis/Core (6)

Observe, Drift, DeepTrance, HypnoticCountdown, TranceInduction, HypnoticVisualization

Conversions (4)

ToInt, ToDouble, ToString, ToBoolean

A complete list is available via hypnoscript builtins and in the Docusaurus documentation.


๐ŸŽฏ Advanced Language Features

๐ŸŽญ Hypnotic Operator Synonyms

HypnoScript offers 14 hypnotic aliases for standard operators:

Standard Hypnotic Description
== youAreFeelingVerySleepy Equality
!= youCannotResist Inequality
> lookAtTheWatch Greater than
>= yourEyesAreGettingHeavy Greater or equal
< fallUnderMySpell Less than
<= goingDeeper Less or equal
&& underMyControl Logical AND
|| resistanceIsFutile Logical OR
! snapOutOfIt Logical NOT
?? lucidFallback Nullish coalescing
?. dreamReach Optional chaining

โš ๏ธ String Concatenation: When one of the operands of the + operator is a string, all other values are automatically converted to strings. Examples: null + "text" yields "nulltext", 42 + "px" yields "42px". Check the type before concatenating if you want to avoid such implicit conversions.

Example:

induce age: number = 25;

if (age yourEyesAreGettingHeavy 18 underMyControl age fallUnderMySpell 65) {
    observe "Adult of working age";
}

๐Ÿ“š Complete Documentation: docs/language-reference/operator-synonyms.md

๐ŸŽฏ Pattern Matching (entrain/when/otherwise)

Powerful pattern matching with:

  • Literal Patterns: Direct value comparison
  • Type Patterns: Type-based matching with binding
  • Array Destructuring: Spread operator, nested patterns
  • Record Patterns: Field-based matching
  • Guards: Conditional patterns with if
  • Identifier Binding: Variable binding in patterns

Example:

induce status: number = 404;

induce message: string = entrain status {
    when 200 => "OK"
    when 404 => "Not Found"
    when 500 => "Server Error"
    when s if s yourEyesAreGettingHeavy 400 underMyControl s fallUnderMySpell 500 => "Client Error"
    otherwise => "Unknown"
};

// Array destructuring
induce coords: array = [10, 20, 30];
entrain coords {
    when [x, y, z] => observe "3D Point: " + x + ", " + y + ", " + z
    when [x, y] => observe "2D Point: " + x + ", " + y
    otherwise => observe "Invalid coordinates"
}

๐Ÿ“š Complete Documentation: docs/language-reference/pattern-matching.md

๐Ÿ”” Triggers (Event-Driven Callbacks)

Triggers are top-level event handlers that respond to events:

Syntax:

trigger triggerName = suggestion(parameters) {
    // Handler code
};

Example:

trigger onStartup = suggestion() {
    observe "Application initialized";
};

trigger onError = suggestion(code: number, message: string) {
    observe "Error " + code + ": " + message;
};

trigger onCleanup = suggestion() {
    observe "Cleaning up resources...";
};

entrance {
    onStartup();

    if (someCondition) {
        onError(404, "Resource not found");
    }

    onCleanup();
}

Use Cases:

  • Event handlers (Click, Load, Error)
  • Lifecycle hooks (Setup, Teardown)
  • Callbacks for async operations
  • Observers for state changes

๐Ÿ“š Complete Documentation: docs/language-reference/triggers.md

๐Ÿ’Ž Nullish Operators

Nullish Coalescing (lucidFallback / ??):

Returns the right value only when the left value is null or undefined (not for 0, false, ""):

induce value: number? = null;
induce result: number = value lucidFallback 100;  // 100

induce zero: number = 0;
induce result2: number = zero lucidFallback 100;  // 0 (not 100!)

Optional Chaining (dreamReach / ?.):

Safe navigation through nested structures:

session User {
    expose profile: Profile?;
}

session Profile {
    expose name: string;
}

induce user: User? = getUser();
induce name: string = user dreamReach profile dreamReach name lucidFallback "Anonymous";

Benefits:

  • โœ… Avoids null pointer exceptions
  • โœ… More readable than nested if checks
  • โœ… Functional programming patterns
  • โœ… Zero-cost abstraction (compiler-optimized)

๐Ÿ“š Complete Documentation: docs/language-reference/nullish-operators.md


๐Ÿ“Š Performance Benefits

Rust offers several advantages over C#:

  1. Zero-cost Abstractions: Compile-time optimizations without runtime overhead
  2. No Garbage Collector: Deterministic memory management
  3. Memory Safety: Compile-time prevention of common bugs
  4. Smaller Binaries: 5-10MB vs. 60+MB for C# with runtime
  5. Better Parallelization: Safe concurrent access via ownership model
  6. Faster Execution: Native code with LLVM optimizations

๐Ÿ”ง Development

Adding New Builtins

  1. Add function to the appropriate module in hypnoscript-runtime/src/
  2. Add tests in the same file
  3. Update builtins list in CLI
  4. Export from lib.rs

Example:

// In math_builtins.rs
pub fn new_function(x: f64) -> f64 {
    // Implementation
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_function() {
        assert_eq!(MathBuiltins::new_function(5.0), expected_result);
    }
}

Code Style

  • Follow Rust standard style (use cargo fmt)
  • Run Clippy for linting: cargo clippy
  • Keep functions focused and well-documented
  • Write tests for new functionality

๐Ÿ“ Migration Status & Features

Compiler Backend

  • โœ… Interpreter (100%) โ€“ Tree-walking interpreter with full builtin support
  • โœ… Type Checker (100%) โ€“ Static type checking, OOP validation
  • โœ… WASM Text Generator (100%) โ€“ WebAssembly Text Format (.wat)
  • โœ… WASM Binary Generator (100%) โ€“ Direct binary generation (.wasm)
  • โœ… Code Optimizer (100%) โ€“ Constant Folding, Dead Code Elimination, CSE, LICM, Inlining
  • ๐Ÿšง Native Code Generator (20%) โ€“ LLVM backend planned

Core System

  • โœ… Core type system (100%)
  • โœ… Symbol table (100%)
  • โœ… Lexer (100%)
  • โœ… Parser (100%)
  • โœ… AST (100%)
  • โœ… OOP/Sessions (100%)
  • โœ… Pattern Matching (entrain/when/otherwise) (100%)
  • โœ… Triggers (Event-Driven Callbacks) (100%)
  • โœ… Nullish Operators (lucidFallback, dreamReach) (100%)
  • โœ… Hypnotic Operator Synonyms (14 aliases) (100%)

Runtime

  • โœ… Runtime Builtins (180+ functions)
    • Math, String, Array, Collections
    • File I/O, Time/Date, System
    • Hashing, Validation, Statistics
    • Advanced String Operations
    • API/HTTP Helpers
  • โœ… Localization (EN, DE, FR, ES)
  • โœ… CLI Framework (100%)
  • โœ… CI/CD Pipelines (100%)

๐ŸŽฏ Roadmap

Completed โœ…

  • Lexer implementation
  • Parser implementation
  • Type Checker implementation
  • Interpreter implementation
  • WASM Text Format Generator (.wat)
  • WASM Binary Format Generator (.wasm)
  • Code optimization framework
  • 180+ builtin functions
  • Session/OOP features
  • Complete program execution
  • CLI integration (10 commands)
  • CI/CD pipelines
  • Comprehensive tests (100+ tests)
  • Multilingual documentation

In Development ๐Ÿšง

  • Native Code Generator โ€“ LLVM backend for platform-specific binaries
    • Windows (x86_64, ARM64)
    • macOS (x86_64, ARM64/Apple Silicon)
    • Linux (x86_64, ARM64, RISC-V)
  • Advanced Optimizations โ€“ Complete implementation of all optimization passes
  • Source Maps โ€“ Debugging support for compiled code

Planned ๐Ÿ”ฎ

  • JIT compilation
  • Incremental compilation
  • Profile-Guided Optimization (PGO)
  • Link-Time Optimization (LTO)
  • Language Server Protocol (LSP) for IDE integration
  • Advanced WASM features (Threads, SIMD)
  • Additional 40 specialized builtins (Network, ML)
  • Session/OOP features
  • Advanced error handling
  • Performance benchmarking vs. C#
  • Optimization passes

๐Ÿ› Known Limitations

  • Some advanced C# builtins still pending (Network, ML features - optional)
  • Session/OOP features are optional extensions

๐Ÿงญ Migration & Project Status

  • โœ… C# codebase removed (all former .csproj projects deleted)
  • โœ… Rust workspace production-ready
  • โœ… Complete port of core functionality
  • โœ… All 48 tests passing
  • ๐Ÿ”„ Optional extensions (e.g., Network/ML builtins) possible as roadmap items

Migration details: see IMPLEMENTATION_SUMMARY.md.


๐Ÿ”— Links & Resources


๐Ÿค Contributing

When contributing to the Rust implementation:

  1. Maintain API compatibility with the C# version where possible
  2. Follow DRY principles (Don't Repeat Yourself)
  3. Write comprehensive tests
  4. Document public APIs
  5. Run cargo fmt and cargo clippy before committing

๐Ÿ“„ License

MIT License (same as the original project)


The Rust runtime is production-ready for HypnoScript core programming! ๐Ÿš€

Enjoy hypnotic programming with Rust!

About

HypnoScript ist eine hypnotisch angehauchte Programmiersprache mit eigener Syntax (Focus { ... } Relax). Die komplette Laufzeitumgebung, der Compiler und die Kommandozeilen-Tools wurden aus C# nach Rust portiert und ab Version 1.0 ausschlieรŸlich in Rust weiterentwickelt.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •