JavaScript的表达式解析器-5. 操作符的实现

整个结构建立好之后,操作符的实现就相当的简单了。

以左移操作为例:

var igame;

importNamespace( 'igame.Expression' );


igame.Expression.Operator.ShiftLeft = function ()
{
	igame.Expression.Operator.BinaryOperator.call( this );
	this.setToken( '<<' );
}

with ( igame.Expression )
{
	ClassDerive( Operator.ShiftLeft, 'ShiftLeft', Operator.BinaryOperator );

	Operator.ShiftLeft.prototype.evaluate = function ( operands )
	{
		Operator.BinaryOperator.prototype.evaluate.call( this, operands );

		var op2 = operands.pop();
		var op1 = operands.pop();

		if ( !( op2 instanceof Operand.Number ) )
			op2 = new Operand.Number( op2.getValue() );

		if ( !( op1 instanceof Operand.Number ) )
			op1 = new Operand.Number( op1.getValue() );

		if ( op1.getValue() < 0 )
			throw new Error( 'Shift count less than 0' );

		return new Operand.Number( op1.getValue() << op2.getValue() );
	}

} // with igame

当然还要适当的修改操作符的优先级。优先级定义在Operator.js中。

/*! Define operators' priority
* Use classname, not token(or operator)
*/
igame.Expression.Operator.OPERATOR_PRIORITY = {
	// Logic
	'Or': 0,
	'And': 0,
	// Compare
	'Greater': 1,
	'GreaterEqual': 1,
	'Equal': 1,
	'NotEquual': 1,
	'Less': 1,
	'LessEqual': 1,
	// Bitwise
	'BitwiseOr': 2,
	'BitwiseAnd': 2,
	'BitwiseXor': 2,
	// Mathematic
	'Add': 3,
	'Sub': 3,
	'Mul': 4,
	'Div': 4,
	'Mod': 4,
	'ShiftLeft': 4,
	'ShiftRight': 4,
	// Function
	'Function': 5,
	// Unary
	'Minus': 6,
	'Plus': 6,
	'Not': 6
};



你可能感兴趣的:(JavaScript,JavaScript,JavaScript,JavaScript,表达式)