package CType::Structural;

# Common functions for all structural types

use 5.6.0;
use strict;
use warnings;

use CType::Fundamental qw/compare_ord/;

sub alignment_exprs
  {
    my $self = shift;
    return @{$self->{alignment_exprs}};
  }

sub compute_alignment
  {
    my $self = shift;

    my $alignment = 1;

    foreach my $a ($self->alignment_exprs)
      {
        my $n = $a->compute;
        if (not defined $alignment or $alignment < $n)
          {
            $alignment = $n;
          }
      }

    return $alignment;
  }

sub add_alignment
  {
    my $self = shift;
    my $new = shift;

    my @alignment;

    # We special-case the handling of explicit integer alignment
    if ($new->isa('CExpr::Integer'))
      {
        foreach my $a ($self->alignment_exprs)
          {
            if ($a->isa('CExpr::Integer'))
              {
                # Integer values are compared numerically
                if ($new->compute > $a->compute)
                  {
                    # Discard the current value in favour of the new one
                    next;
                  }
                else
                  {
                    # Discard the new value in favour of the current one
                    return;
                  }
              }
            else
              {
                # Integer values ignore non-integer ones
                push @alignment, $a;
              }
          }

        unshift @alignment, $new;
        $self->{alignment_exprs} = \@alignment;
        return;
      }

    foreach my $a ($self->alignment_exprs)
      {
        if ($new->isa('CExpr::Integer') and $a->isa('CExpr::Integer'))
          {
            # Integer values are compared numerically
            if ($new->compute > $a->compute)
              {
                # Discard the current value in favour of the new one
                next;
              }
            else
              {
                # Discard the new value in favour of the current one
                return;
              }
          }

        my $c = compare_ord($a, $new);
        if (defined $c and ($c == 1 or $c == 0))
          {
            # There is already an alignment listed which is ordinally
            # greater or equal, so we don't need to add this one
            return;
          }
        if (defined $c and ($c == -1))
          {
            # This alignment is ordinally greater than one which is
            # currently listed, so we dump the current one in favour
            # of this one
            next;
          }
        push @alignment, $a;
      }

    push @alignment, $new;
    $self->{alignment_exprs} = \@alignment;
  }

1;
