expr/operator-bool.go

110 lines
2.1 KiB
Go
Raw Normal View History

2024-03-26 08:45:18 +01:00
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
2024-03-26 07:00:53 +01:00
// operator-bool.go
package expr
//-------- NOT term
func newNotTerm(tk *Token) (inst *term) {
return &term{
tk: *tk,
class: classOperator,
kind: kindBool,
children: make([]*term, 0, 1),
position: posPrefix,
priority: priNot,
evalFunc: evalNot,
}
}
func evalNot(ctx exprContext, self *term) (v any, err error) {
var rightValue any
if rightValue, err = self.evalPrefix(ctx); err != nil {
return
}
if b, ok := toBool(rightValue); ok {
v = !b
} else {
err = self.errIncompatibleType(rightValue)
}
return
}
//-------- AND term
func newAndTerm(tk *Token) (inst *term) {
return &term{
tk: *tk,
class: classOperator,
kind: kindBool,
children: make([]*term, 0, 2),
position: posInfix,
priority: priAnd,
evalFunc: evalAnd,
}
}
func evalAnd(ctx exprContext, self *term) (v any, err error) {
var leftValue, rightValue any
var leftBool, rightBool bool
var lok, rok bool
if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
return
}
leftBool, lok = toBool(leftValue)
rightBool, rok = toBool(rightValue)
if lok && rok {
v = leftBool && rightBool
} else {
err = self.errIncompatibleTypes(leftValue, rightValue)
}
return
}
//-------- OR term
func newOrTerm(tk *Token) (inst *term) {
return &term{
tk: *tk,
class: classOperator,
kind: kindBool,
children: make([]*term, 0, 2),
position: posInfix,
priority: priOr,
evalFunc: evalOr,
}
}
func evalOr(ctx exprContext, self *term) (v any, err error) {
var leftValue, rightValue any
var leftBool, rightBool bool
var lok, rok bool
if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
return
}
leftBool, lok = toBool(leftValue)
rightBool, rok = toBool(rightValue)
if lok && rok {
v = leftBool || rightBool
} else {
err = self.errIncompatibleTypes(leftValue, rightValue)
}
return
}
// init
func init() {
registerTermConstructor(SymNot, newNotTerm)
registerTermConstructor(SymAnd, newAndTerm)
registerTermConstructor(SymOr, newOrTerm)
}