//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
// PLEASE DO NOT EDIT WITHOUT THE EXPLICIT CONSENT OF THE AUTHOR! \\
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

package hlt.language.design.instructions;

/**
 * @version     Last modified on Wed Jun 20 14:29:51 2012 by hak
 * @author      <a href="mailto:hak@acm.org">Hassan A&iuml;t-Kaci</a>
 * @copyright   &copy; <a href="http://www.hassan-ait-kaci.net/">by the author</a>
 */

import hlt.language.design.backend.Runtime;
import hlt.language.design.backend.Indexable;
import hlt.language.design.backend.IntSet;
import hlt.language.design.backend.RuntimeSet;
import hlt.language.design.backend.IntRange;
import hlt.language.design.backend.ArrayAllocationErrorException;

public class ReconcileIndexables extends Instruction
{
  public ReconcileIndexables ()
    {
      setName("RECONCILE_INDEXABLES");
    }

  public final void execute (Runtime r) throws ArrayAllocationErrorException
    {
      Indexable indexable = (Indexable)r.popObject();
      Indexable indexset = (Indexable)r.objectResult();

      int[] permutation = null;

      if (indexset instanceof RuntimeSet || indexable instanceof IntSet)
        {
          RuntimeSet set = indexset instanceof RuntimeSet
                         ? (RuntimeSet)indexset
                         : ((IntRange)indexset).toIntSet();

          permutation = new int[indexable.size()];
          if (!set.equals(indexable,permutation))
            throw new ArrayAllocationErrorException
              ("can't initialize a map from one with a different index set");
        }
      else
        if (!indexset.equals(indexable))
          throw new ArrayAllocationErrorException
            ("can't initialize a map from one with a different index set");

      r.pushObject(permutation);
      r.incIP();
    }
}
