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 warnW- Enable warnings and die handlers with Carp::confessP- 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' statementsi- 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 constantargs- Array reference of constructor argumentssub- 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 objectinit- Boolean: include sigil for initializationrefaddr- 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 scopecurrent_namespace- Current namespace contextfunction- Reference address of current function being deparsedclass- Reference address of current class being deparsedclass_name- Name of the current classpackage_name- Name of the current Perl packageparent_name- [$type, $name] of parent constructdepth- Current nesting depthref_class- Boolean indicating if in reference classblock_declarations- Array of block-scoped declarationsfunction_declarations- Array of function declarationsinherit- Inheritance informationclass_vars- Class variable definitionsclass_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 parentConstructor 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:
diestatements include file and line informationwarnstatements include file and line informationassertgenerates runtime checks with custom messagesTry/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
Scalar::Util - For refaddr()
Sidef::Types::Number::Number - Number type operations
Various Sidef::Types::* modules - Loaded dynamically as needed
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
worWoptions for stack tracesExamine the
before,header, andtop_programfieldsUse Data::Dumper on the AST structure
Check the generated Perl code for syntax errors
SEE ALSO
Sidef - The Sidef programming language
Sidef::Parser - Sidef parser that generates ASTs
Sidef::Types::* - Sidef type system modules
B::Deparse - Perl's built-in deparser
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.