pygolin_runtime

package module
v0.0.0-...-34cf74b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 8, 2020 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package grumpy is the Grumpy runtime's Python API, analogous to CPython's C API.

Data model

All Python objects are represented by structs that are binary compatible with grumpy.Object, so for example the result of the Python expression "object()" is just an Object pointer. More complex primitive types like str and dict are represented by structs that augment Object by embedding it as their first field and holding other data in subsequent fields. These augmented structs can themselves be embedded for yet more complex types.

Objects contain a pointer to their Python type, represented by grumpy.Type, and a pointer to their attribute dict, represented by grumpy.Dict. This dict may be nil as in the case of str or non-nil as in the case of type objects. Note that Grumpy objects do not have a refcount since Grumpy relies on Go's garbage collection to manage object lifetimes.

Every Type object holds references to all its base classes as well as every class in its MRO list.

Grumpy types also hold a reflect.Type instance known as the type's "basis". A type's basis represents the Go struct used to store instances of the type. It is an important invariant of the Grumpy runtime that an instance of a particular Python type is stored in the Go struct that is that type's basis. Violation of this invariant would mean that, for example, a str object could end up being stored in an unaugmented Object and accessing the str's value would access invalid memory. This invariant is enforced by Grumpy's API for primitive types and user defined classes.

Upcasting and downcasting along the basis hierarchy is sometimes necessary, for example when passing a Str to a function accepting an Object. Upcasts are accomplished by accessing the embedded base type basis of the subclass, e.g. accessing the Object member of the Str struct. Downcasting requires unsafe.Pointer conversions. The safety of these conversions is guaranteed by the invariant discussed above. E.g. it is valid to cast an *Object with type StrType to a *Str because it was allocated with storage represented by StrType's basis, which is struct Str.

Execution model

User defined Python code blocks (modules, classes and functions) are implemented as Go closures with a state machine that allows the body of the block to be re-entered for exception handling, yield statements, etc. The generated code for the body of a code block looks something like this:

01:	func(f *Frame) (*Object, *BaseException) {
02:		switch (f.State()) {
03:		case 0: goto Label0
04:		case 1: goto Label1
05:		...
06:		}
07:	Label0:
08:		...
09:	Label1:
10:		...
11:	...
12:	}

Frame is the basis type for Grumpy's "frame" objects and is very similar to CPython's type of the same name. The first argument f, therefore, represents a level in the Python stack. Upon entry into the body, the frame's state variable is checked and control jumps to the appropriate label. Upon first entry, the state variable will be 0 and the so execution will start at Label0. Later invocations may start at other labels. For example, an exception raised in the try block of a try/finally will cause the function above to return an exception as its second return value. The caller will then set state to the label corresponding to the finally clause and call back into the body.

Python exceptions are represented by the BaseException basis struct. Grumpy API functions and generated code blocks propagate exceptions by returning *BaseException as their last return value. Exceptions are raised with the Frame.Raise*() methods which create exception objects to be propagated and set the exc info indicator for the current frame stack, similar to CPython. Python except clauses down the stack can then handle the propagated exception.

Each generated body function is owned by a Block struct that is very similar to CPython's code object. Each Block has a name (e.g. the class' name) and the filename where the Python code was defined. A block is invoked via the *Block.Exec method which pushes a new frame on the call stack and then repeatedly calls the body function. This interplay is depicted below:

 *Block.Exec
 --> +-+
     | | block func
     |1| --> +-+
     | |     |2|
     | | <-- +-+
     | | --> +-+
     | |     |2|
     | | <-- +-+
 <-- +-+

1. *Block.Exec repeatedly calls block function until finished or an
   unhandled exception is encountered

2. Dispatch switch passes control to appropriate part of block function
   and executes

When the body returns with a nil exception, the accompanying value is the returned from the block. If an exception is returned then the "checkpoint stack" is examined. This data structure stores recovery points within body that need to be executed when an exception occurs. Expanding on the try/finally example above, when an exception is raised in the try clause, the finally checkpoint is popped off the stack and its value is assigned to state. Body then gets called again and control is passed to the finally label.

To make things concrete, here is a block of code containing a try/finally:

01:	try:
02:		print "foo"
03:	finally:
04:		print "bar"

The generated code for this sinippet would look something like this:

01:	func(f *Frame) (*Object, *BaseException) {
02:		switch state {
03:		case 0: goto Label0
04:		case 1: goto Label1
05:		}
06:	Label0:
07:		// line 1: try:
08:		f.PushCheckpoint(1)
09:		// line 2: print foo
10:		raised = Print(f, []*Object{NewStr("foo").ToObject()})
11:		if raised != nil {
12:			return nil, raised
13:		}
14:		f.PopCheckpoint()
15:	Label1:
16:		exc, tb = πF.RestoreExc(nil, nil)
17:		// line 4: print bar
18:		raised = Print(f, []*Object{NewStr("bar").ToObject()})
19:		if raised != nil {
20:			return nil, raised
21:		}
22:		if exc != nil {
24:			return nil, f.Raise(exc, nil, tb)
24:		}
25:		return None, nil
26:	}

There are a few relevant things worth noting here:

  1. Upon entering the try clause on line 8, a checkpoint pointing to Label1 (the finally clause) is pushed onto the stack. If the try clause does not raise, the checkpoint is popped on line 14 and control falls through to Label1 without having to re-enter the body function.
  1. Lines 10 and 18 are the two print statements. Exceptions raised during execution of these statements are returned immediately. In general, Python statements map to one or more Grumpy API function calls which may propagate exceptions.
  1. Control of the finally clause begins on line 16 where the exception indicator is cleared and its original value is stored and re-raised at the end of the clause. This matches CPython's behavior where exc info is cleared during the finally block.

A stack is used to store checkpoints because checkpoints can be nested. Continuing the example above, the finally clause itself could be in an except handler, e.g.:

01:	try:
02:		try:
03:			print "foo"
04:		finally:
05:			print "bar"
06:	except SomeException:
07:		print "baz"

Once the finally clause completes, it re-raises the exception and control is passed to the except handler label because it's next in the checkpoint stack. If the exception is an instance of SomeException then execution continues within the except clause. If it is some other kind of exception then it will be returned and control will be passed to the caller to find another checkpoint or unwind the call stack.

Call model

Python callables are represented by the Function basis struct and the corresponding Python "function" type. As in CPython, class methods and global functions are instances of this type. Associated with each instance is a Go function with the signature:

func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException)

The args slice and kwargs dict contain the positional and keyword arguments provided by the caller. Both builtin functions and those in user defined Python code are called using this convention, however the latter are wrapped in a layer represented by the FunctionSpec struct that validates arguments and substitutes absent keyword parameters with their default. Once the spec is validated, it passes control to the spec function:

func(f *Frame, args []*Object) (*Object, *BaseException)

Here, the args slice contains an element for each argument present in the Python function's parameter list, in the same order. Every value is non-nil since default values have been substituted where necessary by the function spec. If parameters with the * or ** specifiers are present in the function signature, they are the last element(s) in args and hold any extra positional or keyword arguments provided by the caller.

Generated code within the spec function consists of three main parts:

+----------------------+
| Spec func            |
| ---------            |
| Declare locals       |
| Declare temporaries  |
| +------------------+ |
| | Body func        | |
| | ----------       | |
| | Dispatch switch  | |
| | Labels           | |
| +------------------+ |
| Block.Exec(body)     |
+----------------------+

Locals and temporaries are defined as local variables at the top of the spec function. Below that, the body function is defined which is stateless except for what it inherits from its enclosing scope and from the passed frame. This is important because the body function will be repeatedly reenetered, but all of the state will have a lifetime longer than any particular invocation because it belongs to the spec function's scope. Finally, *Block.Exec is called which drives the state machine, calling into the body function as appropriate.

Generator functions work much the same way except that instead of calling Exec on the block directly, the block is returned and the generator's next() method calls Exec until its contents are exhausted.

Index

Constants

View Source
const (
	// EncodeStrict causes UnicodeError to be raised on bad chars.
	EncodeStrict = "strict"
	// EncodeReplace replaces bad chars with "\ufffd".
	EncodeReplace = "replace"
	// EncodeIgnore discards bad chars.
	EncodeIgnore = "ignore"
)

Error handling modes that dictate the behavior of *Str.Decode and *Unicode.Encode when they encounter bad chars.

View Source
const (

	// MaxInt is the largest (most positive) number that can be stored as an int.
	MaxInt = _maxuint >> 1
	// MinInt is the smallest (most negative) number that can be stored as an int.
	// The absolute value of MinInt is Maxint+1, thus it can be tricky to deal with.
	MinInt = -(_maxuint + 1) >> 1
)
View Source
const EncodeDefault = "utf8"

EncodeDefault is the system default encoding.

Variables

View Source
var (
	// True is the singleton bool object representing the Python 'True'
	// object.
	True = &Int{Object{typ: BoolType}, 1}
	// False is the singleton bool object representing the Python 'False'
	// object.
	False = &Int{Object{typ: BoolType}, 0}
)
View Source
var (
	// Builtins contains all of the Python built-in identifiers.
	Builtins = NewDict()

	// ExceptionTypes contains all builtin exception types.
	ExceptionTypes []*Type
	// EllipsisType is the object representing the Python 'ellipsis' type
	EllipsisType = newSimpleType("ellipsis", ObjectType)
	// Ellipsis is the singleton ellipsis object representing the Python
	// 'Ellipsis' object.
	Ellipsis = &Object{typ: EllipsisType}
	// NoneType is the object representing the Python 'NoneType' type.
	NoneType = newSimpleType("NoneType", ObjectType)
	// None is the singleton NoneType object representing the Python 'None'
	// object.
	None = &Object{typ: NoneType}
	// NotImplementedType is the object representing the Python
	// 'NotImplementedType' object.
	NotImplementedType = newSimpleType("NotImplementedType", ObjectType)
	// NotImplemented is the singleton NotImplementedType object
	// representing the Python 'NotImplemented' object.
	NotImplemented = newObject(NotImplementedType)

	// UnboundLocal is a singleton held by local variables in generated
	// code before they are bound.
	UnboundLocal = newObject(unboundLocalType)
)
View Source
var (
	// ArithmeticErrorType corresponds to the Python type 'ArithmeticError'.
	ArithmeticErrorType = newSimpleType("ArithmeticError", StandardErrorType)
	// AssertionErrorType corresponds to the Python type 'AssertionError'.
	AssertionErrorType = newSimpleType("AssertionError", StandardErrorType)
	// AttributeErrorType corresponds to the Python type 'AttributeError'.
	AttributeErrorType = newSimpleType("AttributeError", StandardErrorType)
	// BytesWarningType corresponds to the Python type 'BytesWarning'.
	BytesWarningType = newSimpleType("BytesWarning", WarningType)
	// DeprecationWarningType corresponds to the Python type 'DeprecationWarning'.
	DeprecationWarningType = newSimpleType("DeprecationWarning", WarningType)
	// EnvironmentErrorType corresponds to the Python type
	// 'EnvironmentError'.
	EnvironmentErrorType = newSimpleType("EnvironmentError", StandardErrorType)
	// EOFErrorType corresponds to the Python type 'EOFError'.
	EOFErrorType = newSimpleType("EOFError", StandardErrorType)
	// ExceptionType corresponds to the Python type 'Exception'.
	ExceptionType = newSimpleType("Exception", BaseExceptionType)
	// FutureWarningType corresponds to the Python type 'FutureWarning'.
	FutureWarningType = newSimpleType("FutureWarning", WarningType)
	// ImportErrorType corresponds to the Python type 'ImportError'.
	ImportErrorType = newSimpleType("ImportError", StandardErrorType)
	// ImportWarningType corresponds to the Python type 'ImportWarning'.
	ImportWarningType = newSimpleType("ImportWarning", WarningType)
	// IndexErrorType corresponds to the Python type 'IndexError'.
	IndexErrorType = newSimpleType("IndexError", LookupErrorType)
	// IOErrorType corresponds to the Python type 'IOError'.
	IOErrorType = newSimpleType("IOError", EnvironmentErrorType)
	// KeyboardInterruptType corresponds to the Python type 'KeyboardInterrupt'.
	KeyboardInterruptType = newSimpleType("KeyboardInterrupt", BaseExceptionType)
	// KeyErrorType corresponds to the Python type 'KeyError'.
	KeyErrorType = newSimpleType("KeyError", LookupErrorType)
	// LookupErrorType corresponds to the Python type 'LookupError'.
	LookupErrorType = newSimpleType("LookupError", StandardErrorType)
	// MemoryErrorType corresponds to the Python type 'MemoryError'.
	MemoryErrorType = newSimpleType("MemoryError", StandardErrorType)
	// NameErrorType corresponds to the Python type 'NameError'.
	NameErrorType = newSimpleType("NameError", StandardErrorType)
	// NotImplementedErrorType corresponds to the Python type
	// 'NotImplementedError'.
	NotImplementedErrorType = newSimpleType("NotImplementedError", RuntimeErrorType)
	// OSErrorType corresponds to the Python type 'OSError'.
	OSErrorType = newSimpleType("OSError", EnvironmentErrorType)
	// OverflowErrorType corresponds to the Python type 'OverflowError'.
	OverflowErrorType = newSimpleType("OverflowError", ArithmeticErrorType)
	// PendingDeprecationWarningType corresponds to the Python type 'PendingDeprecationWarning'.
	PendingDeprecationWarningType = newSimpleType("PendingDeprecationWarning", WarningType)
	// ReferenceErrorType corresponds to the Python type 'ReferenceError'.
	ReferenceErrorType = newSimpleType("ReferenceError", StandardErrorType)
	// RuntimeErrorType corresponds to the Python type 'RuntimeError'.
	RuntimeErrorType = newSimpleType("RuntimeError", StandardErrorType)
	// RuntimeWarningType corresponds to the Python type 'RuntimeWarning'.
	RuntimeWarningType = newSimpleType("RuntimeWarning", WarningType)
	// StandardErrorType corresponds to the Python type 'StandardError'.
	StandardErrorType = newSimpleType("StandardError", ExceptionType)
	// StopIterationType corresponds to the Python type 'StopIteration'.
	StopIterationType = newSimpleType("StopIteration", ExceptionType)
	// SyntaxErrorType corresponds to the Python type 'SyntaxError'.
	SyntaxErrorType = newSimpleType("SyntaxError", StandardErrorType)
	// SyntaxWarningType corresponds to the Python type 'SyntaxWarning'.
	SyntaxWarningType = newSimpleType("SyntaxWarning", WarningType)
	// SystemErrorType corresponds to the Python type 'SystemError'.
	SystemErrorType = newSimpleType("SystemError", StandardErrorType)
	// SystemExitType corresponds to the Python type 'SystemExit'.
	SystemExitType = newSimpleType("SystemExit", BaseExceptionType)
	// TypeErrorType corresponds to the Python type 'TypeError'.
	TypeErrorType = newSimpleType("TypeError", StandardErrorType)
	// UnboundLocalErrorType corresponds to the Python type
	// 'UnboundLocalError'.
	UnboundLocalErrorType = newSimpleType("UnboundLocalError", NameErrorType)
	// UnicodeDecodeErrorType corresponds to the Python type 'UnicodeDecodeError'.
	UnicodeDecodeErrorType = newSimpleType("UnicodeDecodeError", ValueErrorType)
	// UnicodeEncodeErrorType corresponds to the Python type 'UnicodeEncodeError'.
	UnicodeEncodeErrorType = newSimpleType("UnicodeEncodeError", ValueErrorType)
	// UnicodeErrorType corresponds to the Python type 'UnicodeError'.
	UnicodeErrorType = newSimpleType("UnicodeError", ValueErrorType)
	// UnicodeWarningType corresponds to the Python type 'UnicodeWarning'.
	UnicodeWarningType = newSimpleType("UnicodeWarning", WarningType)
	// UserWarningType corresponds to the Python type 'UserWarning'.
	UserWarningType = newSimpleType("UserWarning", WarningType)
	// ValueErrorType corresponds to the Python type 'ValueError'.
	ValueErrorType = newSimpleType("ValueError", StandardErrorType)
	// WarningType corresponds to the Python type 'Warning'.
	WarningType = newSimpleType("Warning", ExceptionType)
	// ZeroDivisionErrorType corresponds to the Python type
	// 'ZeroDivisionError'.
	ZeroDivisionErrorType = newSimpleType("ZeroDivisionError", ArithmeticErrorType)
)
View Source
var (
	// Stdin is an alias for sys.stdin.
	Stdin = NewFileFromFD(os.Stdin.Fd(), nil)
	// Stdout is an alias for sys.stdout.
	Stdout = NewFileFromFD(os.Stdout.Fd(), nil)
	// Stderr is an alias for sys.stderr.
	Stderr = NewFileFromFD(os.Stderr.Fd(), nil)
)
View Source
var (
	// FunctionType is the object representing the Python 'function' type.
	FunctionType = newBasisType("function", reflect.TypeOf(Function{}), toFunctionUnsafe, ObjectType)
	// StaticMethodType is the object representing the Python
	// 'staticmethod' type.
	StaticMethodType = newBasisType("staticmethod", reflect.TypeOf(staticMethod{}), toStaticMethodUnsafe, ObjectType)
	// ClassMethodType is the object representing the Python
	// 'classmethod' type.
	ClassMethodType = newBasisType("classmethod", reflect.TypeOf(classMethod{}), toClassMethodUnsafe, ObjectType)
)
View Source
var (

	// ModuleType is the object representing the Python 'module' type.
	ModuleType = newBasisType("module", reflect.TypeOf(Module{}), toModuleUnsafe, ObjectType)
	// SysModules is the global dict of imported modules, aka sys.modules.
	SysModules = NewDict()
)
View Source
var (
	// FrozenSetType is the object representing the Python 'set' type.
	FrozenSetType = newBasisType("frozenset", reflect.TypeOf(FrozenSet{}), toFrozenSetUnsafe, ObjectType)
	// SetType is the object representing the Python 'set' type.
	SetType = newBasisType("set", reflect.TypeOf(Set{}), toSetUnsafe, ObjectType)
)
View Source
var BaseExceptionType = newBasisType("BaseException", reflect.TypeOf(BaseException{}), toBaseExceptionUnsafe, ObjectType)

BaseExceptionType corresponds to the Python type 'BaseException'.

View Source
var (
	// BaseStringType is the object representing the Python 'basestring'
	// type.
	BaseStringType = newSimpleType("basestring", ObjectType)
)
View Source
var BoolType = newSimpleType("bool", IntType)

BoolType is the object representing the Python 'bool' type.

View Source
var (
	// ByteArrayType is the object representing the Python 'bytearray' type.
	ByteArrayType = newBasisType("bytearray", reflect.TypeOf(ByteArray{}), toByteArrayUnsafe, ObjectType)
)
View Source
var CodeType = newBasisType("code", reflect.TypeOf(Code{}), toCodeUnsafe, ObjectType)

CodeType is the object representing the Python 'code' type.

View Source
var ComplexType = newBasisType("complex", reflect.TypeOf(Complex{}), toComplexUnsafe, ObjectType)

ComplexType is the object representing the Python 'complex' type.

View Source
var (
	// DictType is the object representing the Python 'dict' type.
	DictType = newBasisType("dict", reflect.TypeOf(Dict{}), toDictUnsafe, ObjectType)
)
View Source
var FileType = newBasisType("file", reflect.TypeOf(File{}), toFileUnsafe, ObjectType)

FileType is the object representing the Python 'file' type.

View Source
var FloatType = newBasisType("float", reflect.TypeOf(Float{}), toFloatUnsafe, ObjectType)

FloatType is the object representing the Python 'float' type.

View Source
var FrameType = newBasisType("frame", reflect.TypeOf(Frame{}), toFrameUnsafe, ObjectType)

FrameType is the object representing the Python 'frame' type.

View Source
var (
	// GeneratorType is the object representing the Python 'generator' type.
	GeneratorType = newBasisType("generator", reflect.TypeOf(Generator{}), toGeneratorUnsafe, ObjectType)
)
View Source
var IntType = newBasisType("int", reflect.TypeOf(Int{}), toIntUnsafe, ObjectType)

IntType is the object representing the Python 'int' type.

View Source
var ListType = newBasisType("list", reflect.TypeOf(List{}), toListUnsafe, ObjectType)

ListType is the object representing the Python 'list' type.

View Source
var LongType = newBasisType("long", reflect.TypeOf(Long{}), toLongUnsafe, ObjectType)

LongType is the object representing the Python 'long' type.

View Source
var MethodType = newBasisType("instancemethod", reflect.TypeOf(Method{}), toMethodUnsafe, ObjectType)

MethodType is the object representing the Python 'instancemethod' type.

View Source
var (

	// ObjectType is the object representing the Python 'object' type.
	//
	// We don't use newBasisType() here since that introduces an initialization
	// cycle between TypeType and ObjectType.
	ObjectType = &Type{
		name:  "object",
		basis: objectBasis,
		flags: typeFlagDefault,
		slots: typeSlots{Basis: &basisSlot{objectBasisFunc}},
	}
)
View Source
var PropertyType = newBasisType("property", reflect.TypeOf(Property{}), toPropertyUnsafe, ObjectType)

PropertyType is the object representing the Python 'property' type.

View Source
var (
	// SliceType is the object representing the Python 'slice' type.
	SliceType = newBasisType("slice", reflect.TypeOf(Slice{}), toSliceUnsafe, ObjectType)
)
View Source
var (
	// StrType is the object representing the Python 'str' type.
	StrType = newBasisType("str", reflect.TypeOf(Str{}), toStrUnsafe, BaseStringType)
)
View Source
var (

	// ThreadCount is the number of goroutines started with StartThread that
	// have not yet joined.
	ThreadCount int64
)
View Source
var TracebackType = newBasisType("traceback", reflect.TypeOf(Traceback{}), toTracebackUnsafe, ObjectType)

TracebackType is the object representing the Python 'traceback' type.

View Source
var TupleType = newBasisType("tuple", reflect.TypeOf(Tuple{}), toTupleUnsafe, ObjectType)

TupleType is the object representing the Python 'tuple' type.

View Source
var TypeType = &Type{
	name:  "type",
	basis: typeBasis,
	bases: []*Type{ObjectType},
	flags: typeFlagDefault,
	slots: typeSlots{Basis: &basisSlot{typeBasisFunc}},
}

TypeType is the object representing the Python 'type' type.

Don't use newType() since that depends on the initialization of TypeType.

View Source
var (
	// UnicodeType is the object representing the Python 'unicode' type.
	UnicodeType = newBasisType("unicode", reflect.TypeOf(Unicode{}), toUnicodeUnsafe, BaseStringType)
)
View Source
var (
	// WeakRefType is the object representing the Python 'weakref' type.
	WeakRefType = newBasisType("weakref", reflect.TypeOf(WeakRef{}), toWeakRefUnsafe, ObjectType)
)

Functions

func Abs

func Abs(f *Frame, o *Object) (*Object, *BaseException)

Abs returns the result of o.__abs__ and is equivalent to the Python expression "abs(o)".

func Add

func Add(f *Frame, v, w *Object) (*Object, *BaseException)

Add returns the result of adding v and w together according to the __add/radd__ operator.

func And

func And(f *Frame, v, w *Object) (*Object, *BaseException)

And returns the result of the bitwise and operator v & w according to __and/rand__.

func Compare

func Compare(f *Frame, v, w *Object) (*Object, *BaseException)

Compare implements a 3-way comparison which returns:

-1 if v < w
 0 if v == w
 1 if v > w

It closely resembles the behavior of CPython's do_cmp in object.c.

func Div

func Div(f *Frame, v, w *Object) (*Object, *BaseException)

Div returns the result of dividing v by w according to the __div/rdiv__ operator.

func DivMod

func DivMod(f *Frame, v, w *Object) (*Object, *BaseException)

DivMod returns the result (quotient and remainder tuple) of dividing v by w according to the __divmod/rdivmod__ operator.

func Eq

func Eq(f *Frame, v, w *Object) (*Object, *BaseException)

Eq returns the equality of v and w according to the __eq__ operator.

func FloorDiv

func FloorDiv(f *Frame, v, w *Object) (*Object, *BaseException)

FloorDiv returns the equality of v and w according to the __floordiv/rfloordiv__ operator.

func FormatExc

func FormatExc(f *Frame) (s string)

FormatExc calls traceback.format_exc, falling back to the single line exception message if that fails, e.g. "NameError: name 'x' is not defined\n".

func GE

func GE(f *Frame, v, w *Object) (*Object, *BaseException)

GE returns the result of operation v >= w.

func GT

func GT(f *Frame, v, w *Object) (*Object, *BaseException)

GT returns the result of operation v > w.

func GetAttr

func GetAttr(f *Frame, o *Object, name *Str, def *Object) (*Object, *BaseException)

GetAttr returns the named attribute of o. Equivalent to the Python expression getattr(o, name, def).

func GetAttrImport

func GetAttrImport(f *Frame, o *Object, name *Str) (*Object, *BaseException)

GetAttrImport behaves as GetAttr, but errors raises ImportError instead of AttributeError

func GetItem

func GetItem(f *Frame, o, key *Object) (*Object, *BaseException)

GetItem returns the result of operation o[key].

func Hash

func Hash(f *Frame, o *Object) (*Int, *BaseException)

Hash returns the hash of o according to its __hash__ operator.

func Hex

func Hex(f *Frame, o *Object) (*Object, *BaseException)

Hex returns the result of o.__hex__ if defined.

func IAdd

func IAdd(f *Frame, v, w *Object) (*Object, *BaseException)

IAdd returns the result of v.__iadd__ if defined, otherwise falls back to Add.

func IAnd

func IAnd(f *Frame, v, w *Object) (*Object, *BaseException)

IAnd returns the result of v.__iand__ if defined, otherwise falls back to And.

func IDiv

func IDiv(f *Frame, v, w *Object) (*Object, *BaseException)

IDiv returns the result of v.__idiv__ if defined, otherwise falls back to div.

func IFloorDiv

func IFloorDiv(f *Frame, v, w *Object) (*Object, *BaseException)

IFloorDiv returns the result of v.__ifloordiv__ if defined, otherwise falls back to floordiv.

func ILShift

func ILShift(f *Frame, v, w *Object) (*Object, *BaseException)

ILShift returns the result of v.__ilshift__ if defined, otherwise falls back to lshift.

func IMod

func IMod(f *Frame, v, w *Object) (*Object, *BaseException)

IMod returns the result of v.__imod__ if defined, otherwise falls back to mod.

func IMul

func IMul(f *Frame, v, w *Object) (*Object, *BaseException)

IMul returns the result of v.__imul__ if defined, otherwise falls back to mul.

func IOr

func IOr(f *Frame, v, w *Object) (*Object, *BaseException)

IOr returns the result of v.__ior__ if defined, otherwise falls back to Or.

func IPow

func IPow(f *Frame, v, w *Object) (*Object, *BaseException)

IPow returns the result of v.__pow__ if defined, otherwise falls back to IPow.

func IRShift

func IRShift(f *Frame, v, w *Object) (*Object, *BaseException)

IRShift returns the result of v.__irshift__ if defined, otherwise falls back to rshift.

func ISub

func ISub(f *Frame, v, w *Object) (*Object, *BaseException)

ISub returns the result of v.__isub__ if defined, otherwise falls back to sub.

func IXor

func IXor(f *Frame, v, w *Object) (*Object, *BaseException)

IXor returns the result of v.__ixor__ if defined, otherwise falls back to Xor.

func ImportModule

func ImportModule(f *Frame, name string) ([]*Object, *BaseException)

ImportModule takes a fully qualified module name (e.g. a.b.c) and a slice of code objects where the name of the i'th module is the prefix of name ending in the i'th dot. The number of dot delimited parts of name must be the same as the number of code objects. For each successive prefix, ImportModule looks in sys.modules for an existing module with that name and if not present creates a new module object, adds it to sys.modules and initializes it with the corresponding code object. If the module was already present in sys.modules, it is not re-initialized. The returned slice contains each package and module initialized in this way in order.

For example, ImportModule(f, "a.b", []*Code{a.Code, b.Code}) causes the initialization and entry into sys.modules of Grumpy module a and then Grumpy module b. The two initialized modules are returned.

If ImportModule is called in two threads concurrently to import the same module, both invocations will produce the same module object and the module is guaranteed to only be initialized once. The second invocation will not return the module until it is fully initialized.

func Index

func Index(f *Frame, o *Object) (*Object, *BaseException)

Index returns the o converted to a Python int or long according to o's __index__ slot.

func Invert

func Invert(f *Frame, o *Object) (*Object, *BaseException)

Invert returns the result of o.__invert__ and is equivalent to the Python expression "~o".

func Invoke

func Invoke(f *Frame, callable *Object, args Args, varargs *Object, keywords KWArgs, kwargs *Object) (*Object, *BaseException)

Invoke calls the given callable with the positional arguments given by args and *varargs, and the keyword arguments by keywords and **kwargs. It first packs the arguments into slices for the positional and keyword arguments, then it passes those to *Object.Call.

func Iter

func Iter(f *Frame, o *Object) (*Object, *BaseException)

Iter implements the Python iter() builtin. It returns an iterator for o if o is iterable. Otherwise it raises TypeError. Note that the iter(f, sentinel) form is implemented by IterCallable.

func IterCallable

func IterCallable(f *Frame, o *Object, sentinel *Object) (*Object, *BaseException)

IterCallable implements the Python iter(f, sentintel) builtin. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned. It raises TypeError if o is not callable.

func LE

func LE(f *Frame, v, w *Object) (*Object, *BaseException)

LE returns the result of operation v <= w.

func LShift

func LShift(f *Frame, v, w *Object) (*Object, *BaseException)

LShift returns the result of v << w according to the __lshift/rlshift__ operator.

func LT

func LT(f *Frame, v, w *Object) (*Object, *BaseException)

LT returns the result of operation v < w.

func Len

func Len(f *Frame, o *Object) (*Int, *BaseException)

Len returns the length of the given sequence object.

func Mod

func Mod(f *Frame, v, w *Object) (*Object, *BaseException)

Mod returns the remainder from the division of v by w according to the __mod/rmod__ operator.

func Mul

func Mul(f *Frame, v, w *Object) (*Object, *BaseException)

Mul returns the result of multiplying v and w together according to the __mul/rmul__ operator.

func NE

func NE(f *Frame, v, w *Object) (*Object, *BaseException)

NE returns the non-equality of v and w according to the __ne__ operator.

func Neg

func Neg(f *Frame, o *Object) (*Object, *BaseException)

Neg returns the result of o.__neg__ and is equivalent to the Python expression "-o".

func Next

func Next(f *Frame, iter *Object) (*Object, *BaseException)

Next implements the Python next() builtin. It calls next on the provided iterator. It raises TypeError if iter is not an iterator object. Note that the next(it, default) form is not yet supported.

func Oct

func Oct(f *Frame, o *Object) (*Object, *BaseException)

Oct returns the result of o.__oct__ if defined.

func Or

func Or(f *Frame, v, w *Object) (*Object, *BaseException)

Or returns the result of the bitwise or operator v | w according to __or/ror__.

func Pos

func Pos(f *Frame, o *Object) (*Object, *BaseException)

Pos returns the result of o.__pos__ and is equivalent to the Python expression "+o".

func Pow

func Pow(f *Frame, v, w *Object) (*Object, *BaseException)

Pow returns the result of x**y, the base-x exponential of y according to the __pow/rpow__ operator.

func RShift

func RShift(f *Frame, v, w *Object) (*Object, *BaseException)

RShift returns the result of v >> w according to the __rshift/rrshift__ operator.

func RegisterModule

func RegisterModule(name string, c *Code)

RegisterModule adds the named module to the registry so that it can be subsequently imported.

func Repr

func Repr(f *Frame, o *Object) (*Str, *BaseException)

Repr returns a string containing a printable representation of o. This is equivalent to the Python expression "repr(o)".

func ResolveClass

func ResolveClass(f *Frame, class *Dict, local *Object, name *Str) (*Object, *BaseException)

ResolveClass resolves name in the class dict given by class, falling back to the provided local if it is non-nil, otherwise falling back to globals. This is used by the code generator to resolve names in the context of a class definition. If the class definition occurs in a closure in which a local of the given name is present then local will be non-nil, otherwise it will be nil.

func ResolveGlobal

func ResolveGlobal(f *Frame, name *Str) (*Object, *BaseException)

ResolveGlobal looks up name in the frame's dict of global variables or in the Builtins dict if absent. It raises NameError when absent from both.

func RunMain

func RunMain(code *Code) int

RunMain execs the given code object as a module under the name "__main__". It handles any exceptions raised during module execution. If no exceptions were raised then the return value is zero. If a SystemExit was raised then the return value depends on its code attribute: None -> zero, integer values are returned as-is. Other code values and exception types produce a return value of 1.

func StartThread

func StartThread(callable *Object)

StartThread runs callable in a new goroutine.

func Sub

func Sub(f *Frame, v, w *Object) (*Object, *BaseException)

Sub returns the result of subtracting v from w according to the __sub/rsub__ operator.

func ToInt

func ToInt(f *Frame, o *Object) (*Object, *BaseException)

ToInt converts o to an integer type according to the __int__ slot. If the result is not an int or long, then an exception is raised.

func ToStr

func ToStr(f *Frame, o *Object) (*Str, *BaseException)

ToStr is a convenience function for calling "str(o)".

func WrapNative

func WrapNative(f *Frame, v reflect.Value) (*Object, *BaseException)

WrapNative takes a reflect.Value object and converts the underlying Go object to a Python object in the following way:

  • Primitive types are converted in the way you'd expect: Go int types map to Python int, Go booleans to Python bool, etc. User-defined primitive Go types are subclasses of the Python primitives.
  • *big.Int is represented by Python long.
  • Functions are represented by Python type that supports calling into native functions.
  • Interfaces are converted to their concrete held type, or None if IsNil.
  • Other native types are wrapped in an opaque native type that does not support directly accessing the underlying object from Python. When these opaque objects are passed back into Go by native function calls, however, they will be unwrapped back to their Go representation.

func Xor

func Xor(f *Frame, v, w *Object) (*Object, *BaseException)

Xor returns the result of the bitwise xor operator v ^ w according to __xor/rxor__.

Types

type Args

type Args []*Object

Args represent positional parameters in a call to a Python function.

type BaseException

type BaseException struct {
	Object
	// contains filtered or unexported fields
}

BaseException represents Python 'BaseException' objects.

func Assert

func Assert(f *Frame, cond *Object, msg *Object) *BaseException

Assert raises an AssertionError if the given cond does not evaluate to true. If msg is not nil, it is converted to a string via ToStr() and passed as args to the raised exception.

func CheckLocal

func CheckLocal(f *Frame, value *Object, name string) *BaseException

CheckLocal validates that the local variable with the given name and value has been bound and raises UnboundLocalError if not.

func Contains

func Contains(f *Frame, seq, value *Object) (bool, *BaseException)

Contains checks whether value is present in seq. It first checks the __contains__ method of seq and, if that is not available, attempts to find value by iteration over seq. It is equivalent to the Python expression "value in seq".

func DelAttr

func DelAttr(f *Frame, o *Object, name *Str) *BaseException

DelAttr removes the attribute of o given by name. Equivalent to the Python expression delattr(o, name).

func DelItem

func DelItem(f *Frame, o, key *Object) *BaseException

DelItem performs the operation del o[key].

func DelVar

func DelVar(f *Frame, namespace *Dict, name *Str) *BaseException

DelVar removes the named variable from the given namespace dictionary such as a module globals dict.

func IndexInt

func IndexInt(f *Frame, o *Object) (i int, raised *BaseException)

IndexInt returns the value of o converted to a Go int according to o's __index__ slot. It raises a TypeError if o doesn't have an __index__ method.

func IsInstance

func IsInstance(f *Frame, o *Object, classinfo *Object) (bool, *BaseException)

IsInstance returns true if the type o is an instance of classinfo, or an instance of an element in classinfo (if classinfo is a tuple). It returns false otherwise. The argument classinfo must be a type or a tuple whose elements are types like the isinstance() Python builtin.

func IsSubclass

func IsSubclass(f *Frame, o *Object, classinfo *Object) (bool, *BaseException)

IsSubclass returns true if the type o is a subtype of classinfo or a subtype of an element in classinfo (if classinfo is a tuple). It returns false otherwise. The argument o must be a type and classinfo must be a type or a tuple whose elements are types like the issubclass() Python builtin.

func IsTrue

func IsTrue(f *Frame, o *Object) (bool, *BaseException)

IsTrue returns the truthiness of o according to the __nonzero__ operator.

func LoadMembers

func LoadMembers(f *Frame, module *Object) *BaseException

LoadMembers scans over all the members in module and populates globals with them, taking __all__ into account.

func Print

func Print(f *Frame, args Args, nl bool) *BaseException

Print implements the Python print statement. It calls str() on the given args and outputs the results to stdout separated by spaces. Similar to the Python print statement.

func SetAttr

func SetAttr(f *Frame, o *Object, name *Str, value *Object) *BaseException

SetAttr sets the attribute of o given by name to value. Equivalent to the Python expression setattr(o, name, value).

func SetItem

func SetItem(f *Frame, o, key, value *Object) *BaseException

SetItem performs the operation o[key] = value.

func Tie

func Tie(f *Frame, t TieTarget, o *Object) *BaseException

Tie takes a (possibly nested) TieTarget and recursively unpacks the elements of o by iteration, assigning the results to the Target fields of t. If the structure of o is not suitable to be unpacked into t, then an exception is raised.

func ToIntValue

func ToIntValue(f *Frame, o *Object) (int, *BaseException)

ToIntValue converts o to an integer according to the __int__ slot. If the result is not an int or long, or if the long value is too large to fit into an int, then an exception is raised.

func ToNative

func ToNative(f *Frame, o *Object) (reflect.Value, *BaseException)

ToNative converts o to a native Go object according to the __native__ operator.

func (*BaseException) ToObject

func (e *BaseException) ToObject() *Object

ToObject upcasts e to an Object.

type ByteArray

type ByteArray struct {
	Object
	// contains filtered or unexported fields
}

ByteArray represents Python 'bytearray' objects.

func (*ByteArray) ToObject

func (a *ByteArray) ToObject() *Object

ToObject upcasts a to an Object.

func (*ByteArray) Value

func (a *ByteArray) Value() []byte

Value returns the underlying bytes held by a.

type Code

type Code struct {
	Object
	// contains filtered or unexported fields
}

Code represents Python 'code' objects.

func NewCode

func NewCode(name, filename string, params []Param, flags CodeFlag, fn func(*Frame, []*Object) (*Object, *BaseException)) *Code

NewCode creates a new Code object that executes the given fn.

func (*Code) Eval

func (c *Code) Eval(f *Frame, globals *Dict, args Args, kwargs KWArgs) (*Object, *BaseException)

Eval runs the code object c in the context of the given globals.

type CodeFlag

type CodeFlag int

CodeFlag is a switch controlling the behavior of a Code object.

const (
	// CodeFlagVarArg means a Code object accepts *arg parameters.
	CodeFlagVarArg CodeFlag = 4
	// CodeFlagKWArg means a Code object accepts **kwarg parameters.
	CodeFlagKWArg CodeFlag = 8
)

type Complex

type Complex struct {
	Object
	// contains filtered or unexported fields
}

Complex represents Python 'complex' objects.

func NewComplex

func NewComplex(value complex128) *Complex

NewComplex returns a new Complex holding the given complex value.

func (*Complex) ToObject

func (c *Complex) ToObject() *Object

ToObject upcasts c to an Object.

func (*Complex) Value

func (c *Complex) Value() complex128

Value returns the underlying complex value held by c.

type Dict

type Dict struct {
	Object
	// contains filtered or unexported fields
}

Dict represents Python 'dict' objects. The public methods of *Dict are thread safe.

func NewDict

func NewDict() *Dict

NewDict returns an empty Dict.

func (*Dict) DelItem

func (d *Dict) DelItem(f *Frame, key *Object) (bool, *BaseException)

DelItem removes the entry associated with key from d. It returns true if an item was removed, or false if it did not exist in d.

func (*Dict) DelItemString

func (d *Dict) DelItemString(f *Frame, key string) (bool, *BaseException)

DelItemString removes the entry associated with key from d. It returns true if an item was removed, or false if it did not exist in d.

func (*Dict) GetItem

func (d *Dict) GetItem(f *Frame, key *Object) (*Object, *BaseException)

GetItem looks up key in d, returning the associated value or nil if key is not present in d.

func (*Dict) GetItemString

func (d *Dict) GetItemString(f *Frame, key string) (*Object, *BaseException)

GetItemString looks up key in d, returning the associated value or nil if key is not present in d.

func (*Dict) Keys

func (d *Dict) Keys(f *Frame) *List

Keys returns a list containing all the keys in d.

func (*Dict) Len

func (d *Dict) Len() int

Len returns the number of entries in d.

func (*Dict) Pop

func (d *Dict) Pop(f *Frame, key *Object) (*Object, *BaseException)

Pop looks up key in d, returning and removing the associalted value if exist, or nil if key is not present in d.

func (*Dict) SetItem

func (d *Dict) SetItem(f *Frame, key, value *Object) *BaseException

SetItem associates value with key in d.

func (*Dict) SetItemString

func (d *Dict) SetItemString(f *Frame, key string, value *Object) *BaseException

SetItemString associates value with key in d.

func (*Dict) ToObject

func (d *Dict) ToObject() *Object

ToObject upcasts d to an Object.

func (*Dict) Update

func (d *Dict) Update(f *Frame, o *Object) (raised *BaseException)

Update copies the items from the mapping or sequence of 2-tuples o into d.

type File

type File struct {
	Object

	Softspace int `attr:"softspace" attr_mode:"rw"`
	// contains filtered or unexported fields
}

File represents Python 'file' objects.

func NewFileFromFD

func NewFileFromFD(fd uintptr, close *Object) *File

NewFileFromFD creates a file object from the given file descriptor fd.

func (*File) ToObject

func (f *File) ToObject() *Object

ToObject upcasts f to an Object.

type Float

type Float struct {
	Object
	// contains filtered or unexported fields
}

Float represents Python 'float' objects.

func NewFloat

func NewFloat(value float64) *Float

NewFloat returns a new Float holding the given floating point value.

func (*Float) ToObject

func (f *Float) ToObject() *Object

ToObject upcasts f to an Object.

func (*Float) Value

func (f *Float) Value() float64

Value returns the underlying floating point value held by f.

type Frame

type Frame struct {
	Object
	// contains filtered or unexported fields
}

Frame represents Python 'frame' objects.

func NewRootFrame

func NewRootFrame() *Frame

NewRootFrame creates a Frame that is the bottom of a new stack.

func (*Frame) ExcInfo

func (f *Frame) ExcInfo() (*BaseException, *Traceback)

ExcInfo returns the exception currently being handled by f's thread and the associated traceback.

func (*Frame) FreeArgs

func (f *Frame) FreeArgs(args Args)

FreeArgs clears the elements of args and returns it to the system. It may later be returned by calls to MakeArgs and therefore references to slices of args should not be held.

func (*Frame) Globals

func (f *Frame) Globals() *Dict

Globals returns the globals dict for this frame.

func (*Frame) MakeArgs

func (f *Frame) MakeArgs(n int) Args

MakeArgs returns an Args slice with the given length. The slice may have been previously used, but all elements will be set to nil.

func (*Frame) PopCheckpoint

func (f *Frame) PopCheckpoint()

PopCheckpoint removes the last element of f's checkpoint stack and returns it.

func (*Frame) PushCheckpoint

func (f *Frame) PushCheckpoint(state RunState)

PushCheckpoint appends state to the end of f's checkpoint stack.

func (*Frame) Raise

func (f *Frame) Raise(typ *Object, inst *Object, tb *Object) *BaseException

Raise creates an exception and sets the exc info indicator in a way that is compatible with the Python raise statement. The semantics are non-trivial and are best described here: https://docs.python.org/2/reference/simple_stmts.html#the-raise-statement If typ, inst and tb are all nil then the currently active exception and traceback according to ExcInfo will be used. Raise returns the exception to propagate.

func (*Frame) RaiseType

func (f *Frame) RaiseType(t *Type, msg string) *BaseException

RaiseType constructs a new object of type t, passing a single str argument built from msg and throws the constructed object.

func (*Frame) RestoreExc

func (f *Frame) RestoreExc(e *BaseException, tb *Traceback) (*BaseException, *Traceback)

RestoreExc assigns the exception currently being handled by f's thread and the associated traceback. The previously set values are returned.

func (*Frame) SetLineno

func (f *Frame) SetLineno(lineno int)

SetLineno sets the current line number for the frame.

func (*Frame) State

func (f *Frame) State() RunState

State returns the current run state for f.

func (*Frame) ToObject

func (f *Frame) ToObject() *Object

ToObject upcasts f to an Object.

type FrozenSet

type FrozenSet setBase

FrozenSet represents Python 'set' objects.

func (*FrozenSet) Contains

func (s *FrozenSet) Contains(f *Frame, key *Object) (bool, *BaseException)

Contains returns true if key exists in s.

func (*FrozenSet) ToObject

func (s *FrozenSet) ToObject() *Object

ToObject upcasts s to an Object.

type Func

type Func func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException)

Func is a Go function underlying a Python Function object.

type Function

type Function struct {
	Object
	// contains filtered or unexported fields
}

Function represents Python 'function' objects.

func NewFunction

func NewFunction(c *Code, globals *Dict) *Function

NewFunction creates a function object corresponding to a Python function taking the given args, vararg and kwarg. When called, the arguments are validated before calling fn. This includes checking that an appropriate number of arguments are provided, populating *args and **kwargs if necessary, etc.

func (*Function) Name

func (f *Function) Name() string

Name returns f's name field.

func (*Function) ToObject

func (f *Function) ToObject() *Object

ToObject upcasts f to an Object.

type Generator

type Generator struct {
	Object
	// contains filtered or unexported fields
}

Generator represents Python 'generator' objects.

func NewGenerator

func NewGenerator(f *Frame, fn func(*Object) (*Object, *BaseException)) *Generator

NewGenerator returns a new Generator object that runs the given Block b.

func (*Generator) ToObject

func (g *Generator) ToObject() *Object

ToObject upcasts g to an Object.

type Int

type Int struct {
	Object
	// contains filtered or unexported fields
}

Int represents Python 'int' objects.

func GetBool

func GetBool(v bool) *Int

GetBool returns True if v is true, False otherwise.

func NewInt

func NewInt(value int) *Int

NewInt returns a new Int holding the given integer value.

func (*Int) IsTrue

func (i *Int) IsTrue() bool

IsTrue returns false if i is zero, true otherwise.

func (*Int) ToObject

func (i *Int) ToObject() *Object

ToObject upcasts i to an Object.

func (*Int) Value

func (i *Int) Value() int

Value returns the underlying integer value held by i.

type KWArg

type KWArg struct {
	Name  string
	Value *Object
}

KWArg represents a keyword argument in a call to a Python function.

type KWArgs

type KWArgs []KWArg

KWArgs represents a list of keyword parameters in a call to a Python function.

func (KWArgs) String

func (k KWArgs) String() string

String returns a string representation of k, e.g. for debugging.

type List

type List struct {
	Object
	// contains filtered or unexported fields
}

List represents Python 'list' objects.

Lists are thread safe, however read operations are not necessarily atomic. E.g. given the list l = [1, 2, 3] executing del l[1] in one thread may give repr(l) == [1, 2] in another which is never correct.

func NewList

func NewList(elems ...*Object) *List

NewList returns a list containing the given elements.

func (*List) Append

func (l *List) Append(o *Object)

Append adds o to the end of l.

func (*List) DelItem

func (l *List) DelItem(f *Frame, index int) *BaseException

DelItem removes the index'th element of l.

func (*List) DelSlice

func (l *List) DelSlice(f *Frame, s *Slice) *BaseException

DelSlice removes the slice of l specified by s.

func (*List) Reverse

func (l *List) Reverse()

Reverse the list in place.

func (*List) SetItem

func (l *List) SetItem(f *Frame, index int, value *Object) *BaseException

SetItem sets the index'th element of l to value.

func (*List) SetSlice

func (l *List) SetSlice(f *Frame, s *Slice, value *Object) *BaseException

SetSlice replaces the slice of l specified by s with the contents of value (an iterable).

func (*List) Sort

func (l *List) Sort(f *Frame) (raised *BaseException)

Sort reorders l so that its elements are in sorted order.

func (*List) ToObject

func (l *List) ToObject() *Object

ToObject upcasts l to an Object.

type Long

type Long struct {
	Object
	// contains filtered or unexported fields
}

Long represents Python 'long' objects.

func NewLong

func NewLong(x *big.Int) *Long

NewLong returns a new Long holding the given value.

func NewLongFromBytes

func NewLongFromBytes(b []byte) *Long

NewLongFromBytes returns a new Long holding the given bytes, interpreted as a big endian unsigned integer.

func (*Long) IntValue

func (l *Long) IntValue(f *Frame) (int, *BaseException)

IntValue returns l's value as a plain int if it will not overflow. Otherwise raises OverflowErrorType.

func (*Long) IsTrue

func (l *Long) IsTrue() bool

IsTrue returns false if l is zero, true otherwise.

func (*Long) Neg

func (l *Long) Neg() *Long

Neg returns a new Long that is the negative of l.

func (*Long) ToObject

func (l *Long) ToObject() *Object

ToObject upcasts l to an Object.

func (*Long) Value

func (l *Long) Value() *big.Int

Value returns the underlying integer value held by l.

type Method

type Method struct {
	Object
	// contains filtered or unexported fields
}

Method represents Python 'instancemethod' objects.

func (*Method) ToObject

func (m *Method) ToObject() *Object

ToObject upcasts m to an Object.

type Module

type Module struct {
	Object
	// contains filtered or unexported fields
}

Module represents Python 'module' objects.

func (*Module) GetFilename

func (m *Module) GetFilename(f *Frame) (*Str, *BaseException)

GetFilename returns the __file__ attribute of m, raising SystemError if it does not exist.

func (*Module) GetName

func (m *Module) GetName(f *Frame) (*Str, *BaseException)

GetName returns the __name__ attribute of m, raising SystemError if it does not exist.

func (*Module) ToObject

func (m *Module) ToObject() *Object

ToObject upcasts m to an Object.

type ModuleInit

type ModuleInit func(f *Frame, m *Module) *BaseException

ModuleInit functions are called when importing Grumpy modules to execute the top level code for that module.

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object represents Python 'object' objects.

func (*Object) Call

func (o *Object) Call(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException)

Call invokes the callable Python object o with the given positional and keyword args. args must be non-nil (but can be empty). kwargs can be nil.

func (*Object) Dict

func (o *Object) Dict() *Dict

Dict returns o's object dict, aka __dict__.

func (*Object) String

func (o *Object) String() string

String returns a string representation of o, e.g. for debugging.

func (*Object) Type

func (o *Object) Type() *Type

Type returns the Python type of o.

type Param

type Param struct {
	// Name is the argument name.
	Name string
	// Def is the default value to use if the argument is not provided. If
	// no default is specified then Def is nil.
	Def *Object
}

Param describes a parameter to a Python function.

type ParamSpec

type ParamSpec struct {
	Count int
	// contains filtered or unexported fields
}

ParamSpec describes a Python function's parameters.

func NewParamSpec

func NewParamSpec(name string, params []Param, varArg bool, kwArg bool) *ParamSpec

NewParamSpec returns a new ParamSpec that accepts the given positional parameters and optional vararg and/or kwarg parameter.

func (*ParamSpec) Validate

func (s *ParamSpec) Validate(f *Frame, validated []*Object, args Args, kwargs KWArgs) *BaseException

Validate ensures that a the args and kwargs passed are valid arguments for the param spec s. The validated parameters are output to the validated slice which must have len s.Count.

type Property

type Property struct {
	Object
	// contains filtered or unexported fields
}

Property represents Python 'property' objects.

func (*Property) ToObject

func (p *Property) ToObject() *Object

ToObject upcasts p to an Object.

type RunState

type RunState int

RunState represents the current point of execution within a Python function.

type Set

type Set setBase

Set represents Python 'set' objects.

func NewSet

func NewSet() *Set

NewSet returns an empty Set.

func (*Set) Add

func (s *Set) Add(f *Frame, key *Object) (bool, *BaseException)

Add inserts key into s. If key already exists then does nothing.

func (*Set) Contains

func (s *Set) Contains(f *Frame, key *Object) (bool, *BaseException)

Contains returns true if key exists in s.

func (*Set) Remove

func (s *Set) Remove(f *Frame, key *Object) (bool, *BaseException)

Remove erases key from s. If key is not in s then raises KeyError.

func (*Set) ToObject

func (s *Set) ToObject() *Object

ToObject upcasts s to an Object.

func (*Set) Update

func (s *Set) Update(f *Frame, o *Object) *BaseException

Update inserts all elements in the iterable o into s.

type Slice

type Slice struct {
	Object
	// contains filtered or unexported fields
}

Slice represents Python 'slice' objects.

func (*Slice) ToObject

func (s *Slice) ToObject() *Object

ToObject upcasts s to an Object.

type Str

type Str struct {
	Object
	// contains filtered or unexported fields
}

Str represents Python 'str' objects.

func InternStr

func InternStr(s string) *Str

InternStr adds s to the interned string map. Subsequent calls to NewStr() will return the same underlying Str. InternStr is not thread safe and should only be called during module initialization time.

func NewStr

func NewStr(value string) *Str

NewStr returns a new Str holding the given string value.

func (*Str) Decode

func (s *Str) Decode(f *Frame, encoding, errors string) (*Unicode, *BaseException)

Decode produces a unicode object from the bytes of s assuming they have the given encoding. Invalid code points are resolved using a strategy given by errors: "ignore" will bypass them, "replace" will substitute the Unicode replacement character (U+FFFD) and "strict" will raise UnicodeDecodeError.

NOTE: Decoding UTF-8 data containing surrogates (e.g. U+D800 encoded as '\xed\xa0\x80') will raise UnicodeDecodeError consistent with CPython 3.x but different than 2.x.

func (*Str) ToObject

func (s *Str) ToObject() *Object

ToObject upcasts s to an Object.

func (*Str) Value

func (s *Str) Value() string

Value returns the underlying string value held by s.

type TieTarget

type TieTarget struct {
	// Target is a destination pointer where an unpacked value will be
	// stored.
	Target **Object
	// Children contains a sequence of TieTargets that should be unpacked
	// into.
	Children []TieTarget
}

TieTarget is a data structure used to facilitate iterator unpacking in assignment statements. A TieTarget should have one of Target or Children populated but not both.

As an example, the targets in the Python assignment 'foo, bar = ...' could be represented as:

TieTarget{
	Children: []TieTarget{{Target: &foo}, {Target: &bar}},
}

type Traceback

type Traceback struct {
	Object
	// contains filtered or unexported fields
}

Traceback represents Python 'traceback' objects.

func (*Traceback) ToObject

func (f *Traceback) ToObject() *Object

ToObject upcasts f to an Object.

type TryableMutex

type TryableMutex struct {
	// contains filtered or unexported fields
}

TryableMutex is a mutex-like object that also supports TryLock().

func NewTryableMutex

func NewTryableMutex() *TryableMutex

NewTryableMutex returns a new TryableMutex.

func (*TryableMutex) Lock

func (m *TryableMutex) Lock()

Lock blocks until the mutex is available and then acquires a lock.

func (*TryableMutex) TryLock

func (m *TryableMutex) TryLock() bool

TryLock returns true and acquires a lock if the mutex is available, otherwise it returns false.

func (*TryableMutex) Unlock

func (m *TryableMutex) Unlock()

Unlock releases the mutex's lock.

type Tuple

type Tuple struct {
	Object
	// contains filtered or unexported fields
}

Tuple represents Python 'tuple' objects.

Tuples are thread safe by virtue of being immutable.

func NewTuple

func NewTuple(elems ...*Object) *Tuple

NewTuple returns a tuple containing the given elements.

func NewTuple0

func NewTuple0() *Tuple

NewTuple0 returns the empty tuple. This is mostly provided for the convenience of the compiler.

func NewTuple1

func NewTuple1(elem0 *Object) *Tuple

NewTuple1 returns a tuple of length 1 containing just elem0.

func NewTuple2

func NewTuple2(elem0, elem1 *Object) *Tuple

NewTuple2 returns a tuple of length 2 containing just elem0 and elem1.

func NewTuple3

func NewTuple3(elem0, elem1, elem2 *Object) *Tuple

NewTuple3 returns a tuple of length 3 containing elem0 to elem2.

func NewTuple4

func NewTuple4(elem0, elem1, elem2, elem3 *Object) *Tuple

NewTuple4 returns a tuple of length 4 containing elem0 to elem3.

func NewTuple5

func NewTuple5(elem0, elem1, elem2, elem3, elem4 *Object) *Tuple

NewTuple5 returns a tuple of length 5 containing elem0 to elem4.

func NewTuple6

func NewTuple6(elem0, elem1, elem2, elem3, elem4, elem5 *Object) *Tuple

NewTuple6 returns a tuple of length 6 containing elem0 to elem5.

func (*Tuple) GetItem

func (t *Tuple) GetItem(i int) *Object

GetItem returns the i'th element of t. Bounds are unchecked and therefore this method will panic unless 0 <= i < t.Len().

func (*Tuple) Len

func (t *Tuple) Len() int

Len returns the number of elements in t.

func (*Tuple) ToObject

func (t *Tuple) ToObject() *Object

ToObject upcasts t to an Object.

type Type

type Type struct {
	Object
	// contains filtered or unexported fields
}

Type represents Python 'type' objects.

func (*Type) FullName

func (t *Type) FullName(f *Frame) (string, *BaseException)

FullName returns t's fully qualified name including the module.

func (*Type) Name

func (t *Type) Name() string

Name returns t's name field.

func (*Type) ToObject

func (t *Type) ToObject() *Object

ToObject upcasts t to an Object.

type Unicode

type Unicode struct {
	Object
	// contains filtered or unexported fields
}

Unicode represents Python 'unicode' objects. The string value is stored as utf-32 data.

func NewUnicode

func NewUnicode(value string) *Unicode

NewUnicode returns a new Unicode holding the given string value. value is assumed to be a valid utf-8 string.

func NewUnicodeFromRunes

func NewUnicodeFromRunes(value []rune) *Unicode

NewUnicodeFromRunes returns a new Unicode holding the given runes.

func (*Unicode) Encode

func (s *Unicode) Encode(f *Frame, encoding, errors string) (*Str, *BaseException)

Encode translates the runes in s into a str with the given encoding.

NOTE: If s contains surrogates (e.g. U+D800), Encode will raise UnicodeDecodeError consistent with CPython 3.x but different than 2.x.

func (*Unicode) ToObject

func (s *Unicode) ToObject() *Object

ToObject upcasts s to an Object.

func (*Unicode) Value

func (s *Unicode) Value() []rune

Value returns the underlying string value held by s.

type WeakRef

type WeakRef struct {
	Object
	// contains filtered or unexported fields
}

WeakRef represents Python 'weakref' objects.

func (*WeakRef) ToObject

func (r *WeakRef) ToObject() *Object

ToObject upcasts r to an Object.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL