package carray.ast;

import polyglot.ast.ArrayInit;
import polyglot.ast.NewArray;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.types.ArrayType;
import polyglot.types.Type;
import polyglot.util.Position;
import polyglot.util.SerialVersionUID;
import carray.visit.ArrayInitRemover;

public class CArrayArrayInitExt extends CArrayExt {
    private static final long serialVersionUID = SerialVersionUID.generate();

    @Override
    public ArrayInitRemover removeArrayInitEnter(ArrayInitRemover v) {
        if (v.inNewArray()) {
            // If this ArrayInit is a direct child of NewArray, undo this fact
            // as we are entering the scope of ArrayInit.
            return v.inNewArray(false);
        }
        return v;
    }

    @Override
    public Node removeArrayInit(ArrayInitRemover v) {
        if (!v.inNewArray()) {
            ArrayInit n = (ArrayInit) node();
            ArrayType type = n.type().toArray();
            Type ultimateBase = type.ultimateBase();
            int dims = type.dims();

            // { ... } --> new X[]{ ... }
            NodeFactory nf = v.nodeFactory();
            NewArray result =
                    nf.NewArray(n.position(),
                                nf.CanonicalTypeNode(Position.COMPILER_GENERATED,
                                                     ultimateBase),
                                dims,
                                n);
            return result.type(type);
        }
        return super.removeArrayInit(v);
    }
}
