pascal 0.1.1

A Pascal compiler in rust implementation with MCP support
Documentation

pascal-rs - A Modern Pascal Compiler in Rust

pascal-rs is a Pascal compiler written in Rust, featuring trait-based architecture, comprehensive testing, and clean code generation. It combines Rust's safety guarantees with Pascal's elegance, creating a modern platform for learning compiler construction and experimenting with language design.


โœจ Status: Active Development | Tests: 169/169 Passing | Language: Core Pascal Complete

Note: pascal-rs is ideal for education, research, and small projects. For production use with large codebases, consider mature compilers like Free Pascal or Delphi.


๐ŸŽฏ Why pascal-rs?

The Problem with Traditional Pascal Compilers

Traditional Pascal compilers suffer from several issues:

  • Aging codebases - Difficult to maintain and extend with modern features
  • Limited test coverage - Insufficient validation of edge cases

The pascal-rs Solution

pascal-rs addresses these problems with a modern, Rust-based architecture:

1. Memory Safety by Design

// Rust's ownership model prevents:
// - Null pointer dereferences โœ…
// - Buffer overflows โœ…
// - Data races โœ…
// - Memory leaks โœ…

2. Trait-Based Architecture

  • Clean abstractions through Rust's trait system
  • Dependency inversion - depend on traits, not concrete implementations
  • Easy testing with mock implementations
  • Extensible design for new features

3. Comprehensive Testing (169 tests)

  • Unit tests for all components
  • Integration tests for end-to-end validation
  • Complex validation tests for edge cases
  • Performance benchmarks
  • 100% test pass rate โœ…

4. Modern Developer Experience

  • Clear, colored error messages with source locations
  • Fast compilation with incremental builds
  • Excellent IDE support via Rust tooling
  • Comprehensive documentation

5. Optimizations

  • Constant folding and dead code elimination
  • Register allocation with graph coloring
  • Common subexpression elimination
  • Function inlining and loop unrolling
  • SIMD vectorization support

๐Ÿ“Š Comparison with Other Pascal Compilers

Feature Comparison Table

Feature pascal-rs Free Pascal (FPC) Delphi GNU Pascal (GPC)
Language โœ… โœ… โœ… โœ…
Memory Safety โœ… Rust guaranteed C++ implementation C++ implementation C implementation
Test Coverage โœ… 169 tests โš ๏ธ Limited โš ๏ธ Limited โŒ Minimal
Trait-Based Design โœ… Yes โŒ No โŒ No โŒ No
Interpreter Mode โœ… Built-in โš ๏ธ Limited โŒ No โŒ No
x86-64 Code Gen โœ… Optimized โœ… Mature โœ… Mature โœ… Basic
Active Development โœ… Yes โœ… Yes โœ… Yes โŒ No (2006)
Cross-Platform โœ… Yes โœ… Yes โš ๏ธ Windows only โœ… Yes
Compilation Speed โœ… Fast โš ๏ธ Moderate โš ๏ธ Moderate โš ๏ธ Slow
Error Messages โœ… Modern, colored โš ๏ธ Basic โœ… Good โš ๏ธ Basic

Unique Advantages

1. Memory Safety

  • Rust's ownership model prevents buffer overflows, null pointers, and data races
  • Traditional C/C++ implementations vulnerable to these issues

2. Trait-Based Architecture

// Easy to test, easy to extend
trait ScopeOperations {
    fn get(&self, name: &str) -> Option<Value>;
    fn set(&mut self, name: &str, value: Value);
}

3. Comprehensive Testing

  • 169 tests, 100% pass rate
  • Edge cases validated
  • Complex scenarios covered

4. Modern Build System

# Simple and fast
cargo build --release
cargo test
cargo run --bin pascal -- compile program.pas

5. Interpreter Mode

# Run directly without assembly/linking
pascal run program.pas

๐Ÿš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/yingkitw/pascal-rs.git
cd pascal-rs

# Build the compiler
cargo build --release

# The binary is now available at ./target/release/pascal

Your First Pascal Program

Create hello.pas:

program Hello;
begin
  writeln('Hello, World!');
end.

Compile and run:

# Compile with assembly output
pascal compile hello.pas -S

# Run using the interpreter
pascal run hello.pas

# View generated assembly
cat hello.s

Output:

Hello, World!

๐Ÿ“– Usage Guide

Basic Compilation

# Compile a Pascal program
pascal compile program.pas

# Compile with optimization
pascal compile program.pas -O2

# Compile with verbose output
pascal compile program.pas -v

# Compile with assembly output
pascal compile program.pas -S

# Compile to specific directory
pascal compile program.pas -o ./build

Running Programs

# Run using interpreter
pascal run program.pas

# Run with verbose output
pascal run program.pas -v

# Run with debug information
pascal run program.pas -d

Working with Units

# Compile a unit (generates .ppu file)
pascal compile MathUtils.pas -v

# Inspect a compiled unit
pascal info mathutils.ppu

# Compile a program that uses the unit
pascal compile Calculator.pas -v

Command Reference

Command Description Example
compile Compile Pascal source pascal compile prog.pas
run Run with interpreter pascal run prog.pas
info Show PPU file info pascal info module.ppu
clean Remove build artifacts pascal clean

Options

Option Description
-o, --output <DIR> Output directory
-O, --optimize <LEVEL> Optimization level (0-3)
-v, --verbose Verbose output
-S, --assembly Generate assembly output
-d, --debug Debug information
-I, --include <DIR> Add search path
--no-cache Disable caching

๐Ÿ’ก Examples

Example 1: Variables and Arithmetic

program Arithmetic;
var
  a, b, c, d: integer;
  result: real;
begin
  a := 10;
  b := 5;
  c := 3;
  d := 2;

  // Complex expression: 10 + 5 * 3 - 2 / 2
  result := a + b * c - d div d;

  writeln('Result: ', result);  // Output: 24.0
end.

Example 2: Control Structures

program ControlStructures;
var
  i, sum, product: integer;
  flag: boolean;
begin
  sum := 0;
  product := 1;
  flag := false;

  // For loop with sum of squares
  for i := 1 to 5 do
  begin
    sum := sum + i * i;
    if (i mod 2) = 0 then
      flag := true;
  end;

  // While loop
  i := 10;
  while i > 0 do
  begin
    product := product * (i mod 3 + 1);
    i := i - 1;
  end;

  writeln('Sum: ', sum);
  writeln('Product: ', product);
  writeln('Flag: ', flag);
end.

Example 3: Arrays and Records

program DataStructures;
type
  Person = record
    name: string;
    age: integer;
    salary: real;
  end;

var
  people: array[1..3] of Person;
  i: integer;
begin
  // Initialize records
  people[1].name := 'Alice';
  people[1].age := 30;
  people[1].salary := 50000.00;

  people[2].name := 'Bob';
  people[2].age := 25;
  people[2].salary := 45000.00;

  people[3].name := 'Charlie';
  people[3].age := 35;
  people[3].salary := 60000.00;

  // Display information
  for i := 1 to 3 do
  begin
    writeln('Name: ', people[i].name);
    writeln('Age: ', people[i].age);
    writeln('Salary: ', people[i].salary);
    writeln('---');
  end;
end.

Example 4: Boolean Logic

program BooleanLogic;
var
  a, b, c, d, result: boolean;
begin
  a := true;
  b := false;
  c := true;
  d := false;

  // Complex boolean expressions
  result := (a and c) or (not b and not d);
  writeln('(true AND true) OR (NOT false AND NOT false) = ', result);

  result := (a and b) or (c and d);
  writeln('(true AND false) OR (true AND false) = ', result);

  result := not ((a and b) or (c and d));
  writeln('NOT ((true AND false) OR (true AND false)) = ', result);
end.

Example 5: Functions and Procedures

program Functions;

function Factorial(n: integer): integer;
begin
  if n <= 1 then
    Factorial := 1
  else
    Factorial := n * Factorial(n - 1);
end;

procedure PrintTriangle(rows: integer);
var
  i, j: integer;
begin
  for i := 1 to rows do
  begin
    for j := 1 to i do
      write('*');
    writeln;
  end;
end;

var
  n: integer;
begin
  n := 5;
  writeln('Factorial of ', n, ' is ', Factorial(n));
  writeln;
  writeln('Triangle:');
  PrintTriangle(5);
end.

Example 6: Real-World Calculator

program Calculator;
var
  num1, num2, result: real;
  operation: char;
begin
  writeln('=== Simple Calculator ===');
  writeln('Enter first number: ');
  readln(num1);
  writeln('Enter operation (+, -, *, /): ');
  readln(operation);
  writeln('Enter second number: ');
  readln(num2);

  case operation of
    '+': result := num1 + num2;
    '-': result := num1 - num2;
    '*': result := num1 * num2;
    '/': result := num1 / num2;
  else
    writeln('Invalid operation!');
    exit;
  end;

  writeln('Result: ', result);
end.

Example 7: Unit System

Create a unit (MathUtils.pas):

unit MathUtils;

interface

function Add(a, b: integer): integer;
function Multiply(a, b: integer): integer;
function IsEven(n: integer): boolean;

implementation

function Add(a, b: integer): integer;
begin
  Add := a + b;
end;

function Multiply(a, b: integer): integer;
begin
  Multiply := a * b;
end;

function IsEven(n: integer): boolean;
begin
  IsEven := (n mod 2) = 0;
end;

end.

Compile the unit:

pascal compile MathUtils.pas -v

Use the unit (Calculator.pas):

program Calculator;

uses MathUtils;

var
  x, y: integer;
begin
  x := 10;
  y := 5;

  writeln('Addition: ', Add(x, y));
  writeln('Multiplication: ', Multiply(x, y));
  writeln('Is Even (10): ', IsEven(x));
  writeln('Is Even (5): ', IsEven(y));
end.

๐Ÿ—๏ธ Latest Capabilities

โœ… Trait-Based Architecture

Our modern trait-based design provides:

Core Traits

  • TryAs<T> - Type-safe conversions with error handling
  • FormattedDisplay - Configurable output formatting
  • ScopeOperations - Variable storage abstraction
  • FunctionRegistry - Function management interface
  • StatementExecutor - Pluggable execution strategies
  • ExpressionEvaluator - Custom evaluation strategies

Benefits

// Before: Tightly coupled code
fn execute(interpreter: &mut Interpreter) { ... }

// After: Trait-based, testable code
fn execute<T: ScopeOperations>(scope: &mut T) { ... }

Benefits:

  • โœ… Easy mocking for testing
  • โœ… Multiple implementations possible
  • โœ… Clear separation of concerns
  • โœ… Better maintainability

See TRAIT_ARCHITECTURE.md for details.

โœ… Comprehensive Testing (169 Tests)

Library tests:        87 โœ…
Basic tests:          1 โœ…
Compiler tests:      10 โœ…
Complex validation:   9 โœ… NEW!
Integration tests:   10 โœ…
Interpreter tests:   11 โœ…
Simple compiler:     18 โœ…
Simple interpreter:  13 โœ…
Type checker:        10 โœ…
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Total:             169 โœ…

Test Categories

1. Complex Validation Tests (NEW!)

  • โœ… Complex arithmetic with operator precedence
  • โœ… Nested control structures (5 levels deep)
  • โœ… Character operations and comparisons
  • โœ… Complex boolean expressions (AND, OR, NOT)
  • โœ… Real number arithmetic
  • โœ… Boundary conditions (zero, positive, negative)
  • โœ… Comprehensive programs combining all features

2. Integration Tests

  • โœ… Hello World
  • โœ… Factorial calculation
  • โœ… Fibonacci sequence
  • โœ… Prime number generation
  • โœ… Nested loops
  • โœ… Record operations
  • โœ… Array operations
  • โœ… Case statements
  • โœ… Repeat until loops
  • โœ… String operations

3. Compiler Tests

  • โœ… Simple program compilation
  • โœ… Arithmetic operations
  • โœ… Control structures
  • โœ… Variable declarations
  • โœ… Type declarations
  • โœ… Arrays and records
  • โœ… Case statements
  • โœ… Repeat until loops
  • โœ… String operations

See COMPLEX_VALIDATION_SUMMARY.md for full details.

โœ… Advanced Interpreter Features

Built-in Functions (20+):

  • abs, sqr, sqrt, sin, cos, ln, exp
  • round, trunc, ord, chr
  • length, pos, concat, copy, upcase, lowercase
  • odd, succ, pred, random
  • inttostr, strtoint

Built-in Procedures:

  • write, writeln, readln
  • inc, dec, halt

Control Flow:

  • โœ… if/else statements
  • โœ… while loops
  • โœ… for loops (to/downto)
  • โœ… repeat until loops
  • โœ… case statements
  • โœ… begin/end blocks

โœ… Code Generation

x86-64 Assembly (Intel syntax):

  • Register allocation with graph coloring
  • Stack-based variable management
  • Proper function prologue/epilogue
  • Multiple calling conventions (System V, Win64)

Optimizations:

  • Constant folding
  • Dead code elimination
  • Common subexpression elimination
  • Function inlining
  • Loop unrolling
  • Peephole optimization

โœ… Language Support

Data Types:

  • โœ… Integer (signed 64-bit)
  • โœ… Real (IEEE 754 double precision)
  • โœ… Boolean
  • โœ… Char
  • โœ… String
  • โœ… Arrays (multi-dimensional)
  • โœ… Records
  • โœ… Pointers
  • โœ… Enumerations
  • โœ… Sets

Operators:

  • โœ… Arithmetic: +, -, *, /, div, mod
  • โœ… Comparison: =, <>, <, <=, >, >=
  • โœ… Logical: and, or, not
  • โœ… Bitwise: &, |, xor, <<, >>
  • โœ… Unary: +, -, not

Control Structures:

  • โœ… if/else
  • โœ… while/do
  • โœ… for/to/downto
  • โœ… repeat/until
  • โœ… case/of
  • โœ… begin/end blocks

โš ๏ธ Current Limitations

While pascal-rs successfully compiles and interprets core Pascal programs, there are features not yet implemented:

Not Yet Implemented:

  • โŒ Object Pascal (classes, inheritance, polymorphism)
  • โŒ Exception handling (try-except-finally)
  • โŒ Generics/templates
  • โŒ File I/O operations
  • โŒ Dynamic arrays
  • โŒ Variant records
  • โŒ Operator overloading
  • โŒ Properties
  • โŒ Interfaces
  • โŒ Advanced standard library (only basic built-ins)

Platform Support:

  • โœ… x86-64 (primary target, well-tested)
  • ๐Ÿšง ARM, RISC-V, MIPS, PowerPC (planned)
  • ๐Ÿšง WebAssembly (planned)

For these features, consider using Free Pascal or Delphi.


๐Ÿงช Testing

Running Tests

# Run all tests
cargo test

# Run specific test categories
cargo test --lib                          # Library tests (87)
cargo test --test run_compiler_tests      # Compiler tests (10)
cargo test --test run_integration_tests   # Integration tests (10)
cargo test --test run_complex_validation_tests  # Complex validation (9)
cargo test --test run_interpreter_tests   # Interpreter tests (11)
cargo test --test run_type_checker_tests  # Type checker tests (10)

# Run with output
cargo test -- --nocapture  # Show test output
cargo test -- --verbose    # Verbose test output

Test Results

running 169 tests
test result: ok. 169 passed; 0 failed; 0 ignored; 0 measured

All tests passing! โœ…

Test Coverage

  • Lexical Analysis: Complete token coverage
  • Parsing: All AST node types
  • Type Checking: All type combinations
  • Code Generation: All statement types
  • Interpreter: All language features
  • Edge Cases: Boundary conditions validated

๐Ÿ“š Architecture

Modular Design

pascal-rs/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lexer.rs              # Lexical analysis
โ”‚   โ”œโ”€โ”€ parser/               # Syntax analysis
โ”‚   โ”‚   โ”œโ”€โ”€ mod.rs
โ”‚   โ”‚   โ”œโ”€โ”€ expression.rs
โ”‚   โ”‚   โ”œโ”€โ”€ statement.rs
โ”‚   โ”‚   โ””โ”€โ”€ decl.rs
โ”‚   โ”œโ”€โ”€ interpreter.rs        # Tree-walking interpreter
โ”‚   โ”œโ”€โ”€ interpreter_value.rs  # Value type
โ”‚   โ”œโ”€โ”€ interpreter_scope.rs  # Scope management
โ”‚   โ”œโ”€โ”€ interpreter_function.rs # Function registry
โ”‚   โ”œโ”€โ”€ interpreter_traits.rs # Trait abstractions
โ”‚   โ”œโ”€โ”€ type_checker.rs       # Type validation
โ”‚   โ”œโ”€โ”€ optimizer.rs          # Optimization passes
โ”‚   โ”œโ”€โ”€ unit_codegen.rs       # Code generation
โ”‚   โ””โ”€โ”€ resolver.rs           # Symbol resolution
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ run_compiler_tests.rs         # Compiler validation
โ”‚   โ”œโ”€โ”€ run_integration_tests.rs      # End-to-end tests
โ”‚   โ”œโ”€โ”€ run_complex_validation_tests.rs # Complex scenarios (NEW!)
โ”‚   โ””โ”€โ”€ integration/
โ”‚       โ””โ”€โ”€ complex_validation_tests.rs
โ””โ”€โ”€ examples/                      # Example programs

Trait-Based Components

// Value operations
impl TryAs<i64> for Value
impl TryAs<f64> for Value
impl TryAs<bool> for Value
impl FormattedDisplay for Value

// Scope management
impl ScopeOperations for Scope
impl ScopeOperations for ScopeStack

// Function registry
impl FunctionRegistry for FunctionRegistryImpl
impl FunctionRegistry for HashMap<String, UserFunction>

Compilation Pipeline

Source Code โ†’ Lexer โ†’ Tokens โ†’ Parser โ†’ AST
                                           โ†“
                                    Type Checker
                                           โ†“
                                    Optimizer
                                           โ†“
                                  Code Generator
                                           โ†“
                                     Assembly

๐Ÿ“– Documentation


๐Ÿ†• What's New

Latest Release Highlights

โœ… Trait-Based Architecture (NEW!)

  • Added comprehensive trait abstractions
  • Improved testability and maintainability
  • Better separation of concerns
  • See TRAIT_ARCHITECTURE.md

โœ… Complex Validation Tests (NEW!)

  • 9 new comprehensive tests
  • Edge cases and boundary conditions
  • Complex operator precedence
  • Nested control structures
  • 100% pass rate

โœ… Enhanced Testing Support

  • Added current_scope() method for testing
  • Added get_variable_value() for value inspection
  • Made Scope struct public with get() method

โœ… Improved Documentation

  • Trait architecture guide
  • Test validation summary
  • Comprehensive examples
  • Better inline documentation

๐ŸŽฏ Use Cases

1. Education

  • Learn compiler construction with clean, modern code
  • Understand trait-based design patterns
  • Study optimization techniques
  • Explore language implementation

2. Research & Experimentation โœ… Perfect Fit

  • Test new optimization algorithms
  • Experiment with trait-based architectures
  • Benchmark compilation strategies
  • Prototype language features
  • Study type systems
  • Research memory-safe compiler design

3. Small Projects โœ… Suitable

  • Command-line utilities
  • Scripts and automation
  • Learning exercises
  • Algorithm implementation
  • Data processing tasks
  • Homework assignments

4. Legacy Modernization โš ๏ธ Consider Limitations

  • Works for standard Pascal code
  • Missing Object Pascal features (classes, exceptions)
  • Good for simple procedural Pascal programs
  • May need modifications for advanced features

Not Recommended For (Yet):

  • โŒ Large commercial applications (use Free Pascal or Delphi)
  • โŒ Complex GUI applications (no framework support yet)
  • โŒ Database-heavy applications (limited database library support)
  • โŒ Embedded systems (limited platform support)
  • โŒ Projects requiring Object Pascal classes/exceptions

๐Ÿ™ Acknowledgments

  • Inspired by the Free Pascal Compiler (FPC)
  • Built with Rust and Cargo
  • Uses modern compiler construction techniques
  • Benefits from the Rust community's expertise

Made with โค๏ธ in Rust

Status: Active Development | Tests: 169/169 Passing | Language: Core Pascal Complete