/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.c.pre.expr;

import net.morilib.c.pre.CpreMacros;
import net.morilib.c.pre.parser.CpreOperatorType;

/**
 * 関係演算子の中間表現です。
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/04/13
 */
public class CpreRelationOp extends CpreExpression {

	private CpreOperatorType op;
	private CpreExpression e1, e2;

	/**
	 * 中間表現を生成します。
	 * 
	 * @param e 式1
	 * @param f 式2
	 * @param op 演算子
	 */
	public CpreRelationOp(CpreExpression e, CpreExpression f,
			CpreOperatorType op) {
		e1 = e;  e2 = f;  this.op = op;
	}

	@Override
	public CpreValue eval(int lineno, CpreMacros m) {
		CpreValue e = e1.eval(lineno, m), f = e2.eval(lineno, m);

		switch(op) {
		case EQ:
			return e.compareTo(f) == 0 ?
					CpreValue.TRUE : CpreValue.FALSE;
		case NE:
			return e.compareTo(f) != 0 ?
					CpreValue.TRUE : CpreValue.FALSE;
		case LT:
			return e.compareTo(f) <  0 ?
					CpreValue.TRUE : CpreValue.FALSE;
		case LE:
			return e.compareTo(f) <= 0 ?
					CpreValue.TRUE : CpreValue.FALSE;
		case GT:
			return e.compareTo(f) >  0 ?
					CpreValue.TRUE : CpreValue.FALSE;
		case GE:
			return e.compareTo(f) >= 0 ?
					CpreValue.TRUE : CpreValue.FALSE;
		default:  throw new RuntimeException();
		}
	}

}
