package jp.kirikiri.tjs2;

import java.util.Vector;

class ExprNode {
	private static final int MEMBERENSURE = 0x00000200; // create a member if not exists

	private int mOp;
	private int mPosition;
	private Vector<ExprNode> mNodes;
	private Variant mVal;

	public ExprNode() {
		mOp = 0;
		mNodes = null;
		mVal = null;
		mPosition = -1;
	}
	protected void finalize() {
		if( mNodes != null ) { mNodes.clear(); mNodes = null; }
		if( mVal != null ) { mVal.clear(); mVal = null; }
	}

	public void setOpecode( int op ) { mOp = op; }
	public void setPosition( int pos ) { mPosition = pos; }
	public void setValue( Variant val ) {
		if( mVal == null ) {
			mVal = new Variant(val);
		} else {
			mVal.copyRef( val );
		}
	}
	public void add( ExprNode node ) {
		if( mNodes == null ) mNodes = new Vector<ExprNode>();
		mNodes.add( node );
	}

	public int getOpecode() { return mOp; }
	public int getPosition() { return mPosition; }
	public Variant getValue() { return mVal; }
	public ExprNode getNode( int index ) {
		if( mNodes == null ) {
			return null;
		} else if( index < mNodes.size() ) {
			return mNodes.get( index );
		} else {
			return null;
		}
	}
	public int getSize() {
		if( mNodes == null ) return 0;
		else return mNodes.size();
	}
	public void addArrayElement( Variant val ) throws TJSException, VariantException {
		final String ss_add = "add";
		IntWrapper hint = new IntWrapper(ss_add.hashCode());
		Variant[] args = new Variant[1];
		args[0] = val;
		mVal.asObjectClosure().funcCall(0, ss_add, hint, null, args, null );
	}
	public void addDictionaryElement( String name, Variant val ) throws TJSException, VariantException {
		IntWrapper hint = new IntWrapper(name.hashCode());
		mVal.asObjectClosure().propSet(MEMBERENSURE, name, hint, val, null);
	}

	public void clear() {
		if( mNodes != null ) { mNodes.clear(); mNodes = null; }
		if( mVal != null ) { mVal.clear(); mVal = null; }
	}
}
