NAME

Sidef::Deparse::Perl - Deparse Sidef AST to Perl source code

VERSION

This documentation refers to Sidef::Deparse::Perl

SYNOPSIS

use Sidef::Deparse::Perl;

# Create a new deparser instance
my $deparser = Sidef::Deparse::Perl->new(
    opt => {
        w => 1,      # Enable warnings with stack traces
        P => 128,    # Set precision for Number operations
        M => 'zero', # Set rounding mode
    }
);

# Deparse a Sidef AST structure to Perl code
my $perl_code = $deparser->deparse($ast_structure);

# Execute the generated Perl code
eval $perl_code;

DESCRIPTION

Sidef::Deparse::Perl is a core component of the Sidef programming language that converts Sidef Abstract Syntax Tree (AST) structures into executable Perl source code. It acts as a transpiler from Sidef's high-level syntax to Perl, enabling Sidef programs to run on the Perl runtime.

The deparser handles all Sidef language constructs including variables, control flow structures, object-oriented features, operators, and more. It performs optimizations, manages namespaces, handles scoping, and generates efficient Perl code that maintains Sidef's semantics.

CONSTRUCTOR

new

my $deparser = Sidef::Deparse::Perl->new(%options);

Creates and returns a new deparser instance.

Parameters:

  • before - Code to prepend before the deparsed output (default: '')

  • header - Header code including pragmas and setup (default: auto-generated)

  • top_program - Top-level program code (default: '')

  • between - Separator between statements (default: ';')

  • after - Code to append after deparsed output (default: ';')

  • opt - Hash reference of compiler options:

    • w - Enable warnings with Carp::cluck on warn

    • W - Enable warnings and die handlers with Carp::confess

    • P - Set numerical precision (e.g., 128 for 512 bits)

    • M - Set rounding mode ('zero', '+inf', '-inf', 'inf', 'faith')

    • c - Use __load_sidef_module__ instead of 'use' statements

    • i - Interactive mode flag

  • environment_name - Name of the execution environment (default: 'main')

Returns: A blessed Sidef::Deparse::Perl object

METHODS

Core Deparsing Methods

deparse

my $perl_code = $deparser->deparse($ast_structure);

Main entry point for deparsing. Converts a complete Sidef AST structure into executable Perl source code.

Parameters:

  • $ast_structure - Hash reference containing the AST to deparse

Returns: String containing the generated Perl code

deparse_script

my @statements = $deparser->deparse_script($struct);

Deparses a script structure into an array of Perl statement strings.

Parameters:

  • $struct - Hash reference containing statements organized by class

Returns: Array of deparsed statement strings (in array context) or the last statement (in scalar context)

deparse_expr

my $perl_expr = $deparser->deparse_expr($expression);

Deparses a single Sidef expression into Perl code.

Parameters:

  • $expression - Hash reference containing the expression AST

Returns: String containing the deparsed Perl expression

deparse_args

my $args = $deparser->deparse_args(@arguments);

Deparses a list of arguments into Perl function call syntax.

Parameters:

  • @arguments - List of argument expressions

Returns: String in the format (arg1, arg2, ...)

deparse_generic

my $code = $deparser->deparse_generic($before, $sep, $after, @items);

Generic deparsing with customizable delimiters.

Parameters:

  • $before - String to prepend

  • $sep - Separator between items

  • $after - String to append

  • @items - Items to deparse

Returns: String with items joined by separator and wrapped

Block and Scope Management

deparse_block_with_scope

my $block_code = $deparser->deparse_block_with_scope($block_obj);

Deparses a code block with proper scoping and variable declarations.

Parameters:

  • $block_obj - Block object containing code and scope information

Returns: String containing the block code wrapped in braces

deparse_bare_block

my $block = $deparser->deparse_bare_block(@statements);

Deparses statements into a bare block without scope handling.

Parameters:

  • @statements - List of statements

Returns: String containing { statement1; statement2; ... }

localize_declarations

my $decl_code = $deparser->localize_declarations($refaddr);

Localizes variable and function declarations for a specific scope.

Parameters:

  • $refaddr - Reference address of the scope

Returns: String containing the declaration code

Helper Methods

make_constant

my $const_ref = $deparser->make_constant(
    $ref_type, $method, $name,
    args => \@args,
    sub  => 1,
    new  => 0
);

Creates a Perl constant for immutable Sidef values.

Parameters:

  • $ref_type - The reference type/class

  • $method - Constructor method name

  • $name - Base name for the constant

  • args - Array reference of constructor arguments

  • sub - Boolean: use '::' instead of '->' (default: 0)

  • new - Boolean: start a new constant block (default: 0)

Returns: String referencing the created constant

top_add

$deparser->top_add($code_line);

Adds code to the top of the generated program (idempotent).

Parameters:

  • $code_line - Line of code to add to the top

load_mod

$deparser->load_mod($module_name);

Ensures a Sidef module is loaded in the generated code.

Parameters:

  • $module_name - Fully qualified module name

Type and Metadata Methods

_get_reftype

my $type = $deparser->_get_reftype($object);

Determines the reference type of a Sidef object, loading required modules.

Parameters:

  • $object - Sidef object

Returns: String containing the type name

_dump_reftype

my $quoted_type = $deparser->_dump_reftype($object);

Returns a quoted string representation of an object's type.

Parameters:

  • $object - Sidef object

Returns: Quoted string like "Sidef::Types::Number::Number"

_dump_class_name

my $class_name = $deparser->_dump_class_name($class_obj);

Generates a unique fully-qualified class name.

Parameters:

  • $class_obj - Class object

Returns: String like main::12345678::ClassName::SubClass

Data Structure Dumping

_dump_string

my $perl_string = $deparser->_dump_string($string);

Converts a string into properly escaped Perl double-quoted string literal.

Parameters:

  • $string - String to dump

Returns: Escaped Perl string literal

_dump_array

my $array_code = $deparser->_dump_array($ref_type, $array_ref);

Deparses a Sidef array into Perl blessed array reference.

Parameters:

  • $ref_type - Target array type

  • $array_ref - Array reference containing elements

Returns: String like bless([elem1, elem2], 'Type')

_dump_var

my $var_name = $deparser->_dump_var($var_obj, %options);

Generates the Perl variable name from a Sidef variable object.

Parameters:

  • $var_obj - Variable object

  • init - Boolean: include sigil for initialization

  • refaddr - Reference address to use (optional)

Returns: String containing the variable name (e.g., $varname12345)

_dump_op_call

my $op_ref = $deparser->_dump_op_call($method_name);

Creates a reference to an operator method, stored as a top-level variable.

Parameters:

  • $method_name - Name of the operator method

Returns: String like ->$main::OP1234

Variable Initialization

_dump_init_vars

my $init_code = $deparser->_dump_init_vars($init_obj);

Generates initialization code for a set of variables.

Parameters:

  • $init_obj - Initialization object with vars and optional args

Returns: String containing the initialization code

_dump_sub_init_vars

my $param_code = $deparser->_dump_sub_init_vars(@vars);

Generates subroutine parameter initialization code.

Parameters:

  • @vars - List of variable objects

Returns: String containing parameter unpacking code

_dump_class_attributes

my $attr_code = $deparser->_dump_class_attributes(@attributes);

Generates code for class attribute initialization.

Parameters:

  • @attributes - List of attribute objects

Returns: String containing attribute setup code

_dump_static_var

my $static_code = $deparser->_dump_static_var($var, $refaddr);

Generates code for a static variable with state keyword.

Parameters:

  • $var - Variable object

  • $refaddr - Reference address

Returns: String containing state $var = ...

Index and Lookup Methods

_dump_indices

my $indices = $deparser->_dump_indices($array_ref);

Converts array indices into Perl array access format.

Parameters:

  • $array_ref - Array reference of index expressions

Returns: Comma-separated string of indices

_dump_lookups

my $keys = $deparser->_dump_lookups($array_ref);

Converts hash keys into Perl hash access format.

Parameters:

  • $array_ref - Array reference of key expressions

Returns: Comma-separated string of keys

_dump_var_attr

my $attrs = $deparser->_dump_var_attr(@vars);

Generates variable attribute metadata.

Parameters:

  • @vars - List of variable objects

Returns: String containing vars and table metadata

Inheritance Methods

_get_inherited_stuff

my @items = $deparser->_get_inherited_stuff($classes, $callback);

Recursively collects inherited attributes using a callback.

Parameters:

  • $classes - Array reference of class objects

  • $callback - Code reference to extract data from each class

Returns: List of collected items from the inheritance chain

INTERNAL HANDLER METHODS

The deparser uses a dispatch table to handle different AST node types. Each handler method follows the naming convention _deparse_* and processes a specific type of Sidef construct.

Variable Handlers

  • _deparse_variable - Standard variables and functions

  • _deparse_local - Local variable declarations

  • _deparse_class_var - Class-scoped variables

  • _deparse_define - Constant definitions with 'define'

  • _deparse_const - Runtime constants

  • _deparse_static - Static variables

  • _deparse_const_init - Constant initialization

  • _deparse_init - Variable initialization

  • _deparse_class_init - Class initialization

  • _deparse_ref_ok - Variable references (handled specially)

Control Flow Handlers

  • _deparse_if - If/elsif/else conditionals

  • _deparse_while - While loops

  • _deparse_foreach - Foreach iterations

  • _deparse_cfor - C-style for loops

  • _deparse_forin - For-in loops over iterables

  • _deparse_loop - Infinite loops

  • _deparse_do - Do blocks

  • _deparse_break - Break statements

  • _deparse_next - Next/continue statements

  • _deparse_return - Return statements

  • _deparse_continue - Continue flag in given/when

Block Handlers

  • _deparse_block_init - Block initialization

  • _deparse_given - Given/when switch statements

  • _deparse_when - When clauses

  • _deparse_case - Case clauses

  • _deparse_default - Default clauses

  • _deparse_with - With blocks (defined checks)

  • _deparse_gather - Gather blocks for lazy collection

  • _deparse_take - Take statements within gather

  • _deparse_try - Try/catch exception handling

Literal and Data Type Handlers

  • _deparse_number - Number literals

  • _deparse_string - String literals

  • _deparse_array - Array literals

  • _deparse_vector - Vector literals

  • _deparse_matrix - Matrix literals

  • _deparse_hash - Hash literals

  • _deparse_bool - Boolean values

  • _deparse_nil - Nil/undef values

  • _deparse_null - Null objects

  • _deparse_regex - Regular expressions

  • _deparse_complex - Complex numbers

  • _deparse_pair - Pair objects

Object-Oriented Handlers

  • _deparse_struct - Struct definitions

  • _deparse_subset - Subset type definitions

  • _deparse_class_attr_ok - Class attributes

  • _deparse_module_oo - Object-oriented module imports

  • _deparse_module_func - Functional module imports

Special Construct Handlers

  • _deparse_ternary - Ternary conditional operator

  • _deparse_named_param - Named function parameters

  • _deparse_prefix_method - Prefix method calls

  • _deparse_unary_ok - Unary operators

  • _deparse_eval - Eval expressions

  • _deparse_assert - Assertion statements

  • _deparse_error - Error/die statements

  • _deparse_warning - Warning statements

  • _deparse_label - Statement labels

  • _deparse_builtin - Built-in function calls

I/O and System Handlers

  • _deparse_stdin - STDIN filehandle

  • _deparse_stdout - STDOUT filehandle

  • _deparse_stderr - STDERR filehandle

  • _deparse_argf - ARGF filehandle

  • _deparse_data - DATA filehandle

  • _deparse_magic - Magic variables

  • _deparse_backtick - Backtick command execution

  • _deparse_pipe - Pipe objects

  • _deparse_file - File objects

  • _deparse_dir - Directory objects

Metadata Handlers

  • _deparse_perl_code - Embedded Perl code

  • _deparse_parser - Parser object references

  • _deparse_meta_module - Module metadata

  • _deparse_included - Included file handling

  • _deparse_unimplemented - Unimplemented features

CONFIGURATION HASHES

The module uses several package-scoped configuration hashes:

%DEFAULT_OPTS

Default options for the deparser instance.

%ASSIGNMENT_OPS

Maps Sidef assignment operators to Perl equivalents.

%LAZY_OPS

Maps lazy evaluation operators (||, &&, //, etc.).

%OVERLOAD_METHODS

Maps operators to overload method names.

%REASSIGN_OPS

Maps compound assignment operators (+=, -=, etc.).

%INC_DEC_OPS

Maps increment/decrement operators to method names.

%COMPOSITE_CONSTANTS

Defines composite constant types like Range, Gauss, Fraction.

%DATA_TYPES

Maps old Sidef::DataTypes namespace to new Sidef::Types namespace.

%handlers

Dispatch table mapping AST node types to handler method names.

INTERNAL STATE

The deparser maintains several pieces of state during operation:

  • current_block - Reference address of the current block scope

  • current_namespace - Current namespace context

  • function - Reference address of current function being deparsed

  • class - Reference address of current class being deparsed

  • class_name - Name of the current class

  • package_name - Name of the current Perl package

  • parent_name - [$type, $name] of parent construct

  • depth - Current nesting depth

  • ref_class - Boolean indicating if in reference class

  • block_declarations - Array of block-scoped declarations

  • function_declarations - Array of function declarations

  • inherit - Inheritance information

  • class_vars - Class variable definitions

  • class_attributes - Class attribute definitions

OPERATOR HANDLING

The deparser handles Sidef operators through several mechanisms:

Lazy Operators

Operators like ||, &&, ?, and // are handled specially to preserve short-circuit evaluation semantics.

Assignment Operators

Simple assignment (=) and compound assignments (+=, -=, etc.) are converted to Perl equivalents, with compound assignments wrapped in lvalue subroutines.

Increment/Decrement

Pre-increment (++$x) and post-increment ($x++) operators are handled differently to maintain proper semantics and return values.

Comparison Operators

Comparison operators (==, !=, <=>, ~~, !~) are converted to appropriate Perl operations, with proper handling of Sidef's Bool objects.

Unary Operators

Unary operators (!, -, +, @, ~, etc.) are handled with special cases for constant folding and type conversions.

CONSTANT OPTIMIZATION

The deparser performs constant optimization for:

  • Number literals (cached to avoid recreation)

  • String literals (cached and converted to String objects)

  • Composite constants (Range, Complex, Fraction, etc.)

  • Negation of number literals (constant folding)

Constants are created using the use constant pragma and stored in the environment namespace for efficient reuse.

SCOPE AND NAMESPACE MANAGEMENT

Scope Tracking

The deparser maintains scope information through:

  • Reference addresses (refaddr) for uniqueness

  • Block nesting depth tracking

  • Declaration arrays for lexical scoping

Namespace Handling

  • Global variables use fully-qualified names

  • Class methods are installed in package symbol tables

  • Module loading is tracked to avoid duplicates

  • Environment namespace prefix for constants

CLASS AND OBJECT HANDLING

Class Definition

Classes are deparsed into Perl packages with:

  • Parent class relationships via use parent

  • Constructor methods (new/call)

  • Accessor methods for attributes

  • Method overloading support

  • Symbol table manipulation for method installation

Struct Types

Structs create lightweight objects with:

  • Blessed hash references

  • Lvalue accessor methods

  • Constructor validation

Subset Types

Subset types create type constraints with:

  • Inheritance from parent types

  • Custom validation blocks

  • __subset_validation__ hooks

MEMORY MANAGEMENT

The deparser uses several caching mechanisms:

  • %addr - Tracks already-deparsed objects by reference address

  • %top_add - Prevents duplicate top-level code additions

  • %constant_number_cache - Caches number constant definitions

  • %constant_string_cache - Caches string constant definitions

  • _reftype_cache - Caches module loading state

These caches are cleared on each new() call to prevent memory leaks.

ERROR HANDLING

Error handling constructs are deparsed as follows:

  • die statements include file and line information

  • warn statements include file and line information

  • assert generates runtime checks with custom messages

  • Try/catch blocks use Sidef's exception handling system

EXAMPLES

Basic Usage

use Sidef::Deparse::Perl;
use Sidef::Parser;

# Parse Sidef code
my $parser = Sidef::Parser->new;
my $ast = $parser->parse_script(code => 'say "Hello, World!"');

# Deparse to Perl
my $deparser = Sidef::Deparse::Perl->new;
my $perl_code = $deparser->deparse($ast);

# Execute
eval $perl_code;

With Compiler Options

my $deparser = Sidef::Deparse::Perl->new(
    opt => {
        w => 1,      # Enable warnings
        P => 256,    # 1024-bit precision
        M => 'zero', # Round toward zero
    }
);

Custom Environment

my $deparser = Sidef::Deparse::Perl->new(
    environment_name => 'MyApp',
    before => 'use strict; use warnings;',
    after  => 'exit 0;',
);

DEPENDENCIES

PERFORMANCE CONSIDERATIONS

  • Reference addresses are used for uniqueness to avoid string comparisons

  • Constants are cached to avoid recreation

  • Module loading is tracked to avoid redundant use statements

  • Handler dispatch uses a hash table for O(1) lookups

  • Scope management uses arrays instead of hashes where possible

LIMITATIONS

  • Generated code is not optimized for human readability

  • Variable names include reference addresses for uniqueness

  • Some Sidef constructs may generate verbose Perl code

  • The deparser assumes a working Sidef installation

DEBUGGING

To debug the deparser:

  • Set w or W options for stack traces

  • Examine the before, header, and top_program fields

  • Use Data::Dumper on the AST structure

  • Check the generated Perl code for syntax errors

SEE ALSO

AUTHOR

Daniel Șuteu (trizen)

LICENSE

This module is free software; you can redistribute it and/or modify it under the same terms as Sidef itself.