Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

binaryop and equals diff #432

Open
KaranaLJX opened this issue Oct 8, 2023 · 1 comment
Open

binaryop and equals diff #432

KaranaLJX opened this issue Oct 8, 2023 · 1 comment

Comments

@KaranaLJX
Copy link

for int and float type,Why is binaryop compatible with both int and float fields, but not with equal function?

func (o *Int) Equals(x Object) bool {
	t, ok := x.(*Int) //if x is float,then return false
	if !ok {
		return false
	}
	return o.Value == t.Value
}

func (o *Int) BinaryOp(op token.Token, rhs Object) (Object, error) {
	switch rhs := rhs.(type) {
	case *Int:

	case *Float: //here compatible with both int and float

	case *Char:

		}
	}
	return nil, ErrInvalidOperator
}
@KaranaLJX
Copy link
Author

		case parser.OpEqual:
			right := v.stack[v.sp-1]
			left := v.stack[v.sp-2]
			v.sp -= 2
			if left.Equals(right) { //here use Equals func
				v.stack[v.sp] = TrueValue
			} else {
				v.stack[v.sp] = FalseValue
			}
			v.sp++
		case parser.OpBinaryOp:
			v.ip++
			right := v.stack[v.sp-1]
			left := v.stack[v.sp-2]
			tok := token.Token(v.curInsts[v.ip])
			res, e := left.BinaryOp(tok, right) //here use binaryop func
			if e != nil {
				v.sp -= 2
				if e == ErrInvalidOperator {
					v.err = fmt.Errorf("invalid operation: %s %s %s",
						left.TypeName(), tok.String(), right.TypeName())
					return
				}
				v.err = e
				return
			}

			v.allocs--
			if v.allocs == 0 {
				v.err = ErrObjectAllocLimit
				return
			}

			v.stack[v.sp-2] = res
			v.sp--

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant