//
//  EXPTernOp.m
//  ExpTest
//
//  Created by Ashley on 08/01/2007.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "EXPExpression.h"
#import "EXPUnaryOp.h"
#import "EXPBinOp.h"
#import "EXPTernOp.h"
#import "EXPAssemblerConstants.h"

@implementation EXPTernOp

- (id) initWithLeft:(id)left andRight:(id)right andThird:(id)third
{
	[super initWithLeft:left AndRight:right];
	[self setThird:third];
	return self;
}

- (void) setThird:(id)third
{
	[third retain];
	[_third release];
	_third = third;
}

- (id) third
{
	return _third;
}

- (BOOL) compile:(EXPStackMachine *)machine error:(NSError **)err 
{
	EXPExpression *left = [self left];
	EXPExpression *right = [self right];
	EXPExpression *third = [self third];
	
	[left compile:machine error:err];
	[machine putUInt:BEQ];
	unsigned int branch1 = [machine pc];
	[machine putUInt:0];
	
	[right compile:machine error:err];
	[machine putUInt:BRA];
	unsigned int branch2 = [machine pc];
	[machine putUInt:0];
	
	[machine putUInt:[machine pc] at:branch1];
	[third compile:machine error:err];
	
	[machine putUInt:[machine pc] at:branch2];
	
	return YES;
}
	
- (NSString *)description
{
	return [NSString stringWithFormat:@"(%@) ? (%@) : (%@)", [[self left] description], [[self right] description], [[self third] description]];
}

- (double) result
{
	double y = [[self left] result];
	if ((int)y!=0) {
		return [[self right] result];
	} else {
		return [[self third] result];
	}
}

- (void)dealloc
{
//	printf("EXPTernOp - (void)dealloc\n");
	[_third release];
	[super dealloc];
}

@end
