github.com/google/grumpy@v0.0.0-20171122020858-3ec87959189c/runtime/bool.go (about) 1 // Copyright 2016 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package grumpy 16 17 import ( 18 "fmt" 19 "reflect" 20 ) 21 22 // GetBool returns True if v is true, False otherwise. 23 func GetBool(v bool) *Int { 24 if v { 25 return True 26 } 27 return False 28 } 29 30 // BoolType is the object representing the Python 'bool' type. 31 var BoolType = newSimpleType("bool", IntType) 32 33 func boolNative(_ *Frame, o *Object) (reflect.Value, *BaseException) { 34 return reflect.ValueOf(toIntUnsafe(o).Value() != 0), nil 35 } 36 37 func boolNew(f *Frame, _ *Type, args Args, _ KWArgs) (*Object, *BaseException) { 38 argc := len(args) 39 if argc == 0 { 40 return False.ToObject(), nil 41 } 42 if argc != 1 { 43 return nil, f.RaiseType(TypeErrorType, fmt.Sprintf("bool() takes at most 1 argument (%d given)", argc)) 44 } 45 ret, raised := IsTrue(f, args[0]) 46 if raised != nil { 47 return nil, raised 48 } 49 return GetBool(ret).ToObject(), nil 50 } 51 52 func boolRepr(_ *Frame, o *Object) (*Object, *BaseException) { 53 i := toIntUnsafe(o) 54 if i.Value() != 0 { 55 return trueStr, nil 56 } 57 return falseStr, nil 58 } 59 60 func initBoolType(map[string]*Object) { 61 BoolType.flags &= ^(typeFlagInstantiable | typeFlagBasetype) 62 BoolType.slots.Native = &nativeSlot{boolNative} 63 BoolType.slots.New = &newSlot{boolNew} 64 BoolType.slots.Repr = &unaryOpSlot{boolRepr} 65 } 66 67 var ( 68 // True is the singleton bool object representing the Python 'True' 69 // object. 70 True = &Int{Object{typ: BoolType}, 1} 71 // False is the singleton bool object representing the Python 'False' 72 // object. 73 False = &Int{Object{typ: BoolType}, 0} 74 trueStr = NewStr("True").ToObject() 75 falseStr = NewStr("False").ToObject() 76 )