// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// operator-shift.go
package expr

//-------- bit right shift term

func newRightShiftTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		children: make([]*term, 0, 2),
		position: posInfix,
		priority: priBinShift,
		evalFunc: evalRightShift,
	}
}

func bitRightShift(opTerm *term, leftValue, rightValue any) (v any, err error) {
	if IsInteger(leftValue) && IsInteger(rightValue) {
		leftInt := leftValue.(int64)
		rightInt := rightValue.(int64)
		v = leftInt >> rightInt
	} else {
		err = opTerm.errIncompatibleTypes(leftValue, rightValue)
	}
	return
}

func evalRightShift(ctx ExprContext, opTerm *term) (v any, err error) {
	var leftValue, rightValue any

	if leftValue, rightValue, err = opTerm.evalInfix(ctx); err != nil {
		return
	}

	v, err = bitRightShift(opTerm, leftValue, rightValue)
	return
}

func newLeftShiftTerm(tk *Token) (inst *term) {
	return &term{
		tk:       *tk,
		children: make([]*term, 0, 2),
		position: posInfix,
		priority: priBinShift,
		evalFunc: evalLeftShift,
	}
}

func bitLeftShift(opTerm *term, leftValue, rightValue any) (v any, err error) {
	if IsInteger(leftValue) && IsInteger(rightValue) {
		leftInt := leftValue.(int64)
		rightInt := rightValue.(int64)
		v = leftInt << rightInt
	} else {
		err = opTerm.errIncompatibleTypes(leftValue, rightValue)
	}
	return
}

func evalLeftShift(ctx ExprContext, opTerm *term) (v any, err error) {
	var leftValue, rightValue any

	if leftValue, rightValue, err = opTerm.evalInfix(ctx); err != nil {
		return
	}

	v, err = bitLeftShift(opTerm, leftValue, rightValue)
	return
}

// init
func init() {
	registerTermConstructor(SymDoubleGreater, newRightShiftTerm)
	registerTermConstructor(SymDoubleLess, newLeftShiftTerm)
}
