const BuilderModeDoc = `Options controlling the SSA builder.
The value is a sequence of zero or more of these letters:
C perform sanity [C]hecking of the SSA form.
D include [D]ebug info for every function.
P print [P]ackage inventory.
F print [F]unction SSA code.
S log [S]ource locations as SSA builder progresses.
L build distinct packages seria[L]ly instead of in parallel.
N build [N]aive SSA form: don't replace local loads/stores with registers.
I build bare [I]nit functions: no init guards or calls to dependent inits.
`
func DefaultType(typ types.Type) types.Type
DefaultType returns the default "typed" type for an "untyped" type; it returns the incoming type for all other types. The default type for untyped nil is untyped nil.
Exported to ssa/interp.
TODO(adonovan): use go/types.DefaultType after 1.8.
func FindTests(pkg *Package) (tests, benchmarks, examples []*Function, main *Function)
FindTests returns the Test, Benchmark, and Example functions (as defined by "go test") defined in the specified package, and its TestMain function, if any.
Deprecated: Use golang.org/x/tools/go/packages to access synthetic testmain packages.
func HasEnclosingFunction(pkg *Package, path []ast.Node) bool
HasEnclosingFunction returns true if the AST node denoted by path is contained within the declaration of some function or package-level variable.
Unlike EnclosingFunction, the behaviour of this function does not depend on whether SSA code for pkg has been built, so it can be used to quickly reject check inputs that will cause EnclosingFunction to fail, prior to SSA building.
func WriteFunction(buf *bytes.Buffer, f *Function)
WriteFunction writes to buf a human-readable "disassembly" of f.
func WritePackage(buf *bytes.Buffer, p *Package)
WritePackage writes to buf a human-readable summary of p.
The Alloc instruction reserves space for a variable of the given type, zero-initializes it, and yields its address.
Alloc values are always addresses, and have pointer types, so the type of the allocated variable is actually Type().Underlying().(*types.Pointer).Elem().
If Heap is false, Alloc allocates space in the function's activation record (frame); we refer to an Alloc(Heap=false) as a "local" alloc. Each local Alloc returns the same address each time it is executed within the same activation; the space is re-initialized to zero.
If Heap is true, Alloc allocates space in the heap; we refer to an Alloc(Heap=true) as a "new" alloc. Each new Alloc returns a different address each time it is executed.
When Alloc is applied to a channel, map or slice type, it returns the address of an uninitialized (nil) reference of that kind; store the result of MakeSlice, MakeMap or MakeChan in that location to instantiate these types.
Pos() returns the ast.CompositeLit.Lbrace for a composite literal, or the ast.CallExpr.Rparen for a call to new() or for a call that allocates a varargs slice.
Example printed form:
t0 = local int t1 = new int
type Alloc struct { Comment string Heap bool // contains filtered or unexported fields }
func (v *Alloc) Name() string
func (v *Alloc) Operands(rands []*Value) []*Value
func (v *Alloc) Pos() token.Pos
func (v *Alloc) Referrers() *[]Instruction
func (v *Alloc) String() string
func (v *Alloc) Type() types.Type
BasicBlock represents an SSA basic block.
The final element of Instrs is always an explicit transfer of control (If, Jump, Return, or Panic).
A block may contain no Instructions only if it is unreachable, i.e., Preds is nil. Empty blocks are typically pruned.
BasicBlocks and their Preds/Succs relation form a (possibly cyclic) graph independent of the SSA Value graph: the control-flow graph or CFG. It is illegal for multiple edges to exist between the same pair of blocks.
Each BasicBlock is also a node in the dominator tree of the CFG. The tree may be navigated using Idom()/Dominees() and queried using Dominates().
The order of Preds and Succs is significant (to Phi and If instructions, respectively).
type BasicBlock struct { Index int // index of this block within Parent().Blocks Comment string // optional label; no semantic significance Instrs []Instruction // instructions in order Preds, Succs []*BasicBlock // predecessors and successors // contains filtered or unexported fields }
func (b *BasicBlock) Dominates(c *BasicBlock) bool
Dominates reports whether b dominates c.
func (b *BasicBlock) Dominees() []*BasicBlock
Dominees returns the list of blocks that b immediately dominates: its children in the dominator tree.
func (b *BasicBlock) Idom() *BasicBlock
Idom returns the block that immediately dominates b: its parent in the dominator tree, if any. Neither the entry node (b.Index==0) nor recover node (b==b.Parent().Recover()) have a parent.
func (b *BasicBlock) Parent() *Function
Parent returns the function that contains block b.
func (b *BasicBlock) String() string
String returns a human-readable label of this block. It is not guaranteed unique within the function.
The BinOp instruction yields the result of binary operation X Op Y.
Pos() returns the ast.BinaryExpr.OpPos, if explicit in the source.
Example printed form:
t1 = t0 + 1:int
type BinOp struct { // One of: // ADD SUB MUL QUO REM + - * / % // AND OR XOR SHL SHR AND_NOT & | ^ << >> &^ // EQL NEQ LSS LEQ GTR GEQ == != < <= < >= Op token.Token X, Y Value // contains filtered or unexported fields }
func (v *BinOp) Name() string
func (v *BinOp) Operands(rands []*Value) []*Value
func (v *BinOp) Pos() token.Pos
func (v *BinOp) Referrers() *[]Instruction
func (v *BinOp) String() string
func (v *BinOp) Type() types.Type
BuilderMode is a bitmask of options for diagnostics and checking.
*BuilderMode satisfies the flag.Value interface. Example:
var mode = ssa.BuilderMode(0) func init() { flag.Var(&mode, "build", ssa.BuilderModeDoc) }
type BuilderMode uint
const ( PrintPackages BuilderMode = 1 << iota // Print package inventory to stdout PrintFunctions // Print function SSA code to stdout LogSource // Log source locations as SSA builder progresses SanityCheckFunctions // Perform sanity checking of function bodies NaiveForm // Build naïve SSA form: don't replace local loads/stores with registers BuildSerially // Build packages serially, not in parallel. GlobalDebug // Enable debug info for all packages BareInits // Build init functions without guards or calls to dependent inits )
func (m BuilderMode) Get() interface{}
Get returns m.
func (m *BuilderMode) Set(s string) error
Set parses the flag characters in s and updates *m.
func (m BuilderMode) String() string
A Builtin represents a specific use of a built-in function, e.g. len.
Builtins are immutable values. Builtins do not have addresses. Builtins can only appear in CallCommon.Func.
Name() indicates the function: one of the built-in functions from the Go spec (excluding "make" and "new") or one of these ssa-defined intrinsics:
// wrapnilchk returns ptr if non-nil, panics otherwise. // (For use in indirection wrappers.) func ssa:wrapnilchk(ptr *T, recvType, methodName string) *T
Object() returns a *types.Builtin for built-ins defined by the spec, nil for others.
Type() returns a *types.Signature representing the effective signature of the built-in for this call.
type Builtin struct {
// contains filtered or unexported fields
}
func (v *Builtin) Name() string
func (v *Builtin) Object() types.Object
func (v *Builtin) Operands(rands []*Value) []*Value
Non-Instruction Values:
func (v *Builtin) Parent() *Function
func (v *Builtin) Pos() token.Pos
func (*Builtin) Referrers() *[]Instruction
func (v *Builtin) String() string
func (v *Builtin) Type() types.Type
The Call instruction represents a function or method call.
The Call instruction yields the function result if there is exactly one. Otherwise it returns a tuple, the components of which are accessed via Extract.
See CallCommon for generic function call documentation.
Pos() returns the ast.CallExpr.Lparen, if explicit in the source.
Example printed form:
t2 = println(t0, t1) t4 = t3() t7 = invoke t5.Println(...t6)
type Call struct { Call CallCommon // contains filtered or unexported fields }
func (s *Call) Common() *CallCommon
func (v *Call) Name() string
func (s *Call) Operands(rands []*Value) []*Value
func (v *Call) Pos() token.Pos
func (v *Call) Referrers() *[]Instruction
func (v *Call) String() string
func (v *Call) Type() types.Type
func (s *Call) Value() *Call
CallCommon is contained by Go, Defer and Call to hold the common parts of a function or method call.
Each CallCommon exists in one of two modes, function call and interface method invocation, or "call" and "invoke" for short.
1. "call" mode: when Method is nil (!IsInvoke), a CallCommon represents an ordinary function call of the value in Value, which may be a *Builtin, a *Function or any other value of kind 'func'.
Value may be one of:
(a) a *Function, indicating a statically dispatched call to a package-level function, an anonymous function, or a method of a named type. (b) a *MakeClosure, indicating an immediately applied function literal with free variables. (c) a *Builtin, indicating a statically dispatched call to a built-in function. (d) any other value, indicating a dynamically dispatched function call.
StaticCallee returns the identity of the callee in cases (a) and (b), nil otherwise.
Args contains the arguments to the call. If Value is a method, Args[0] contains the receiver parameter.
Example printed form:
t2 = println(t0, t1) go t3() defer t5(...t6)
2. "invoke" mode: when Method is non-nil (IsInvoke), a CallCommon represents a dynamically dispatched call to an interface method. In this mode, Value is the interface value and Method is the interface's abstract method. Note: an abstract method may be shared by multiple interfaces due to embedding; Value.Type() provides the specific interface used for this call.
Value is implicitly supplied to the concrete method implementation as the receiver parameter; in other words, Args[0] holds not the receiver but the first true argument.
Example printed form:
t1 = invoke t0.String() go invoke t3.Run(t2) defer invoke t4.Handle(...t5)
For all calls to variadic functions (Signature().Variadic()), the last element of Args is a slice.
type CallCommon struct { Value Value // receiver (invoke mode) or func value (call mode) Method *types.Func // abstract method (invoke mode) Args []Value // actual parameters (in static method call, includes receiver) // contains filtered or unexported fields }
func (c *CallCommon) Description() string
Description returns a description of the mode of this call suitable for a user interface, e.g., "static method call".
func (c *CallCommon) IsInvoke() bool
IsInvoke returns true if this call has "invoke" (not "call") mode.
func (c *CallCommon) Operands(rands []*Value) []*Value
func (c *CallCommon) Pos() token.Pos
func (c *CallCommon) Signature() *types.Signature
Signature returns the signature of the called function.
For an "invoke"-mode call, the signature of the interface method is returned.
In either "call" or "invoke" mode, if the callee is a method, its receiver is represented by sig.Recv, not sig.Params().At(0).
func (c *CallCommon) StaticCallee() *Function
StaticCallee returns the callee if this is a trivially static "call"-mode call to a function.
func (c *CallCommon) String() string
The CallInstruction interface, implemented by *Go, *Defer and *Call, exposes the common parts of function-calling instructions, yet provides a way back to the Value defined by *Call alone.
type CallInstruction interface { Instruction Common() *CallCommon // returns the common parts of the call Value() *Call // returns the result value of the call (*Call) or nil (*Go, *Defer) }
ChangeInterface constructs a value of one interface type from a value of another interface type known to be assignable to it. This operation cannot fail.
Pos() returns the ast.CallExpr.Lparen if the instruction arose from an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the instruction arose from an explicit e.(T) operation; or token.NoPos otherwise.
Example printed form:
t1 = change interface interface{} <- I (t0)
type ChangeInterface struct { X Value // contains filtered or unexported fields }
func (v *ChangeInterface) Name() string
func (v *ChangeInterface) Operands(rands []*Value) []*Value
func (v *ChangeInterface) Pos() token.Pos
func (v *ChangeInterface) Referrers() *[]Instruction
func (v *ChangeInterface) String() string
func (v *ChangeInterface) Type() types.Type
The ChangeType instruction applies to X a value-preserving type change to Type().
Type changes are permitted:
- between a named type and its underlying type. - between two named types of the same underlying type. - between (possibly named) pointers to identical base types. - from a bidirectional channel to a read- or write-channel, optionally adding/removing a name.
This operation cannot fail dynamically.
Pos() returns the ast.CallExpr.Lparen, if the instruction arose from an explicit conversion in the source.
Example printed form:
t1 = changetype *int <- IntPtr (t0)
type ChangeType struct { X Value // contains filtered or unexported fields }
func (v *ChangeType) Name() string
func (v *ChangeType) Operands(rands []*Value) []*Value
func (v *ChangeType) Pos() token.Pos
func (v *ChangeType) Referrers() *[]Instruction
func (v *ChangeType) String() string
func (v *ChangeType) Type() types.Type
A Const represents the value of a constant expression.
The underlying type of a constant may be any boolean, numeric, or string type. In addition, a Const may represent the nil value of any reference type---interface, map, channel, pointer, slice, or function---but not "untyped nil".
All source-level constant expressions are represented by a Const of the same type and value.
Value holds the value of the constant, independent of its Type(), using go/constant representation, or nil for a typed nil value.
Pos() returns token.NoPos.
Example printed form:
42:int "hello":untyped string 3+4i:MyComplex
type Const struct { Value constant.Value // contains filtered or unexported fields }
func NewConst(val constant.Value, typ types.Type) *Const
NewConst returns a new constant of the specified value and type. val must be valid according to the specification of Const.Value.
func (c *Const) Complex128() complex128
Complex128 returns the complex value of this constant truncated to fit a complex128.
func (c *Const) Float64() float64
Float64 returns the numeric value of this constant truncated to fit a float64.
func (c *Const) Int64() int64
Int64 returns the numeric value of this constant truncated to fit a signed 64-bit integer.
func (c *Const) IsNil() bool
IsNil returns true if this constant represents a typed or untyped nil value.
func (c *Const) Name() string
func (v *Const) Operands(rands []*Value) []*Value
func (c *Const) Parent() *Function
func (c *Const) Pos() token.Pos
func (c *Const) Referrers() *[]Instruction
func (c *Const) RelString(from *types.Package) string
func (c *Const) String() string
func (c *Const) Type() types.Type
func (c *Const) Uint64() uint64
Uint64 returns the numeric value of this constant truncated to fit an unsigned 64-bit integer.
The Convert instruction yields the conversion of value X to type Type(). One or both of those types is basic (but possibly named).
A conversion may change the value and representation of its operand. Conversions are permitted:
- between real numeric types. - between complex numeric types. - between string and []byte or []rune. - between pointers and unsafe.Pointer. - between unsafe.Pointer and uintptr. - from (Unicode) integer to (UTF-8) string.
A conversion may imply a type name change also.
This operation cannot fail dynamically.
Conversions of untyped string/number/bool constants to a specific representation are eliminated during SSA construction.
Pos() returns the ast.CallExpr.Lparen, if the instruction arose from an explicit conversion in the source.
Example printed form:
t1 = convert []byte <- string (t0)
type Convert struct { X Value // contains filtered or unexported fields }
func (v *Convert) Name() string
func (v *Convert) Operands(rands []*Value) []*Value
func (v *Convert) Pos() token.Pos
func (v *Convert) Referrers() *[]Instruction
func (v *Convert) String() string
func (v *Convert) Type() types.Type
A DebugRef instruction maps a source-level expression Expr to the SSA value X that represents the value (!IsAddr) or address (IsAddr) of that expression.
DebugRef is a pseudo-instruction: it has no dynamic effect.
Pos() returns Expr.Pos(), the start position of the source-level expression. This is not the same as the "designated" token as documented at Value.Pos(). e.g. CallExpr.Pos() does not return the position of the ("designated") Lparen token.
If Expr is an *ast.Ident denoting a var or func, Object() returns the object; though this information can be obtained from the type checker, including it here greatly facilitates debugging. For non-Ident expressions, Object() returns nil.
DebugRefs are generated only for functions built with debugging enabled; see Package.SetDebugMode() and the GlobalDebug builder mode flag.
DebugRefs are not emitted for ast.Idents referring to constants or predeclared identifiers, since they are trivial and numerous. Nor are they emitted for ast.ParenExprs.
(By representing these as instructions, rather than out-of-band, consistency is maintained during transformation passes by the ordinary SSA renaming machinery.)
Example printed form:
; *ast.CallExpr @ 102:9 is t5 ; var x float64 @ 109:72 is x ; address of *ast.CompositeLit @ 216:10 is t0
type DebugRef struct { Expr ast.Expr // the referring expression (never *ast.ParenExpr) IsAddr bool // Expr is addressable and X is the address it denotes X Value // the value or address of Expr // contains filtered or unexported fields }
func (v *DebugRef) Block() *BasicBlock
func (s *DebugRef) Operands(rands []*Value) []*Value
func (v *DebugRef) Parent() *Function
func (s *DebugRef) Pos() token.Pos
func (v *DebugRef) Referrers() *[]Instruction
func (s *DebugRef) String() string
The Defer instruction pushes the specified call onto a stack of functions to be called by a RunDefers instruction or by a panic.
See CallCommon for generic function call documentation.
Pos() returns the ast.DeferStmt.Defer.
Example printed form:
defer println(t0, t1) defer t3() defer invoke t5.Println(...t6)
type Defer struct { Call CallCommon // contains filtered or unexported fields }
func (v *Defer) Block() *BasicBlock
func (s *Defer) Common() *CallCommon
func (s *Defer) Operands(rands []*Value) []*Value
func (v *Defer) Parent() *Function
func (s *Defer) Pos() token.Pos
func (v *Defer) Referrers() *[]Instruction
func (s *Defer) String() string
func (s *Defer) Value() *Call
The Extract instruction yields component Index of Tuple.
This is used to access the results of instructions with multiple return values, such as Call, TypeAssert, Next, UnOp(ARROW) and IndexExpr(Map).
Example printed form:
t1 = extract t0 #1
type Extract struct { Tuple Value Index int // contains filtered or unexported fields }
func (v *Extract) Name() string
func (v *Extract) Operands(rands []*Value) []*Value
func (v *Extract) Pos() token.Pos
func (v *Extract) Referrers() *[]Instruction
func (v *Extract) String() string
func (v *Extract) Type() types.Type
The Field instruction yields the Field of struct X.
The field is identified by its index within the field list of the struct type of X; by using numeric indices we avoid ambiguity of package-local identifiers and permit compact representations.
Pos() returns the position of the ast.SelectorExpr.Sel for the field, if explicit in the source.
Example printed form:
t1 = t0.name [#1]
type Field struct { X Value // struct Field int // index into X.Type().(*types.Struct).Fields // contains filtered or unexported fields }
func (v *Field) Name() string
func (v *Field) Operands(rands []*Value) []*Value
func (v *Field) Pos() token.Pos
func (v *Field) Referrers() *[]Instruction
func (v *Field) String() string
func (v *Field) Type() types.Type
The FieldAddr instruction yields the address of Field of *struct X.
The field is identified by its index within the field list of the struct type of X.
Dynamically, this instruction panics if X evaluates to a nil pointer.
Type() returns a (possibly named) *types.Pointer.
Pos() returns the position of the ast.SelectorExpr.Sel for the field, if explicit in the source.
Example printed form:
t1 = &t0.name [#1]
type FieldAddr struct { X Value // *struct Field int // field is X.Type().Underlying().(*types.Pointer).Elem().Underlying().(*types.Struct).Field(Field) // contains filtered or unexported fields }
func (v *FieldAddr) Name() string
func (v *FieldAddr) Operands(rands []*Value) []*Value
func (v *FieldAddr) Pos() token.Pos
func (v *FieldAddr) Referrers() *[]Instruction
func (v *FieldAddr) String() string
func (v *FieldAddr) Type() types.Type
A FreeVar represents a free variable of the function to which it belongs.
FreeVars are used to implement anonymous functions, whose free variables are lexically captured in a closure formed by MakeClosure. The value of such a free var is an Alloc or another FreeVar and is considered a potentially escaping heap address, with pointer type.
FreeVars are also used to implement bound method closures. Such a free var represents the receiver value and may be of any type that has concrete methods.
Pos() returns the position of the value that was captured, which belongs to an enclosing function.
type FreeVar struct {
// contains filtered or unexported fields
}
func (v *FreeVar) Name() string
func (v *FreeVar) Operands(rands []*Value) []*Value
func (v *FreeVar) Parent() *Function
func (v *FreeVar) Pos() token.Pos
func (v *FreeVar) Referrers() *[]Instruction
func (v *FreeVar) String() string
func (v *FreeVar) Type() types.Type
Function represents the parameters, results, and code of a function or method.
If Blocks is nil, this indicates an external function for which no Go source code is available. In this case, FreeVars and Locals are nil too. Clients performing whole-program analysis must handle external functions specially.
Blocks contains the function's control-flow graph (CFG). Blocks[0] is the function entry point; block order is not otherwise semantically significant, though it may affect the readability of the disassembly. To iterate over the blocks in dominance order, use DomPreorder().
Recover is an optional second entry point to which control resumes after a recovered panic. The Recover block may contain only a return statement, preceded by a load of the function's named return parameters, if any.
A nested function (Parent()!=nil) that refers to one or more lexically enclosing local variables ("free variables") has FreeVars. Such functions cannot be called directly but require a value created by MakeClosure which, via its Bindings, supplies values for these parameters.
If the function is a method (Signature.Recv() != nil) then the first element of Params is the receiver parameter.
A Go package may declare many functions called "init". For each one, Object().Name() returns "init" but Name() returns "init#1", etc, in declaration order.
Pos() returns the declaring ast.FuncLit.Type.Func or the position of the ast.FuncDecl.Name, if the function was explicit in the source. Synthetic wrappers, for which Synthetic != "", may share the same position as the function they wrap. Syntax.Pos() always returns the position of the declaring "func" token.
Type() returns the function's Signature.
type Function struct { Signature *types.Signature Synthetic string // provenance of synthetic function; "" for true source functions Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) Prog *Program // enclosing program Params []*Parameter // function parameters; for methods, includes receiver FreeVars []*FreeVar // free variables whose values must be supplied by closure Locals []*Alloc // local variables of this function Blocks []*BasicBlock // basic blocks of the function; nil => external Recover *BasicBlock // optional; control transfers here after recovered panic AnonFuncs []*Function // anonymous functions directly beneath this one // contains filtered or unexported fields }
func EnclosingFunction(pkg *Package, path []ast.Node) *Function
EnclosingFunction returns the function that contains the syntax node denoted by path.
Syntax associated with package-level variable specifications is enclosed by the package's init() function.
Returns nil if not found; reasons might include:
- the node is not enclosed by any function. - the node is within an anonymous function (FuncLit) and its SSA function has not been created yet (pkg.Build() has not yet been called).
func (f *Function) DomPreorder() []*BasicBlock
DomPreorder returns a new slice containing the blocks of f in dominator tree preorder.
func (v *Function) Name() string
func (v *Function) Object() types.Object
func (v *Function) Operands(rands []*Value) []*Value
func (v *Function) Package() *Package
func (v *Function) Parent() *Function
func (v *Function) Pos() token.Pos
func (v *Function) Referrers() *[]Instruction
func (f *Function) RelString(from *types.Package) string
RelString returns the full name of this function, qualified by package name, receiver type, etc.
The specific formatting rules are not guaranteed and may change.
Examples:
"math.IsNaN" // a package-level function "(*bytes.Buffer).Bytes" // a declared method or a wrapper "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) "main.main$1" // an anonymous function in main "main.init#1" // a declared init function "main.init" // the synthesized package initializer
When these functions are referred to from within the same package (i.e. from == f.Pkg.Object), they are rendered without the package path. For example: "IsNaN", "(*Buffer).Bytes", etc.
All non-synthetic functions have distinct package-qualified names. (But two methods may have the same name "(T).f" if one is a synthetic wrapper promoting a non-exported method "f" from another package; in that case, the strings are equal but the identifiers "f" are distinct.)
func (v *Function) String() string
func (f *Function) Syntax() ast.Node
Syntax returns an ast.Node whose Pos/End methods provide the lexical extent of the function if it was defined by Go source code (f.Synthetic==""), or nil otherwise.
If f was built with debug information (see Package.SetDebugRef), the result is the *ast.FuncDecl or *ast.FuncLit that declared the function. Otherwise, it is an opaque Node providing only position information; this avoids pinning the AST in memory.
func (v *Function) Token() token.Token
func (v *Function) Type() types.Type
func (f *Function) ValueForExpr(e ast.Expr) (value Value, isAddr bool)
ValueForExpr returns the SSA Value that corresponds to non-constant expression e.
It returns nil if no value was found, e.g.
- the expression is not lexically contained within f; - f was not built with debug information; or - e is a constant expression. (For efficiency, no debug information is stored for constants. Use go/types.Info.Types[e].Value instead.) - e is a reference to nil or a built-in function. - the value was optimised away.
If e is an addressable expression used in an lvalue context, value is the address denoted by e, and isAddr is true.
The types of e (or &e, if isAddr) and the result are equal (modulo "untyped" bools resulting from comparisons).
(Tip: to find the ssa.Value given a source position, use astutil.PathEnclosingInterval to locate the ast.Node, then EnclosingFunction to locate the Function, then ValueForExpr to find the ssa.Value.)
func (f *Function) WriteTo(w io.Writer) (int64, error)
A Global is a named Value holding the address of a package-level variable.
Pos() returns the position of the ast.ValueSpec.Names[*] identifier.
type Global struct { Pkg *Package // contains filtered or unexported fields }
func (v *Global) Name() string
func (v *Global) Object() types.Object
func (v *Global) Operands(rands []*Value) []*Value
func (v *Global) Package() *Package
func (v *Global) Parent() *Function
func (v *Global) Pos() token.Pos
func (v *Global) Referrers() *[]Instruction
func (v *Global) RelString(from *types.Package) string
func (v *Global) String() string
func (v *Global) Token() token.Token
func (v *Global) Type() types.Type
The Go instruction creates a new goroutine and calls the specified function within it.
See CallCommon for generic function call documentation.
Pos() returns the ast.GoStmt.Go.
Example printed form:
go println(t0, t1) go t3() go invoke t5.Println(...t6)
type Go struct { Call CallCommon // contains filtered or unexported fields }
func (v *Go) Block() *BasicBlock
func (s *Go) Common() *CallCommon
func (s *Go) Operands(rands []*Value) []*Value
func (v *Go) Parent() *Function
func (s *Go) Pos() token.Pos
func (v *Go) Referrers() *[]Instruction
func (s *Go) String() string
func (s *Go) Value() *Call
The If instruction transfers control to one of the two successors of its owning block, depending on the boolean Cond: the first if true, the second if false.
An If instruction must be the last instruction of its containing BasicBlock.
Pos() returns NoPos.
Example printed form:
if t0 goto done else body
type If struct { Cond Value // contains filtered or unexported fields }
func (v *If) Block() *BasicBlock
func (s *If) Operands(rands []*Value) []*Value
func (v *If) Parent() *Function
func (s *If) Pos() token.Pos
func (v *If) Referrers() *[]Instruction
func (s *If) String() string
The Index instruction yields element Index of array X.
Pos() returns the ast.IndexExpr.Lbrack for the index operation, if explicit in the source.
Example printed form:
t2 = t0[t1]
type Index struct { X Value // array Index Value // integer index // contains filtered or unexported fields }
func (v *Index) Name() string
func (v *Index) Operands(rands []*Value) []*Value
func (v *Index) Pos() token.Pos
func (v *Index) Referrers() *[]Instruction
func (v *Index) String() string
func (v *Index) Type() types.Type
The IndexAddr instruction yields the address of the element at index Index of collection X. Index is an integer expression.
The elements of maps and strings are not addressable; use Lookup or MapUpdate instead.
Dynamically, this instruction panics if X evaluates to a nil *array pointer.
Type() returns a (possibly named) *types.Pointer.
Pos() returns the ast.IndexExpr.Lbrack for the index operation, if explicit in the source.
Example printed form:
t2 = &t0[t1]
type IndexAddr struct { X Value // slice or *array, Index Value // numeric index // contains filtered or unexported fields }
func (v *IndexAddr) Name() string
func (v *IndexAddr) Operands(rands []*Value) []*Value
func (v *IndexAddr) Pos() token.Pos
func (v *IndexAddr) Referrers() *[]Instruction
func (v *IndexAddr) String() string
func (v *IndexAddr) Type() types.Type
An Instruction is an SSA instruction that computes a new Value or has some effect.
An Instruction that defines a value (e.g. BinOp) also implements the Value interface; an Instruction that only has an effect (e.g. Store) does not.
type Instruction interface { // String returns the disassembled form of this value. // // Examples of Instructions that are Values: // "x + y" (BinOp) // "len([])" (Call) // Note that the name of the Value is not printed. // // Examples of Instructions that are not Values: // "return x" (Return) // "*y = x" (Store) // // (The separation Value.Name() from Value.String() is useful // for some analyses which distinguish the operation from the // value it defines, e.g., 'y = local int' is both an allocation // of memory 'local int' and a definition of a pointer y.) String() string // Parent returns the function to which this instruction // belongs. Parent() *Function // Block returns the basic block to which this instruction // belongs. Block() *BasicBlock // Operands returns the operands of this instruction: the // set of Values it references. // // Specifically, it appends their addresses to rands, a // user-provided slice, and returns the resulting slice, // permitting avoidance of memory allocation. // // The operands are appended in undefined order, but the order // is consistent for a given Instruction; the addresses are // always non-nil but may point to a nil Value. Clients may // store through the pointers, e.g. to effect a value // renaming. // // Value.Referrers is a subset of the inverse of this // relation. (Referrers are not tracked for all types of // Values.) Operands(rands []*Value) []*Value // Pos returns the location of the AST token most closely // associated with the operation that gave rise to this // instruction, or token.NoPos if it was not explicit in the // source. // // For each ast.Node type, a particular token is designated as // the closest location for the expression, e.g. the Go token // for an *ast.GoStmt. This permits a compact but approximate // mapping from Instructions to source positions for use in // diagnostic messages, for example. // // (Do not use this position to determine which Instruction // corresponds to an ast.Expr; see the notes for Value.Pos. // This position may be used to determine which non-Value // Instruction corresponds to some ast.Stmts, but not all: If // and Jump instructions have no Pos(), for example.) Pos() token.Pos // contains filtered or unexported methods }
The Jump instruction transfers control to the sole successor of its owning block.
A Jump must be the last instruction of its containing BasicBlock.
Pos() returns NoPos.
Example printed form:
jump done
type Jump struct {
// contains filtered or unexported fields
}
func (v *Jump) Block() *BasicBlock
func (*Jump) Operands(rands []*Value) []*Value
func (v *Jump) Parent() *Function
func (s *Jump) Pos() token.Pos
func (v *Jump) Referrers() *[]Instruction
func (s *Jump) String() string
The Lookup instruction yields element Index of collection X, a map or string. Index is an integer expression if X is a string or the appropriate key type if X is a map.
If CommaOk, the result is a 2-tuple of the value above and a boolean indicating the result of a map membership test for the key. The components of the tuple are accessed using Extract.
Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source.
Example printed form:
t2 = t0[t1] t5 = t3[t4],ok
type Lookup struct { X Value // string or map Index Value // numeric or key-typed index CommaOk bool // return a value,ok pair // contains filtered or unexported fields }
func (v *Lookup) Name() string
func (v *Lookup) Operands(rands []*Value) []*Value
func (v *Lookup) Pos() token.Pos
func (v *Lookup) Referrers() *[]Instruction
func (v *Lookup) String() string
func (v *Lookup) Type() types.Type
The MakeChan instruction creates a new channel object and yields a value of kind chan.
Type() returns a (possibly named) *types.Chan.
Pos() returns the ast.CallExpr.Lparen for the make(chan) that created it.
Example printed form:
t0 = make chan int 0 t0 = make IntChan 0
type MakeChan struct { Size Value // int; size of buffer; zero => synchronous. // contains filtered or unexported fields }
func (v *MakeChan) Name() string
func (v *MakeChan) Operands(rands []*Value) []*Value
func (v *MakeChan) Pos() token.Pos
func (v *MakeChan) Referrers() *[]Instruction
func (v *MakeChan) String() string
func (v *MakeChan) Type() types.Type
The MakeClosure instruction yields a closure value whose code is Fn and whose free variables' values are supplied by Bindings.
Type() returns a (possibly named) *types.Signature.
Pos() returns the ast.FuncLit.Type.Func for a function literal closure or the ast.SelectorExpr.Sel for a bound method closure.
Example printed form:
t0 = make closure<EMAIL_ADDRESS>[x y z] t1 = make closure bound$(main.I).add [i]
type MakeClosure struct { Fn Value // always a *Function Bindings []Value // values for each free variable in Fn.FreeVars // contains filtered or unexported fields }
func (v *MakeClosure) Name() string
func (v *MakeClosure) Operands(rands []*Value) []*Value
func (v *MakeClosure) Pos() token.Pos
func (v *MakeClosure) Referrers() *[]Instruction
func (v *MakeClosure) String() string
func (v *MakeClosure) Type() types.Type
MakeInterface constructs an instance of an interface type from a value of a concrete type.
Use Program.MethodSets.MethodSet(X.Type()) to find the method-set of X, and Program.MethodValue(m) to find the implementation of a method.
To construct the zero value of an interface type T, use:
NewConst(constant.MakeNil(), T, pos)
Pos() returns the ast.CallExpr.Lparen, if the instruction arose from an explicit conversion in the source.
Example printed form:
t1 = make interface{} <- int (42:int) t2 = make Stringer <- t0
type MakeInterface struct { X Value // contains filtered or unexported fields }
func (v *MakeInterface) Name() string
func (v *MakeInterface) Operands(rands []*Value) []*Value
func (v *MakeInterface) Pos() token.Pos
func (v *MakeInterface) Referrers() *[]Instruction
func (v *MakeInterface) String() string
func (v *MakeInterface) Type() types.Type
The MakeMap instruction creates a new hash-table-based map object and yields a value of kind map.
Type() returns a (possibly named) *types.Map.
Pos() returns the ast.CallExpr.Lparen, if created by make(map), or the ast.CompositeLit.Lbrack if created by a literal.
Example printed form:
t1 = make map[string]int t0 t1 = make StringIntMap t0
type MakeMap struct { Reserve Value // initial space reservation; nil => default // contains filtered or unexported fields }
func (v *MakeMap) Name() string
func (v *MakeMap) Operands(rands []*Value) []*Value
func (v *MakeMap) Pos() token.Pos
func (v *MakeMap) Referrers() *[]Instruction
func (v *MakeMap) String() string
func (v *MakeMap) Type() types.Type
The MakeSlice instruction yields a slice of length Len backed by a newly allocated array of length Cap.
Both Len and Cap must be non-nil Values of integer type.
(Alloc(types.Array) followed by Slice will not suffice because Alloc can only create arrays of constant length.)
Type() returns a (possibly named) *types.Slice.
Pos() returns the ast.CallExpr.Lparen for the make([]T) that created it.
Example printed form:
t1 = make []string 1:int t0 t1 = make StringSlice 1:int t0
type MakeSlice struct { Len Value Cap Value // contains filtered or unexported fields }
func (v *MakeSlice) Name() string
func (v *MakeSlice) Operands(rands []*Value) []*Value
func (v *MakeSlice) Pos() token.Pos
func (v *MakeSlice) Referrers() *[]Instruction
func (v *MakeSlice) String() string
func (v *MakeSlice) Type() types.Type
The MapUpdate instruction updates the association of Map[Key] to Value.
Pos() returns the ast.KeyValueExpr.Colon or ast.IndexExpr.Lbrack, if explicit in the source.
Example printed form:
t0[t1] = t2
type MapUpdate struct { Map Value Key Value Value Value // contains filtered or unexported fields }
func (v *MapUpdate) Block() *BasicBlock
func (v *MapUpdate) Operands(rands []*Value) []*Value
func (v *MapUpdate) Parent() *Function
func (s *MapUpdate) Pos() token.Pos
func (v *MapUpdate) Referrers() *[]Instruction
func (s *MapUpdate) String() string
A Member is a member of a Go package, implemented by *NamedConst, *Global, *Function, or *Type; they are created by package-level const, var, func and type declarations respectively.
type Member interface { Name() string // declared name of the package member String() string // package-qualified name of the package member RelString(*types.Package) string // like String, but relative refs are unqualified Object() types.Object // typechecker's object for this member, if any Pos() token.Pos // position of member's declaration, if known Type() types.Type // type of the package member Token() token.Token // token.{VAR,FUNC,CONST,TYPE} Package() *Package // the containing package }
A NamedConst is a Member of a Package representing a package-level named constant.
Pos() returns the position of the declaring ast.ValueSpec.Names[*] identifier.
NB: a NamedConst is not a Value; it contains a constant Value, which it augments with the name and position of its 'const' declaration.
type NamedConst struct { Value *Const // contains filtered or unexported fields }
func (c *NamedConst) Name() string
func (c *NamedConst) Object() types.Object
func (c *NamedConst) Package() *Package
func (c *NamedConst) Pos() token.Pos
func (c *NamedConst) RelString(from *types.Package) string
func (c *NamedConst) String() string
func (c *NamedConst) Token() token.Token
func (c *NamedConst) Type() types.Type
The Next instruction reads and advances the (map or string) iterator Iter and returns a 3-tuple value (ok, k, v). If the iterator is not exhausted, ok is true and k and v are the next elements of the domain and range, respectively. Otherwise ok is false and k and v are undefined.
Components of the tuple are accessed using Extract.
The IsString field distinguishes iterators over strings from those over maps, as the Type() alone is insufficient: consider map[int]rune.
Type() returns a *types.Tuple for the triple (ok, k, v). The types of k and/or v may be types.Invalid.
Example printed form:
t1 = next t0
type Next struct { Iter Value IsString bool // true => string iterator; false => map iterator. // contains filtered or unexported fields }
func (v *Next) Name() string
func (v *Next) Operands(rands []*Value) []*Value
func (v *Next) Pos() token.Pos
func (v *Next) Referrers() *[]Instruction
func (v *Next) String() string
func (v *Next) Type() types.Type
A Node is a node in the SSA value graph. Every concrete type that implements Node is also either a Value, an Instruction, or both.
Node contains the methods common to Value and Instruction, plus the Operands and Referrers methods generalized to return nil for non-Instructions and non-Values, respectively.
Node is provided to simplify SSA graph algorithms. Clients should use the more specific and informative Value or Instruction interfaces where appropriate.
type Node interface { // Common methods: String() string Pos() token.Pos Parent() *Function // Partial methods: Operands(rands []*Value) []*Value // nil for non-Instructions Referrers() *[]Instruction // nil for non-Values }
A Package is a single analyzed Go package containing Members for all package-level functions, variables, constants and types it declares. These may be accessed directly via Members, or via the type-specific accessor methods Func, Type, Var and Const.
Members also contains entries for "init" (the synthetic package initializer) and "init#%d", the nth declared init function, and unspecified other things too.
type Package struct { Prog *Program // the owning program Pkg *types.Package // the corresponding go/types.Package Members map[string]Member // all package members keyed by name (incl. init and init#%d) // contains filtered or unexported fields }
func (p *Package) Build()
Build builds SSA code for all functions and vars in package p.
Precondition: CreatePackage must have been called for all of p's direct imports (and hence its direct imports must have been error-free).
Build is idempotent and thread-safe.
func (p *Package) Const(name string) (c *NamedConst)
Const returns the package-level constant of the specified name, or nil if not found.
func (p *Package) Func(name string) (f *Function)
Func returns the package-level function of the specified name, or nil if not found.
func (pkg *Package) SetDebugMode(debug bool)
SetDebugMode sets the debug mode for package pkg. If true, all its functions will include full debug info. This greatly increases the size of the instruction stream, and causes Functions to depend upon the ASTs, potentially keeping them live in memory for longer.
func (p *Package) String() string
func (p *Package) Type(name string) (t *Type)
Type returns the package-level type of the specified name, or nil if not found.
func (p *Package) Var(name string) (g *Global)
Var returns the package-level variable of the specified name, or nil if not found.
func (p *Package) WriteTo(w io.Writer) (int64, error)
The Panic instruction initiates a panic with value X.
A Panic instruction must be the last instruction of its containing BasicBlock, which must have no successors.
NB: 'go panic(x)' and 'defer panic(x)' do not use this instruction; they are treated as calls to a built-in function.
Pos() returns the ast.CallExpr.Lparen if this panic was explicit in the source.
Example printed form:
panic t0
type Panic struct { X Value // an interface{} // contains filtered or unexported fields }
func (v *Panic) Block() *BasicBlock
func (s *Panic) Operands(rands []*Value) []*Value
func (v *Panic) Parent() *Function
func (s *Panic) Pos() token.Pos
func (v *Panic) Referrers() *[]Instruction
func (s *Panic) String() string
A Parameter represents an input parameter of a function.
type Parameter struct {
// contains filtered or unexported fields
}
func (v *Parameter) Name() string
func (v *Parameter) Object() types.Object
func (v *Parameter) Operands(rands []*Value) []*Value
func (v *Parameter) Parent() *Function
func (v *Parameter) Pos() token.Pos
func (v *Parameter) Referrers() *[]Instruction
func (v *Parameter) String() string
func (v *Parameter) Type() types.Type
The Phi instruction represents an SSA φ-node, which combines values that differ across incoming control-flow edges and yields a new value. Within a block, all φ-nodes must appear before all non-φ nodes.
Pos() returns the position of the && or || for short-circuit control-flow joins, or that of the *Alloc for φ-nodes inserted during SSA renaming.
Example printed form:
t2 = phi [0: t0, 1: t1]
type Phi struct { Comment string // a hint as to its purpose Edges []Value // Edges[i] is value for Block().Preds[i] // contains filtered or unexported fields }
func (v *Phi) Name() string
func (v *Phi) Operands(rands []*Value) []*Value
func (v *Phi) Pos() token.Pos
func (v *Phi) Referrers() *[]Instruction
func (v *Phi) String() string
func (v *Phi) Type() types.Type
A Program is a partial or complete Go program converted to SSA form.
type Program struct { Fset *token.FileSet // position information for the files of this Program MethodSets typeutil.MethodSetCache // cache of type-checker's method-sets // contains filtered or unexported fields }
func NewProgram(fset *token.FileSet, mode BuilderMode) *Program
NewProgram returns a new SSA Program.
mode controls diagnostics and checking during SSA construction.
func (prog *Program) AllPackages() []*Package
AllPackages returns a new slice containing all packages in the program prog in unspecified order.
func (prog *Program) Build()
Build calls Package.Build for each package in prog. Building occurs in parallel unless the BuildSerially mode flag was set.
Build is intended for whole-program analysis; a typical compiler need only build a single package.
Build is idempotent and thread-safe.
func (prog *Program) ConstValue(obj *types.Const) *Const
ConstValue returns the SSA Value denoted by the source-level named constant obj.
func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info *types.Info, importable bool) *Package
CreatePackage constructs and returns an SSA Package from the specified type-checked, error-free file ASTs, and populates its Members mapping.
importable determines whether this package should be returned by a subsequent call to ImportedPackage(pkg.Path()).
The real work of building SSA form for each function is not done until a subsequent call to Package.Build().
func (prog *Program) CreateTestMainPackage(pkg *Package) *Package
CreateTestMainPackage creates and returns a synthetic "testmain" package for the specified package if it defines tests, benchmarks or executable examples, or nil otherwise. The new package is named "main" and provides a function named "main" that runs the tests, similar to the one that would be created by the 'go test' tool.
Subsequent calls to prog.AllPackages include the new package. The package pkg must belong to the program prog.
Deprecated: Use golang.org/x/tools/go/packages to access synthetic testmain packages.
func (prog *Program) FuncValue(obj *types.Func) *Function
FuncValue returns the concrete Function denoted by the source-level named function obj, or nil if obj denotes an interface method.
TODO(adonovan): check the invariant that obj.Type() matches the result's Signature, both in the params/results and in the receiver.
func (prog *Program) ImportedPackage(path string) *Package
ImportedPackage returns the importable Package whose PkgPath is path, or nil if no such Package has been created.
A parameter to CreatePackage determines whether a package should be considered importable. For example, no import declaration can resolve to the ad-hoc main package created by 'go build foo.go'.
TODO(adonovan): rethink this function and the "importable" concept; most packages are importable. This function assumes that all types.Package.Path values are unique within the ssa.Program, which is false---yet this function remains very convenient. Clients should use (*Program).Package instead where possible. SSA doesn't really need a string-keyed map of packages.
func (prog *Program) LookupMethod(T types.Type, pkg *types.Package, name string) *Function
LookupMethod returns the implementation of the method of type T identified by (pkg, name). It returns nil if the method exists but is abstract, and panics if T has no such method.
func (prog *Program) MethodValue(sel *types.Selection) *Function
MethodValue returns the Function implementing method sel, building wrapper methods on demand. It returns nil if sel denotes an abstract (interface) method.
Precondition: sel.Kind() == MethodVal.
Thread-safe.
EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu)
func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function
NewFunction returns a new synthetic Function instance belonging to prog, with its name and signature fields set as specified.
The caller is responsible for initializing the remaining fields of the function object, e.g. Pkg, Params, Blocks.
It is practically impossible for clients to construct well-formed SSA functions/packages/programs directly, so we assume this is the job of the Builder alone. NewFunction exists to provide clients a little flexibility. For example, analysis tools may wish to construct fake Functions for the root of the callgraph, a fake "reflect" package, etc.
TODO(adonovan): think harder about the API here.
func (prog *Program) Package(obj *types.Package) *Package
Package returns the SSA Package corresponding to the specified type-checker package object. It returns nil if no such SSA package has been created.
func (prog *Program) RuntimeTypes() []types.Type
RuntimeTypes returns a new unordered slice containing all concrete types in the program for which a complete (non-empty) method set is required at run-time.
Thread-safe.
EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu)
func (prog *Program) VarValue(obj *types.Var, pkg *Package, ref []ast.Node) (value Value, isAddr bool)
VarValue returns the SSA Value that corresponds to a specific identifier denoting the source-level named variable obj.
VarValue returns nil if a local variable was not found, perhaps because its package was not built, the debug information was not requested during SSA construction, or the value was optimized away.
ref is the path to an ast.Ident (e.g. from PathEnclosingInterval), and that ident must resolve to obj.
pkg is the package enclosing the reference. (A reference to a var always occurs within a function, so we need to know where to find it.)
If the identifier is a field selector and its base expression is non-addressable, then VarValue returns the value of that field. For example:
func f() struct {x int} f().x // VarValue(x) returns a *Field instruction of type int
All other identifiers denote addressable locations (variables). For them, VarValue may return either the variable's address or its value, even when the expression is evaluated only for its value; the situation is reported by isAddr, the second component of the result.
If !isAddr, the returned value is the one associated with the specific identifier. For example,
var x int // VarValue(x) returns Const 0 here x = 1 // VarValue(x) returns Const 1 here
It is not specified whether the value or the address is returned in any particular case, as it may depend upon optimizations performed during SSA code generation, such as registerization, constant folding, avoidance of materialization of subexpressions, etc.
The Range instruction yields an iterator over the domain and range of X, which must be a string or map.
Elements are accessed via Next.
Type() returns an opaque and degenerate "rangeIter" type.
Pos() returns the ast.RangeStmt.For.
Example printed form:
t0 = range "hello":string
type Range struct { X Value // string or map // contains filtered or unexported fields }
func (v *Range) Name() string
func (v *Range) Operands(rands []*Value) []*Value
func (v *Range) Pos() token.Pos
func (v *Range) Referrers() *[]Instruction
func (v *Range) String() string
func (v *Range) Type() types.Type
The Return instruction returns values and control back to the calling function.
len(Results) is always equal to the number of results in the function's signature.
If len(Results) > 1, Return returns a tuple value with the specified components which the caller must access using Extract instructions.
There is no instruction to return a ready-made tuple like those returned by a "value,ok"-mode TypeAssert, Lookup or UnOp(ARROW) or a tail-call to a function with multiple result parameters.
Return must be the last instruction of its containing BasicBlock. Such a block has no successors.
Pos() returns the ast.ReturnStmt.Return, if explicit in the source.
Example printed form:
return return nil:I, 2:int
type Return struct { Results []Value // contains filtered or unexported fields }
func (v *Return) Block() *BasicBlock
func (s *Return) Operands(rands []*Value) []*Value
func (v *Return) Parent() *Function
func (s *Return) Pos() token.Pos
func (v *Return) Referrers() *[]Instruction
func (s *Return) String() string
The RunDefers instruction pops and invokes the entire stack of procedure calls pushed by Defer instructions in this function.
It is legal to encounter multiple 'rundefers' instructions in a single control-flow path through a function; this is useful in the combined init() function, for example.
Pos() returns NoPos.
Example printed form:
rundefers
type RunDefers struct {
// contains filtered or unexported fields
}
func (v *RunDefers) Block() *BasicBlock
func (*RunDefers) Operands(rands []*Value) []*Value
func (v *RunDefers) Parent() *Function
func (s *RunDefers) Pos() token.Pos
func (v *RunDefers) Referrers() *[]Instruction
func (*RunDefers) String() string
The Select instruction tests whether (or blocks until) one of the specified sent or received states is entered.
Let n be the number of States for which Dir==RECV and T_i (0<=i<n) be the element type of each such state's Chan. Select returns an n+2-tuple
(index int, recvOk bool, r_0 T_0, ... r_n-1 T_n-1)
The tuple's components, described below, must be accessed via the Extract instruction.
If Blocking, select waits until exactly one state holds, i.e. a channel becomes ready for the designated operation of sending or receiving; select chooses one among the ready states pseudorandomly, performs the send or receive operation, and sets 'index' to the index of the chosen channel.
If !Blocking, select doesn't block if no states hold; instead it returns immediately with index equal to -1.
If the chosen channel was used for a receive, the r_i component is set to the received value, where i is the index of that state among all n receive states; otherwise r_i has the zero value of type T_i. Note that the receive index i is not the same as the state index index.
The second component of the triple, recvOk, is a boolean whose value is true iff the selected operation was a receive and the receive successfully yielded a value.
Pos() returns the ast.SelectStmt.Select.
Example printed form:
t3 = select nonblocking [<-t0, t1<-t2] t4 = select blocking []
type Select struct { States []*SelectState Blocking bool // contains filtered or unexported fields }
func (v *Select) Name() string
func (v *Select) Operands(rands []*Value) []*Value
func (v *Select) Pos() token.Pos
func (v *Select) Referrers() *[]Instruction
func (s *Select) String() string
func (v *Select) Type() types.Type
SelectState is a helper for Select. It represents one goal state and its corresponding communication.
type SelectState struct { Dir types.ChanDir // direction of case (SendOnly or RecvOnly) Chan Value // channel to use (for send or receive) Send Value // value to send (for send) Pos token.Pos // position of token.ARROW DebugNode ast.Node // ast.SendStmt or ast.UnaryExpr(<-) [debug mode] }
The Send instruction sends X on channel Chan.
Pos() returns the ast.SendStmt.Arrow, if explicit in the source.
Example printed form:
send t0 <- t1
type Send struct { Chan, X Value // contains filtered or unexported fields }
func (v *Send) Block() *BasicBlock
func (s *Send) Operands(rands []*Value) []*Value
func (v *Send) Parent() *Function
func (s *Send) Pos() token.Pos
func (v *Send) Referrers() *[]Instruction
func (s *Send) String() string
The Slice instruction yields a slice of an existing string, slice or *array X between optional integer bounds Low and High.
Dynamically, this instruction panics if X evaluates to a nil *array pointer.
Type() returns string if the type of X was string, otherwise a *types.Slice with the same element type as X.
Pos() returns the ast.SliceExpr.Lbrack if created by a x[:] slice operation, the ast.CompositeLit.Lbrace if created by a literal, or NoPos if not explicit in the source (e.g. a variadic argument slice).
Example printed form:
t1 = slice t0[1:]
type Slice struct { X Value // slice, string, or *array Low, High, Max Value // each may be nil // contains filtered or unexported fields }
func (v *Slice) Name() string
func (v *Slice) Operands(rands []*Value) []*Value
func (v *Slice) Pos() token.Pos
func (v *Slice) Referrers() *[]Instruction
func (v *Slice) String() string
func (v *Slice) Type() types.Type
The Store instruction stores Val at address Addr. Stores can be of arbitrary types.
Pos() returns the position of the source-level construct most closely associated with the memory store operation. Since implicit memory stores are numerous and varied and depend upon implementation choices, the details are not specified.
Example printed form:
*x = y
type Store struct { Addr Value Val Value // contains filtered or unexported fields }
func (v *Store) Block() *BasicBlock
func (s *Store) Operands(rands []*Value) []*Value
func (v *Store) Parent() *Function
func (s *Store) Pos() token.Pos
func (v *Store) Referrers() *[]Instruction
func (s *Store) String() string
A Type is a Member of a Package representing a package-level named type.
type Type struct {
// contains filtered or unexported fields
}
func (t *Type) Name() string
func (t *Type) Object() types.Object
func (t *Type) Package() *Package
func (t *Type) Pos() token.Pos
func (t *Type) RelString(from *types.Package) string
func (t *Type) String() string
func (t *Type) Token() token.Token
func (t *Type) Type() types.Type
The TypeAssert instruction tests whether interface value X has type AssertedType.
If !CommaOk, on success it returns v, the result of the conversion (defined below); on failure it panics.
If CommaOk: on success it returns a pair (v, true) where v is the result of the conversion; on failure it returns (z, false) where z is AssertedType's zero value. The components of the pair must be accessed using the Extract instruction.
If AssertedType is a concrete type, TypeAssert checks whether the dynamic type in interface X is equal to it, and if so, the result of the conversion is a copy of the value in the interface.
If AssertedType is an interface, TypeAssert checks whether the dynamic type of the interface is assignable to it, and if so, the result of the conversion is a copy of the interface value X. If AssertedType is a superinterface of X.Type(), the operation will fail iff the operand is nil. (Contrast with ChangeInterface, which performs no nil-check.)
Type() reflects the actual type of the result, possibly a 2-types.Tuple; AssertedType is the asserted type.
Pos() returns the ast.CallExpr.Lparen if the instruction arose from an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the instruction arose from an explicit e.(T) operation; or the ast.CaseClause.Case if the instruction arose from a case of a type-switch statement.
Example printed form:
t1 = typeassert t0.(int) t3 = typeassert,ok t2.(T)
type TypeAssert struct { X Value AssertedType types.Type CommaOk bool // contains filtered or unexported fields }
func (v *TypeAssert) Name() string
func (v *TypeAssert) Operands(rands []*Value) []*Value
func (v *TypeAssert) Pos() token.Pos
func (v *TypeAssert) Referrers() *[]Instruction
func (v *TypeAssert) String() string
func (v *TypeAssert) Type() types.Type
The UnOp instruction yields the result of Op X. ARROW is channel receive. MUL is pointer indirection (load). XOR is bitwise complement. SUB is negation. NOT is logical negation.
If CommaOk and Op=ARROW, the result is a 2-tuple of the value above and a boolean indicating the success of the receive. The components of the tuple are accessed using Extract.
Pos() returns the ast.UnaryExpr.OpPos, if explicit in the source. For receive operations (ARROW) implicit in ranging over a channel, Pos() returns the ast.RangeStmt.For. For implicit memory loads (STAR), Pos() returns the position of the most closely associated source-level construct; the details are not specified.
Example printed form:
t0 = *x t2 = <-t1,ok
type UnOp struct { Op token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^ X Value CommaOk bool // contains filtered or unexported fields }
func (v *UnOp) Name() string
func (v *UnOp) Operands(rands []*Value) []*Value
func (v *UnOp) Pos() token.Pos
func (v *UnOp) Referrers() *[]Instruction
func (v *UnOp) String() string
func (v *UnOp) Type() types.Type
A Value is an SSA value that can be referenced by an instruction.
type Value interface { // Name returns the name of this value, and determines how // this Value appears when used as an operand of an // Instruction. // // This is the same as the source name for Parameters, // Builtins, Functions, FreeVars, Globals. // For constants, it is a representation of the constant's value // and type. For all other Values this is the name of the // virtual register defined by the instruction. // // The name of an SSA Value is not semantically significant, // and may not even be unique within a function. Name() string // If this value is an Instruction, String returns its // disassembled form; otherwise it returns unspecified // human-readable information about the Value, such as its // kind, name and type. String() string // Type returns the type of this value. Many instructions // (e.g. IndexAddr) change their behaviour depending on the // types of their operands. Type() types.Type // Parent returns the function to which this Value belongs. // It returns nil for named Functions, Builtin, Const and Global. Parent() *Function // Referrers returns the list of instructions that have this // value as one of their operands; it may contain duplicates // if an instruction has a repeated operand. // // Referrers actually returns a pointer through which the // caller may perform mutations to the object's state. // // Referrers is currently only defined if Parent()!=nil, // i.e. for the function-local values FreeVar, Parameter, // Functions (iff anonymous) and all value-defining instructions. // It returns nil for named Functions, Builtin, Const and Global. // // Instruction.Operands contains the inverse of this relation. Referrers() *[]Instruction // Pos returns the location of the AST token most closely // associated with the operation that gave rise to this value, // or token.NoPos if it was not explicit in the source. // // For each ast.Node type, a particular token is designated as // the closest location for the expression, e.g. the Lparen // for an *ast.CallExpr. This permits a compact but // approximate mapping from Values to source positions for use // in diagnostic messages, for example. // // (Do not use this position to determine which Value // corresponds to an ast.Expr; use Function.ValueForExpr // instead. NB: it requires that the function was built with // debug information.) Pos() token.Pos }


| | |
- create_shingle()
- Creates shingles of size k from documents in
the corpus
:returns shingle set and hashed shingle set
- create_shingle_matrix(shingle_set)
- Creates boolean vector shingle matrix.
:returns 2D array
- print_shingle_matrix(matrix_list)
- sha = openssl_sha256(...)
- Returns a sha256 hash object; optionally initialized with a string
|


In 1995 dad talked about his war Reminisces (one of only a few times that he did so.) Two recordings below were made.


Main Header
Topic 1
Paragraph 1 Sentence 1
Sentence 2
Paragraph 2 Sentence 1
Sentence 2
Topic 2
Paragraph 1 Sentence 1
Sentence 2
Paragraph 2 Sentence 1
Sentence 2


Resizes the panel with animation
sizeTo(type, size, [instant])
| type |
string, name of the panel |
| size |
integer, new size |
| instant |
boolean, indicate if to perform resize of the panel instantly, (optional) |
Description
The first argument type is the name of the panel. It can be one of the following:
- top
- left
- main
- right
- preview
- bottom
The second argument size is the new size for the panel. For different types of panels it varies, for left
and right panels it is width, for all other panels it is height.
For left and right panel you can define size as a negative value. If it is negative, it will take all available width but the size value (in pixels)
you defined.
An example below illustrates the use of resizeTo method:


HTML5 Hotel Room Booking Tutorial (JavaScript/PHP)
DayPilot for JavaScript: http://javascript.daypilot.org/
License
- The code of this tutorial, including the DayPilot Pro library, is licensed for testing and evaluation purposes. See also the attached license (LicenseAgreementTrial.pdf). You can use it for development and production purposes if you are a licensed user of DayPilot Pro for JavaScript. Buy a license.
- This tutorial includes jQuery which is released under the MIT License. Read more about jQuery licensing.
DayPilot Documentation


Trader Lara:
Then I will write down the things that I need. If you can bring me what's written on the list, I will make you two Beginner's Arcanas. Okay, it's a deal.


This website needs JavaScript
This uses technologies that will work bestwith modern browsers with JavaScript enabled.


call psb_spasb(a, desc_a, info, afmt, upd, dupl, mold)
- Type:
- Synchronous.
- On Entry
-
- desc_a
- the communication descriptor.
Scope:local.
Type:required.
Intent: in.
Specified as: a structured data of type descdatapsb_desc_type.
- afmt
- the storage format for the sparse matrix.
Scope: local.
Type: optional.
Intent: in.
Specified as: an array of characters. Defalt: 'CSR'.
- upd
- Provide for updates to the matrix coefficients.
Scope: global.
Type: optional.
Intent: in.
Specified as: integer, possible values: psb_upd_srch_
, psb_upd_perm_
- dupl
- How to handle duplicate coefficients.
Scope: global.
Type: optional.
Intent: in.
Specified as: integer, possible values: psb_dupl_ovwrt_
,
psb_dupl_add_
, psb_dupl_err_
.
- mold
- The desired dynamic type for the internal matrix storage.
Scope: local.
Type: optional.
Intent: in.
Specified as: an object of a class derived from spbasedatapsb_T_base_sparse_mat.
- On Return
-
- a
- the matrix to be assembled.
Scope:local
Type:required
Intent: inout.
Specified as: a structured data of type spdatapsb_Tspmat_type.
- info
- Error code.
Scope: local
Type: required
Intent: out.
An integer value; 0 means no error has been detected.
Notes
- On entry to this routine the descriptor must be in the
assembled state, i.e.
psb_cdasb
must already have been called.
- The sparse matrix may be in either the build or update state;
- Duplicate entries are detected and handled in both build and
update state, with the exception of the error action that is only
taken in the build state, i.e. on the first assembly;
- If the update choice is
psb_upd_perm_
, then subsequent
calls to psb_spins
to update the matrix must be arranged in
such a way as to produce exactly the same sequence of coefficient
values as encountered at the first assembly;
- The output storage format need not be the same on all
processes;
- On exit from this routine the matrix is in the assembled state,
and thus is suitable for the computational routines.


website to learn the things very easily. This website make u to learn the things very easily even without free of cost which would be available for everyone.
{% load static %}
{% load static %}
{% load static %}
{% load static %}
Discover a place
dhfcfukwdfjiowdjcdkvdkvidjvdkjvvjefjvfvfjv


top
|
up
|
prev
|
next
GdbExitRecord Class
Definition at line
408
of
Gdb.hpp
Constructors
GdbExitRecord
(
GdbResults
* results)
Member Functions
bool
Stopped
()
const override
Constructor Details
GdbExitRecord Constructor
cmajor::debug::GdbExitRecord::GdbExitRecord(
GdbResults
* results)
Definition at line
461
of
Gdb.cpp
:
461
:
GdbResultRecord
(
Class
::
exit
,
results
)
462
{
463
}
Declaration at line
411
of
Gdb.hpp
Member Function Details
Stopped Member Function
bool
cmajor::debug::GdbExitRecord::Stopped()
const override
Definition at line
412
of
Gdb.hpp
:
412
{
return
true
;
}
Base class overridden functions:
cmajor::debug::GdbReplyRecord::Stopped
top
|
up
|
prev
|
next


| base85_encode {qs} | R Documentation |
Encodes binary data (a raw vector) as ascii text using Z85 encoding format
base85_encode(rawdata)
rawdata |
A raw vector |
Z85 is a binary to ascii encoding format created by Pieter Hintjens in 2010 and is part of the ZeroMQ RFC. The encoding has a dictionary using 85 out of 94 printable ASCII characters. There are other base 85 encoding schemes, including Ascii85, which is popularized and used by Adobe. Z85 is distinguished by its choice of dictionary, which is suitable for easier inclusion into source code for many programming languages. The dictionary excludes all quote marks and other control characters, and requires no special treatment in R and most other languages. Note: although the official specification restricts input length to multiples of four bytes, the implementation here works with any input length. The overhead (extra bytes used relative to binary) is 25%. In comparison, base 64 encoding has an overhead of 33.33%.
https://rfc.zeromq.org/spec/32/


We're sorry but PlantUML Editor doesn't work properly without JavaScript enabled. Please enable it to continue.


Home
My Profile
My Posts
My Friends
My Events
Sign Out
My Profile
Name:
Jim Walker
Username:
Jim.Walker
Birthday:
11/23/1990
About Me:
Hi there, I'm Jim Walker. I am a data analyst at Google and I love IT, haha get it? I live in San Francisco and love to eat healthy.


SIS
Dashboard
Suggestions
Queries
Logout
Dashboard
Suggestions
Queries
Logout
menu
Suggestions
Name
Suggestion
Alvin
Eclair
Alan
Jellybean
Jonathan
Lollipop
Shannon
KitKat


Home
Artists
View All
Search
Popular
Trending
Recently Updated
Favorites
Random
Posts
Recently Added
Favorites
By Favorite Artists
Random
About
{% include 'components/telegram_link.html' %}
Contact
Takedown Requests
Import
Import
Leaderboard
{% if is_logged_in() %}
Account
My Account
Logout
{% else %}
Login
Register
{% endif %}
Seiso
☰


As a standard, bibtex is used as a citation-renderer in Pandoc’s Markdown, that is, in RMarkdown as well. bibtex is useful for a fair amount of citation task, but biblatex allows for a finer control. For instance, multiple bibliographies for one document are possible.
For instance, citing a newspaper article using bibtex left me scratching my head, as I wanted to have the exact day of the date (not only the year) cited. However, I could not convince bibtex to show these details.
That’s what I wanted to get:
Krugman, P. (2013, 13. April). The Excel Depression. The New York Times, A31. Zugriff unter https://www.nytimes.com/2013/04/19/opinion/krugman-the- excel-depression.html
But that’s what I got:
Krugman, P. (2013). The Excel Depression. The New York Times, A31. Newspaper Article. Abgerufen von https://www.nytimes.com/2013/04/19/opinion/ krugman-the-excel-depression.html
See the difference in date formatting; for a newspaper article, one would want a day-based date, not a year-date only.
After some Google research, I found that bibtex appears rather limited in some nuanced fine tuning such as the exact day of an article. bibtex seems to have little patience for such subtleties.
By the way, that’s the bib(la)tex source of the citation just rendered:
@article{Krugman:2013aa,
Author = {Krugman, Paul},
Date-Added = {2018-02-13 17:22:18 +0000},
Date-Modified = {2018-02-13 17:23:26 +0000},
Journal = {The New York Times},
date = {2013-04-13},
type = {Newspaper Article},
url = {https://www.nytimes.com/2013/04/19/opinion/krugman-the-excel-depression.html},
Pages = {A31},
month = 04,
day = 13,
Title = {The Excel Depression}
}
The following yaml header can be used to switch to biblatex for citation rendering:
---
output:
pdf_document:
citation_package: biblatex
title: "Untitled"
lang: de-De
header-includes:
- \usepackage{csquotes}
biblio-style: apa
bibliography: test.bib
#csl: "/Users/sebastiansaueruser/Documents/Literatur/ref_mgt/apa.csl"
---
Note that no csl file is needed for biblatex, the specs are included in an included latex package (biblatex-apa). csquotes
is a latex packages that helps to print non-English quotation marks such as Germans.
Below and beyond the yaml header, one continues as usual: citing the source, and not caring for the literature section, which will be put automatically to the end of the document.
For instance, let’s cite the Krugman article from the New York Times:
@Krugman:2013aa
Caveat
The biblatex approach only works for Latex output (pdf) only, not for html.
For LaTeX output, you can also use natbib or biblatex to render the bibliography.
I’m no expert in biblatex, so there are surely aspects I’m not aware of.
Put the literature section at an arbitrary place
BTW, to have the literature section appear at some different point, and not necessarily at the very end of the document, use this approach.


Track time
Timer
Current work item
Time
Session time
Time
Total time
Recent work items
Issue
Total time
Last activity
Actions
Loading...
Delete work item
Close
Are you sure you want to delete this work item?
Log work item
Close
Log work on work item?


todoappStoredData
filter,all
todoLayout,replace,propagate,*
{ "total": 0, "active": 0, "done": 0 }
.todoapp/storeList
todoappStoredData
total
completed
add,completed,$completeAll=1
editing
editing
list
.todo-text
completed,completed
completed
todoText
todoText
todoText
active "items_left"^active
todoText
{
"items_left": [ "item left", "items left" ]
}


Toggle navigation
CoffeeMedia
Home
Public Chat
CoffeeTalk
Profiles
Login
Enter the chat code below to enter the chat
Chat Name
Password
Join Chat
Add chat to my Website
Copy this code
Comment Box
is loading comments...


Handcrafting Recurrent Neural Networks to count
Recurrent neural networks (RNNs) handle complex problems like convert speech to text like a pro. This blog shows the basics of RNNs by teaching a RNN to count.
RNNs are well suited for problems with sequences like captioning images and converting speech to text. The former generates an sequence of words from an image, the latter translate a stream of audio into words.
State of the art RNNs can choose to remember or forget a part of a sequence, and can learn to which part to attend to. Some fantastic blogs on this topic are The Unreasonable Effectiveness of Recurrent Neural Networks , Understanding LSTM Networks and Attention and Augmented Recurrent Neural Networks.
I wrote this blog while trying to reproduce some of the results of Exploring LSTMs. Let's first go back to the basics!
1. The basics
Consider the situation where we start of with \(\mathbf{x}\), some image data, and \(\mathbf{y}\), labels indicating if the image does or does not contain a dog. Our neural network should do some magical operations to find all the dogs in the images.
Feedforward nets
The most basic neural network is a feedforward network, shown in the figure below. On the left, a network with one layer with two hidden units. On the right, a compact notation of the left image representing a network with an arbitrary number of hidden units.
This network adds constant values to the input \(\mathbf{x}\), weights the result and passes this through some function \(f\). This gives use the activations \(\mathbf{h}\) in the hidden layer:
To get our predictions \(\hat{\mathbf{y}}\) we'll do the same with \(\mathbf{h}\):
Learning is the process of optimizing the parameters \(\mathbf{W}\), \(\mathbf{b}\), \(\mathbf{w}\) and \(\mathbf{c}\) so that we get correct predictions.
Before learning, the network starts with some random values for its parameters. The data \(\mathbf{X}\) is fed forward through our functions, resulting in predictions. The predictions are compared to the ground truth and the error is backpropagated through the network so we can find better values for our values. Doing this many times will (hopefully) teach the network to recognize dogs.
Deep Learning is the process of finding the architecture of the network (e.g. how many hidden layers & units to use) and teaching it to learn. This process often involves waiting, throwing a lot of money on GPU's and burning out PhD students. Deep Learning is not for the faint of heart.
The network in the figure above does not really deal well with sequences. Let's say you get one of these ambiguous images:
If you just saw a picture of a tiny dog house, you're probably more likely to think that the weird object in the picture is a chihuahua and not a muffin. This makes sense: context matters.
Our network learns its parameters once and has a fixed state, so it cannot take context into account. It's opinion doesn't change depending on what it just saw. We'll have to find a network architecture that can remember.
Recurrent neural nets
A recurrent neural network updates an internal state based on what it has seen so far. A diagram is shown below.
\(\mathbf{x}\) is now a sequence of data for multiple time steps \(t\). A sequence can consist, for exampe, of images, words or phrases uttered. At any given time \(t\), we construct an idea \(\mathbf{h}^{(t)}\) from \(\mathbf{x}^{(t)}\), our new input, and \(\mathbf{h}^{(t-1)}\), our ideas so far. For the formula-minded audience:
(All the parameters for this layer are put in \(\boldsymbol{\theta}\).)
This specific architecture waits for the whole sequence to end, but there are also forms that generate output for each time step. Similarly in real life, we can wait for someone to finish her sentence before translating it or try to translate someone on the fly. We'll learn a neural network to count with the former approach.
2. The counting problem
This counting problem will show that a RNN is able to keep a state.
Our RNN will see a sequence of a
's and has to output the same number of b
's.
Counting for this tasks means keeping track of how many a
's it has seen and the b
's outputted so far.
The data looks like this:
['axb',
'aaxbb',
'aaaxbbb',
'aaaaxbbbb',
'aaaaaxbbbbb',
'aaaaaaxbbbbbb',
'aaaaaaaxbbbbbbb',
'aaaaaaaaxbbbbbbbb',
'aaaaaaaaaxbbbbbbbbb',
'aaaaaaaaaaxbbbbbbbbbb',
'aaaaaaaaaaaxbbbbbbbbbbb',
'aaaaaaaaaaaaxbbbbbbbbbbbb',
'aaaaaaaaaaaaaxbbbbbbbbbbbbb',
'aaaaaaaaaaaaaaxbbbbbbbbbbbbbb']
Here we have:
aaa
: the sequence to count;x
: a switch character telling that the sequence has ended and prediction should start;bbb
: the sequence to output.
We'll add another special character: s
.
s
signals that the sequence has ended and is also used for padding so that all our sequences are of the same length.
3. Preprocessing
We'll generate all possible combinations of sentences and the next character to be predicted by moving through the text.
The network is asked to predict b
's after x
, for example:
Text: aaxbb
Sentences: ['aax', 'aaxb', 'aaxbb']
Next char: ['b', 'b', 's']
We'll have to vectorize the text into numerical features so that keras
can use it.
Element of X:
a b x s
0 True False False False
1 True False False False
2 False False True False
3 False True False False
4 False False False False
...
26 False False False False
27 False False False False
28 False False False False
29 False False False False
30 False False False False
Element of y:
True
In this example, the columns correspond with a
, b
, x
or s
and the rows are the characters of the sequence (note that we're missing padding in this example).
Our X
consists of matrices stacked like this.
An element of y
is a single boolean value indicating if a b
should be predicted.
4. The network
What kind of architecture should our model have?
We'll feed in X
and want to predict for a single class (b
or not b
).
The last layer should thus be a single node dense layer with sigmoid activation, but how is the network going to count?
As this is a fairly simple task, a plain old RNN should be good enough:
Our RNN should keep track of the number a
's seen and b
's outputted so far and decide whether to output another b
.
Handcrafting
We can let the model learn, but we can also handcraft the neural network ourself!
Our RNN should increment a counter for every a
it has seen and increase a different counter for every b
it has predicted.
A b
should only be predicted if the count for observed a
's is higher than for predicted b
's.
The RNN should thus consist of two units with a linear activation function. The update equations for our neural network are:
We can create this network in keras
with:
n_remember_units = 2
sequence_input = layers.Input(X.shape[1:])
x = layers.SimpleRNN(n_remember_units, activation='linear',
name='rnn')(sequence_input)
x = layers.Dense(1, activation='sigmoid', name='dense')(x)
counting_model = models.Model(sequence_input, x)
Each unit focusses on one character: \(\mathbf{U}_{RNN}\) is only non-zero if an a
or b
is seen for its unit.
The units should only look at its own previous states, so \(\mathbf{W}_{RNN}\) is a diagonal matrix with ones.
Choosing a value of one for these matrices will add the input (if it's b
or not) to the number of b
's seen.
The dense layer substracts the input of the b
unit from the a
unit, and converts it to a probability.
We'll weigh the counts coming from the RNNs with +0.5 for a
and -0.5 for b
.
The probability will be higher than 0.5 if n_a
> n_b
.
All biases are zero.
(Question for the reader: why do we need \(> 0.5\) and not \(\geq 0.5\)?).
weights = [
np.array([[1, 0],
[0, 1],
[0, 0],
[0, 0]
]), # U_RNN
np.array([[1, 0],
[0, 1]]), # W_RNN
np.array([0, 0]), # b_RNN
np.array([[0.5], [-0.5]]), # W_dense
np.array([0]) # b_dense
]
counting_model.set_weights(weights) # No .compile() and .fit() needed!
Will this really work?
from sklearn.metrics import classification_report
y_pred = counting_model.predict(X) > 0.5
print(classification_report(y_pred, y))
precision recall f1-score support
False 1.00 1.00 1.00 196
True 1.00 1.00 1.00 105
avg / total 1.00 1.00 1.00 301
Yes, it works!
Let's investigate what's happening inside the RNN. To see what the the RNN is doing, we can discard the last classification layer and look into the RNN layer. Create a new model without the dense layer and tell the RNN layer to return the full sequences instead of only the last hidden state:
sequence_input = layers.Input(X.shape[1:])
x = layers.SimpleRNN(n_remember_units, return_sequences=True,
weights=counting_model.layers[1].get_weights())(sequence_input)
hidden_model = models.Model(sequence_input, x)
Calling hidden_model.predict(X)
will give use the full sequence.
Let's look at what the hidden states are for a full sequence:
The hidden state of cell 0 slowly increases as it sees more a
's.
If no a
's are present, the weighted average of the hidden state and the input (0) slowly decreases its value.
The same happens for cell 1 that's looking at b
's.
The output of cell 1 is substracted from the output of cell 0 and comparing it to 0.5 indicates if another b
should be outputted.
This allows our RNN to perfectly solve this problem!
4. Conclusion
We solved the problem, but did our RNN learn how to count? Not really: our RNN perfectly solves the problem but does not understand the concept of counting. The RNN can hold states and can compare them but it did not solve the underlying problem. Nevertheless, this blog (hopefully) demonstrated that RNNs can hold state and this can be used for far more complex problems!


x
x
Select new name
Zones
Behavior
Normal
24hours
GPIO
Hikvision
MQTT
BCM Pin:
IP Address
Username
Password
MQTT Topic
MQTT Payload
Delete
OK
Cancel
x
USER/SERVER
Change User
Logout
Restart
UI Settings
username
password
timezone
port
Serene Settings
BCM Pin:
Siren Start HTTP Request
Siren Stop HTTP Request
Mail Settings
username
password
SMTP Server
smtpPort
recipients
messageSubject
messageBody
Voip Settings
domain
username
password
numbersToCall
timesOfRepeat
MQTT Settings
Host
Port
State Topic
Command Topic
Username
Authentication
Password
HomeAssistant Integration
Host Alarm Settings
Host
Port
Https
Username
Password
OK
Cancel
⚙
Show all Logs
Sensors
Alarm Actions
User Actions
System
Errors
10
20
40
50
100
200
⚛
+


Umang Kantesaria - Texas A&M University
Computer Science and Engineering
Search:
Homepage
About
Portfolio
Service
Professional Image
Content Comming Soon


siberian husky
Siberian Huskies have captured the imagination of the masses, as well as artists, writers, and film producers, with their eye-catching looks and awe-inspiring talents.
History and Origins
The Siberian Husky is believed to have originated among the Chukchi, a tribe of Siberian nomads. The breed's history is relatively unknown but DNA tests confirm that they are among the oldest of dog breeds. We do know that the Chukchi used the dogs as fast transportation and that they interacted with the Chukchi as a family dog. Huskies often slept with the children and provided warm comfortable beds for them.
Lifespan
11-14 years
Health
Huskies are generally healthy, but like all breeds, they're prone to certain health conditions. Not all Huskies will get any or all of these diseases, but it's important to be aware of them if you're considering this breed. If you're buying a puppy, find a good breeder who will show you health clearances for both your puppy's parents. Health clearances prove that a dog has been tested for and cleared of a particular condition.


Home
Projects
Teams
Welcome, pesho!
Profile
Logout
My Profile
My Teams
Developers
My Projects
You have no projects!


Build the community your fans will love
Huddle re-imagines the way we build communities. You have a voice, but so does your audience. Create connections with your users as you engage in genuine discussion.
Grow together
Generate meaningful discussions with your audience and build a strong, loyal community. Think of the insightful conversations you miss out on with a feedback form.
Flowing conversations
You wouln't paginate a conversation in real life, so why do it online? Our threads have just-in-time loading for a more natural flow.
Your users
It takes no time at all to integrate Huddle with your app's authentication solution. This means, once signed in to your app, your users can start chatting immediately.