=encoding utf8

=head1 NAME

Sidef::Deparse::Sidef - Deparse Sidef abstract syntax trees back into Sidef source code

=head1 SYNOPSIS

    use Sidef::Deparse::Sidef;
    
    # Create a new deparser instance
    my $deparser = Sidef::Deparse::Sidef->new(
        before       => '',
        between      => ";\n",
        after        => ";\n",
        class        => 'main',
        extra_parens => 0,
    );
    
    # Deparse an AST structure
    my $code = $deparser->deparse($ast);
    
    # Deparse individual expressions
    my $expr_code = $deparser->deparse_expr({self => $expression});
    
    # Deparse with arguments
    my $args_code = $deparser->deparse_args(@arguments);

=head1 DESCRIPTION

C<Sidef::Deparse::Sidef> is the deparsing component of the Sidef programming language. 
It takes abstract syntax tree (AST) structures generated by the Sidef parser and 
reconstructs them into valid Sidef source code. This is useful for code analysis, 
transformation, pretty-printing, and metaprogramming tasks.

The deparser maintains information about data types, handles complex nested structures, 
and preserves semantic meaning while generating readable code output.

=head1 CONSTRUCTOR

=head2 new

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

Creates a new deparser instance with the specified options.

B<Options:>

=over 4

=item * C<before> - String to prepend before the deparsed output (default: '')

=item * C<between> - String to insert between statements (default: ";\n")

=item * C<after> - String to append after the deparsed output (default: ";\n")

=item * C<class> - Current class context for deparsing (default: 'main')

=item * C<extra_parens> - Whether to add extra parentheses for clarity (default: 0)

=item * C<opt> - Hash reference for additional options (default: {})

=item * C<data_types> - Hash reference mapping internal types to Sidef type names

=back

The constructor also initializes a comprehensive mapping of Sidef data types, including:

=over 4

=item * Basic types (Bool, String, Number, Array, Hash, etc.)

=item * Numeric types (Complex, Fraction, Polynomial, Quaternion, etc.)

=item * Range types (Range, RangeNum, RangeStr)

=item * File and I/O types (File, Dir, FileHandle, Socket, etc.)

=item * Control flow types (Block, next, break, continue)

=item * Special types (nil, null, Lazy, Enumerator, etc.)

=back

=head1 METHODS

=head2 Core Deparsing Methods

=head3 deparse

    my $code = $deparser->deparse($struct);

Main entry point for deparsing a complete AST structure. Takes a hash reference 
representing the AST and returns the complete deparsed Sidef source code.

The method processes all statements in the structure, joins them with the configured 
separator, and adds before/after strings.

=head3 deparse_script

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

Deparses a script structure (hash of class-keyed expression arrays). In list context, 
returns an array of deparsed statements. In scalar context, returns only the last statement.

=head3 deparse_expr

    my $code = $deparser->deparse_expr($expr);

Deparses a single expression. The C<$expr> parameter is typically a hash reference 
with a C<self> key containing the object to deparse, and optional C<call>, C<ind>, 
or other keys for method calls and indexing operations.

This is the most complex method in the deparser, handling numerous Sidef language 
constructs including:

=over 4

=item * Variables (var, static, const, has, global)

=item * Functions and methods

=item * Classes, structs, and subsets

=item * Control structures (if, while, for, given, when, etc.)

=item * Blocks and closures

=item * Operators and method calls

=item * Literals (numbers, strings, arrays, hashes)

=item * Special constructs (try/catch, gather/take, etc.)

=back

=head2 Generic Deparsing Utilities

=head3 deparse_generic

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

Generic method for deparsing a list of arguments with configurable delimiters. 
Used internally by other deparsing methods.

=over 4

=item * C<$before> - String to prepend

=item * C<$sep> - Separator between elements

=item * C<$after> - String to append

=item * C<@args> - List of arguments to deparse (can be strings, hash refs, or objects)

=back

=head3 deparse_args

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

Deparses a list of arguments enclosed in parentheses with comma separation.
Equivalent to C<deparse_generic('(', ', ', ')', @args)>.

=head3 deparse_bare_block

    my $code = $deparser->deparse_bare_block(@args);

Deparses a bare block structure with proper indentation. Used for blocks that 
don't have the standard block syntax (like in loops or conditionals).

=head2 Variable and Type Handling

=head3 _dump_vars

    my $code = $deparser->_dump_vars(@vars);

Internal method that deparses variable declarations. Handles:

=over 4

=item * Variable sigils (*, : for arrays and hashes)

=item * Class qualification (Class::var)

=item * Type constraints

=item * Subsets

=item * Where clauses (conditions)

=item * Default values

=back

=head3 _dump_init_vars

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

Deparses variable initialization constructs (var, has, const, etc.) with optional 
assignment from arguments.

=head3 _dump_reftype

    my $type_name = $deparser->_dump_reftype($obj);

Returns the Sidef type name for a given object reference. Handles special cases 
like ClassInit, Struct, and Subset types.

=head3 _dump_class_name

    my $name = $deparser->_dump_class_name($obj);

Extracts and formats the fully qualified class name from a class-related object.

=head2 Literal Deparsing

=head3 _dump_string

    my $code = $deparser->_dump_string($str);

Deparses a string literal, properly escaping special characters and wrapping in quotes.

=head3 _dump_number

    my $code = $deparser->_dump_number($num);

Deparses a number literal. Handles:

=over 4

=item * Special values (Inf, NaN)

=item * Floating point numbers (with 'f' suffix)

=item * Complex numbers (using Complex constructor)

=item * Rational numbers (fractions)

=item * Regular integers and decimals

=back

=head3 _dump_array

    my $code = $deparser->_dump_array($array);

Deparses an array literal with square bracket notation [elem1, elem2, ...].

=head1 SUPPORTED LANGUAGE CONSTRUCTS

The deparser handles the complete Sidef language syntax, including:

=head2 Variable Declarations

    var x = 42
    const PI = 3.14159
    static counter = 0
    has @items
    global $config

=head2 Functions and Methods

    func fibonacci(n) {
        # ...
    }
    
    method calculate(x, y) -> Number {
        # ...
    }
    
    func cached_result() is cached {
        # ...
    }

=head2 Classes and Objects

    class Point(x, y) {
        method distance(other) {
            # ...
        }
    }
    
    class Circle < Shape {
        # ...
    }

=head2 Structs and Subsets

    struct Person {
        String name,
        Number age
    }
    
    subset PositiveInt < Number {
        .is_pos && .is_int
    }

=head2 Control Flow

    if (condition) {
        # ...
    } elsif (other) {
        # ...
    } else {
        # ...
    }
    
    while (running) {
        # ...
    }
    
    for i in (1..10) {
        # ...
    }
    
    foreach item in array {
        # ...
    }

=head2 Pattern Matching

    given value {
        when (1) { "one" }
        when (2) { "two" }
        default  { "other" }
    }
    
    case (x) {
        # ...
    }

=head2 Exception Handling

    try {
        # risky operation
    } catch {
        warn "Error occurred"
    }

=head2 Operators and Expressions

    x + y * z
    array[index]
    hash{key}
    obj->method(args)
    condition ? true_val : false_val

=head2 Special Constructs

    gather {
        take(1)
        take(2)
    }
    
    do {
        # ...
    }
    
    loop {
        # ...
    }
    
    eval { ... }
    
    local(x)

=head1 INDENTATION AND FORMATTING

The deparser uses the global variables C<$Sidef::SPACES> and C<$Sidef::SPACES_INCR> 
to manage indentation:

=over 4

=item * C<$Sidef::SPACES> - Current indentation level (in spaces)

=item * C<$Sidef::SPACES_INCR> - Indentation increment per nesting level

=back

The deparser automatically adjusts indentation when entering and exiting blocks, 
creating readable, properly formatted output.

=head1 CIRCULAR REFERENCE HANDLING

The deparser maintains an internal C<%addr> hash (using C<refaddr>) to track 
already-deparsed objects and prevent infinite recursion when dealing with:

=over 4

=item * Recursive function definitions

=item * Mutually referencing classes

=item * Self-referential data structures

=item * Circular class inheritance

=back

When an object is encountered for the second time, the deparser outputs a reference 
or placeholder (like C<__FUNC__> or C<__BLOCK__>) instead of recursing infinitely.

=head1 DATA AFTER __DATA__

The deparser handles the special C<__DATA__> marker. When a DATA section is 
encountered, it appends the data content to the C<after> field to ensure it's 
included in the final output.

=head1 EXAMPLES

=head2 Basic Usage

    use Sidef::Deparse::Sidef;
    
    my $deparser = Sidef::Deparse::Sidef->new();
    
    # Assuming $ast is a parsed Sidef AST
    my $source_code = $deparser->deparse($ast);
    print $source_code;

=head2 Custom Formatting

    my $deparser = Sidef::Deparse::Sidef->new(
        between => ";\n\n",  # Double space between statements
        after   => ";\n\n",
    );

=head2 Deparsing with Extra Parentheses

    my $deparser = Sidef::Deparse::Sidef->new(
        extra_parens => 1,  # Add extra parens for clarity
    );

=head1 INTERNAL STRUCTURE

The deparser works with AST structures that are typically hash references with 
specific keys:

=over 4

=item * C<self> - The primary object/expression

=item * C<call> - Array of method calls to apply

=item * C<ind> - Array of index operations

=item * C<arg> - Arguments for operations

=item * C<block> - Block/closure code

=back

Different Sidef object types (Variable, Block, Class, etc.) have their own 
internal structures that the deparser knows how to handle.

=head1 LIMITATIONS

=over 4

=item * The deparser assumes well-formed AST input

=item * Some internal optimizations in the AST may not be perfectly preserved

=item * Comments are not preserved (as they're typically not part of the AST)

=item * The exact original formatting/whitespace is not preserved

=back

=head1 SEE ALSO

=over 4

=item * L<Sidef::Parser> - The Sidef parser that generates ASTs

=item * L<Sidef> - The main Sidef language module

=item * L<https://github.com/trizen/sidef> - Sidef language repository

=back

=head1 AUTHOR

Daniel "trizen" Șuteu

=head1 LICENSE

This module is part of the Sidef programming language and is licensed under 
the same terms as Sidef itself.

=cut
