NAME

Sidef - The Sidef programming language

VERSION

This document describes Sidef version 26.01 and later.

DESCRIPTION

Sidef is a modern, expressive programming language that elegantly blends object-oriented and functional programming paradigms. Drawing inspiration from Ruby, Raku, and Go, Sidef provides a powerful and flexible environment for both scripting and complex application development.

            **   **         ****   *           *********   *********
          * * ** * *        ****   **          ** ** **    ** ** **
           **   **          ****   ***         *********   *  *  *
  **        **        **    ****   *  *        ******      ******
* * *     * * *     * * *   ****   ** **       ** **       ** **
 **        **        **     ****   ******      ******      *  *
       **   **              ****   *  *  *     *********   ***
     * * ** * *             ****   ** ** **    ** ** **    **
      **   **               ****   *********   *********   *

Key Features

  • Multi-Paradigm Design

    Seamlessly combines object-oriented and functional programming styles, allowing you to choose the best approach for each problem.

  • Rich Type System

    Native support for arbitrary-precision integers, rationals, floating-point numbers, and complex numbers. All numeric types are first-class citizens.

  • Advanced OOP Support

    Complete class system with inheritance, multiple dispatch, method overloading, and operator overloading.

  • Functional Programming

    First-class functions, lexical closures, pattern matching, lazy evaluation, and higher-order functions.

  • Perl Interoperability

    Direct access to the entire Perl ecosystem. Use any CPAN module without wrapper code.

  • Modern Language Features

    Built-in regular expressions, Unicode support, optional type checking, keyword arguments, and destructuring.

  • Code Caching & Optimization

    Intelligent compilation caching with DBM backend for faster repeated execution and multi-level optimization support.

  • Developer-Friendly

    Clear syntax, expressive constructs, and helpful error messages with suggestions make development productive and enjoyable.

SYNOPSIS

Basic Usage

The Sidef module provides a programmatic interface to the Sidef language engine, allowing you to parse, compile, and execute Sidef code from Perl.

use Sidef;

# Create a Sidef engine instance
my $sidef = Sidef->new(
    name       => 'my_program',    # Program name (for error messages)
    opt        => {},              # Command-line options
    parser_opt => {},              # Parser-specific options
);

# Execute Sidef code directly
my $code = 'say "Hello, World!"';
$sidef->execute_code($code);
# Output: Hello, World!

Using Optimization and Caching

# Enable optimization and caching for better performance
my $sidef = Sidef->new(
    name => 'calculator',
    opt  => {
        O => 2,    # Optimization level (0, 1, or 2)
        s => 1,    # Enable code caching with DBM
    }
);

my $code = 'func fib(n) { (n < 2) ? n : (fib(n-1) + fib(n-2)) }; fib(20)';

# First run: compiles and caches
my $result = $sidef->execute_code($code);

# Second run: uses cached compiled code (much faster)
$result = $sidef->execute_code($code);

String Interpolation and Expressions

my $math_code = 'say "The answer is: #{6 * 7}"';
$sidef->execute_code($math_code);
# Output: The answer is: 42

Working with Return Values

my $result = $sidef->execute_code('2 + 2');
# $result is a Sidef::Types::Number::Number object
say $result;  # Outputs: 4

Compiling to Perl

Transform Sidef code into Perl source code for inspection or optimization:

my $sidef_code = q{
    func fibonacci(n) {
        (n < 2) ? n : (fibonacci(n-1) + fibonacci(n-2))
    }
    fibonacci(10)
};

my $perl_code = $sidef->compile_code($sidef_code, 'Perl');
print $perl_code;  # Shows generated Perl code

AST Manipulation

For advanced use cases, you can work directly with the Abstract Syntax Tree:

my $code = '2 + 3*4';

# Parse into AST
my $ast = $sidef->parse_code($code);

# Optimize (performs constant folding and other optimizations)
my $optimized_ast = $sidef->optimize_ast($ast);

# Compile back to Sidef (to see the optimized form)
my $optimized_code = $sidef->compile_ast($optimized_ast, 'Sidef');
print $optimized_code;  # May show: 14

# Or compile to Perl
my $perl = $sidef->compile_ast($optimized_ast, 'Perl');

Direct Perl Execution

Execute pre-compiled Perl code directly:

my $perl_code = $sidef->compile_code('say "Fast execution"', 'Perl');
$sidef->execute_perl($perl_code);

Error Handling

my $invalid_code = 'say "missing quote';

eval {
    $sidef->execute_code($invalid_code);
};
if ($@) {
    warn "Sidef error: $@";
    # Error messages include helpful suggestions for typos
}

CONSTRUCTOR

new

my $sidef = Sidef->new(%options);

Creates and returns a new Sidef object representing a Sidef language engine instance.

Parameters:

  • name (optional)

    A string identifying the program name. Used in error messages and diagnostics. Defaults to '-'.

    my $sidef = Sidef->new(name => 'calculator.sf');
  • opt (optional)

    A hashref of command-line options that affect execution behavior. Defaults to {}.

    Common options include:

    • O - Optimization level (0, 1, or 2)

      • 0 - No optimization (default)

      • 1 - Basic constant folding and dead code elimination

      • 2 - Advanced optimization: deparse and re-parse for additional optimization passes

    • s - Enable compilation caching using DBM

      When enabled, compiled code is stored in a database for faster subsequent executions. Requires DB_File or GDBM_File.

    • warnings - Enable/disable warnings

    • strict - Enable strict mode

    Example:

    my $sidef = Sidef->new(
        opt => {
            O        => 2,    # Maximum optimization
            s        => 1,    # Enable caching
            warnings => 1,
            strict   => 1,
        }
    );
  • parser_opt (optional)

    A hashref of parser-specific options. Defaults to {}.

    Example:

    my $sidef = Sidef->new(
        parser_opt => {
            interactive => 1,
        }
    );

Returns: A new Sidef object.

call

my $sidef = Sidef->call(%options);

Alias for new(). Creates and returns a new Sidef object with the same parameters as new().

Example:

my $sidef = Sidef->call(name => 'test');

CORE METHODS

execute_code

my $result = $sidef->execute_code($code);

Parses, compiles, and executes the provided Sidef source code. This is the primary method for running Sidef code from Perl.

Parameters:

  • $code

    A string containing Sidef source code to execute.

Returns: The result of the last expression evaluated in the Sidef code, as a Sidef object. For statements that don't produce a value, returns nil.

Example:

# Simple expression
my $result = $sidef->execute_code('10 + 20');
say $result;  # 30

# Multiple statements (returns last value)
my $result = $sidef->execute_code(q{
    var x = 10;
    var y = 20;
    x + y
});
say $result;  # 30

execute_perl

my $result = $sidef->execute_perl($perl_code);

Executes pre-compiled Perl code that was generated from Sidef source. This is a lower-level method used internally by execute_code().

Parameters:

  • $perl_code

    A string containing Perl source code (typically generated by compile_code() or compile_ast()).

Returns: The result of evaluating the Perl code.

Example:

# Compile once
my $perl_code = $sidef->compile_code('2 + 2', 'Perl');

# Execute multiple times without re-compilation
my $result1 = $sidef->execute_perl($perl_code);
my $result2 = $sidef->execute_perl($perl_code);

Use Case: Useful when you want to compile once and execute many times, or when you need fine-grained control over the compilation and execution phases.

compile_code

my $compiled = $sidef->compile_code($code, $backend);

Parses the source code and compiles it to the specified backend format without executing it. If caching is enabled (opt => {s => 1}), the compiled code may be retrieved from or stored to the DBM cache.

Parameters:

  • $code

    A string containing Sidef source code to compile.

  • $backend

    The target compilation backend. Valid options:

    • 'Sidef' - Decompile back to Sidef source (useful for code formatting)

    • 'Perl' - Compile to Perl source code (default)

Returns: A string containing the compiled code in the target language.

Implementation Details:

  • When caching is enabled and code length > 1024 bytes, the compiled code is stored with an MD5 hash as the key

  • Cached code is compressed using RawDeflate for storage efficiency

  • The cache automatically sanitizes old entries (older than 3 days) and removes very old entries (older than 2 days)

  • Code containing eval() is not cached to prevent security issues

  • Each compilation is wrapped in a unique package namespace (Sidef::RuntimeXXXX) to avoid conflicts

Example:

my $sidef_code = 'func square(n) { n * n }; square(5)';

# Decompile to Sidef (useful for code formatting/normalization)
my $formatted = $sidef->compile_code($sidef_code, 'Sidef');
print $formatted;

# Compile to Perl
my $perl_code = $sidef->compile_code($sidef_code, 'Perl');
print $perl_code;

parse_code

my $ast = $sidef->parse_code($code);

Parses the provided Sidef source code and returns its Abstract Syntax Tree (AST) representation. The parser is lazily initialized on first use.

Parameters:

  • $code

    A string containing Sidef source code to parse.

Returns: A Sidef AST object representing the parsed code structure.

Automatic Optimization:

If the O option is set to 1 or higher, the returned AST is automatically optimized:

  • Level 1: Calls optimize_ast() on the parsed tree

  • Level 2: Performs level 1 optimization, then deparses to Sidef, and re-parses for additional optimization opportunities

Example:

my $ast = $sidef->parse_code('2 + 2*2');
# $ast contains the tree structure representing the expression
# You can now pass this to optimize_ast() or compile_ast()

Use Cases:

  • Building code analysis tools

  • Implementing custom optimizations

  • Creating code transformation utilities

  • Developing Sidef IDE features (syntax highlighting, autocomplete)

  • AST-based code metrics and complexity analysis

optimize_ast

my $optimized_ast = $sidef->optimize_ast($ast);

Performs optimization passes on an existing AST, including constant folding, dead code elimination, and other improvements.

Parameters:

  • $ast

    An AST object obtained from parse_code().

Returns: A new, optimized AST object.

Optimizations Performed:

  • Constant folding (e.g., 2 + 3 becomes 5)

  • Dead code elimination

  • Expression simplification

  • Redundancy removal

Example:

my $ast = $sidef->parse_code('2 + 3*4 + 5');
my $optimized = $sidef->optimize_ast($ast);

# See what the optimizer did
my $result = $sidef->compile_ast($optimized, 'Sidef');
print $result;  # Likely: 19 (constant folded at compile time)

Note: The original AST is not modified; a new optimized tree is returned.

compile_ast

my $code = $sidef->compile_ast($ast, $backend);

Compiles an existing AST to the specified backend format. The deparser is lazily initialized on first use.

Parameters:

  • $ast

    An AST object (from parse_code() or optimize_ast()).

  • $backend

    The target compilation backend: 'Sidef' or 'Perl'.

Returns: A string containing the compiled code.

Example:

my $ast = $sidef->parse_code('func add(a, b) { a + b }');
my $optimized = $sidef->optimize_ast($ast);

# Compile to Perl for embedding
my $perl_code = $sidef->compile_ast($optimized, 'Perl');

# Or decompile to Sidef to see optimized form
my $sidef_code = $sidef->compile_ast($optimized, 'Sidef');

UTILITY METHODS

get_sidef_config_dir

my $config_dir = $sidef->get_sidef_config_dir();

Returns the path to the Sidef configuration directory. Creates the directory if it doesn't exist.

Directory Resolution Order:

1. $ENV{SIDEF_CONFIG_DIR} if set
2. $ENV{XDG_CONFIG_DIR}/sidef if XDG_CONFIG_DIR is set
3. $HOME/.config/sidef on Unix-like systems
4. \Local Settings\Application Data\.config\sidef on Windows
5. Current directory as fallback

Returns: A string containing the absolute path to the config directory.

Example:

my $config_dir = $sidef->get_sidef_config_dir();
print "Config directory: $config_dir\n";
# Output: Config directory: /home/user/.config/sidef

Use Case: Store user preferences, cached data, or custom modules.

get_sidef_vdir

my $version_dir = $sidef->get_sidef_vdir();

Returns the version-specific subdirectory within the Sidef config directory. This directory is used for version-specific cached compiled code.

Returns: A string containing the path to the version-specific directory (e.g., ~/.config/sidef/v25.12).

Example:

my $vdir = $sidef->get_sidef_vdir();
print "Version directory: $vdir\n";
# Output: Version directory: /home/user/.config/sidef/v25.12

Use Case: Allows different Sidef versions to maintain separate caches without conflicts.

has_dbm_driver

my $has_driver = $sidef->has_dbm_driver();

Checks for the availability of a supported DBM driver for code caching functionality.

Supported Drivers (in order of preference):

1. DB_File (Berkeley DB) - returned as 'bdbm'
2. GDBM_File (GNU DBM) - returned as 'gdbm'

Returns:

  • The driver name string ('bdbm' or 'gdbm') if a driver is available

  • undef if no driver is found

Example:

if (my $driver = $sidef->has_dbm_driver()) {
    print "Using DBM driver: $driver\n";
    # Enable caching
    $sidef->{opt}{s} = 1;
} else {
    warn "No DBM driver available, caching disabled\n";
}

Note: A warning is issued if no driver is found, suggesting installation of DB_File or GDBM_File.

dbm_lookup

my $cached_code = $sidef->dbm_lookup($backend, $md5_hash);

Low-level method to retrieve compiled code from the DBM cache.

Parameters:

  • $backend

    The compilation backend ('Perl' or 'Sidef').

  • $md5_hash

    MD5 hash of the source code (used as cache key).

Returns:

  • The cached compiled code as a string if found

  • undef if not found or cache is unavailable

Cache Management:

  • Updates the access timestamp if the entry hasn't been accessed for 5 hours

  • Decompresses the stored code using RawInflate

  • Decodes from UTF-8

Example:

use Digest::MD5 qw(md5_hex);
use Encode qw(encode_utf8);

my $code = 'say "test"';
my $md5 = md5_hex(encode_utf8($code));

if (my $cached = $sidef->dbm_lookup('Perl', $md5)) {
    print "Found cached code!\n";
}

Note: This is typically used internally by compile_code(). Direct use is rare.

dbm_store

$sidef->dbm_store($backend, $md5_hash, $code);

Low-level method to store compiled code in the DBM cache.

Parameters:

  • $backend

    The compilation backend ('Perl' or 'Sidef').

  • $md5_hash

    MD5 hash of the source code (used as cache key).

  • $code

    The compiled code string to store.

Storage Process:

  • Compresses the code using RawDeflate

  • Stores with current timestamp

  • Periodically sanitizes old entries (every 3 days)

  • Removes entries not accessed for 2+ days during sanitization

Example:

use Digest::MD5 qw(md5_hex);
use Encode qw(encode_utf8);

my $code = 'say "test"';
my $compiled = $sidef->compile_ast($ast, 'Perl');
my $md5 = md5_hex(encode_utf8($code));

$sidef->dbm_store('Perl', $md5, encode_utf8($compiled));

Note: This is typically used internally by compile_code(). Direct use is rare.

CLASS METHODS

version

my $version = Sidef->version;

Returns the Sidef version as a Sidef String object.

Parameters: None.

Returns: A Sidef::Types::String::String object representing the version (e.g., 'v25.12').

Example:

my $v = Sidef->version;
say "Running Sidef version: $v";
# Output: Running Sidef version: v25.12

numeric_version

my $num_version = Sidef->numeric_version;

Returns the Sidef version as a Sidef Number object, suitable for numeric comparisons.

Parameters: None.

Returns: A Sidef::Types::Number::Number object representing the version (e.g., 26.01).

Example:

my $ver = Sidef->numeric_version;
if ($ver >= 25.0) {
    say "Running modern Sidef version";
}

PACKAGE UTILITY FUNCTIONS

These functions are available in the Sidef package namespace but are primarily used internally.

normalize_type

my $short_name = Sidef::normalize_type($full_type);

Converts a full Perl package name to a short, readable type name.

Parameters:

  • $full_type

    A full package name (e.g., 'Sidef::Types::Number::Number').

Returns: The short type name (e.g., 'Number').

Example:

my $type = Sidef::normalize_type('Sidef::Types::String::String');
print $type;  # String

normalize_method

my $short_signature = Sidef::normalize_method($full_method);

Converts a full method signature to a short, readable format.

Parameters:

  • $full_method

    A full method name (e.g., 'Sidef::Types::Array::Array::length').

Returns: The short signature (e.g., 'Array#length').

Example:

my $sig = Sidef::normalize_method('Sidef::Types::Hash::Hash::keys');
print $sig;  # Hash#keys

jaro

my $similarity = Sidef::jaro($string1, $string2);

Calculates the Jaro similarity between two strings. Used internally for suggesting method names on typos.

Parameters:

  • $string1, $string2

    Two strings to compare.

Returns: A number between 0 and 1, where 1 means identical strings.

Example:

my $sim = Sidef::jaro('hello', 'hallo');
print $sim;  # 0.933333333333333

jaro_winkler

my $similarity = Sidef::jaro_winkler($string1, $string2);

Calculates the Jaro-Winkler similarity, which gives more weight to strings with matching prefixes. Used for better suggestions on method name typos.

Parameters:

  • $string1, $string2

    Two strings to compare.

Returns: A number between 0 and 1, where 1 means identical strings.

Example:

my $sim = Sidef::jaro_winkler('hello', 'hallo');
print $sim;  # 0.96 (higher than plain Jaro)

best_matches

my @suggestions = Sidef::best_matches($name, \@candidate_list);

Finds the best matching strings from a candidate list for a given name. Returns matches with Jaro-Winkler similarity >= 0.8.

Parameters:

  • $name

    The string to match (e.g., a mistyped method name).

  • \@candidate_list

    Array reference containing possible correct names.

Returns: A list of the best matching candidates, sorted by similarity.

Example:

my @methods = qw(push pop shift unshift length each map);
my @matches = Sidef::best_matches('posh', \@methods);
print join(', ', @matches);  # push, pop

Use Case: Powers the "Did you mean?" suggestions in error messages.

LANGUAGE OVERVIEW

Sidef is designed to be expressive and intuitive. Here's a quick taste of the language syntax:

Variables and Types

var name = "Alice"          # String
var age = 30                # Integer
var pi = 3.14159f           # Float
var ratio = 22/7            # Rational (exact fraction)
var items = [1, 2, 3, 4]    # Array
var person = Hash(          # Hash
    name => "Bob",
    age => 25,
)

Functions

# Function definition
func greet(name) {
    say "Hello, #{name}!"
}

# Function with multiple parameters and default values
func power(base, exp=2) {
    base ** exp
}

# Lambda expressions
var square = { |n| n * n }
say square(5)  # 25

Object-Oriented Programming

class Person (String name, Number age) {
    method greet {
        say "Hello, I'm #{name} and I'm #{age} years old."
    }
}

var alice = Person(name: "Alice", age: 30)
alice.greet()

Functional Programming

# Map, filter, reduce
var numbers = [1..10]
var squares = numbers.map { |n| n**2 }
var evens = numbers.grep { |n| n.is_even }
var sum = numbers.reduce { |a, b| a + b }

# Pattern matching
func factorial(n) {
    case (n) {
        when (0) { 1 }
        when (1) { 1 }
        else     { n * factorial(n-1) }
    }
}

Advanced Features

# Multiple dispatch
func process(Number n) { n * 2 }
func process(String s) { s.uc }

# Lazy evaluation
var infinite = (1..Inf -> lazy)
var first_even_ten = infinite.grep{.is_even}.first(10)

# Regular expressions
if ("hello@example.com" ~~ /^\w+@\w+\.\w+$/) {
    say "Valid email!"
}

EMBEDDING SIDEF IN PERL

The Sidef module makes it easy to embed Sidef code within larger Perl applications:

Example: Using Sidef as a Configuration Language

use Sidef;

my $sidef = Sidef->new(name => 'config');

my $config_code = q{
    Hash(
        database => Hash(
            host => "localhost",
            port => 5432,
            name => "myapp"
        ),
        features => Hash(
            caching => true,
            debug => false
        )
    )
};

my $config = $sidef->execute_code($config_code);
# $config is now a Sidef Hash object
# Access values with Perl syntax:
say $config->{database}{host};  # localhost

Example: Using Sidef for Safe Expression Evaluation

use Sidef;

my $calculator = Sidef->new(
    name => 'calc',
    opt  => { O => 2, s => 1 }  # Optimize and cache
);

sub safe_eval {
    my ($expr) = @_;
    eval {
        return $calculator->execute_code($expr);
    } or do {
        warn "Invalid expression: $@";
        return undef;
    };
}

my $result = safe_eval("2 + 2*10");
say $result;  # 22

Example: Code Generation and Metaprogramming

use Sidef;

my $sidef = Sidef->new();

# Generate Sidef functions programmatically
my $func_name = 'calculate_total';
my @operations = ('sum', 'prod', 'avg');

for my $op (@operations) {
    my $code = qq{
        func ${func_name}_$op(numbers) {
            numbers.$op
        }
    };
    $sidef->execute_code($code);
}

Example: High-Performance Repeated Execution

use Sidef;

my $sidef = Sidef->new(
    name => 'repeated',
    opt  => { O => 2, s => 1 }
);

my $complex_code = q{
    func compute(n) {
        (1..n).sum_by { |k| 1/k**2 }
    }
    compute(1000)
};

# First execution: parse, optimize, compile, cache, execute
my $start = time;
my $result1 = $sidef->execute_code($complex_code);
my $time1 = time - $start;

# Subsequent executions: retrieve from cache, execute
$start = time;
my $result2 = $sidef->execute_code($complex_code);
my $time2 = time - $start;

print "First run: ${time1}s, Cached run: ${time2}s\n";
# Cached run will be significantly faster

ADVANCED TOPICS

Performance Considerations

  • Enable caching for production: opt => {s => 1}

    Speeds up repeated execution by caching compiled code.

  • Use optimization for CPU-intensive code: opt => {O => 2}

    Level 2 optimization provides maximum performance but increases initial compilation time.

  • Compile to Perl for maximum performance

    Generate Perl code once and execute it directly for the fastest runtime performance.

  • Cache Sidef instances to avoid repeated initialization

    Creating a new Sidef object has overhead. Reuse instances when possible.

  • Use lazy evaluation for large data sets

    Sidef's lazy evaluation can significantly reduce memory usage.

  • Consider DBM driver choice

    DB_File (Berkeley DB) generally performs better than GDBM_File for caching.

Cache Management

The compilation cache provides significant performance benefits but requires understanding:

  • Cache location: ~/.config/sidef/v25.12/ (version-specific)

  • Storage format: Two DBM databases (time and code)

  • Compression: RawDeflate compression for efficient storage

  • Automatic cleanup: Entries not accessed for 2+ days are removed every 3 days

  • MD5 hashing: Source code is hashed to create unique cache keys

  • Update interval: Access timestamps updated every 5 hours

To manually clear the cache:

rm -rf ~/.config/sidef/v25.12/

Thread Safety

Each Sidef instance maintains its own state, including parser and deparser objects. For multi-threaded applications:

  • Create separate instances per thread for true parallel execution

  • Use appropriate locking if sharing a single instance

  • The DBM cache is not thread-safe; use separate cache directories per thread if needed

Memory Management

  • Sidef objects are reference-counted through Perl's system

  • Circular references are handled by Perl's garbage collector

  • Large data structures are automatically freed when no longer referenced

  • The parser and deparser are lazily initialized and cached per instance

  • Use undef to explicitly release large Sidef instances

Error Handling and Debugging

Sidef provides helpful error messages with suggestions:

# Typo in method name
my $result = $sidef->execute_code('[1,2,3].lnegth');
# Error: Undefined method 'Array#lnegth'
# [?] Did you mean: length

The AUTOLOAD mechanism:

  • Catches undefined method calls

  • Uses Jaro-Winkler similarity to suggest corrections

  • Shows context (calling method/function)

  • Provides similarity threshold of 0.8 for suggestions

COMPARISON WITH OTHER LANGUAGES

Sidef vs Ruby

Sidef draws heavy inspiration from Ruby's elegant syntax but adds:

  • Native arbitrary-precision arithmetic (rationals, big integers)

  • Stronger Perl interoperability

  • Built-in optimization and caching

  • Pattern matching and functional features

Sidef vs Raku

While Raku focuses on language experimentation and advanced features, Sidef prioritizes:

  • Practical usability with simpler learning curve

  • Seamless Perl ecosystem integration

  • Faster development iteration

  • Performance through Perl compilation

Sidef vs Python

Sidef offers:

  • More flexible and expressive syntax

  • Stronger metaprogramming capabilities

  • Native exact arithmetic (rationals)

  • Ideal for mathematical and symbolic computation

  • Ruby-like elegance with functional features

OPTIMIZATION LEVELS

Understanding the O option values:

Level 0 (No Optimization)

my $sidef = Sidef->new(opt => { O => 0 });
  • No optimization passes applied

  • Fastest compilation time

  • Suitable for development and debugging

  • AST used as-is for code generation

Level 1 (Standard Optimization)

my $sidef = Sidef->new(opt => { O => 1 });
  • Constant folding: 2 + 3 becomes 5

  • Dead code elimination

  • Expression simplification

  • Recommended for most production use

  • Good balance of compilation time and runtime performance

Level 2 (Aggressive Optimization)

my $sidef = Sidef->new(opt => { O => 2 });
  • Performs level 1 optimizations

  • Deparses optimized AST back to Sidef source

  • Re-parses the deparsed code with level 1 optimization

  • Allows additional optimization opportunities

  • Longer compilation time but maximum runtime performance

  • Best for CPU-intensive production code

TROUBLESHOOTING

Common Issues

"Undefined method" errors

Sidef uses . for method calls. Check spelling and capitalization. The error message will suggest similar method names.

Example error:

[AUTOLOAD] Undefined method 'Array#lnegth' called from main()
[?] Did you mean: length
Type errors

Enable strict mode for better type checking:

my $sidef = Sidef->new(opt => { strict => 1 });
Module not found

Sidef can use Perl modules via require. Ensure the module is installed:

cpan Module::Name
# or
cpanm Module::Name
Performance issues
  • Enable optimization: opt => {O => 2}

  • Enable caching: opt => {s => 1}

  • Install faster math libraries (Math::Prime::Util)

  • Compile to Perl for production use

Cache not working

Check if a DBM driver is installed:

perl -e 'use DB_File; print "DB_File OK\n"'
# or
perl -e 'use GDBM_File; print "GDBM_File OK\n"'

Install if missing:

cpan DB_File
# or
cpanm DB_File
Memory usage

For large data processing:

  • Use lazy evaluation where possible

  • Process data in chunks

  • Clear large structures when done

  • Consider streaming approaches for file processing

Debugging Tips

  • Use warn statements liberally for debugging

  • Examine compiled Perl code: compile_code($code, 'Perl')

  • Inspect optimized AST: compile_ast(optimize_ast($ast), 'Sidef')

  • Check parser state with $sidef->{parser}

  • Review cache entries in ~/.config/sidef/v25.12/

RESOURCES AND COMMUNITY

Official Resources

Getting Help

Contributing

Contributions are welcome! See the GitHub repository for contribution guidelines. Areas where help is particularly appreciated:

  • Documentation improvements

  • Bug reports and fixes

  • Performance optimizations

  • New library modules

  • Example programs and tutorials

  • Porting RosettaCode examples

DEPENDENCIES

Required

Sidef requires:

  • Perl 5.16.0 or later

  • List::Util - Core utility functions

  • File::Spec - Portable file path operations

  • Encode - UTF-8 encoding/decoding (for caching)

  • Digest::MD5 - Hash generation (for caching)

  • IO::Compress::RawDeflate - Compression (for caching)

  • IO::Uncompress::RawInflate - Decompression (for caching)

  • Various Sidef type modules (automatically loaded)

Optional (for enhanced functionality)

  • DB_File or GDBM_File - For compilation caching

    Without these, the s option (caching) will not be available.

  • Math::GMPz - Faster arbitrary-precision integer arithmetic

  • Math::GMPq - Faster arbitrary-precision rational arithmetic

  • Math::MPFR - Faster arbitrary-precision floating-point arithmetic

  • Math::MPC - Faster arbitrary-precision complex arithmetic

These optional math libraries can provide 10-100x speed improvement for mathematical operations.

CONSTANTS

The Sidef module defines several internal constants:

  • UPDATE_SEC - 18000 seconds (5 hours)

    Interval for updating cache access timestamps.

  • DELETE_SEC - 172800 seconds (2 days)

    Age threshold for cache entry deletion.

  • SANITIZE_SEC - 259200 seconds (3 days)

    Interval between cache sanitization runs.

PACKAGE VARIABLES

  • $Sidef::VERSION - Current version string

  • $Sidef::SPACES - Current indentation level (for deparsing)

  • $Sidef::SPACES_INCR - Indentation increment (4 spaces)

  • %Sidef::INCLUDED - Tracks included modules

  • %Sidef::EVALS - Information for eval() handling

  • $Sidef::PARSER - Current parser instance

  • $Sidef::DEPARSER - Current deparser instance

SEE ALSO

BUGS AND LIMITATIONS

Please report bugs via the GitHub issue tracker at https://github.com/trizen/sidef/issues.

Known limitations:

  • Unicode support depends on Perl's Unicode implementation

  • Performance for some operations may not match natively compiled languages

  • DBM cache is not thread-safe without external synchronization

  • Very large source files may exceed DBM record size limits

ACKNOWLEDGMENTS

Sidef builds upon decades of programming language research and draws inspiration from many sources:

  • Ruby for elegant syntax and object model

  • Raku for advanced language features and metaprogramming

  • Go for design simplicity

  • Perl for providing the robust foundation

Special thanks to the Perl community for providing the robust foundation upon which Sidef is built, and to all contributors who have helped improve the language.

AUTHORS

  • Daniel Șuteu (trizen) - Lead developer and maintainer

    Primary developer responsible for language design, implementation, and maintenance.

  • Ioana Fălcușan - Core contributor

    Contributions to language features and standard library in the early days of Sidef.

LICENSE AND COPYRIGHT

Copyright (C) 2013-2026 Daniel Șuteu, Ioana Fălcușan.

This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0. You may obtain a copy of the Artistic License 2.0 at:

http://www.perlfoundation.org/artistic_license_2_0

Disclaimer of Warranty

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.