Skip to content
This repository was archived by the owner on Mar 23, 2023. It is now read-only.

Commit cb88351

Browse files
committed
Add pow builtin
1 parent 6bdfc4b commit cb88351

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

runtime/builtin_types.go

+15
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,20 @@ func builtinOrd(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
546546
return NewInt(result).ToObject(), nil
547547
}
548548

549+
func builtinPower(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
550+
argc := len(args)
551+
expectedTypes := []*Type{ObjectType, ObjectType}
552+
if argc == 3 {
553+
expectedTypes = append(expectedTypes, ObjectType)
554+
}
555+
if raised := checkFunctionArgs(f, "pow", args, expectedTypes...); raised != nil {
556+
return nil, raised
557+
}
558+
v := args[0]
559+
w := args[1]
560+
return binaryOp(f, v, w, v.typ.slots.Pow, v.typ.slots.RPow, w.typ.slots.RPow, "** or pow()")
561+
}
562+
549563
func builtinPrint(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
550564
sep := " "
551565
end := "\n"
@@ -787,6 +801,7 @@ func init() {
787801
"oct": newBuiltinFunction("oct", builtinOct).ToObject(),
788802
"open": newBuiltinFunction("open", builtinOpen).ToObject(),
789803
"ord": newBuiltinFunction("ord", builtinOrd).ToObject(),
804+
"pow": newBuiltinFunction("pow", builtinPower).ToObject(),
790805
"print": newBuiltinFunction("print", builtinPrint).ToObject(),
791806
"range": newBuiltinFunction("range", builtinRange).ToObject(),
792807
"raw_input": newBuiltinFunction("raw_input", builtinRawInput).ToObject(),

runtime/builtin_types_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@ func TestBuiltinFuncs(t *testing.T) {
294294
{f: "ord", args: wrapArgs("foo"), wantExc: mustCreateException(ValueErrorType, "ord() expected a character, but string of length 3 found")},
295295
{f: "ord", args: wrapArgs(NewUnicode("волн")), wantExc: mustCreateException(ValueErrorType, "ord() expected a character, but string of length 4 found")},
296296
{f: "ord", args: wrapArgs(1, 2, 3), wantExc: mustCreateException(TypeErrorType, "'ord' requires 1 arguments")},
297+
{f: "pow", args: wrapArgs(1), wantExc: mustCreateException(TypeErrorType, "'pow' requires 2 arguments")},
298+
{f: "pow", args: wrapArgs(2, 3), want: NewInt(8).ToObject()},
297299
{f: "range", args: wrapArgs(), wantExc: mustCreateException(TypeErrorType, "'__new__' of 'int' requires 3 arguments")},
298300
{f: "range", args: wrapArgs(3), want: newTestList(0, 1, 2).ToObject()},
299301
{f: "range", args: wrapArgs(10, 0), want: NewList().ToObject()},

0 commit comments

Comments
 (0)