id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
6,600
google/skylark
value.go
CompareDepth
func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error) { if depth < 1 { return false, fmt.Errorf("comparison exceeded maximum recursion depth") } if sameType(x, y) { if xcomp, ok := x.(Comparable); ok { return xcomp.CompareSameType(op, y, depth) } // use identity comparison switch op { case syntax.EQL: return x == y, nil case syntax.NEQ: return x != y, nil } return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) } // different types // int/float ordered comparisons switch x := x.(type) { case Int: if y, ok := y.(Float); ok { if y != y { return false, nil // y is NaN } var cmp int if !math.IsInf(float64(y), 0) { cmp = x.rational().Cmp(y.rational()) // y is finite } else if y > 0 { cmp = -1 // y is +Inf } else { cmp = +1 // y is -Inf } return threeway(op, cmp), nil } case Float: if y, ok := y.(Int); ok { if x != x { return false, nil // x is NaN } var cmp int if !math.IsInf(float64(x), 0) { cmp = x.rational().Cmp(y.rational()) // x is finite } else if x > 0 { cmp = -1 // x is +Inf } else { cmp = +1 // x is -Inf } return threeway(op, cmp), nil } } // All other values of different types compare unequal. switch op { case syntax.EQL: return false, nil case syntax.NEQ: return true, nil } return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) }
go
func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error) { if depth < 1 { return false, fmt.Errorf("comparison exceeded maximum recursion depth") } if sameType(x, y) { if xcomp, ok := x.(Comparable); ok { return xcomp.CompareSameType(op, y, depth) } // use identity comparison switch op { case syntax.EQL: return x == y, nil case syntax.NEQ: return x != y, nil } return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) } // different types // int/float ordered comparisons switch x := x.(type) { case Int: if y, ok := y.(Float); ok { if y != y { return false, nil // y is NaN } var cmp int if !math.IsInf(float64(y), 0) { cmp = x.rational().Cmp(y.rational()) // y is finite } else if y > 0 { cmp = -1 // y is +Inf } else { cmp = +1 // y is -Inf } return threeway(op, cmp), nil } case Float: if y, ok := y.(Int); ok { if x != x { return false, nil // x is NaN } var cmp int if !math.IsInf(float64(x), 0) { cmp = x.rational().Cmp(y.rational()) // x is finite } else if x > 0 { cmp = -1 // x is +Inf } else { cmp = +1 // x is -Inf } return threeway(op, cmp), nil } } // All other values of different types compare unequal. switch op { case syntax.EQL: return false, nil case syntax.NEQ: return true, nil } return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type()) }
[ "func", "CompareDepth", "(", "op", "syntax", ".", "Token", ",", "x", ",", "y", "Value", ",", "depth", "int", ")", "(", "bool", ",", "error", ")", "{", "if", "depth", "<", "1", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "sameType", "(", "x", ",", "y", ")", "{", "if", "xcomp", ",", "ok", ":=", "x", ".", "(", "Comparable", ")", ";", "ok", "{", "return", "xcomp", ".", "CompareSameType", "(", "op", ",", "y", ",", "depth", ")", "\n", "}", "\n\n", "// use identity comparison", "switch", "op", "{", "case", "syntax", ".", "EQL", ":", "return", "x", "==", "y", ",", "nil", "\n", "case", "syntax", ".", "NEQ", ":", "return", "x", "!=", "y", ",", "nil", "\n", "}", "\n", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "x", ".", "Type", "(", ")", ",", "op", ",", "y", ".", "Type", "(", ")", ")", "\n", "}", "\n\n", "// different types", "// int/float ordered comparisons", "switch", "x", ":=", "x", ".", "(", "type", ")", "{", "case", "Int", ":", "if", "y", ",", "ok", ":=", "y", ".", "(", "Float", ")", ";", "ok", "{", "if", "y", "!=", "y", "{", "return", "false", ",", "nil", "// y is NaN", "\n", "}", "\n", "var", "cmp", "int", "\n", "if", "!", "math", ".", "IsInf", "(", "float64", "(", "y", ")", ",", "0", ")", "{", "cmp", "=", "x", ".", "rational", "(", ")", ".", "Cmp", "(", "y", ".", "rational", "(", ")", ")", "// y is finite", "\n", "}", "else", "if", "y", ">", "0", "{", "cmp", "=", "-", "1", "// y is +Inf", "\n", "}", "else", "{", "cmp", "=", "+", "1", "// y is -Inf", "\n", "}", "\n", "return", "threeway", "(", "op", ",", "cmp", ")", ",", "nil", "\n", "}", "\n", "case", "Float", ":", "if", "y", ",", "ok", ":=", "y", ".", "(", "Int", ")", ";", "ok", "{", "if", "x", "!=", "x", "{", "return", "false", ",", "nil", "// x is NaN", "\n", "}", "\n", "var", "cmp", "int", "\n", "if", "!", "math", ".", "IsInf", "(", "float64", "(", "x", ")", ",", "0", ")", "{", "cmp", "=", "x", ".", "rational", "(", ")", ".", "Cmp", "(", "y", ".", "rational", "(", ")", ")", "// x is finite", "\n", "}", "else", "if", "x", ">", "0", "{", "cmp", "=", "-", "1", "// x is +Inf", "\n", "}", "else", "{", "cmp", "=", "+", "1", "// x is -Inf", "\n", "}", "\n", "return", "threeway", "(", "op", ",", "cmp", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "// All other values of different types compare unequal.", "switch", "op", "{", "case", "syntax", ".", "EQL", ":", "return", "false", ",", "nil", "\n", "case", "syntax", ".", "NEQ", ":", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "x", ".", "Type", "(", ")", ",", "op", ",", "y", ".", "Type", "(", ")", ")", "\n", "}" ]
// CompareDepth compares two Skylark values. // The comparison operation must be one of EQL, NEQ, LT, LE, GT, or GE. // CompareDepth returns an error if an ordered comparison was // requested for a pair of values that do not support it. // // The depth parameter limits the maximum depth of recursion // in cyclic data structures.
[ "CompareDepth", "compares", "two", "Skylark", "values", ".", "The", "comparison", "operation", "must", "be", "one", "of", "EQL", "NEQ", "LT", "LE", "GT", "or", "GE", ".", "CompareDepth", "returns", "an", "error", "if", "an", "ordered", "comparison", "was", "requested", "for", "a", "pair", "of", "values", "that", "do", "not", "support", "it", ".", "The", "depth", "parameter", "limits", "the", "maximum", "depth", "of", "recursion", "in", "cyclic", "data", "structures", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/value.go#L1078-L1141
6,601
google/skylark
hashtable.go
dump
func (ht *hashtable) dump() { fmt.Printf("hashtable %p len=%d head=%p tailLink=%p", ht, ht.len, ht.head, ht.tailLink) if ht.tailLink != nil { fmt.Printf(" *tailLink=%p", *ht.tailLink) } fmt.Println() for j := range ht.table { fmt.Printf("bucket chain %d\n", j) for p := &ht.table[j]; p != nil; p = p.next { fmt.Printf("bucket %p\n", p) for i := range p.entries { e := &p.entries[i] fmt.Printf("\tentry %d @ %p hash=%d key=%v value=%v\n", i, e, e.hash, e.key, e.value) fmt.Printf("\t\tnext=%p &next=%p prev=%p", e.next, &e.next, e.prevLink) if e.prevLink != nil { fmt.Printf(" *prev=%p", *e.prevLink) } fmt.Println() } } } }
go
func (ht *hashtable) dump() { fmt.Printf("hashtable %p len=%d head=%p tailLink=%p", ht, ht.len, ht.head, ht.tailLink) if ht.tailLink != nil { fmt.Printf(" *tailLink=%p", *ht.tailLink) } fmt.Println() for j := range ht.table { fmt.Printf("bucket chain %d\n", j) for p := &ht.table[j]; p != nil; p = p.next { fmt.Printf("bucket %p\n", p) for i := range p.entries { e := &p.entries[i] fmt.Printf("\tentry %d @ %p hash=%d key=%v value=%v\n", i, e, e.hash, e.key, e.value) fmt.Printf("\t\tnext=%p &next=%p prev=%p", e.next, &e.next, e.prevLink) if e.prevLink != nil { fmt.Printf(" *prev=%p", *e.prevLink) } fmt.Println() } } } }
[ "func", "(", "ht", "*", "hashtable", ")", "dump", "(", ")", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "ht", ",", "ht", ".", "len", ",", "ht", ".", "head", ",", "ht", ".", "tailLink", ")", "\n", "if", "ht", ".", "tailLink", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "*", "ht", ".", "tailLink", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", ")", "\n", "for", "j", ":=", "range", "ht", ".", "table", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "j", ")", "\n", "for", "p", ":=", "&", "ht", ".", "table", "[", "j", "]", ";", "p", "!=", "nil", ";", "p", "=", "p", ".", "next", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "p", ")", "\n", "for", "i", ":=", "range", "p", ".", "entries", "{", "e", ":=", "&", "p", ".", "entries", "[", "i", "]", "\n", "fmt", ".", "Printf", "(", "\"", "\\t", "\\n", "\"", ",", "i", ",", "e", ",", "e", ".", "hash", ",", "e", ".", "key", ",", "e", ".", "value", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\t", "\\t", "\"", ",", "e", ".", "next", ",", "&", "e", ".", "next", ",", "e", ".", "prevLink", ")", "\n", "if", "e", ".", "prevLink", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "*", "e", ".", "prevLink", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// dump is provided as an aid to debugging.
[ "dump", "is", "provided", "as", "an", "aid", "to", "debugging", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/hashtable.go#L284-L308
6,602
google/skylark
hashtable.go
hashString
func hashString(s string) uint32 { if len(s) >= 12 { // Call the Go runtime's optimized hash implementation, // which uses the AESENC instruction on amd64 machines. return uint32(goStringHash(s, 0)) } return softHashString(s) }
go
func hashString(s string) uint32 { if len(s) >= 12 { // Call the Go runtime's optimized hash implementation, // which uses the AESENC instruction on amd64 machines. return uint32(goStringHash(s, 0)) } return softHashString(s) }
[ "func", "hashString", "(", "s", "string", ")", "uint32", "{", "if", "len", "(", "s", ")", ">=", "12", "{", "// Call the Go runtime's optimized hash implementation,", "// which uses the AESENC instruction on amd64 machines.", "return", "uint32", "(", "goStringHash", "(", "s", ",", "0", ")", ")", "\n", "}", "\n", "return", "softHashString", "(", "s", ")", "\n", "}" ]
// hashString computes the hash of s.
[ "hashString", "computes", "the", "hash", "of", "s", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/hashtable.go#L338-L345
6,603
google/skylark
hashtable.go
softHashString
func softHashString(s string) uint32 { var h uint32 for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } return h }
go
func softHashString(s string) uint32 { var h uint32 for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } return h }
[ "func", "softHashString", "(", "s", "string", ")", "uint32", "{", "var", "h", "uint32", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "h", "^=", "uint32", "(", "s", "[", "i", "]", ")", "\n", "h", "*=", "16777619", "\n", "}", "\n", "return", "h", "\n", "}" ]
// softHashString computes the FNV hash of s in software.
[ "softHashString", "computes", "the", "FNV", "hash", "of", "s", "in", "software", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/hashtable.go#L351-L358
6,604
google/skylark
syntax/parse.go
ParseExpr
func ParseExpr(filename string, src interface{}, mode Mode) (expr Expr, err error) { in, err := newScanner(filename, src, mode&RetainComments != 0) if err != nil { return nil, err } p := parser{in: in} defer p.in.recover(&err) p.nextToken() // read first lookahead token expr = p.parseTest() // A following newline (e.g. "f()\n") appears outside any brackets, // on a non-blank line, and thus results in a NEWLINE token. if p.tok == NEWLINE { p.nextToken() } if p.tok != EOF { p.in.errorf(p.in.pos, "got %#v after expression, want EOF", p.tok) } p.assignComments(expr) return expr, nil }
go
func ParseExpr(filename string, src interface{}, mode Mode) (expr Expr, err error) { in, err := newScanner(filename, src, mode&RetainComments != 0) if err != nil { return nil, err } p := parser{in: in} defer p.in.recover(&err) p.nextToken() // read first lookahead token expr = p.parseTest() // A following newline (e.g. "f()\n") appears outside any brackets, // on a non-blank line, and thus results in a NEWLINE token. if p.tok == NEWLINE { p.nextToken() } if p.tok != EOF { p.in.errorf(p.in.pos, "got %#v after expression, want EOF", p.tok) } p.assignComments(expr) return expr, nil }
[ "func", "ParseExpr", "(", "filename", "string", ",", "src", "interface", "{", "}", ",", "mode", "Mode", ")", "(", "expr", "Expr", ",", "err", "error", ")", "{", "in", ",", "err", ":=", "newScanner", "(", "filename", ",", "src", ",", "mode", "&", "RetainComments", "!=", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ":=", "parser", "{", "in", ":", "in", "}", "\n", "defer", "p", ".", "in", ".", "recover", "(", "&", "err", ")", "\n\n", "p", ".", "nextToken", "(", ")", "// read first lookahead token", "\n", "expr", "=", "p", ".", "parseTest", "(", ")", "\n\n", "// A following newline (e.g. \"f()\\n\") appears outside any brackets,", "// on a non-blank line, and thus results in a NEWLINE token.", "if", "p", ".", "tok", "==", "NEWLINE", "{", "p", ".", "nextToken", "(", ")", "\n", "}", "\n\n", "if", "p", ".", "tok", "!=", "EOF", "{", "p", ".", "in", ".", "errorf", "(", "p", ".", "in", ".", "pos", ",", "\"", "\"", ",", "p", ".", "tok", ")", "\n", "}", "\n", "p", ".", "assignComments", "(", "expr", ")", "\n", "return", "expr", ",", "nil", "\n", "}" ]
// ParseExpr parses a Skylark expression. // See Parse for explanation of parameters.
[ "ParseExpr", "parses", "a", "Skylark", "expression", ".", "See", "Parse", "for", "explanation", "of", "parameters", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/parse.go#L52-L74
6,605
google/skylark
syntax/parse.go
nextToken
func (p *parser) nextToken() Position { oldpos := p.tokval.pos p.tok = p.in.nextToken(&p.tokval) // enable to see the token stream if debug { log.Printf("nextToken: %-20s%+v\n", p.tok, p.tokval.pos) } return oldpos }
go
func (p *parser) nextToken() Position { oldpos := p.tokval.pos p.tok = p.in.nextToken(&p.tokval) // enable to see the token stream if debug { log.Printf("nextToken: %-20s%+v\n", p.tok, p.tokval.pos) } return oldpos }
[ "func", "(", "p", "*", "parser", ")", "nextToken", "(", ")", "Position", "{", "oldpos", ":=", "p", ".", "tokval", ".", "pos", "\n", "p", ".", "tok", "=", "p", ".", "in", ".", "nextToken", "(", "&", "p", ".", "tokval", ")", "\n", "// enable to see the token stream", "if", "debug", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "p", ".", "tok", ",", "p", ".", "tokval", ".", "pos", ")", "\n", "}", "\n", "return", "oldpos", "\n", "}" ]
// nextToken advances the scanner and returns the position of the // previous token.
[ "nextToken", "advances", "the", "scanner", "and", "returns", "the", "position", "of", "the", "previous", "token", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/parse.go#L84-L92
6,606
google/skylark
syntax/parse.go
parseLambda
func (p *parser) parseLambda(allowCond bool) Expr { lambda := p.nextToken() var params []Expr if p.tok != COLON { params = p.parseParams() } p.consume(COLON) var body Expr if allowCond { body = p.parseTest() } else { body = p.parseTestNoCond() } return &LambdaExpr{ Lambda: lambda, Function: Function{ StartPos: lambda, Params: params, Body: []Stmt{&ReturnStmt{Result: body}}, }, } }
go
func (p *parser) parseLambda(allowCond bool) Expr { lambda := p.nextToken() var params []Expr if p.tok != COLON { params = p.parseParams() } p.consume(COLON) var body Expr if allowCond { body = p.parseTest() } else { body = p.parseTestNoCond() } return &LambdaExpr{ Lambda: lambda, Function: Function{ StartPos: lambda, Params: params, Body: []Stmt{&ReturnStmt{Result: body}}, }, } }
[ "func", "(", "p", "*", "parser", ")", "parseLambda", "(", "allowCond", "bool", ")", "Expr", "{", "lambda", ":=", "p", ".", "nextToken", "(", ")", "\n", "var", "params", "[", "]", "Expr", "\n", "if", "p", ".", "tok", "!=", "COLON", "{", "params", "=", "p", ".", "parseParams", "(", ")", "\n", "}", "\n", "p", ".", "consume", "(", "COLON", ")", "\n\n", "var", "body", "Expr", "\n", "if", "allowCond", "{", "body", "=", "p", ".", "parseTest", "(", ")", "\n", "}", "else", "{", "body", "=", "p", ".", "parseTestNoCond", "(", ")", "\n", "}", "\n\n", "return", "&", "LambdaExpr", "{", "Lambda", ":", "lambda", ",", "Function", ":", "Function", "{", "StartPos", ":", "lambda", ",", "Params", ":", "params", ",", "Body", ":", "[", "]", "Stmt", "{", "&", "ReturnStmt", "{", "Result", ":", "body", "}", "}", ",", "}", ",", "}", "\n", "}" ]
// parseLambda parses a lambda expression. // The allowCond flag allows the body to be an 'a if b else c' conditional.
[ "parseLambda", "parses", "a", "lambda", "expression", ".", "The", "allowCond", "flag", "allows", "the", "body", "to", "be", "an", "a", "if", "b", "else", "c", "conditional", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/parse.go#L508-L531
6,607
google/skylark
syntax/parse.go
parsePrimaryWithSuffix
func (p *parser) parsePrimaryWithSuffix() Expr { x := p.parsePrimary() for { switch p.tok { case DOT: dot := p.nextToken() id := p.parseIdent() x = &DotExpr{Dot: dot, X: x, Name: id} case LBRACK: x = p.parseSliceSuffix(x) case LPAREN: x = p.parseCallSuffix(x) default: return x } } }
go
func (p *parser) parsePrimaryWithSuffix() Expr { x := p.parsePrimary() for { switch p.tok { case DOT: dot := p.nextToken() id := p.parseIdent() x = &DotExpr{Dot: dot, X: x, Name: id} case LBRACK: x = p.parseSliceSuffix(x) case LPAREN: x = p.parseCallSuffix(x) default: return x } } }
[ "func", "(", "p", "*", "parser", ")", "parsePrimaryWithSuffix", "(", ")", "Expr", "{", "x", ":=", "p", ".", "parsePrimary", "(", ")", "\n", "for", "{", "switch", "p", ".", "tok", "{", "case", "DOT", ":", "dot", ":=", "p", ".", "nextToken", "(", ")", "\n", "id", ":=", "p", ".", "parseIdent", "(", ")", "\n", "x", "=", "&", "DotExpr", "{", "Dot", ":", "dot", ",", "X", ":", "x", ",", "Name", ":", "id", "}", "\n", "case", "LBRACK", ":", "x", "=", "p", ".", "parseSliceSuffix", "(", "x", ")", "\n", "case", "LPAREN", ":", "x", "=", "p", ".", "parseCallSuffix", "(", "x", ")", "\n", "default", ":", "return", "x", "\n", "}", "\n", "}", "\n", "}" ]
// primary_with_suffix = primary // | primary '.' IDENT // | primary slice_suffix // | primary call_suffix
[ "primary_with_suffix", "=", "primary", "|", "primary", ".", "IDENT", "|", "primary", "slice_suffix", "|", "primary", "call_suffix" ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/parse.go#L622-L638
6,608
google/skylark
syntax/parse.go
flattenAST
func flattenAST(root Node) (pre, post []Node) { stack := []Node{} Walk(root, func(n Node) bool { if n != nil { pre = append(pre, n) stack = append(stack, n) } else { post = append(post, stack[len(stack)-1]) stack = stack[:len(stack)-1] } return true }) return pre, post }
go
func flattenAST(root Node) (pre, post []Node) { stack := []Node{} Walk(root, func(n Node) bool { if n != nil { pre = append(pre, n) stack = append(stack, n) } else { post = append(post, stack[len(stack)-1]) stack = stack[:len(stack)-1] } return true }) return pre, post }
[ "func", "flattenAST", "(", "root", "Node", ")", "(", "pre", ",", "post", "[", "]", "Node", ")", "{", "stack", ":=", "[", "]", "Node", "{", "}", "\n", "Walk", "(", "root", ",", "func", "(", "n", "Node", ")", "bool", "{", "if", "n", "!=", "nil", "{", "pre", "=", "append", "(", "pre", ",", "n", ")", "\n", "stack", "=", "append", "(", "stack", ",", "n", ")", "\n", "}", "else", "{", "post", "=", "append", "(", "post", ",", "stack", "[", "len", "(", "stack", ")", "-", "1", "]", ")", "\n", "stack", "=", "stack", "[", ":", "len", "(", "stack", ")", "-", "1", "]", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "return", "pre", ",", "post", "\n", "}" ]
// Comment assignment. // We build two lists of all subnodes, preorder and postorder. // The preorder list is ordered by start location, with outer nodes first. // The postorder list is ordered by end location, with outer nodes last. // We use the preorder list to assign each whole-line comment to the syntax // immediately following it, and we use the postorder list to assign each // end-of-line comment to the syntax immediately preceding it. // flattenAST returns the list of AST nodes, both in prefix order and in postfix // order.
[ "Comment", "assignment", ".", "We", "build", "two", "lists", "of", "all", "subnodes", "preorder", "and", "postorder", ".", "The", "preorder", "list", "is", "ordered", "by", "start", "location", "with", "outer", "nodes", "first", ".", "The", "postorder", "list", "is", "ordered", "by", "end", "location", "with", "outer", "nodes", "last", ".", "We", "use", "the", "preorder", "list", "to", "assign", "each", "whole", "-", "line", "comment", "to", "the", "syntax", "immediately", "following", "it", "and", "we", "use", "the", "postorder", "list", "to", "assign", "each", "end", "-", "of", "-", "line", "comment", "to", "the", "syntax", "immediately", "preceding", "it", ".", "flattenAST", "returns", "the", "list", "of", "AST", "nodes", "both", "in", "prefix", "order", "and", "in", "postfix", "order", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/parse.go#L947-L960
6,609
google/skylark
library.go
isCasedString
func isCasedString(s string) bool { for _, r := range s { if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || unicode.SimpleFold(r) != r { return true } } return false }
go
func isCasedString(s string) bool { for _, r := range s { if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || unicode.SimpleFold(r) != r { return true } } return false }
[ "func", "isCasedString", "(", "s", "string", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "s", "{", "if", "'a'", "<=", "r", "&&", "r", "<=", "'z'", "||", "'A'", "<=", "r", "&&", "r", "<=", "'Z'", "||", "unicode", ".", "SimpleFold", "(", "r", ")", "!=", "r", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isCasedString reports whether its argument contains any cased characters.
[ "isCasedString", "reports", "whether", "its", "argument", "contains", "any", "cased", "characters", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/library.go#L1535-L1542
6,610
google/skylark
int.go
MakeInt64
func MakeInt64(x int64) Int { if 0 <= x && x < int64(len(smallint)) { if !smallintok { panic("MakeInt64 used before initialization") } return Int{&smallint[x]} } return Int{new(big.Int).SetInt64(x)} }
go
func MakeInt64(x int64) Int { if 0 <= x && x < int64(len(smallint)) { if !smallintok { panic("MakeInt64 used before initialization") } return Int{&smallint[x]} } return Int{new(big.Int).SetInt64(x)} }
[ "func", "MakeInt64", "(", "x", "int64", ")", "Int", "{", "if", "0", "<=", "x", "&&", "x", "<", "int64", "(", "len", "(", "smallint", ")", ")", "{", "if", "!", "smallintok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "Int", "{", "&", "smallint", "[", "x", "]", "}", "\n", "}", "\n", "return", "Int", "{", "new", "(", "big", ".", "Int", ")", ".", "SetInt64", "(", "x", ")", "}", "\n", "}" ]
// MakeInt64 returns a Skylark int for the specified int64.
[ "MakeInt64", "returns", "a", "Skylark", "int", "for", "the", "specified", "int64", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L22-L30
6,611
google/skylark
int.go
MakeUint64
func MakeUint64(x uint64) Int { if x < uint64(len(smallint)) { if !smallintok { panic("MakeUint64 used before initialization") } return Int{&smallint[x]} } return Int{new(big.Int).SetUint64(uint64(x))} }
go
func MakeUint64(x uint64) Int { if x < uint64(len(smallint)) { if !smallintok { panic("MakeUint64 used before initialization") } return Int{&smallint[x]} } return Int{new(big.Int).SetUint64(uint64(x))} }
[ "func", "MakeUint64", "(", "x", "uint64", ")", "Int", "{", "if", "x", "<", "uint64", "(", "len", "(", "smallint", ")", ")", "{", "if", "!", "smallintok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "Int", "{", "&", "smallint", "[", "x", "]", "}", "\n", "}", "\n", "return", "Int", "{", "new", "(", "big", ".", "Int", ")", ".", "SetUint64", "(", "uint64", "(", "x", ")", ")", "}", "\n", "}" ]
// MakeUint64 returns a Skylark int for the specified uint64.
[ "MakeUint64", "returns", "a", "Skylark", "int", "for", "the", "specified", "uint64", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L36-L44
6,612
google/skylark
int.go
Int64
func (i Int) Int64() (_ int64, ok bool) { x, acc := bigintToInt64(i.bigint) if acc != big.Exact { return // inexact } return x, true }
go
func (i Int) Int64() (_ int64, ok bool) { x, acc := bigintToInt64(i.bigint) if acc != big.Exact { return // inexact } return x, true }
[ "func", "(", "i", "Int", ")", "Int64", "(", ")", "(", "_", "int64", ",", "ok", "bool", ")", "{", "x", ",", "acc", ":=", "bigintToInt64", "(", "i", ".", "bigint", ")", "\n", "if", "acc", "!=", "big", ".", "Exact", "{", "return", "// inexact", "\n", "}", "\n", "return", "x", ",", "true", "\n", "}" ]
// Int64 returns the value as an int64. // If it is not exactly representable the result is undefined and ok is false.
[ "Int64", "returns", "the", "value", "as", "an", "int64", ".", "If", "it", "is", "not", "exactly", "representable", "the", "result", "is", "undefined", "and", "ok", "is", "false", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L64-L70
6,613
google/skylark
int.go
Uint64
func (i Int) Uint64() (_ uint64, ok bool) { x, acc := bigintToUint64(i.bigint) if acc != big.Exact { return // inexact } return x, true }
go
func (i Int) Uint64() (_ uint64, ok bool) { x, acc := bigintToUint64(i.bigint) if acc != big.Exact { return // inexact } return x, true }
[ "func", "(", "i", "Int", ")", "Uint64", "(", ")", "(", "_", "uint64", ",", "ok", "bool", ")", "{", "x", ",", "acc", ":=", "bigintToUint64", "(", "i", ".", "bigint", ")", "\n", "if", "acc", "!=", "big", ".", "Exact", "{", "return", "// inexact", "\n", "}", "\n", "return", "x", ",", "true", "\n", "}" ]
// Uint64 returns the value as a uint64. // If it is not exactly representable the result is undefined and ok is false.
[ "Uint64", "returns", "the", "value", "as", "a", "uint64", ".", "If", "it", "is", "not", "exactly", "representable", "the", "result", "is", "undefined", "and", "ok", "is", "false", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L74-L80
6,614
google/skylark
int.go
Float
func (i Int) Float() Float { // TODO(adonovan): opt: handle common values without allocation. f, _ := new(big.Float).SetInt(i.bigint).Float64() return Float(f) }
go
func (i Int) Float() Float { // TODO(adonovan): opt: handle common values without allocation. f, _ := new(big.Float).SetInt(i.bigint).Float64() return Float(f) }
[ "func", "(", "i", "Int", ")", "Float", "(", ")", "Float", "{", "// TODO(adonovan): opt: handle common values without allocation.", "f", ",", "_", ":=", "new", "(", "big", ".", "Float", ")", ".", "SetInt", "(", "i", ".", "bigint", ")", ".", "Float64", "(", ")", "\n", "return", "Float", "(", "f", ")", "\n", "}" ]
// Float returns the float value nearest i.
[ "Float", "returns", "the", "float", "value", "nearest", "i", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L131-L135
6,615
google/skylark
int.go
AsInt32
func AsInt32(x Value) (int, error) { i, ok := x.(Int) if !ok { return 0, fmt.Errorf("got %s, want int", x.Type()) } if i.bigint.BitLen() <= 32 { v := i.bigint.Int64() if v >= math.MinInt32 && v <= math.MaxInt32 { return int(v), nil } } return 0, fmt.Errorf("%s out of range", i) }
go
func AsInt32(x Value) (int, error) { i, ok := x.(Int) if !ok { return 0, fmt.Errorf("got %s, want int", x.Type()) } if i.bigint.BitLen() <= 32 { v := i.bigint.Int64() if v >= math.MinInt32 && v <= math.MaxInt32 { return int(v), nil } } return 0, fmt.Errorf("%s out of range", i) }
[ "func", "AsInt32", "(", "x", "Value", ")", "(", "int", ",", "error", ")", "{", "i", ",", "ok", ":=", "x", ".", "(", "Int", ")", "\n", "if", "!", "ok", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "x", ".", "Type", "(", ")", ")", "\n", "}", "\n", "if", "i", ".", "bigint", ".", "BitLen", "(", ")", "<=", "32", "{", "v", ":=", "i", ".", "bigint", ".", "Int64", "(", ")", "\n", "if", "v", ">=", "math", ".", "MinInt32", "&&", "v", "<=", "math", ".", "MaxInt32", "{", "return", "int", "(", "v", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ")", "\n", "}" ]
// AsInt32 returns the value of x if is representable as an int32.
[ "AsInt32", "returns", "the", "value", "of", "x", "if", "is", "representable", "as", "an", "int32", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L172-L184
6,616
google/skylark
int.go
NumberToInt
func NumberToInt(x Value) (Int, error) { switch x := x.(type) { case Int: return x, nil case Float: f := float64(x) if math.IsInf(f, 0) { return zero, fmt.Errorf("cannot convert float infinity to integer") } else if math.IsNaN(f) { return zero, fmt.Errorf("cannot convert float NaN to integer") } return finiteFloatToInt(x), nil } return zero, fmt.Errorf("cannot convert %s to int", x.Type()) }
go
func NumberToInt(x Value) (Int, error) { switch x := x.(type) { case Int: return x, nil case Float: f := float64(x) if math.IsInf(f, 0) { return zero, fmt.Errorf("cannot convert float infinity to integer") } else if math.IsNaN(f) { return zero, fmt.Errorf("cannot convert float NaN to integer") } return finiteFloatToInt(x), nil } return zero, fmt.Errorf("cannot convert %s to int", x.Type()) }
[ "func", "NumberToInt", "(", "x", "Value", ")", "(", "Int", ",", "error", ")", "{", "switch", "x", ":=", "x", ".", "(", "type", ")", "{", "case", "Int", ":", "return", "x", ",", "nil", "\n", "case", "Float", ":", "f", ":=", "float64", "(", "x", ")", "\n", "if", "math", ".", "IsInf", "(", "f", ",", "0", ")", "{", "return", "zero", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "if", "math", ".", "IsNaN", "(", "f", ")", "{", "return", "zero", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "finiteFloatToInt", "(", "x", ")", ",", "nil", "\n\n", "}", "\n", "return", "zero", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "x", ".", "Type", "(", ")", ")", "\n", "}" ]
// NumberToInt converts a number x to an integer value. // An int is returned unchanged, a float is truncated towards zero. // NumberToInt reports an error for all other values.
[ "NumberToInt", "converts", "a", "number", "x", "to", "an", "integer", "value", ".", "An", "int", "is", "returned", "unchanged", "a", "float", "is", "truncated", "towards", "zero", ".", "NumberToInt", "reports", "an", "error", "for", "all", "other", "values", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L189-L204
6,617
google/skylark
int.go
finiteFloatToInt
func finiteFloatToInt(f Float) Int { var i big.Int if math.MinInt64 <= f && f <= math.MaxInt64 { // small values i.SetInt64(int64(f)) } else { rat := f.rational() if rat == nil { panic(f) // non-finite } i.Div(rat.Num(), rat.Denom()) } return Int{&i} }
go
func finiteFloatToInt(f Float) Int { var i big.Int if math.MinInt64 <= f && f <= math.MaxInt64 { // small values i.SetInt64(int64(f)) } else { rat := f.rational() if rat == nil { panic(f) // non-finite } i.Div(rat.Num(), rat.Denom()) } return Int{&i} }
[ "func", "finiteFloatToInt", "(", "f", "Float", ")", "Int", "{", "var", "i", "big", ".", "Int", "\n", "if", "math", ".", "MinInt64", "<=", "f", "&&", "f", "<=", "math", ".", "MaxInt64", "{", "// small values", "i", ".", "SetInt64", "(", "int64", "(", "f", ")", ")", "\n", "}", "else", "{", "rat", ":=", "f", ".", "rational", "(", ")", "\n", "if", "rat", "==", "nil", "{", "panic", "(", "f", ")", "// non-finite", "\n", "}", "\n", "i", ".", "Div", "(", "rat", ".", "Num", "(", ")", ",", "rat", ".", "Denom", "(", ")", ")", "\n", "}", "\n", "return", "Int", "{", "&", "i", "}", "\n", "}" ]
// finiteFloatToInt converts f to an Int, truncating towards zero. // f must be finite.
[ "finiteFloatToInt", "converts", "f", "to", "an", "Int", "truncating", "towards", "zero", ".", "f", "must", "be", "finite", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/int.go#L208-L221
6,618
google/skylark
cmd/skylark/skylark.go
init
func init() { flag.BoolVar(&resolve.AllowFloat, "fp", resolve.AllowFloat, "allow floating-point numbers") flag.BoolVar(&resolve.AllowSet, "set", resolve.AllowSet, "allow set data type") flag.BoolVar(&resolve.AllowLambda, "lambda", resolve.AllowLambda, "allow lambda expressions") flag.BoolVar(&resolve.AllowNestedDef, "nesteddef", resolve.AllowNestedDef, "allow nested def statements") flag.BoolVar(&resolve.AllowBitwise, "bitwise", resolve.AllowBitwise, "allow bitwise operations (&, |, ^, ~, <<, and >>)") }
go
func init() { flag.BoolVar(&resolve.AllowFloat, "fp", resolve.AllowFloat, "allow floating-point numbers") flag.BoolVar(&resolve.AllowSet, "set", resolve.AllowSet, "allow set data type") flag.BoolVar(&resolve.AllowLambda, "lambda", resolve.AllowLambda, "allow lambda expressions") flag.BoolVar(&resolve.AllowNestedDef, "nesteddef", resolve.AllowNestedDef, "allow nested def statements") flag.BoolVar(&resolve.AllowBitwise, "bitwise", resolve.AllowBitwise, "allow bitwise operations (&, |, ^, ~, <<, and >>)") }
[ "func", "init", "(", ")", "{", "flag", ".", "BoolVar", "(", "&", "resolve", ".", "AllowFloat", ",", "\"", "\"", ",", "resolve", ".", "AllowFloat", ",", "\"", "\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "resolve", ".", "AllowSet", ",", "\"", "\"", ",", "resolve", ".", "AllowSet", ",", "\"", "\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "resolve", ".", "AllowLambda", ",", "\"", "\"", ",", "resolve", ".", "AllowLambda", ",", "\"", "\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "resolve", ".", "AllowNestedDef", ",", "\"", "\"", ",", "resolve", ".", "AllowNestedDef", ",", "\"", "\"", ")", "\n", "flag", ".", "BoolVar", "(", "&", "resolve", ".", "AllowBitwise", ",", "\"", "\"", ",", "resolve", ".", "AllowBitwise", ",", "\"", "\"", ")", "\n", "}" ]
// non-standard dialect flags
[ "non", "-", "standard", "dialect", "flags" ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/cmd/skylark/skylark.go#L30-L36
6,619
google/skylark
eval.go
SetLocal
func (thread *Thread) SetLocal(key string, value interface{}) { if thread.locals == nil { thread.locals = make(map[string]interface{}) } thread.locals[key] = value }
go
func (thread *Thread) SetLocal(key string, value interface{}) { if thread.locals == nil { thread.locals = make(map[string]interface{}) } thread.locals[key] = value }
[ "func", "(", "thread", "*", "Thread", ")", "SetLocal", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "if", "thread", ".", "locals", "==", "nil", "{", "thread", ".", "locals", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "\n", "thread", ".", "locals", "[", "key", "]", "=", "value", "\n", "}" ]
// SetLocal sets the thread-local value associated with the specified key. // It must not be called after execution begins.
[ "SetLocal", "sets", "the", "thread", "-", "local", "value", "associated", "with", "the", "specified", "key", ".", "It", "must", "not", "be", "called", "after", "execution", "begins", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L53-L58
6,620
google/skylark
eval.go
errorf
func (fr *Frame) errorf(posn syntax.Position, format string, args ...interface{}) *EvalError { fr.posn = posn msg := fmt.Sprintf(format, args...) return &EvalError{Msg: msg, Frame: fr} }
go
func (fr *Frame) errorf(posn syntax.Position, format string, args ...interface{}) *EvalError { fr.posn = posn msg := fmt.Sprintf(format, args...) return &EvalError{Msg: msg, Frame: fr} }
[ "func", "(", "fr", "*", "Frame", ")", "errorf", "(", "posn", "syntax", ".", "Position", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "EvalError", "{", "fr", ".", "posn", "=", "posn", "\n", "msg", ":=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n", "return", "&", "EvalError", "{", "Msg", ":", "msg", ",", "Frame", ":", "fr", "}", "\n", "}" ]
// The Frames of a thread are structured as a spaghetti stack, not a // slice, so that an EvalError can copy a stack efficiently and immutably. // In hindsight using a slice would have led to a more convenient API.
[ "The", "Frames", "of", "a", "thread", "are", "structured", "as", "a", "spaghetti", "stack", "not", "a", "slice", "so", "that", "an", "EvalError", "can", "copy", "a", "stack", "efficiently", "and", "immutably", ".", "In", "hindsight", "using", "a", "slice", "would", "have", "led", "to", "a", "more", "convenient", "API", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L121-L125
6,621
google/skylark
eval.go
Position
func (fr *Frame) Position() syntax.Position { if fr.posn.IsValid() { return fr.posn // leaf frame only (the error) } if fn, ok := fr.callable.(*Function); ok { return fn.funcode.Position(fr.callpc) // position of active call } return syntax.MakePosition(&builtinFilename, 1, 0) }
go
func (fr *Frame) Position() syntax.Position { if fr.posn.IsValid() { return fr.posn // leaf frame only (the error) } if fn, ok := fr.callable.(*Function); ok { return fn.funcode.Position(fr.callpc) // position of active call } return syntax.MakePosition(&builtinFilename, 1, 0) }
[ "func", "(", "fr", "*", "Frame", ")", "Position", "(", ")", "syntax", ".", "Position", "{", "if", "fr", ".", "posn", ".", "IsValid", "(", ")", "{", "return", "fr", ".", "posn", "// leaf frame only (the error)", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "fr", ".", "callable", ".", "(", "*", "Function", ")", ";", "ok", "{", "return", "fn", ".", "funcode", ".", "Position", "(", "fr", ".", "callpc", ")", "// position of active call", "\n", "}", "\n", "return", "syntax", ".", "MakePosition", "(", "&", "builtinFilename", ",", "1", ",", "0", ")", "\n", "}" ]
// Position returns the source position of the current point of execution in this frame.
[ "Position", "returns", "the", "source", "position", "of", "the", "current", "point", "of", "execution", "in", "this", "frame", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L128-L136
6,622
google/skylark
eval.go
Backtrace
func (e *EvalError) Backtrace() string { var buf bytes.Buffer e.Frame.WriteBacktrace(&buf) fmt.Fprintf(&buf, "Error: %s", e.Msg) return buf.String() }
go
func (e *EvalError) Backtrace() string { var buf bytes.Buffer e.Frame.WriteBacktrace(&buf) fmt.Fprintf(&buf, "Error: %s", e.Msg) return buf.String() }
[ "func", "(", "e", "*", "EvalError", ")", "Backtrace", "(", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "e", ".", "Frame", ".", "WriteBacktrace", "(", "&", "buf", ")", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "e", ".", "Msg", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Backtrace returns a user-friendly error message describing the stack // of calls that led to this error.
[ "Backtrace", "returns", "a", "user", "-", "friendly", "error", "message", "describing", "the", "stack", "of", "calls", "that", "led", "to", "this", "error", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L156-L161
6,623
google/skylark
eval.go
WriteBacktrace
func (fr *Frame) WriteBacktrace(out *bytes.Buffer) { fmt.Fprintf(out, "Traceback (most recent call last):\n") var print func(fr *Frame) print = func(fr *Frame) { if fr != nil { print(fr.parent) fmt.Fprintf(out, " %s: in %s\n", fr.Position(), fr.Callable().Name()) } } print(fr) }
go
func (fr *Frame) WriteBacktrace(out *bytes.Buffer) { fmt.Fprintf(out, "Traceback (most recent call last):\n") var print func(fr *Frame) print = func(fr *Frame) { if fr != nil { print(fr.parent) fmt.Fprintf(out, " %s: in %s\n", fr.Position(), fr.Callable().Name()) } } print(fr) }
[ "func", "(", "fr", "*", "Frame", ")", "WriteBacktrace", "(", "out", "*", "bytes", ".", "Buffer", ")", "{", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\n", "\"", ")", "\n", "var", "print", "func", "(", "fr", "*", "Frame", ")", "\n", "print", "=", "func", "(", "fr", "*", "Frame", ")", "{", "if", "fr", "!=", "nil", "{", "print", "(", "fr", ".", "parent", ")", "\n", "fmt", ".", "Fprintf", "(", "out", ",", "\"", "\\n", "\"", ",", "fr", ".", "Position", "(", ")", ",", "fr", ".", "Callable", "(", ")", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "print", "(", "fr", ")", "\n", "}" ]
// WriteBacktrace writes a user-friendly description of the stack to buf.
[ "WriteBacktrace", "writes", "a", "user", "-", "friendly", "description", "of", "the", "stack", "to", "buf", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L164-L174
6,624
google/skylark
eval.go
Stack
func (e *EvalError) Stack() []*Frame { var stack []*Frame for fr := e.Frame; fr != nil; fr = fr.parent { stack = append(stack, fr) } return stack }
go
func (e *EvalError) Stack() []*Frame { var stack []*Frame for fr := e.Frame; fr != nil; fr = fr.parent { stack = append(stack, fr) } return stack }
[ "func", "(", "e", "*", "EvalError", ")", "Stack", "(", ")", "[", "]", "*", "Frame", "{", "var", "stack", "[", "]", "*", "Frame", "\n", "for", "fr", ":=", "e", ".", "Frame", ";", "fr", "!=", "nil", ";", "fr", "=", "fr", ".", "parent", "{", "stack", "=", "append", "(", "stack", ",", "fr", ")", "\n", "}", "\n", "return", "stack", "\n", "}" ]
// Stack returns the stack of frames, innermost first.
[ "Stack", "returns", "the", "stack", "of", "frames", "innermost", "first", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L177-L183
6,625
google/skylark
eval.go
SourceProgram
func SourceProgram(filename string, src interface{}, isPredeclared func(string) bool) (*syntax.File, *Program, error) { f, err := syntax.Parse(filename, src, 0) if err != nil { return nil, nil, err } if err := resolve.File(f, isPredeclared, Universe.Has); err != nil { return f, nil, err } compiled := compile.File(f.Stmts, f.Locals, f.Globals) return f, &Program{compiled}, nil }
go
func SourceProgram(filename string, src interface{}, isPredeclared func(string) bool) (*syntax.File, *Program, error) { f, err := syntax.Parse(filename, src, 0) if err != nil { return nil, nil, err } if err := resolve.File(f, isPredeclared, Universe.Has); err != nil { return f, nil, err } compiled := compile.File(f.Stmts, f.Locals, f.Globals) return f, &Program{compiled}, nil }
[ "func", "SourceProgram", "(", "filename", "string", ",", "src", "interface", "{", "}", ",", "isPredeclared", "func", "(", "string", ")", "bool", ")", "(", "*", "syntax", ".", "File", ",", "*", "Program", ",", "error", ")", "{", "f", ",", "err", ":=", "syntax", ".", "Parse", "(", "filename", ",", "src", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "resolve", ".", "File", "(", "f", ",", "isPredeclared", ",", "Universe", ".", "Has", ")", ";", "err", "!=", "nil", "{", "return", "f", ",", "nil", ",", "err", "\n", "}", "\n\n", "compiled", ":=", "compile", ".", "File", "(", "f", ".", "Stmts", ",", "f", ".", "Locals", ",", "f", ".", "Globals", ")", "\n\n", "return", "f", ",", "&", "Program", "{", "compiled", "}", ",", "nil", "\n", "}" ]
// SourceProgram produces a new program by parsing, resolving, // and compiling a Skylark source file. // On success, it returns the parsed file and the compiled program. // The filename and src parameters are as for syntax.Parse. // // The isPredeclared predicate reports whether a name is // a pre-declared identifier of the current module. // Its typical value is predeclared.Has, // where predeclared is a StringDict of pre-declared values.
[ "SourceProgram", "produces", "a", "new", "program", "by", "parsing", "resolving", "and", "compiling", "a", "Skylark", "source", "file", ".", "On", "success", "it", "returns", "the", "parsed", "file", "and", "the", "compiled", "program", ".", "The", "filename", "and", "src", "parameters", "are", "as", "for", "syntax", ".", "Parse", ".", "The", "isPredeclared", "predicate", "reports", "whether", "a", "name", "is", "a", "pre", "-", "declared", "identifier", "of", "the", "current", "module", ".", "Its", "typical", "value", "is", "predeclared", ".", "Has", "where", "predeclared", "is", "a", "StringDict", "of", "pre", "-", "declared", "values", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L252-L265
6,626
google/skylark
eval.go
CompiledProgram
func CompiledProgram(in io.Reader) (*Program, error) { prog, err := compile.ReadProgram(in) if err != nil { return nil, err } return &Program{prog}, nil }
go
func CompiledProgram(in io.Reader) (*Program, error) { prog, err := compile.ReadProgram(in) if err != nil { return nil, err } return &Program{prog}, nil }
[ "func", "CompiledProgram", "(", "in", "io", ".", "Reader", ")", "(", "*", "Program", ",", "error", ")", "{", "prog", ",", "err", ":=", "compile", ".", "ReadProgram", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Program", "{", "prog", "}", ",", "nil", "\n", "}" ]
// CompiledProgram produces a new program from the representation // of a compiled program previously saved by Program.Write.
[ "CompiledProgram", "produces", "a", "new", "program", "from", "the", "representation", "of", "a", "compiled", "program", "previously", "saved", "by", "Program", ".", "Write", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L269-L275
6,627
google/skylark
eval.go
Init
func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) { toplevel := makeToplevelFunction(prog.compiled.Toplevel, predeclared) _, err := Call(thread, toplevel, nil, nil) // Convert the global environment to a map and freeze it. // We return a (partial) map even in case of error. return toplevel.Globals(), err }
go
func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) { toplevel := makeToplevelFunction(prog.compiled.Toplevel, predeclared) _, err := Call(thread, toplevel, nil, nil) // Convert the global environment to a map and freeze it. // We return a (partial) map even in case of error. return toplevel.Globals(), err }
[ "func", "(", "prog", "*", "Program", ")", "Init", "(", "thread", "*", "Thread", ",", "predeclared", "StringDict", ")", "(", "StringDict", ",", "error", ")", "{", "toplevel", ":=", "makeToplevelFunction", "(", "prog", ".", "compiled", ".", "Toplevel", ",", "predeclared", ")", "\n\n", "_", ",", "err", ":=", "Call", "(", "thread", ",", "toplevel", ",", "nil", ",", "nil", ")", "\n\n", "// Convert the global environment to a map and freeze it.", "// We return a (partial) map even in case of error.", "return", "toplevel", ".", "Globals", "(", ")", ",", "err", "\n", "}" ]
// Init creates a set of global variables for the program, // executes the toplevel code of the specified program, // and returns a new, unfrozen dictionary of the globals.
[ "Init", "creates", "a", "set", "of", "global", "variables", "for", "the", "program", "executes", "the", "toplevel", "code", "of", "the", "specified", "program", "and", "returns", "a", "new", "unfrozen", "dictionary", "of", "the", "globals", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L280-L288
6,628
google/skylark
eval.go
listExtend
func listExtend(x *List, y Iterable) { if ylist, ok := y.(*List); ok { // fast path: list += list x.elems = append(x.elems, ylist.elems...) } else { iter := y.Iterate() defer iter.Done() var z Value for iter.Next(&z) { x.elems = append(x.elems, z) } } }
go
func listExtend(x *List, y Iterable) { if ylist, ok := y.(*List); ok { // fast path: list += list x.elems = append(x.elems, ylist.elems...) } else { iter := y.Iterate() defer iter.Done() var z Value for iter.Next(&z) { x.elems = append(x.elems, z) } } }
[ "func", "listExtend", "(", "x", "*", "List", ",", "y", "Iterable", ")", "{", "if", "ylist", ",", "ok", ":=", "y", ".", "(", "*", "List", ")", ";", "ok", "{", "// fast path: list += list", "x", ".", "elems", "=", "append", "(", "x", ".", "elems", ",", "ylist", ".", "elems", "...", ")", "\n", "}", "else", "{", "iter", ":=", "y", ".", "Iterate", "(", ")", "\n", "defer", "iter", ".", "Done", "(", ")", "\n", "var", "z", "Value", "\n", "for", "iter", ".", "Next", "(", "&", "z", ")", "{", "x", ".", "elems", "=", "append", "(", "x", ".", "elems", ",", "z", ")", "\n", "}", "\n", "}", "\n", "}" ]
// The following functions are primitive operations of the byte code interpreter. // list += iterable
[ "The", "following", "functions", "are", "primitive", "operations", "of", "the", "byte", "code", "interpreter", ".", "list", "+", "=", "iterable" ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L347-L359
6,629
google/skylark
eval.go
getAttr
func getAttr(fr *Frame, x Value, name string) (Value, error) { // field or method? if x, ok := x.(HasAttrs); ok { if v, err := x.Attr(name); v != nil || err != nil { return v, err } } return nil, fmt.Errorf("%s has no .%s field or method", x.Type(), name) }
go
func getAttr(fr *Frame, x Value, name string) (Value, error) { // field or method? if x, ok := x.(HasAttrs); ok { if v, err := x.Attr(name); v != nil || err != nil { return v, err } } return nil, fmt.Errorf("%s has no .%s field or method", x.Type(), name) }
[ "func", "getAttr", "(", "fr", "*", "Frame", ",", "x", "Value", ",", "name", "string", ")", "(", "Value", ",", "error", ")", "{", "// field or method?", "if", "x", ",", "ok", ":=", "x", ".", "(", "HasAttrs", ")", ";", "ok", "{", "if", "v", ",", "err", ":=", "x", ".", "Attr", "(", "name", ")", ";", "v", "!=", "nil", "||", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "x", ".", "Type", "(", ")", ",", "name", ")", "\n", "}" ]
// getAttr implements x.dot.
[ "getAttr", "implements", "x", ".", "dot", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L362-L371
6,630
google/skylark
eval.go
setField
func setField(fr *Frame, x Value, name string, y Value) error { if x, ok := x.(HasSetField); ok { err := x.SetField(name, y) return err } return fmt.Errorf("can't assign to .%s field of %s", name, x.Type()) }
go
func setField(fr *Frame, x Value, name string, y Value) error { if x, ok := x.(HasSetField); ok { err := x.SetField(name, y) return err } return fmt.Errorf("can't assign to .%s field of %s", name, x.Type()) }
[ "func", "setField", "(", "fr", "*", "Frame", ",", "x", "Value", ",", "name", "string", ",", "y", "Value", ")", "error", "{", "if", "x", ",", "ok", ":=", "x", ".", "(", "HasSetField", ")", ";", "ok", "{", "err", ":=", "x", ".", "SetField", "(", "name", ",", "y", ")", "\n", "return", "err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "x", ".", "Type", "(", ")", ")", "\n", "}" ]
// setField implements x.name = y.
[ "setField", "implements", "x", ".", "name", "=", "y", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L374-L380
6,631
google/skylark
eval.go
Call
func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) { c, ok := fn.(Callable) if !ok { return nil, fmt.Errorf("invalid call of non-function (%s)", fn.Type()) } thread.frame = &Frame{parent: thread.frame, callable: c} result, err := c.CallInternal(thread, args, kwargs) thread.frame = thread.frame.parent // Sanity check: nil is not a valid Skylark value. if result == nil && err == nil { return nil, fmt.Errorf("internal error: nil (not None) returned from %s", fn) } return result, err }
go
func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) { c, ok := fn.(Callable) if !ok { return nil, fmt.Errorf("invalid call of non-function (%s)", fn.Type()) } thread.frame = &Frame{parent: thread.frame, callable: c} result, err := c.CallInternal(thread, args, kwargs) thread.frame = thread.frame.parent // Sanity check: nil is not a valid Skylark value. if result == nil && err == nil { return nil, fmt.Errorf("internal error: nil (not None) returned from %s", fn) } return result, err }
[ "func", "Call", "(", "thread", "*", "Thread", ",", "fn", "Value", ",", "args", "Tuple", ",", "kwargs", "[", "]", "Tuple", ")", "(", "Value", ",", "error", ")", "{", "c", ",", "ok", ":=", "fn", ".", "(", "Callable", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ".", "Type", "(", ")", ")", "\n", "}", "\n\n", "thread", ".", "frame", "=", "&", "Frame", "{", "parent", ":", "thread", ".", "frame", ",", "callable", ":", "c", "}", "\n", "result", ",", "err", ":=", "c", ".", "CallInternal", "(", "thread", ",", "args", ",", "kwargs", ")", "\n", "thread", ".", "frame", "=", "thread", ".", "frame", ".", "parent", "\n\n", "// Sanity check: nil is not a valid Skylark value.", "if", "result", "==", "nil", "&&", "err", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fn", ")", "\n", "}", "\n\n", "return", "result", ",", "err", "\n", "}" ]
// Call calls the function fn with the specified positional and keyword arguments.
[ "Call", "calls", "the", "function", "fn", "with", "the", "specified", "positional", "and", "keyword", "arguments", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/eval.go#L850-L866
6,632
google/skylark
resolve/resolve.go
Expr
func Expr(expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*syntax.Ident, error) { r := newResolver(isPredeclared, isUniversal) r.expr(expr) r.env.resolveLocalUses() r.resolveNonLocalUses(r.env) // globals & universals if len(r.errors) > 0 { return nil, r.errors } return r.moduleLocals, nil }
go
func Expr(expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*syntax.Ident, error) { r := newResolver(isPredeclared, isUniversal) r.expr(expr) r.env.resolveLocalUses() r.resolveNonLocalUses(r.env) // globals & universals if len(r.errors) > 0 { return nil, r.errors } return r.moduleLocals, nil }
[ "func", "Expr", "(", "expr", "syntax", ".", "Expr", ",", "isPredeclared", ",", "isUniversal", "func", "(", "name", "string", ")", "bool", ")", "(", "[", "]", "*", "syntax", ".", "Ident", ",", "error", ")", "{", "r", ":=", "newResolver", "(", "isPredeclared", ",", "isUniversal", ")", "\n", "r", ".", "expr", "(", "expr", ")", "\n", "r", ".", "env", ".", "resolveLocalUses", "(", ")", "\n", "r", ".", "resolveNonLocalUses", "(", "r", ".", "env", ")", "// globals & universals", "\n", "if", "len", "(", "r", ".", "errors", ")", ">", "0", "{", "return", "nil", ",", "r", ".", "errors", "\n", "}", "\n", "return", "r", ".", "moduleLocals", ",", "nil", "\n", "}" ]
// Expr resolves the specified expression. // It returns the local variables bound within the expression. // // The isPredeclared and isUniversal predicates behave as for the File function.
[ "Expr", "resolves", "the", "specified", "expression", ".", "It", "returns", "the", "local", "variables", "bound", "within", "the", "expression", ".", "The", "isPredeclared", "and", "isUniversal", "predicates", "behave", "as", "for", "the", "File", "function", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/resolve/resolve.go#L136-L145
6,633
google/skylark
resolve/resolve.go
bind
func (r *resolver) bind(id *syntax.Ident, allowRebind bool) bool { // Binding outside any local (comprehension/function) block? if r.env.isModule() { id.Scope = uint8(Global) prev, ok := r.globals[id.Name] if ok { // Global reassignments are permitted only if // they are of the form x += y. We can't tell // statically whether it's a reassignment // (e.g. int += int) or a mutation (list += list). if !allowRebind && !AllowGlobalReassign { r.errorf(id.NamePos, "cannot reassign global %s declared at %s", id.Name, prev.NamePos) } id.Index = prev.Index } else { // first global binding of this name r.globals[id.Name] = id id.Index = len(r.moduleGlobals) r.moduleGlobals = append(r.moduleGlobals, id) } return ok } // Mark this name as local to current block. // Assign it a new local (positive) index in the current container. _, ok := r.env.bindings[id.Name] if !ok { var locals *[]*syntax.Ident if fn := r.container().function; fn != nil { locals = &fn.Locals } else { locals = &r.moduleLocals } r.env.bind(id.Name, binding{Local, len(*locals)}) *locals = append(*locals, id) } r.use(id) return ok }
go
func (r *resolver) bind(id *syntax.Ident, allowRebind bool) bool { // Binding outside any local (comprehension/function) block? if r.env.isModule() { id.Scope = uint8(Global) prev, ok := r.globals[id.Name] if ok { // Global reassignments are permitted only if // they are of the form x += y. We can't tell // statically whether it's a reassignment // (e.g. int += int) or a mutation (list += list). if !allowRebind && !AllowGlobalReassign { r.errorf(id.NamePos, "cannot reassign global %s declared at %s", id.Name, prev.NamePos) } id.Index = prev.Index } else { // first global binding of this name r.globals[id.Name] = id id.Index = len(r.moduleGlobals) r.moduleGlobals = append(r.moduleGlobals, id) } return ok } // Mark this name as local to current block. // Assign it a new local (positive) index in the current container. _, ok := r.env.bindings[id.Name] if !ok { var locals *[]*syntax.Ident if fn := r.container().function; fn != nil { locals = &fn.Locals } else { locals = &r.moduleLocals } r.env.bind(id.Name, binding{Local, len(*locals)}) *locals = append(*locals, id) } r.use(id) return ok }
[ "func", "(", "r", "*", "resolver", ")", "bind", "(", "id", "*", "syntax", ".", "Ident", ",", "allowRebind", "bool", ")", "bool", "{", "// Binding outside any local (comprehension/function) block?", "if", "r", ".", "env", ".", "isModule", "(", ")", "{", "id", ".", "Scope", "=", "uint8", "(", "Global", ")", "\n", "prev", ",", "ok", ":=", "r", ".", "globals", "[", "id", ".", "Name", "]", "\n", "if", "ok", "{", "// Global reassignments are permitted only if", "// they are of the form x += y. We can't tell", "// statically whether it's a reassignment", "// (e.g. int += int) or a mutation (list += list).", "if", "!", "allowRebind", "&&", "!", "AllowGlobalReassign", "{", "r", ".", "errorf", "(", "id", ".", "NamePos", ",", "\"", "\"", ",", "id", ".", "Name", ",", "prev", ".", "NamePos", ")", "\n", "}", "\n", "id", ".", "Index", "=", "prev", ".", "Index", "\n", "}", "else", "{", "// first global binding of this name", "r", ".", "globals", "[", "id", ".", "Name", "]", "=", "id", "\n", "id", ".", "Index", "=", "len", "(", "r", ".", "moduleGlobals", ")", "\n", "r", ".", "moduleGlobals", "=", "append", "(", "r", ".", "moduleGlobals", ",", "id", ")", "\n", "}", "\n", "return", "ok", "\n", "}", "\n\n", "// Mark this name as local to current block.", "// Assign it a new local (positive) index in the current container.", "_", ",", "ok", ":=", "r", ".", "env", ".", "bindings", "[", "id", ".", "Name", "]", "\n", "if", "!", "ok", "{", "var", "locals", "*", "[", "]", "*", "syntax", ".", "Ident", "\n", "if", "fn", ":=", "r", ".", "container", "(", ")", ".", "function", ";", "fn", "!=", "nil", "{", "locals", "=", "&", "fn", ".", "Locals", "\n", "}", "else", "{", "locals", "=", "&", "r", ".", "moduleLocals", "\n", "}", "\n", "r", ".", "env", ".", "bind", "(", "id", ".", "Name", ",", "binding", "{", "Local", ",", "len", "(", "*", "locals", ")", "}", ")", "\n", "*", "locals", "=", "append", "(", "*", "locals", ",", "id", ")", "\n", "}", "\n\n", "r", ".", "use", "(", "id", ")", "\n", "return", "ok", "\n", "}" ]
// bind creates a binding for id in the current block, // if there is not one already, and reports an error if // a global was re-bound and allowRebind is false. // It returns whether a binding already existed.
[ "bind", "creates", "a", "binding", "for", "id", "in", "the", "current", "block", "if", "there", "is", "not", "one", "already", "and", "reports", "an", "error", "if", "a", "global", "was", "re", "-", "bound", "and", "allowRebind", "is", "false", ".", "It", "returns", "whether", "a", "binding", "already", "existed", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/resolve/resolve.go#L297-L336
6,634
google/skylark
resolve/resolve.go
lookupLocal
func lookupLocal(use use) binding { for env := use.env; env != nil; env = env.parent { if bind, ok := env.bindings[use.id.Name]; ok { if bind.scope == Free { // shouldn't exist till later log.Fatalf("%s: internal error: %s, %d", use.id.NamePos, use.id.Name, bind) } return bind // found } if env.function != nil { break } } return binding{} // not found in this function }
go
func lookupLocal(use use) binding { for env := use.env; env != nil; env = env.parent { if bind, ok := env.bindings[use.id.Name]; ok { if bind.scope == Free { // shouldn't exist till later log.Fatalf("%s: internal error: %s, %d", use.id.NamePos, use.id.Name, bind) } return bind // found } if env.function != nil { break } } return binding{} // not found in this function }
[ "func", "lookupLocal", "(", "use", "use", ")", "binding", "{", "for", "env", ":=", "use", ".", "env", ";", "env", "!=", "nil", ";", "env", "=", "env", ".", "parent", "{", "if", "bind", ",", "ok", ":=", "env", ".", "bindings", "[", "use", ".", "id", ".", "Name", "]", ";", "ok", "{", "if", "bind", ".", "scope", "==", "Free", "{", "// shouldn't exist till later", "log", ".", "Fatalf", "(", "\"", "\"", ",", "use", ".", "id", ".", "NamePos", ",", "use", ".", "id", ".", "Name", ",", "bind", ")", "\n", "}", "\n", "return", "bind", "// found", "\n", "}", "\n", "if", "env", ".", "function", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "return", "binding", "{", "}", "// not found in this function", "\n", "}" ]
// lookupLocal looks up an identifier within its immediately enclosing function.
[ "lookupLocal", "looks", "up", "an", "identifier", "within", "its", "immediately", "enclosing", "function", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/resolve/resolve.go#L766-L780
6,635
google/skylark
resolve/resolve.go
lookupLexical
func (r *resolver) lookupLexical(id *syntax.Ident, env *block) (bind binding) { if debug { fmt.Printf("lookupLexical %s in %s = ...\n", id.Name, env) defer func() { fmt.Printf("= %d\n", bind) }() } // Is this the module block? if env.isModule() { return r.useGlobal(id) // global, predeclared, or not found } // Defined in this block? bind, ok := env.bindings[id.Name] if !ok { // Defined in parent block? bind = r.lookupLexical(id, env.parent) if env.function != nil && (bind.scope == Local || bind.scope == Free) { // Found in parent block, which belongs to enclosing function. id := &syntax.Ident{ Name: id.Name, Scope: uint8(bind.scope), Index: bind.index, } bind.scope = Free bind.index = len(env.function.FreeVars) env.function.FreeVars = append(env.function.FreeVars, id) if debug { fmt.Printf("creating freevar %v in function at %s: %s\n", len(env.function.FreeVars), fmt.Sprint(env.function.Span()), id.Name) } } // Memoize, to avoid duplicate free vars // and redundant global (failing) lookups. env.bind(id.Name, bind) } return bind }
go
func (r *resolver) lookupLexical(id *syntax.Ident, env *block) (bind binding) { if debug { fmt.Printf("lookupLexical %s in %s = ...\n", id.Name, env) defer func() { fmt.Printf("= %d\n", bind) }() } // Is this the module block? if env.isModule() { return r.useGlobal(id) // global, predeclared, or not found } // Defined in this block? bind, ok := env.bindings[id.Name] if !ok { // Defined in parent block? bind = r.lookupLexical(id, env.parent) if env.function != nil && (bind.scope == Local || bind.scope == Free) { // Found in parent block, which belongs to enclosing function. id := &syntax.Ident{ Name: id.Name, Scope: uint8(bind.scope), Index: bind.index, } bind.scope = Free bind.index = len(env.function.FreeVars) env.function.FreeVars = append(env.function.FreeVars, id) if debug { fmt.Printf("creating freevar %v in function at %s: %s\n", len(env.function.FreeVars), fmt.Sprint(env.function.Span()), id.Name) } } // Memoize, to avoid duplicate free vars // and redundant global (failing) lookups. env.bind(id.Name, bind) } return bind }
[ "func", "(", "r", "*", "resolver", ")", "lookupLexical", "(", "id", "*", "syntax", ".", "Ident", ",", "env", "*", "block", ")", "(", "bind", "binding", ")", "{", "if", "debug", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "id", ".", "Name", ",", "env", ")", "\n", "defer", "func", "(", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "bind", ")", "}", "(", ")", "\n", "}", "\n\n", "// Is this the module block?", "if", "env", ".", "isModule", "(", ")", "{", "return", "r", ".", "useGlobal", "(", "id", ")", "// global, predeclared, or not found", "\n", "}", "\n\n", "// Defined in this block?", "bind", ",", "ok", ":=", "env", ".", "bindings", "[", "id", ".", "Name", "]", "\n", "if", "!", "ok", "{", "// Defined in parent block?", "bind", "=", "r", ".", "lookupLexical", "(", "id", ",", "env", ".", "parent", ")", "\n", "if", "env", ".", "function", "!=", "nil", "&&", "(", "bind", ".", "scope", "==", "Local", "||", "bind", ".", "scope", "==", "Free", ")", "{", "// Found in parent block, which belongs to enclosing function.", "id", ":=", "&", "syntax", ".", "Ident", "{", "Name", ":", "id", ".", "Name", ",", "Scope", ":", "uint8", "(", "bind", ".", "scope", ")", ",", "Index", ":", "bind", ".", "index", ",", "}", "\n", "bind", ".", "scope", "=", "Free", "\n", "bind", ".", "index", "=", "len", "(", "env", ".", "function", ".", "FreeVars", ")", "\n", "env", ".", "function", ".", "FreeVars", "=", "append", "(", "env", ".", "function", ".", "FreeVars", ",", "id", ")", "\n", "if", "debug", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "len", "(", "env", ".", "function", ".", "FreeVars", ")", ",", "fmt", ".", "Sprint", "(", "env", ".", "function", ".", "Span", "(", ")", ")", ",", "id", ".", "Name", ")", "\n", "}", "\n", "}", "\n\n", "// Memoize, to avoid duplicate free vars", "// and redundant global (failing) lookups.", "env", ".", "bind", "(", "id", ".", "Name", ",", "bind", ")", "\n", "}", "\n", "return", "bind", "\n", "}" ]
// lookupLexical looks up an identifier within its lexically enclosing environment.
[ "lookupLexical", "looks", "up", "an", "identifier", "within", "its", "lexically", "enclosing", "environment", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/resolve/resolve.go#L783-L820
6,636
google/skylark
skylarkstruct/struct.go
FromStringDict
func FromStringDict(constructor skylark.Value, d skylark.StringDict) *Struct { if constructor == nil { panic("nil constructor") } s := &Struct{ constructor: constructor, entries: make(entries, 0, len(d)), } for k, v := range d { s.entries = append(s.entries, entry{k, v}) } sort.Sort(s.entries) return s }
go
func FromStringDict(constructor skylark.Value, d skylark.StringDict) *Struct { if constructor == nil { panic("nil constructor") } s := &Struct{ constructor: constructor, entries: make(entries, 0, len(d)), } for k, v := range d { s.entries = append(s.entries, entry{k, v}) } sort.Sort(s.entries) return s }
[ "func", "FromStringDict", "(", "constructor", "skylark", ".", "Value", ",", "d", "skylark", ".", "StringDict", ")", "*", "Struct", "{", "if", "constructor", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "s", ":=", "&", "Struct", "{", "constructor", ":", "constructor", ",", "entries", ":", "make", "(", "entries", ",", "0", ",", "len", "(", "d", ")", ")", ",", "}", "\n", "for", "k", ",", "v", ":=", "range", "d", "{", "s", ".", "entries", "=", "append", "(", "s", ".", "entries", ",", "entry", "{", "k", ",", "v", "}", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "s", ".", "entries", ")", "\n", "return", "s", "\n", "}" ]
// FromStringDict returns a whose elements are those of d. // The constructor parameter specifies the constructor; use Default for an ordinary struct.
[ "FromStringDict", "returns", "a", "whose", "elements", "are", "those", "of", "d", ".", "The", "constructor", "parameter", "specifies", "the", "constructor", ";", "use", "Default", "for", "an", "ordinary", "struct", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/skylarkstruct/struct.go#L71-L84
6,637
google/skylark
skylarkstruct/struct.go
Attr
func (s *Struct) Attr(name string) (skylark.Value, error) { // Binary search the entries. // This implementation is a specialization of // sort.Search that avoids dynamic dispatch. n := len(s.entries) i, j := 0, n for i < j { h := int(uint(i+j) >> 1) if s.entries[h].name < name { i = h + 1 } else { j = h } } if i < n && s.entries[i].name == name { return s.entries[i].value, nil } // TODO(adonovan): there may be a nice feature for core // skylark.Value here, especially for JSON, but the current // features are incomplete and underspecified. // // to_{json,proto} are deprecated, appropriately; see Google issue b/36412967. switch name { case "to_json", "to_proto": return skylark.NewBuiltin(name, func(thread *skylark.Thread, fn *skylark.Builtin, args skylark.Tuple, kwargs []skylark.Tuple) (skylark.Value, error) { var buf bytes.Buffer var err error if name == "to_json" { err = writeJSON(&buf, s) } else { err = writeProtoStruct(&buf, 0, s) } if err != nil { // TODO(adonovan): improve error error messages // to show the path through the object graph. return nil, err } return skylark.String(buf.String()), nil }), nil } var ctor string if s.constructor != Default { ctor = s.constructor.String() + " " } return nil, fmt.Errorf("%sstruct has no .%s attribute", ctor, name) }
go
func (s *Struct) Attr(name string) (skylark.Value, error) { // Binary search the entries. // This implementation is a specialization of // sort.Search that avoids dynamic dispatch. n := len(s.entries) i, j := 0, n for i < j { h := int(uint(i+j) >> 1) if s.entries[h].name < name { i = h + 1 } else { j = h } } if i < n && s.entries[i].name == name { return s.entries[i].value, nil } // TODO(adonovan): there may be a nice feature for core // skylark.Value here, especially for JSON, but the current // features are incomplete and underspecified. // // to_{json,proto} are deprecated, appropriately; see Google issue b/36412967. switch name { case "to_json", "to_proto": return skylark.NewBuiltin(name, func(thread *skylark.Thread, fn *skylark.Builtin, args skylark.Tuple, kwargs []skylark.Tuple) (skylark.Value, error) { var buf bytes.Buffer var err error if name == "to_json" { err = writeJSON(&buf, s) } else { err = writeProtoStruct(&buf, 0, s) } if err != nil { // TODO(adonovan): improve error error messages // to show the path through the object graph. return nil, err } return skylark.String(buf.String()), nil }), nil } var ctor string if s.constructor != Default { ctor = s.constructor.String() + " " } return nil, fmt.Errorf("%sstruct has no .%s attribute", ctor, name) }
[ "func", "(", "s", "*", "Struct", ")", "Attr", "(", "name", "string", ")", "(", "skylark", ".", "Value", ",", "error", ")", "{", "// Binary search the entries.", "// This implementation is a specialization of", "// sort.Search that avoids dynamic dispatch.", "n", ":=", "len", "(", "s", ".", "entries", ")", "\n", "i", ",", "j", ":=", "0", ",", "n", "\n", "for", "i", "<", "j", "{", "h", ":=", "int", "(", "uint", "(", "i", "+", "j", ")", ">>", "1", ")", "\n", "if", "s", ".", "entries", "[", "h", "]", ".", "name", "<", "name", "{", "i", "=", "h", "+", "1", "\n", "}", "else", "{", "j", "=", "h", "\n", "}", "\n", "}", "\n", "if", "i", "<", "n", "&&", "s", ".", "entries", "[", "i", "]", ".", "name", "==", "name", "{", "return", "s", ".", "entries", "[", "i", "]", ".", "value", ",", "nil", "\n", "}", "\n\n", "// TODO(adonovan): there may be a nice feature for core", "// skylark.Value here, especially for JSON, but the current", "// features are incomplete and underspecified.", "//", "// to_{json,proto} are deprecated, appropriately; see Google issue b/36412967.", "switch", "name", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "skylark", ".", "NewBuiltin", "(", "name", ",", "func", "(", "thread", "*", "skylark", ".", "Thread", ",", "fn", "*", "skylark", ".", "Builtin", ",", "args", "skylark", ".", "Tuple", ",", "kwargs", "[", "]", "skylark", ".", "Tuple", ")", "(", "skylark", ".", "Value", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "var", "err", "error", "\n", "if", "name", "==", "\"", "\"", "{", "err", "=", "writeJSON", "(", "&", "buf", ",", "s", ")", "\n", "}", "else", "{", "err", "=", "writeProtoStruct", "(", "&", "buf", ",", "0", ",", "s", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "// TODO(adonovan): improve error error messages", "// to show the path through the object graph.", "return", "nil", ",", "err", "\n", "}", "\n", "return", "skylark", ".", "String", "(", "buf", ".", "String", "(", ")", ")", ",", "nil", "\n", "}", ")", ",", "nil", "\n", "}", "\n\n", "var", "ctor", "string", "\n", "if", "s", ".", "constructor", "!=", "Default", "{", "ctor", "=", "s", ".", "constructor", ".", "String", "(", ")", "+", "\"", "\"", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctor", ",", "name", ")", "\n", "}" ]
// Attr returns the value of the specified field, // or deprecated method if the name is "to_json" or "to_proto" // and the struct has no field of that name.
[ "Attr", "returns", "the", "value", "of", "the", "specified", "field", "or", "deprecated", "method", "if", "the", "name", "is", "to_json", "or", "to_proto", "and", "the", "struct", "has", "no", "field", "of", "that", "name", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/skylarkstruct/struct.go#L211-L258
6,638
google/skylark
internal/chunkedfile/chunkedfile.go
Read
func Read(filename string, report Reporter) (chunks []Chunk) { data, err := ioutil.ReadFile(filename) if err != nil { report.Errorf("%s", err) return } linenum := 1 for i, chunk := range strings.Split(string(data), "\n---\n") { chunk := string(chunk) if debug { fmt.Printf("chunk %d at line %d: %s\n", i, linenum, chunk) } // Pad with newlines so the line numbers match the original file. src := strings.Repeat("\n", linenum-1) + chunk wantErrs := make(map[int]*regexp.Regexp) // Parse comments of the form: // ### "expected error". lines := strings.Split(chunk, "\n") for j := 0; j < len(lines); j, linenum = j+1, linenum+1 { line := lines[j] hashes := strings.Index(line, "###") if hashes < 0 { continue } rest := strings.TrimSpace(line[hashes+len("###"):]) pattern, err := strconv.Unquote(rest) if err != nil { report.Errorf("%s:%d: not a quoted regexp: %s", filename, linenum, rest) continue } rx, err := regexp.Compile(pattern) if err != nil { report.Errorf("%s:%d: %v", filename, linenum, err) continue } wantErrs[linenum] = rx if debug { fmt.Printf("\t%d\t%s\n", linenum, rx) } } linenum++ chunks = append(chunks, Chunk{src, filename, report, wantErrs}) } return chunks }
go
func Read(filename string, report Reporter) (chunks []Chunk) { data, err := ioutil.ReadFile(filename) if err != nil { report.Errorf("%s", err) return } linenum := 1 for i, chunk := range strings.Split(string(data), "\n---\n") { chunk := string(chunk) if debug { fmt.Printf("chunk %d at line %d: %s\n", i, linenum, chunk) } // Pad with newlines so the line numbers match the original file. src := strings.Repeat("\n", linenum-1) + chunk wantErrs := make(map[int]*regexp.Regexp) // Parse comments of the form: // ### "expected error". lines := strings.Split(chunk, "\n") for j := 0; j < len(lines); j, linenum = j+1, linenum+1 { line := lines[j] hashes := strings.Index(line, "###") if hashes < 0 { continue } rest := strings.TrimSpace(line[hashes+len("###"):]) pattern, err := strconv.Unquote(rest) if err != nil { report.Errorf("%s:%d: not a quoted regexp: %s", filename, linenum, rest) continue } rx, err := regexp.Compile(pattern) if err != nil { report.Errorf("%s:%d: %v", filename, linenum, err) continue } wantErrs[linenum] = rx if debug { fmt.Printf("\t%d\t%s\n", linenum, rx) } } linenum++ chunks = append(chunks, Chunk{src, filename, report, wantErrs}) } return chunks }
[ "func", "Read", "(", "filename", "string", ",", "report", "Reporter", ")", "(", "chunks", "[", "]", "Chunk", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "report", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "linenum", ":=", "1", "\n", "for", "i", ",", "chunk", ":=", "range", "strings", ".", "Split", "(", "string", "(", "data", ")", ",", "\"", "\\n", "\\n", "\"", ")", "{", "chunk", ":=", "string", "(", "chunk", ")", "\n", "if", "debug", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "i", ",", "linenum", ",", "chunk", ")", "\n", "}", "\n", "// Pad with newlines so the line numbers match the original file.", "src", ":=", "strings", ".", "Repeat", "(", "\"", "\\n", "\"", ",", "linenum", "-", "1", ")", "+", "chunk", "\n\n", "wantErrs", ":=", "make", "(", "map", "[", "int", "]", "*", "regexp", ".", "Regexp", ")", "\n\n", "// Parse comments of the form:", "// ### \"expected error\".", "lines", ":=", "strings", ".", "Split", "(", "chunk", ",", "\"", "\\n", "\"", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "len", "(", "lines", ")", ";", "j", ",", "linenum", "=", "j", "+", "1", ",", "linenum", "+", "1", "{", "line", ":=", "lines", "[", "j", "]", "\n", "hashes", ":=", "strings", ".", "Index", "(", "line", ",", "\"", "\"", ")", "\n", "if", "hashes", "<", "0", "{", "continue", "\n", "}", "\n", "rest", ":=", "strings", ".", "TrimSpace", "(", "line", "[", "hashes", "+", "len", "(", "\"", "\"", ")", ":", "]", ")", "\n", "pattern", ",", "err", ":=", "strconv", ".", "Unquote", "(", "rest", ")", "\n", "if", "err", "!=", "nil", "{", "report", ".", "Errorf", "(", "\"", "\"", ",", "filename", ",", "linenum", ",", "rest", ")", "\n", "continue", "\n", "}", "\n", "rx", ",", "err", ":=", "regexp", ".", "Compile", "(", "pattern", ")", "\n", "if", "err", "!=", "nil", "{", "report", ".", "Errorf", "(", "\"", "\"", ",", "filename", ",", "linenum", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "wantErrs", "[", "linenum", "]", "=", "rx", "\n", "if", "debug", "{", "fmt", ".", "Printf", "(", "\"", "\\t", "\\t", "\\n", "\"", ",", "linenum", ",", "rx", ")", "\n", "}", "\n", "}", "\n", "linenum", "++", "\n\n", "chunks", "=", "append", "(", "chunks", ",", "Chunk", "{", "src", ",", "filename", ",", "report", ",", "wantErrs", "}", ")", "\n", "}", "\n", "return", "chunks", "\n", "}" ]
// Read parses a chunked file and returns its chunks. // It reports failures using the reporter.
[ "Read", "parses", "a", "chunked", "file", "and", "returns", "its", "chunks", ".", "It", "reports", "failures", "using", "the", "reporter", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/chunkedfile/chunkedfile.go#L53-L100
6,639
google/skylark
internal/chunkedfile/chunkedfile.go
GotError
func (chunk *Chunk) GotError(linenum int, msg string) { if rx, ok := chunk.wantErrs[linenum]; ok { delete(chunk.wantErrs, linenum) if !rx.MatchString(msg) { chunk.report.Errorf("%s:%d: error %q does not match pattern %q", chunk.filename, linenum, msg, rx) } } else { chunk.report.Errorf("%s:%d: unexpected error: %v", chunk.filename, linenum, msg) } }
go
func (chunk *Chunk) GotError(linenum int, msg string) { if rx, ok := chunk.wantErrs[linenum]; ok { delete(chunk.wantErrs, linenum) if !rx.MatchString(msg) { chunk.report.Errorf("%s:%d: error %q does not match pattern %q", chunk.filename, linenum, msg, rx) } } else { chunk.report.Errorf("%s:%d: unexpected error: %v", chunk.filename, linenum, msg) } }
[ "func", "(", "chunk", "*", "Chunk", ")", "GotError", "(", "linenum", "int", ",", "msg", "string", ")", "{", "if", "rx", ",", "ok", ":=", "chunk", ".", "wantErrs", "[", "linenum", "]", ";", "ok", "{", "delete", "(", "chunk", ".", "wantErrs", ",", "linenum", ")", "\n", "if", "!", "rx", ".", "MatchString", "(", "msg", ")", "{", "chunk", ".", "report", ".", "Errorf", "(", "\"", "\"", ",", "chunk", ".", "filename", ",", "linenum", ",", "msg", ",", "rx", ")", "\n", "}", "\n", "}", "else", "{", "chunk", ".", "report", ".", "Errorf", "(", "\"", "\"", ",", "chunk", ".", "filename", ",", "linenum", ",", "msg", ")", "\n", "}", "\n", "}" ]
// GotError should be called by the client to report an error at a particular line. // GotError reports unexpected errors to the chunk's reporter.
[ "GotError", "should", "be", "called", "by", "the", "client", "to", "report", "an", "error", "at", "a", "particular", "line", ".", "GotError", "reports", "unexpected", "errors", "to", "the", "chunk", "s", "reporter", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/chunkedfile/chunkedfile.go#L104-L113
6,640
google/skylark
internal/chunkedfile/chunkedfile.go
Done
func (chunk *Chunk) Done() { for linenum, rx := range chunk.wantErrs { chunk.report.Errorf("%s:%d: expected error matching %q", chunk.filename, linenum, rx) } }
go
func (chunk *Chunk) Done() { for linenum, rx := range chunk.wantErrs { chunk.report.Errorf("%s:%d: expected error matching %q", chunk.filename, linenum, rx) } }
[ "func", "(", "chunk", "*", "Chunk", ")", "Done", "(", ")", "{", "for", "linenum", ",", "rx", ":=", "range", "chunk", ".", "wantErrs", "{", "chunk", ".", "report", ".", "Errorf", "(", "\"", "\"", ",", "chunk", ".", "filename", ",", "linenum", ",", "rx", ")", "\n", "}", "\n", "}" ]
// Done should be called by the client to indicate that the chunk has no more errors. // Done reports expected errors that did not occur to the chunk's reporter.
[ "Done", "should", "be", "called", "by", "the", "client", "to", "indicate", "that", "the", "chunk", "has", "no", "more", "errors", ".", "Done", "reports", "expected", "errors", "that", "did", "not", "occur", "to", "the", "chunk", "s", "reporter", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/chunkedfile/chunkedfile.go#L117-L121
6,641
google/skylark
syntax/scan.go
add
func (p Position) add(s string) Position { if n := strings.Count(s, "\n"); n > 0 { p.Line += int32(n) s = s[strings.LastIndex(s, "\n")+1:] p.Col = 1 } p.Col += int32(utf8.RuneCountInString(s)) return p }
go
func (p Position) add(s string) Position { if n := strings.Count(s, "\n"); n > 0 { p.Line += int32(n) s = s[strings.LastIndex(s, "\n")+1:] p.Col = 1 } p.Col += int32(utf8.RuneCountInString(s)) return p }
[ "func", "(", "p", "Position", ")", "add", "(", "s", "string", ")", "Position", "{", "if", "n", ":=", "strings", ".", "Count", "(", "s", ",", "\"", "\\n", "\"", ")", ";", "n", ">", "0", "{", "p", ".", "Line", "+=", "int32", "(", "n", ")", "\n", "s", "=", "s", "[", "strings", ".", "LastIndex", "(", "s", ",", "\"", "\\n", "\"", ")", "+", "1", ":", "]", "\n", "p", ".", "Col", "=", "1", "\n", "}", "\n", "p", ".", "Col", "+=", "int32", "(", "utf8", ".", "RuneCountInString", "(", "s", ")", ")", "\n", "return", "p", "\n", "}" ]
// add returns the position at the end of s, assuming it starts at p.
[ "add", "returns", "the", "position", "at", "the", "end", "of", "s", "assuming", "it", "starts", "at", "p", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/scan.go#L206-L214
6,642
google/skylark
syntax/scan.go
peekRune
func (sc *scanner) peekRune() rune { if len(sc.rest) == 0 { return 0 } // fast path: ASCII if b := sc.rest[0]; b < utf8.RuneSelf { if b == '\r' { return '\n' } return rune(b) } r, _ := utf8.DecodeRune(sc.rest) return r }
go
func (sc *scanner) peekRune() rune { if len(sc.rest) == 0 { return 0 } // fast path: ASCII if b := sc.rest[0]; b < utf8.RuneSelf { if b == '\r' { return '\n' } return rune(b) } r, _ := utf8.DecodeRune(sc.rest) return r }
[ "func", "(", "sc", "*", "scanner", ")", "peekRune", "(", ")", "rune", "{", "if", "len", "(", "sc", ".", "rest", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "// fast path: ASCII", "if", "b", ":=", "sc", ".", "rest", "[", "0", "]", ";", "b", "<", "utf8", ".", "RuneSelf", "{", "if", "b", "==", "'\\r'", "{", "return", "'\\n'", "\n", "}", "\n", "return", "rune", "(", "b", ")", "\n", "}", "\n\n", "r", ",", "_", ":=", "utf8", ".", "DecodeRune", "(", "sc", ".", "rest", ")", "\n", "return", "r", "\n", "}" ]
// peekRune returns the next rune in the input without consuming it. // Newlines in Unix, DOS, or Mac format are treated as one rune, '\n'.
[ "peekRune", "returns", "the", "next", "rune", "in", "the", "input", "without", "consuming", "it", ".", "Newlines", "in", "Unix", "DOS", "or", "Mac", "format", "are", "treated", "as", "one", "rune", "\\", "n", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/scan.go#L322-L337
6,643
google/skylark
syntax/scan.go
readRune
func (sc *scanner) readRune() rune { if len(sc.rest) == 0 { sc.error(sc.pos, "internal scanner error: readRune at EOF") return 0 // unreachable but eliminates bounds-check below } // fast path: ASCII if b := sc.rest[0]; b < utf8.RuneSelf { r := rune(b) sc.rest = sc.rest[1:] if r == '\r' { if len(sc.rest) > 0 && sc.rest[0] == '\n' { sc.rest = sc.rest[1:] } r = '\n' } if r == '\n' { sc.pos.Line++ sc.pos.Col = 1 } else { sc.pos.Col++ } return r } r, size := utf8.DecodeRune(sc.rest) sc.rest = sc.rest[size:] sc.pos.Col++ return r }
go
func (sc *scanner) readRune() rune { if len(sc.rest) == 0 { sc.error(sc.pos, "internal scanner error: readRune at EOF") return 0 // unreachable but eliminates bounds-check below } // fast path: ASCII if b := sc.rest[0]; b < utf8.RuneSelf { r := rune(b) sc.rest = sc.rest[1:] if r == '\r' { if len(sc.rest) > 0 && sc.rest[0] == '\n' { sc.rest = sc.rest[1:] } r = '\n' } if r == '\n' { sc.pos.Line++ sc.pos.Col = 1 } else { sc.pos.Col++ } return r } r, size := utf8.DecodeRune(sc.rest) sc.rest = sc.rest[size:] sc.pos.Col++ return r }
[ "func", "(", "sc", "*", "scanner", ")", "readRune", "(", ")", "rune", "{", "if", "len", "(", "sc", ".", "rest", ")", "==", "0", "{", "sc", ".", "error", "(", "sc", ".", "pos", ",", "\"", "\"", ")", "\n", "return", "0", "// unreachable but eliminates bounds-check below", "\n", "}", "\n\n", "// fast path: ASCII", "if", "b", ":=", "sc", ".", "rest", "[", "0", "]", ";", "b", "<", "utf8", ".", "RuneSelf", "{", "r", ":=", "rune", "(", "b", ")", "\n", "sc", ".", "rest", "=", "sc", ".", "rest", "[", "1", ":", "]", "\n", "if", "r", "==", "'\\r'", "{", "if", "len", "(", "sc", ".", "rest", ")", ">", "0", "&&", "sc", ".", "rest", "[", "0", "]", "==", "'\\n'", "{", "sc", ".", "rest", "=", "sc", ".", "rest", "[", "1", ":", "]", "\n", "}", "\n", "r", "=", "'\\n'", "\n", "}", "\n", "if", "r", "==", "'\\n'", "{", "sc", ".", "pos", ".", "Line", "++", "\n", "sc", ".", "pos", ".", "Col", "=", "1", "\n", "}", "else", "{", "sc", ".", "pos", ".", "Col", "++", "\n", "}", "\n", "return", "r", "\n", "}", "\n\n", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "sc", ".", "rest", ")", "\n", "sc", ".", "rest", "=", "sc", ".", "rest", "[", "size", ":", "]", "\n", "sc", ".", "pos", ".", "Col", "++", "\n", "return", "r", "\n", "}" ]
// readRune consumes and returns the next rune in the input. // Newlines in Unix, DOS, or Mac format are treated as one rune, '\n'.
[ "readRune", "consumes", "and", "returns", "the", "next", "rune", "in", "the", "input", ".", "Newlines", "in", "Unix", "DOS", "or", "Mac", "format", "are", "treated", "as", "one", "rune", "\\", "n", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/scan.go#L341-L370
6,644
google/skylark
syntax/scan.go
startToken
func (sc *scanner) startToken(val *tokenValue) { sc.token = sc.rest val.raw = "" val.pos = sc.pos }
go
func (sc *scanner) startToken(val *tokenValue) { sc.token = sc.rest val.raw = "" val.pos = sc.pos }
[ "func", "(", "sc", "*", "scanner", ")", "startToken", "(", "val", "*", "tokenValue", ")", "{", "sc", ".", "token", "=", "sc", ".", "rest", "\n", "val", ".", "raw", "=", "\"", "\"", "\n", "val", ".", "pos", "=", "sc", ".", "pos", "\n", "}" ]
// startToken marks the beginning of the next input token. // It must be followed by a call to endToken once the token has // been consumed using readRune.
[ "startToken", "marks", "the", "beginning", "of", "the", "next", "input", "token", ".", "It", "must", "be", "followed", "by", "a", "call", "to", "endToken", "once", "the", "token", "has", "been", "consumed", "using", "readRune", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/scan.go#L386-L390
6,645
google/skylark
syntax/scan.go
endToken
func (sc *scanner) endToken(val *tokenValue) { if val.raw == "" { val.raw = string(sc.token[:len(sc.token)-len(sc.rest)]) } }
go
func (sc *scanner) endToken(val *tokenValue) { if val.raw == "" { val.raw = string(sc.token[:len(sc.token)-len(sc.rest)]) } }
[ "func", "(", "sc", "*", "scanner", ")", "endToken", "(", "val", "*", "tokenValue", ")", "{", "if", "val", ".", "raw", "==", "\"", "\"", "{", "val", ".", "raw", "=", "string", "(", "sc", ".", "token", "[", ":", "len", "(", "sc", ".", "token", ")", "-", "len", "(", "sc", ".", "rest", ")", "]", ")", "\n", "}", "\n", "}" ]
// endToken marks the end of an input token. // It records the actual token string in val.raw if the caller // has not done that already.
[ "endToken", "marks", "the", "end", "of", "an", "input", "token", ".", "It", "records", "the", "actual", "token", "string", "in", "val", ".", "raw", "if", "the", "caller", "has", "not", "done", "that", "already", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/syntax/scan.go#L395-L399
6,646
google/skylark
repl/repl.go
PrintError
func PrintError(err error) { if evalErr, ok := err.(*skylark.EvalError); ok { fmt.Fprintln(os.Stderr, evalErr.Backtrace()) } else { fmt.Fprintln(os.Stderr, err) } }
go
func PrintError(err error) { if evalErr, ok := err.(*skylark.EvalError); ok { fmt.Fprintln(os.Stderr, evalErr.Backtrace()) } else { fmt.Fprintln(os.Stderr, err) } }
[ "func", "PrintError", "(", "err", "error", ")", "{", "if", "evalErr", ",", "ok", ":=", "err", ".", "(", "*", "skylark", ".", "EvalError", ")", ";", "ok", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "evalErr", ".", "Backtrace", "(", ")", ")", "\n", "}", "else", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "}", "\n", "}" ]
// PrintError prints the error to stderr, // or its backtrace if it is a Skylark evaluation error.
[ "PrintError", "prints", "the", "error", "to", "stderr", "or", "its", "backtrace", "if", "it", "is", "a", "Skylark", "evaluation", "error", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/repl/repl.go#L187-L193
6,647
google/skylark
repl/repl.go
MakeLoad
func MakeLoad() func(thread *skylark.Thread, module string) (skylark.StringDict, error) { type entry struct { globals skylark.StringDict err error } var cache = make(map[string]*entry) return func(thread *skylark.Thread, module string) (skylark.StringDict, error) { e, ok := cache[module] if e == nil { if ok { // request for package whose loading is in progress return nil, fmt.Errorf("cycle in load graph") } // Add a placeholder to indicate "load in progress". cache[module] = nil // Load it. thread := &skylark.Thread{Load: thread.Load} globals, err := skylark.ExecFile(thread, module, nil, nil) e = &entry{globals, err} // Update the cache. cache[module] = e } return e.globals, e.err } }
go
func MakeLoad() func(thread *skylark.Thread, module string) (skylark.StringDict, error) { type entry struct { globals skylark.StringDict err error } var cache = make(map[string]*entry) return func(thread *skylark.Thread, module string) (skylark.StringDict, error) { e, ok := cache[module] if e == nil { if ok { // request for package whose loading is in progress return nil, fmt.Errorf("cycle in load graph") } // Add a placeholder to indicate "load in progress". cache[module] = nil // Load it. thread := &skylark.Thread{Load: thread.Load} globals, err := skylark.ExecFile(thread, module, nil, nil) e = &entry{globals, err} // Update the cache. cache[module] = e } return e.globals, e.err } }
[ "func", "MakeLoad", "(", ")", "func", "(", "thread", "*", "skylark", ".", "Thread", ",", "module", "string", ")", "(", "skylark", ".", "StringDict", ",", "error", ")", "{", "type", "entry", "struct", "{", "globals", "skylark", ".", "StringDict", "\n", "err", "error", "\n", "}", "\n\n", "var", "cache", "=", "make", "(", "map", "[", "string", "]", "*", "entry", ")", "\n\n", "return", "func", "(", "thread", "*", "skylark", ".", "Thread", ",", "module", "string", ")", "(", "skylark", ".", "StringDict", ",", "error", ")", "{", "e", ",", "ok", ":=", "cache", "[", "module", "]", "\n", "if", "e", "==", "nil", "{", "if", "ok", "{", "// request for package whose loading is in progress", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Add a placeholder to indicate \"load in progress\".", "cache", "[", "module", "]", "=", "nil", "\n\n", "// Load it.", "thread", ":=", "&", "skylark", ".", "Thread", "{", "Load", ":", "thread", ".", "Load", "}", "\n", "globals", ",", "err", ":=", "skylark", ".", "ExecFile", "(", "thread", ",", "module", ",", "nil", ",", "nil", ")", "\n", "e", "=", "&", "entry", "{", "globals", ",", "err", "}", "\n\n", "// Update the cache.", "cache", "[", "module", "]", "=", "e", "\n", "}", "\n", "return", "e", ".", "globals", ",", "e", ".", "err", "\n", "}", "\n", "}" ]
// MakeLoad returns a simple sequential implementation of module loading // suitable for use in the REPL. // Each function returned by MakeLoad accesses a distinct private cache.
[ "MakeLoad", "returns", "a", "simple", "sequential", "implementation", "of", "module", "loading", "suitable", "for", "use", "in", "the", "REPL", ".", "Each", "function", "returned", "by", "MakeLoad", "accesses", "a", "distinct", "private", "cache", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/repl/repl.go#L198-L227
6,648
google/skylark
internal/compile/serial.go
Write
func (prog *Program) Write(out io.Writer) error { out.Write([]byte(magic)) gobIdents := func(idents []Ident) []gobIdent { res := make([]gobIdent, len(idents)) for i, id := range idents { res[i].Name = id.Name res[i].Line = id.Pos.Line res[i].Col = id.Pos.Col } return res } gobFunc := func(fn *Funcode) gobFunction { return gobFunction{ Id: gobIdent{ Name: fn.Name, Line: fn.Pos.Line, Col: fn.Pos.Col, }, Code: fn.Code, Pclinetab: fn.pclinetab, Locals: gobIdents(fn.Locals), Freevars: gobIdents(fn.Freevars), MaxStack: fn.MaxStack, NumParams: fn.NumParams, HasVarargs: fn.HasVarargs, HasKwargs: fn.HasKwargs, } } gp := &gobProgram{ Version: Version, Filename: prog.Toplevel.Pos.Filename(), Loads: gobIdents(prog.Loads), Names: prog.Names, Constants: prog.Constants, Functions: make([]gobFunction, len(prog.Functions)), Globals: gobIdents(prog.Globals), Toplevel: gobFunc(prog.Toplevel), } for i, f := range prog.Functions { gp.Functions[i] = gobFunc(f) } return gob.NewEncoder(out).Encode(gp) }
go
func (prog *Program) Write(out io.Writer) error { out.Write([]byte(magic)) gobIdents := func(idents []Ident) []gobIdent { res := make([]gobIdent, len(idents)) for i, id := range idents { res[i].Name = id.Name res[i].Line = id.Pos.Line res[i].Col = id.Pos.Col } return res } gobFunc := func(fn *Funcode) gobFunction { return gobFunction{ Id: gobIdent{ Name: fn.Name, Line: fn.Pos.Line, Col: fn.Pos.Col, }, Code: fn.Code, Pclinetab: fn.pclinetab, Locals: gobIdents(fn.Locals), Freevars: gobIdents(fn.Freevars), MaxStack: fn.MaxStack, NumParams: fn.NumParams, HasVarargs: fn.HasVarargs, HasKwargs: fn.HasKwargs, } } gp := &gobProgram{ Version: Version, Filename: prog.Toplevel.Pos.Filename(), Loads: gobIdents(prog.Loads), Names: prog.Names, Constants: prog.Constants, Functions: make([]gobFunction, len(prog.Functions)), Globals: gobIdents(prog.Globals), Toplevel: gobFunc(prog.Toplevel), } for i, f := range prog.Functions { gp.Functions[i] = gobFunc(f) } return gob.NewEncoder(out).Encode(gp) }
[ "func", "(", "prog", "*", "Program", ")", "Write", "(", "out", "io", ".", "Writer", ")", "error", "{", "out", ".", "Write", "(", "[", "]", "byte", "(", "magic", ")", ")", "\n\n", "gobIdents", ":=", "func", "(", "idents", "[", "]", "Ident", ")", "[", "]", "gobIdent", "{", "res", ":=", "make", "(", "[", "]", "gobIdent", ",", "len", "(", "idents", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "idents", "{", "res", "[", "i", "]", ".", "Name", "=", "id", ".", "Name", "\n", "res", "[", "i", "]", ".", "Line", "=", "id", ".", "Pos", ".", "Line", "\n", "res", "[", "i", "]", ".", "Col", "=", "id", ".", "Pos", ".", "Col", "\n", "}", "\n", "return", "res", "\n", "}", "\n\n", "gobFunc", ":=", "func", "(", "fn", "*", "Funcode", ")", "gobFunction", "{", "return", "gobFunction", "{", "Id", ":", "gobIdent", "{", "Name", ":", "fn", ".", "Name", ",", "Line", ":", "fn", ".", "Pos", ".", "Line", ",", "Col", ":", "fn", ".", "Pos", ".", "Col", ",", "}", ",", "Code", ":", "fn", ".", "Code", ",", "Pclinetab", ":", "fn", ".", "pclinetab", ",", "Locals", ":", "gobIdents", "(", "fn", ".", "Locals", ")", ",", "Freevars", ":", "gobIdents", "(", "fn", ".", "Freevars", ")", ",", "MaxStack", ":", "fn", ".", "MaxStack", ",", "NumParams", ":", "fn", ".", "NumParams", ",", "HasVarargs", ":", "fn", ".", "HasVarargs", ",", "HasKwargs", ":", "fn", ".", "HasKwargs", ",", "}", "\n", "}", "\n\n", "gp", ":=", "&", "gobProgram", "{", "Version", ":", "Version", ",", "Filename", ":", "prog", ".", "Toplevel", ".", "Pos", ".", "Filename", "(", ")", ",", "Loads", ":", "gobIdents", "(", "prog", ".", "Loads", ")", ",", "Names", ":", "prog", ".", "Names", ",", "Constants", ":", "prog", ".", "Constants", ",", "Functions", ":", "make", "(", "[", "]", "gobFunction", ",", "len", "(", "prog", ".", "Functions", ")", ")", ",", "Globals", ":", "gobIdents", "(", "prog", ".", "Globals", ")", ",", "Toplevel", ":", "gobFunc", "(", "prog", ".", "Toplevel", ")", ",", "}", "\n", "for", "i", ",", "f", ":=", "range", "prog", ".", "Functions", "{", "gp", ".", "Functions", "[", "i", "]", "=", "gobFunc", "(", "f", ")", "\n", "}", "\n\n", "return", "gob", ".", "NewEncoder", "(", "out", ")", ".", "Encode", "(", "gp", ")", "\n", "}" ]
// Write writes a compiled Skylark program to out.
[ "Write", "writes", "a", "compiled", "Skylark", "program", "to", "out", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/serial.go#L49-L95
6,649
google/skylark
internal/compile/serial.go
ReadProgram
func ReadProgram(in io.Reader) (*Program, error) { magicBuf := []byte(magic) n, err := in.Read(magicBuf) if err != nil { return nil, err } if n != len(magic) { return nil, fmt.Errorf("not a compiled module: no magic number") } if string(magicBuf) != magic { return nil, fmt.Errorf("not a compiled module: got magic number %q, want %q", magicBuf, magic) } dec := gob.NewDecoder(in) var gp gobProgram if err := dec.Decode(&gp); err != nil { return nil, fmt.Errorf("decoding program: %v", err) } if gp.Version != Version { return nil, fmt.Errorf("version mismatch: read %d, want %d", gp.Version, Version) } file := gp.Filename // copy, to avoid keeping gp live ungobIdents := func(idents []gobIdent) []Ident { res := make([]Ident, len(idents)) for i, id := range idents { res[i].Name = id.Name res[i].Pos = syntax.MakePosition(&file, id.Line, id.Col) } return res } prog := &Program{ Loads: ungobIdents(gp.Loads), Names: gp.Names, Constants: gp.Constants, Globals: ungobIdents(gp.Globals), Functions: make([]*Funcode, len(gp.Functions)), } ungobFunc := func(gf *gobFunction) *Funcode { pos := syntax.MakePosition(&file, gf.Id.Line, gf.Id.Col) return &Funcode{ Prog: prog, Pos: pos, Name: gf.Id.Name, Code: gf.Code, pclinetab: gf.Pclinetab, Locals: ungobIdents(gf.Locals), Freevars: ungobIdents(gf.Freevars), MaxStack: gf.MaxStack, NumParams: gf.NumParams, HasVarargs: gf.HasVarargs, HasKwargs: gf.HasKwargs, } } for i := range gp.Functions { prog.Functions[i] = ungobFunc(&gp.Functions[i]) } prog.Toplevel = ungobFunc(&gp.Toplevel) return prog, nil }
go
func ReadProgram(in io.Reader) (*Program, error) { magicBuf := []byte(magic) n, err := in.Read(magicBuf) if err != nil { return nil, err } if n != len(magic) { return nil, fmt.Errorf("not a compiled module: no magic number") } if string(magicBuf) != magic { return nil, fmt.Errorf("not a compiled module: got magic number %q, want %q", magicBuf, magic) } dec := gob.NewDecoder(in) var gp gobProgram if err := dec.Decode(&gp); err != nil { return nil, fmt.Errorf("decoding program: %v", err) } if gp.Version != Version { return nil, fmt.Errorf("version mismatch: read %d, want %d", gp.Version, Version) } file := gp.Filename // copy, to avoid keeping gp live ungobIdents := func(idents []gobIdent) []Ident { res := make([]Ident, len(idents)) for i, id := range idents { res[i].Name = id.Name res[i].Pos = syntax.MakePosition(&file, id.Line, id.Col) } return res } prog := &Program{ Loads: ungobIdents(gp.Loads), Names: gp.Names, Constants: gp.Constants, Globals: ungobIdents(gp.Globals), Functions: make([]*Funcode, len(gp.Functions)), } ungobFunc := func(gf *gobFunction) *Funcode { pos := syntax.MakePosition(&file, gf.Id.Line, gf.Id.Col) return &Funcode{ Prog: prog, Pos: pos, Name: gf.Id.Name, Code: gf.Code, pclinetab: gf.Pclinetab, Locals: ungobIdents(gf.Locals), Freevars: ungobIdents(gf.Freevars), MaxStack: gf.MaxStack, NumParams: gf.NumParams, HasVarargs: gf.HasVarargs, HasKwargs: gf.HasKwargs, } } for i := range gp.Functions { prog.Functions[i] = ungobFunc(&gp.Functions[i]) } prog.Toplevel = ungobFunc(&gp.Toplevel) return prog, nil }
[ "func", "ReadProgram", "(", "in", "io", ".", "Reader", ")", "(", "*", "Program", ",", "error", ")", "{", "magicBuf", ":=", "[", "]", "byte", "(", "magic", ")", "\n", "n", ",", "err", ":=", "in", ".", "Read", "(", "magicBuf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "n", "!=", "len", "(", "magic", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "string", "(", "magicBuf", ")", "!=", "magic", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "magicBuf", ",", "magic", ")", "\n", "}", "\n\n", "dec", ":=", "gob", ".", "NewDecoder", "(", "in", ")", "\n", "var", "gp", "gobProgram", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "gp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "gp", ".", "Version", "!=", "Version", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "gp", ".", "Version", ",", "Version", ")", "\n", "}", "\n\n", "file", ":=", "gp", ".", "Filename", "// copy, to avoid keeping gp live", "\n\n", "ungobIdents", ":=", "func", "(", "idents", "[", "]", "gobIdent", ")", "[", "]", "Ident", "{", "res", ":=", "make", "(", "[", "]", "Ident", ",", "len", "(", "idents", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "idents", "{", "res", "[", "i", "]", ".", "Name", "=", "id", ".", "Name", "\n", "res", "[", "i", "]", ".", "Pos", "=", "syntax", ".", "MakePosition", "(", "&", "file", ",", "id", ".", "Line", ",", "id", ".", "Col", ")", "\n", "}", "\n", "return", "res", "\n", "}", "\n\n", "prog", ":=", "&", "Program", "{", "Loads", ":", "ungobIdents", "(", "gp", ".", "Loads", ")", ",", "Names", ":", "gp", ".", "Names", ",", "Constants", ":", "gp", ".", "Constants", ",", "Globals", ":", "ungobIdents", "(", "gp", ".", "Globals", ")", ",", "Functions", ":", "make", "(", "[", "]", "*", "Funcode", ",", "len", "(", "gp", ".", "Functions", ")", ")", ",", "}", "\n\n", "ungobFunc", ":=", "func", "(", "gf", "*", "gobFunction", ")", "*", "Funcode", "{", "pos", ":=", "syntax", ".", "MakePosition", "(", "&", "file", ",", "gf", ".", "Id", ".", "Line", ",", "gf", ".", "Id", ".", "Col", ")", "\n", "return", "&", "Funcode", "{", "Prog", ":", "prog", ",", "Pos", ":", "pos", ",", "Name", ":", "gf", ".", "Id", ".", "Name", ",", "Code", ":", "gf", ".", "Code", ",", "pclinetab", ":", "gf", ".", "Pclinetab", ",", "Locals", ":", "ungobIdents", "(", "gf", ".", "Locals", ")", ",", "Freevars", ":", "ungobIdents", "(", "gf", ".", "Freevars", ")", ",", "MaxStack", ":", "gf", ".", "MaxStack", ",", "NumParams", ":", "gf", ".", "NumParams", ",", "HasVarargs", ":", "gf", ".", "HasVarargs", ",", "HasKwargs", ":", "gf", ".", "HasKwargs", ",", "}", "\n", "}", "\n\n", "for", "i", ":=", "range", "gp", ".", "Functions", "{", "prog", ".", "Functions", "[", "i", "]", "=", "ungobFunc", "(", "&", "gp", ".", "Functions", "[", "i", "]", ")", "\n", "}", "\n", "prog", ".", "Toplevel", "=", "ungobFunc", "(", "&", "gp", ".", "Toplevel", ")", "\n", "return", "prog", ",", "nil", "\n", "}" ]
// ReadProgram reads a compiled Skylark program from in.
[ "ReadProgram", "reads", "a", "compiled", "Skylark", "program", "from", "in", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/serial.go#L98-L164
6,650
google/skylark
internal/compile/compile.go
idents
func idents(ids []*syntax.Ident) []Ident { res := make([]Ident, len(ids)) for i, id := range ids { res[i].Name = id.Name res[i].Pos = id.NamePos } return res }
go
func idents(ids []*syntax.Ident) []Ident { res := make([]Ident, len(ids)) for i, id := range ids { res[i].Name = id.Name res[i].Pos = id.NamePos } return res }
[ "func", "idents", "(", "ids", "[", "]", "*", "syntax", ".", "Ident", ")", "[", "]", "Ident", "{", "res", ":=", "make", "(", "[", "]", "Ident", ",", "len", "(", "ids", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "ids", "{", "res", "[", "i", "]", ".", "Name", "=", "id", ".", "Name", "\n", "res", "[", "i", "]", ".", "Pos", "=", "id", ".", "NamePos", "\n", "}", "\n", "return", "res", "\n", "}" ]
// idents convert syntactic identifiers to compiled form.
[ "idents", "convert", "syntactic", "identifiers", "to", "compiled", "form", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L395-L402
6,651
google/skylark
internal/compile/compile.go
Expr
func Expr(expr syntax.Expr, locals []*syntax.Ident) *Funcode { stmts := []syntax.Stmt{&syntax.ReturnStmt{Result: expr}} return File(stmts, locals, nil).Toplevel }
go
func Expr(expr syntax.Expr, locals []*syntax.Ident) *Funcode { stmts := []syntax.Stmt{&syntax.ReturnStmt{Result: expr}} return File(stmts, locals, nil).Toplevel }
[ "func", "Expr", "(", "expr", "syntax", ".", "Expr", ",", "locals", "[", "]", "*", "syntax", ".", "Ident", ")", "*", "Funcode", "{", "stmts", ":=", "[", "]", "syntax", ".", "Stmt", "{", "&", "syntax", ".", "ReturnStmt", "{", "Result", ":", "expr", "}", "}", "\n", "return", "File", "(", "stmts", ",", "locals", ",", "nil", ")", ".", "Toplevel", "\n", "}" ]
// Expr compiles an expression to a program consisting of a single toplevel function.
[ "Expr", "compiles", "an", "expression", "to", "a", "program", "consisting", "of", "a", "single", "toplevel", "function", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L405-L408
6,652
google/skylark
internal/compile/compile.go
File
func File(stmts []syntax.Stmt, locals, globals []*syntax.Ident) *Program { pcomp := &pcomp{ prog: &Program{ Globals: idents(globals), }, names: make(map[string]uint32), constants: make(map[interface{}]uint32), functions: make(map[*Funcode]uint32), } var pos syntax.Position if len(stmts) > 0 { pos = syntax.Start(stmts[0]) } pcomp.prog.Toplevel = pcomp.function("<toplevel>", pos, stmts, locals, nil) return pcomp.prog }
go
func File(stmts []syntax.Stmt, locals, globals []*syntax.Ident) *Program { pcomp := &pcomp{ prog: &Program{ Globals: idents(globals), }, names: make(map[string]uint32), constants: make(map[interface{}]uint32), functions: make(map[*Funcode]uint32), } var pos syntax.Position if len(stmts) > 0 { pos = syntax.Start(stmts[0]) } pcomp.prog.Toplevel = pcomp.function("<toplevel>", pos, stmts, locals, nil) return pcomp.prog }
[ "func", "File", "(", "stmts", "[", "]", "syntax", ".", "Stmt", ",", "locals", ",", "globals", "[", "]", "*", "syntax", ".", "Ident", ")", "*", "Program", "{", "pcomp", ":=", "&", "pcomp", "{", "prog", ":", "&", "Program", "{", "Globals", ":", "idents", "(", "globals", ")", ",", "}", ",", "names", ":", "make", "(", "map", "[", "string", "]", "uint32", ")", ",", "constants", ":", "make", "(", "map", "[", "interface", "{", "}", "]", "uint32", ")", ",", "functions", ":", "make", "(", "map", "[", "*", "Funcode", "]", "uint32", ")", ",", "}", "\n\n", "var", "pos", "syntax", ".", "Position", "\n", "if", "len", "(", "stmts", ")", ">", "0", "{", "pos", "=", "syntax", ".", "Start", "(", "stmts", "[", "0", "]", ")", "\n", "}", "\n\n", "pcomp", ".", "prog", ".", "Toplevel", "=", "pcomp", ".", "function", "(", "\"", "\"", ",", "pos", ",", "stmts", ",", "locals", ",", "nil", ")", "\n\n", "return", "pcomp", ".", "prog", "\n", "}" ]
// File compiles the statements of a file into a program.
[ "File", "compiles", "the", "statements", "of", "a", "file", "into", "a", "program", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L411-L429
6,653
google/skylark
internal/compile/compile.go
generate
func (fcomp *fcomp) generate(blocks []*block, codelen uint32) { code := make([]byte, 0, codelen) var pclinetab []uint16 var prev struct { pc uint32 line int32 } for _, b := range blocks { if debug { fmt.Fprintf(os.Stderr, "%d:\n", b.index) } pc := b.addr for _, insn := range b.insns { if insn.line != 0 { // Instruction has a source position. Delta-encode it. // See Funcode.Position for the encoding. for { var incomplete uint16 deltapc := pc - prev.pc if deltapc > 0xff { deltapc = 0xff incomplete = 1 } prev.pc += deltapc deltaline := insn.line - prev.line if deltaline > 0x3f { deltaline = 0x3f incomplete = 1 } else if deltaline < -0x40 { deltaline = -0x40 incomplete = 1 } prev.line += deltaline entry := uint16(deltapc<<8) | uint16(uint8(deltaline<<1)) | incomplete pclinetab = append(pclinetab, entry) if incomplete == 0 { break } } if debug { fmt.Fprintf(os.Stderr, "\t\t\t\t\t; %s %d\n", filepath.Base(fcomp.fn.Pos.Filename()), insn.line) } } if debug { PrintOp(fcomp.fn, pc, insn.op, insn.arg) } code = append(code, byte(insn.op)) pc++ if insn.op >= OpcodeArgMin { if insn.op == CJMP || insn.op == ITERJMP { code = addUint32(code, insn.arg, 4) // pad arg to 4 bytes } else { code = addUint32(code, insn.arg, 0) } pc = uint32(len(code)) } } if b.jmp != nil && b.jmp.index != b.index+1 { addr := b.jmp.addr if debug { fmt.Fprintf(os.Stderr, "\t%d\tjmp\t\t%d\t; block %d\n", pc, addr, b.jmp.index) } code = append(code, byte(JMP)) code = addUint32(code, addr, 4) } } if len(code) != int(codelen) { panic("internal error: wrong code length") } fcomp.fn.pclinetab = pclinetab fcomp.fn.Code = code }
go
func (fcomp *fcomp) generate(blocks []*block, codelen uint32) { code := make([]byte, 0, codelen) var pclinetab []uint16 var prev struct { pc uint32 line int32 } for _, b := range blocks { if debug { fmt.Fprintf(os.Stderr, "%d:\n", b.index) } pc := b.addr for _, insn := range b.insns { if insn.line != 0 { // Instruction has a source position. Delta-encode it. // See Funcode.Position for the encoding. for { var incomplete uint16 deltapc := pc - prev.pc if deltapc > 0xff { deltapc = 0xff incomplete = 1 } prev.pc += deltapc deltaline := insn.line - prev.line if deltaline > 0x3f { deltaline = 0x3f incomplete = 1 } else if deltaline < -0x40 { deltaline = -0x40 incomplete = 1 } prev.line += deltaline entry := uint16(deltapc<<8) | uint16(uint8(deltaline<<1)) | incomplete pclinetab = append(pclinetab, entry) if incomplete == 0 { break } } if debug { fmt.Fprintf(os.Stderr, "\t\t\t\t\t; %s %d\n", filepath.Base(fcomp.fn.Pos.Filename()), insn.line) } } if debug { PrintOp(fcomp.fn, pc, insn.op, insn.arg) } code = append(code, byte(insn.op)) pc++ if insn.op >= OpcodeArgMin { if insn.op == CJMP || insn.op == ITERJMP { code = addUint32(code, insn.arg, 4) // pad arg to 4 bytes } else { code = addUint32(code, insn.arg, 0) } pc = uint32(len(code)) } } if b.jmp != nil && b.jmp.index != b.index+1 { addr := b.jmp.addr if debug { fmt.Fprintf(os.Stderr, "\t%d\tjmp\t\t%d\t; block %d\n", pc, addr, b.jmp.index) } code = append(code, byte(JMP)) code = addUint32(code, addr, 4) } } if len(code) != int(codelen) { panic("internal error: wrong code length") } fcomp.fn.pclinetab = pclinetab fcomp.fn.Code = code }
[ "func", "(", "fcomp", "*", "fcomp", ")", "generate", "(", "blocks", "[", "]", "*", "block", ",", "codelen", "uint32", ")", "{", "code", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "codelen", ")", "\n", "var", "pclinetab", "[", "]", "uint16", "\n", "var", "prev", "struct", "{", "pc", "uint32", "\n", "line", "int32", "\n", "}", "\n\n", "for", "_", ",", "b", ":=", "range", "blocks", "{", "if", "debug", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "b", ".", "index", ")", "\n", "}", "\n", "pc", ":=", "b", ".", "addr", "\n", "for", "_", ",", "insn", ":=", "range", "b", ".", "insns", "{", "if", "insn", ".", "line", "!=", "0", "{", "// Instruction has a source position. Delta-encode it.", "// See Funcode.Position for the encoding.", "for", "{", "var", "incomplete", "uint16", "\n\n", "deltapc", ":=", "pc", "-", "prev", ".", "pc", "\n", "if", "deltapc", ">", "0xff", "{", "deltapc", "=", "0xff", "\n", "incomplete", "=", "1", "\n", "}", "\n", "prev", ".", "pc", "+=", "deltapc", "\n\n", "deltaline", ":=", "insn", ".", "line", "-", "prev", ".", "line", "\n", "if", "deltaline", ">", "0x3f", "{", "deltaline", "=", "0x3f", "\n", "incomplete", "=", "1", "\n", "}", "else", "if", "deltaline", "<", "-", "0x40", "{", "deltaline", "=", "-", "0x40", "\n", "incomplete", "=", "1", "\n", "}", "\n", "prev", ".", "line", "+=", "deltaline", "\n\n", "entry", ":=", "uint16", "(", "deltapc", "<<", "8", ")", "|", "uint16", "(", "uint8", "(", "deltaline", "<<", "1", ")", ")", "|", "incomplete", "\n", "pclinetab", "=", "append", "(", "pclinetab", ",", "entry", ")", "\n", "if", "incomplete", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "debug", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\n", "\"", ",", "filepath", ".", "Base", "(", "fcomp", ".", "fn", ".", "Pos", ".", "Filename", "(", ")", ")", ",", "insn", ".", "line", ")", "\n", "}", "\n", "}", "\n", "if", "debug", "{", "PrintOp", "(", "fcomp", ".", "fn", ",", "pc", ",", "insn", ".", "op", ",", "insn", ".", "arg", ")", "\n", "}", "\n", "code", "=", "append", "(", "code", ",", "byte", "(", "insn", ".", "op", ")", ")", "\n", "pc", "++", "\n", "if", "insn", ".", "op", ">=", "OpcodeArgMin", "{", "if", "insn", ".", "op", "==", "CJMP", "||", "insn", ".", "op", "==", "ITERJMP", "{", "code", "=", "addUint32", "(", "code", ",", "insn", ".", "arg", ",", "4", ")", "// pad arg to 4 bytes", "\n", "}", "else", "{", "code", "=", "addUint32", "(", "code", ",", "insn", ".", "arg", ",", "0", ")", "\n", "}", "\n", "pc", "=", "uint32", "(", "len", "(", "code", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "b", ".", "jmp", "!=", "nil", "&&", "b", ".", "jmp", ".", "index", "!=", "b", ".", "index", "+", "1", "{", "addr", ":=", "b", ".", "jmp", ".", "addr", "\n", "if", "debug", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\n", "\"", ",", "pc", ",", "addr", ",", "b", ".", "jmp", ".", "index", ")", "\n", "}", "\n", "code", "=", "append", "(", "code", ",", "byte", "(", "JMP", ")", ")", "\n", "code", "=", "addUint32", "(", "code", ",", "addr", ",", "4", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "code", ")", "!=", "int", "(", "codelen", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "fcomp", ".", "fn", ".", "pclinetab", "=", "pclinetab", "\n", "fcomp", ".", "fn", ".", "Code", "=", "code", "\n", "}" ]
// generate emits the linear instruction stream from the CFG, // and builds the PC-to-line number table.
[ "generate", "emits", "the", "linear", "instruction", "stream", "from", "the", "CFG", "and", "builds", "the", "PC", "-", "to", "-", "line", "number", "table", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L628-L708
6,654
google/skylark
internal/compile/compile.go
PrintOp
func PrintOp(fn *Funcode, pc uint32, op Opcode, arg uint32) { if op < OpcodeArgMin { fmt.Fprintf(os.Stderr, "\t%d\t%s\n", pc, op) return } var comment string switch op { case CONSTANT: switch x := fn.Prog.Constants[arg].(type) { case string: comment = strconv.Quote(x) default: comment = fmt.Sprint(x) } case MAKEFUNC: comment = fn.Prog.Functions[arg].Name case SETLOCAL, LOCAL: comment = fn.Locals[arg].Name case SETGLOBAL, GLOBAL: comment = fn.Prog.Globals[arg].Name case ATTR, SETFIELD, PREDECLARED, UNIVERSAL: comment = fn.Prog.Names[arg] case FREE: comment = fn.Freevars[arg].Name case CALL, CALL_VAR, CALL_KW, CALL_VAR_KW: comment = fmt.Sprintf("%d pos, %d named", arg>>8, arg&0xff) default: // JMP, CJMP, ITERJMP, MAKETUPLE, MAKELIST, LOAD, UNPACK: // arg is just a number } var buf bytes.Buffer fmt.Fprintf(&buf, "\t%d\t%-10s\t%d", pc, op, arg) if comment != "" { fmt.Fprint(&buf, "\t; ", comment) } fmt.Fprintln(&buf) os.Stderr.Write(buf.Bytes()) }
go
func PrintOp(fn *Funcode, pc uint32, op Opcode, arg uint32) { if op < OpcodeArgMin { fmt.Fprintf(os.Stderr, "\t%d\t%s\n", pc, op) return } var comment string switch op { case CONSTANT: switch x := fn.Prog.Constants[arg].(type) { case string: comment = strconv.Quote(x) default: comment = fmt.Sprint(x) } case MAKEFUNC: comment = fn.Prog.Functions[arg].Name case SETLOCAL, LOCAL: comment = fn.Locals[arg].Name case SETGLOBAL, GLOBAL: comment = fn.Prog.Globals[arg].Name case ATTR, SETFIELD, PREDECLARED, UNIVERSAL: comment = fn.Prog.Names[arg] case FREE: comment = fn.Freevars[arg].Name case CALL, CALL_VAR, CALL_KW, CALL_VAR_KW: comment = fmt.Sprintf("%d pos, %d named", arg>>8, arg&0xff) default: // JMP, CJMP, ITERJMP, MAKETUPLE, MAKELIST, LOAD, UNPACK: // arg is just a number } var buf bytes.Buffer fmt.Fprintf(&buf, "\t%d\t%-10s\t%d", pc, op, arg) if comment != "" { fmt.Fprint(&buf, "\t; ", comment) } fmt.Fprintln(&buf) os.Stderr.Write(buf.Bytes()) }
[ "func", "PrintOp", "(", "fn", "*", "Funcode", ",", "pc", "uint32", ",", "op", "Opcode", ",", "arg", "uint32", ")", "{", "if", "op", "<", "OpcodeArgMin", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\t", "\\t", "\\n", "\"", ",", "pc", ",", "op", ")", "\n", "return", "\n", "}", "\n\n", "var", "comment", "string", "\n", "switch", "op", "{", "case", "CONSTANT", ":", "switch", "x", ":=", "fn", ".", "Prog", ".", "Constants", "[", "arg", "]", ".", "(", "type", ")", "{", "case", "string", ":", "comment", "=", "strconv", ".", "Quote", "(", "x", ")", "\n", "default", ":", "comment", "=", "fmt", ".", "Sprint", "(", "x", ")", "\n", "}", "\n", "case", "MAKEFUNC", ":", "comment", "=", "fn", ".", "Prog", ".", "Functions", "[", "arg", "]", ".", "Name", "\n", "case", "SETLOCAL", ",", "LOCAL", ":", "comment", "=", "fn", ".", "Locals", "[", "arg", "]", ".", "Name", "\n", "case", "SETGLOBAL", ",", "GLOBAL", ":", "comment", "=", "fn", ".", "Prog", ".", "Globals", "[", "arg", "]", ".", "Name", "\n", "case", "ATTR", ",", "SETFIELD", ",", "PREDECLARED", ",", "UNIVERSAL", ":", "comment", "=", "fn", ".", "Prog", ".", "Names", "[", "arg", "]", "\n", "case", "FREE", ":", "comment", "=", "fn", ".", "Freevars", "[", "arg", "]", ".", "Name", "\n", "case", "CALL", ",", "CALL_VAR", ",", "CALL_KW", ",", "CALL_VAR_KW", ":", "comment", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "arg", ">>", "8", ",", "arg", "&", "0xff", ")", "\n", "default", ":", "// JMP, CJMP, ITERJMP, MAKETUPLE, MAKELIST, LOAD, UNPACK:", "// arg is just a number", "}", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\\t", "\\t", "\\t", "\"", ",", "pc", ",", "op", ",", "arg", ")", "\n", "if", "comment", "!=", "\"", "\"", "{", "fmt", ".", "Fprint", "(", "&", "buf", ",", "\"", "\\t", "\"", ",", "comment", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "&", "buf", ")", "\n", "os", ".", "Stderr", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// PrintOp prints an instruction. // It is provided for debugging.
[ "PrintOp", "prints", "an", "instruction", ".", "It", "is", "provided", "for", "debugging", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L738-L776
6,655
google/skylark
internal/compile/compile.go
emit
func (fcomp *fcomp) emit(op Opcode) { if op >= OpcodeArgMin { panic("missing arg: " + op.String()) } insn := insn{op: op, line: fcomp.pos.Line} fcomp.block.insns = append(fcomp.block.insns, insn) fcomp.pos.Line = 0 }
go
func (fcomp *fcomp) emit(op Opcode) { if op >= OpcodeArgMin { panic("missing arg: " + op.String()) } insn := insn{op: op, line: fcomp.pos.Line} fcomp.block.insns = append(fcomp.block.insns, insn) fcomp.pos.Line = 0 }
[ "func", "(", "fcomp", "*", "fcomp", ")", "emit", "(", "op", "Opcode", ")", "{", "if", "op", ">=", "OpcodeArgMin", "{", "panic", "(", "\"", "\"", "+", "op", ".", "String", "(", ")", ")", "\n", "}", "\n", "insn", ":=", "insn", "{", "op", ":", "op", ",", "line", ":", "fcomp", ".", "pos", ".", "Line", "}", "\n", "fcomp", ".", "block", ".", "insns", "=", "append", "(", "fcomp", ".", "block", ".", "insns", ",", "insn", ")", "\n", "fcomp", ".", "pos", ".", "Line", "=", "0", "\n", "}" ]
// emit emits an instruction to the current block.
[ "emit", "emits", "an", "instruction", "to", "the", "current", "block", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L784-L791
6,656
google/skylark
internal/compile/compile.go
emit1
func (fcomp *fcomp) emit1(op Opcode, arg uint32) { if op < OpcodeArgMin { panic("unwanted arg: " + op.String()) } insn := insn{op: op, arg: arg, line: fcomp.pos.Line} fcomp.block.insns = append(fcomp.block.insns, insn) fcomp.pos.Line = 0 }
go
func (fcomp *fcomp) emit1(op Opcode, arg uint32) { if op < OpcodeArgMin { panic("unwanted arg: " + op.String()) } insn := insn{op: op, arg: arg, line: fcomp.pos.Line} fcomp.block.insns = append(fcomp.block.insns, insn) fcomp.pos.Line = 0 }
[ "func", "(", "fcomp", "*", "fcomp", ")", "emit1", "(", "op", "Opcode", ",", "arg", "uint32", ")", "{", "if", "op", "<", "OpcodeArgMin", "{", "panic", "(", "\"", "\"", "+", "op", ".", "String", "(", ")", ")", "\n", "}", "\n", "insn", ":=", "insn", "{", "op", ":", "op", ",", "arg", ":", "arg", ",", "line", ":", "fcomp", ".", "pos", ".", "Line", "}", "\n", "fcomp", ".", "block", ".", "insns", "=", "append", "(", "fcomp", ".", "block", ".", "insns", ",", "insn", ")", "\n", "fcomp", ".", "pos", ".", "Line", "=", "0", "\n", "}" ]
// emit1 emits an instruction with an immediate operand.
[ "emit1", "emits", "an", "instruction", "with", "an", "immediate", "operand", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L794-L801
6,657
google/skylark
internal/compile/compile.go
jump
func (fcomp *fcomp) jump(b *block) { if b == fcomp.block { panic("self-jump") // unreachable: Skylark has no arbitrary looping constructs } fcomp.block.jmp = b fcomp.block = nil }
go
func (fcomp *fcomp) jump(b *block) { if b == fcomp.block { panic("self-jump") // unreachable: Skylark has no arbitrary looping constructs } fcomp.block.jmp = b fcomp.block = nil }
[ "func", "(", "fcomp", "*", "fcomp", ")", "jump", "(", "b", "*", "block", ")", "{", "if", "b", "==", "fcomp", ".", "block", "{", "panic", "(", "\"", "\"", ")", "// unreachable: Skylark has no arbitrary looping constructs", "\n", "}", "\n", "fcomp", ".", "block", ".", "jmp", "=", "b", "\n", "fcomp", ".", "block", "=", "nil", "\n", "}" ]
// jump emits a jump to the specified block. // On return, the current block is unset.
[ "jump", "emits", "a", "jump", "to", "the", "specified", "block", ".", "On", "return", "the", "current", "block", "is", "unset", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L805-L811
6,658
google/skylark
internal/compile/compile.go
nameIndex
func (pcomp *pcomp) nameIndex(name string) uint32 { index, ok := pcomp.names[name] if !ok { index = uint32(len(pcomp.prog.Names)) pcomp.names[name] = index pcomp.prog.Names = append(pcomp.prog.Names, name) } return index }
go
func (pcomp *pcomp) nameIndex(name string) uint32 { index, ok := pcomp.names[name] if !ok { index = uint32(len(pcomp.prog.Names)) pcomp.names[name] = index pcomp.prog.Names = append(pcomp.prog.Names, name) } return index }
[ "func", "(", "pcomp", "*", "pcomp", ")", "nameIndex", "(", "name", "string", ")", "uint32", "{", "index", ",", "ok", ":=", "pcomp", ".", "names", "[", "name", "]", "\n", "if", "!", "ok", "{", "index", "=", "uint32", "(", "len", "(", "pcomp", ".", "prog", ".", "Names", ")", ")", "\n", "pcomp", ".", "names", "[", "name", "]", "=", "index", "\n", "pcomp", ".", "prog", ".", "Names", "=", "append", "(", "pcomp", ".", "prog", ".", "Names", ",", "name", ")", "\n", "}", "\n", "return", "index", "\n", "}" ]
// nameIndex returns the index of the specified name // within the name pool, adding it if necessary.
[ "nameIndex", "returns", "the", "index", "of", "the", "specified", "name", "within", "the", "name", "pool", "adding", "it", "if", "necessary", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L828-L836
6,659
google/skylark
internal/compile/compile.go
constantIndex
func (pcomp *pcomp) constantIndex(v interface{}) uint32 { index, ok := pcomp.constants[v] if !ok { index = uint32(len(pcomp.prog.Constants)) pcomp.constants[v] = index pcomp.prog.Constants = append(pcomp.prog.Constants, v) } return index }
go
func (pcomp *pcomp) constantIndex(v interface{}) uint32 { index, ok := pcomp.constants[v] if !ok { index = uint32(len(pcomp.prog.Constants)) pcomp.constants[v] = index pcomp.prog.Constants = append(pcomp.prog.Constants, v) } return index }
[ "func", "(", "pcomp", "*", "pcomp", ")", "constantIndex", "(", "v", "interface", "{", "}", ")", "uint32", "{", "index", ",", "ok", ":=", "pcomp", ".", "constants", "[", "v", "]", "\n", "if", "!", "ok", "{", "index", "=", "uint32", "(", "len", "(", "pcomp", ".", "prog", ".", "Constants", ")", ")", "\n", "pcomp", ".", "constants", "[", "v", "]", "=", "index", "\n", "pcomp", ".", "prog", ".", "Constants", "=", "append", "(", "pcomp", ".", "prog", ".", "Constants", ",", "v", ")", "\n", "}", "\n", "return", "index", "\n", "}" ]
// constantIndex returns the index of the specified constant // within the constant pool, adding it if necessary.
[ "constantIndex", "returns", "the", "index", "of", "the", "specified", "constant", "within", "the", "constant", "pool", "adding", "it", "if", "necessary", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L840-L848
6,660
google/skylark
internal/compile/compile.go
functionIndex
func (pcomp *pcomp) functionIndex(fn *Funcode) uint32 { index, ok := pcomp.functions[fn] if !ok { index = uint32(len(pcomp.prog.Functions)) pcomp.functions[fn] = index pcomp.prog.Functions = append(pcomp.prog.Functions, fn) } return index }
go
func (pcomp *pcomp) functionIndex(fn *Funcode) uint32 { index, ok := pcomp.functions[fn] if !ok { index = uint32(len(pcomp.prog.Functions)) pcomp.functions[fn] = index pcomp.prog.Functions = append(pcomp.prog.Functions, fn) } return index }
[ "func", "(", "pcomp", "*", "pcomp", ")", "functionIndex", "(", "fn", "*", "Funcode", ")", "uint32", "{", "index", ",", "ok", ":=", "pcomp", ".", "functions", "[", "fn", "]", "\n", "if", "!", "ok", "{", "index", "=", "uint32", "(", "len", "(", "pcomp", ".", "prog", ".", "Functions", ")", ")", "\n", "pcomp", ".", "functions", "[", "fn", "]", "=", "index", "\n", "pcomp", ".", "prog", ".", "Functions", "=", "append", "(", "pcomp", ".", "prog", ".", "Functions", ",", "fn", ")", "\n", "}", "\n", "return", "index", "\n", "}" ]
// functionIndex returns the index of the specified function // AST the nestedfun pool, adding it if necessary.
[ "functionIndex", "returns", "the", "index", "of", "the", "specified", "function", "AST", "the", "nestedfun", "pool", "adding", "it", "if", "necessary", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L852-L860
6,661
google/skylark
internal/compile/compile.go
string
func (fcomp *fcomp) string(s string) { fcomp.emit1(CONSTANT, fcomp.pcomp.constantIndex(s)) }
go
func (fcomp *fcomp) string(s string) { fcomp.emit1(CONSTANT, fcomp.pcomp.constantIndex(s)) }
[ "func", "(", "fcomp", "*", "fcomp", ")", "string", "(", "s", "string", ")", "{", "fcomp", ".", "emit1", "(", "CONSTANT", ",", "fcomp", ".", "pcomp", ".", "constantIndex", "(", "s", ")", ")", "\n", "}" ]
// string emits code to push the specified string.
[ "string", "emits", "code", "to", "push", "the", "specified", "string", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L863-L865
6,662
google/skylark
internal/compile/compile.go
set
func (fcomp *fcomp) set(id *syntax.Ident) { switch resolve.Scope(id.Scope) { case resolve.Local: fcomp.emit1(SETLOCAL, uint32(id.Index)) case resolve.Global: fcomp.emit1(SETGLOBAL, uint32(id.Index)) default: log.Fatalf("%s: set(%s): neither global nor local (%d)", id.NamePos, id.Name, id.Scope) } }
go
func (fcomp *fcomp) set(id *syntax.Ident) { switch resolve.Scope(id.Scope) { case resolve.Local: fcomp.emit1(SETLOCAL, uint32(id.Index)) case resolve.Global: fcomp.emit1(SETGLOBAL, uint32(id.Index)) default: log.Fatalf("%s: set(%s): neither global nor local (%d)", id.NamePos, id.Name, id.Scope) } }
[ "func", "(", "fcomp", "*", "fcomp", ")", "set", "(", "id", "*", "syntax", ".", "Ident", ")", "{", "switch", "resolve", ".", "Scope", "(", "id", ".", "Scope", ")", "{", "case", "resolve", ".", "Local", ":", "fcomp", ".", "emit1", "(", "SETLOCAL", ",", "uint32", "(", "id", ".", "Index", ")", ")", "\n", "case", "resolve", ".", "Global", ":", "fcomp", ".", "emit1", "(", "SETGLOBAL", ",", "uint32", "(", "id", ".", "Index", ")", ")", "\n", "default", ":", "log", ".", "Fatalf", "(", "\"", "\"", ",", "id", ".", "NamePos", ",", "id", ".", "Name", ",", "id", ".", "Scope", ")", "\n", "}", "\n", "}" ]
// set emits code to store the top-of-stack value // to the specified local or global variable.
[ "set", "emits", "code", "to", "store", "the", "top", "-", "of", "-", "stack", "value", "to", "the", "specified", "local", "or", "global", "variable", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L876-L885
6,663
google/skylark
internal/compile/compile.go
lookup
func (fcomp *fcomp) lookup(id *syntax.Ident) { switch resolve.Scope(id.Scope) { case resolve.Local: fcomp.setPos(id.NamePos) fcomp.emit1(LOCAL, uint32(id.Index)) case resolve.Free: fcomp.emit1(FREE, uint32(id.Index)) case resolve.Global: fcomp.setPos(id.NamePos) fcomp.emit1(GLOBAL, uint32(id.Index)) case resolve.Predeclared: fcomp.setPos(id.NamePos) fcomp.emit1(PREDECLARED, fcomp.pcomp.nameIndex(id.Name)) case resolve.Universal: fcomp.emit1(UNIVERSAL, fcomp.pcomp.nameIndex(id.Name)) default: log.Fatalf("%s: compiler.lookup(%s): scope = %d", id.NamePos, id.Name, id.Scope) } }
go
func (fcomp *fcomp) lookup(id *syntax.Ident) { switch resolve.Scope(id.Scope) { case resolve.Local: fcomp.setPos(id.NamePos) fcomp.emit1(LOCAL, uint32(id.Index)) case resolve.Free: fcomp.emit1(FREE, uint32(id.Index)) case resolve.Global: fcomp.setPos(id.NamePos) fcomp.emit1(GLOBAL, uint32(id.Index)) case resolve.Predeclared: fcomp.setPos(id.NamePos) fcomp.emit1(PREDECLARED, fcomp.pcomp.nameIndex(id.Name)) case resolve.Universal: fcomp.emit1(UNIVERSAL, fcomp.pcomp.nameIndex(id.Name)) default: log.Fatalf("%s: compiler.lookup(%s): scope = %d", id.NamePos, id.Name, id.Scope) } }
[ "func", "(", "fcomp", "*", "fcomp", ")", "lookup", "(", "id", "*", "syntax", ".", "Ident", ")", "{", "switch", "resolve", ".", "Scope", "(", "id", ".", "Scope", ")", "{", "case", "resolve", ".", "Local", ":", "fcomp", ".", "setPos", "(", "id", ".", "NamePos", ")", "\n", "fcomp", ".", "emit1", "(", "LOCAL", ",", "uint32", "(", "id", ".", "Index", ")", ")", "\n", "case", "resolve", ".", "Free", ":", "fcomp", ".", "emit1", "(", "FREE", ",", "uint32", "(", "id", ".", "Index", ")", ")", "\n", "case", "resolve", ".", "Global", ":", "fcomp", ".", "setPos", "(", "id", ".", "NamePos", ")", "\n", "fcomp", ".", "emit1", "(", "GLOBAL", ",", "uint32", "(", "id", ".", "Index", ")", ")", "\n", "case", "resolve", ".", "Predeclared", ":", "fcomp", ".", "setPos", "(", "id", ".", "NamePos", ")", "\n", "fcomp", ".", "emit1", "(", "PREDECLARED", ",", "fcomp", ".", "pcomp", ".", "nameIndex", "(", "id", ".", "Name", ")", ")", "\n", "case", "resolve", ".", "Universal", ":", "fcomp", ".", "emit1", "(", "UNIVERSAL", ",", "fcomp", ".", "pcomp", ".", "nameIndex", "(", "id", ".", "Name", ")", ")", "\n", "default", ":", "log", ".", "Fatalf", "(", "\"", "\"", ",", "id", ".", "NamePos", ",", "id", ".", "Name", ",", "id", ".", "Scope", ")", "\n", "}", "\n", "}" ]
// lookup emits code to push the value of the specified variable.
[ "lookup", "emits", "code", "to", "push", "the", "value", "of", "the", "specified", "variable", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L888-L906
6,664
google/skylark
internal/compile/compile.go
assign
func (fcomp *fcomp) assign(pos syntax.Position, lhs syntax.Expr) { switch lhs := lhs.(type) { case *syntax.ParenExpr: // (lhs) = rhs fcomp.assign(pos, lhs.X) case *syntax.Ident: // x = rhs fcomp.set(lhs) case *syntax.TupleExpr: // x, y = rhs fcomp.assignSequence(pos, lhs.List) case *syntax.ListExpr: // [x, y] = rhs fcomp.assignSequence(pos, lhs.List) case *syntax.IndexExpr: // x[y] = rhs fcomp.expr(lhs.X) fcomp.emit(EXCH) fcomp.expr(lhs.Y) fcomp.emit(EXCH) fcomp.setPos(lhs.Lbrack) fcomp.emit(SETINDEX) case *syntax.DotExpr: // x.f = rhs fcomp.expr(lhs.X) fcomp.emit(EXCH) fcomp.setPos(lhs.Dot) fcomp.emit1(SETFIELD, fcomp.pcomp.nameIndex(lhs.Name.Name)) default: panic(lhs) } }
go
func (fcomp *fcomp) assign(pos syntax.Position, lhs syntax.Expr) { switch lhs := lhs.(type) { case *syntax.ParenExpr: // (lhs) = rhs fcomp.assign(pos, lhs.X) case *syntax.Ident: // x = rhs fcomp.set(lhs) case *syntax.TupleExpr: // x, y = rhs fcomp.assignSequence(pos, lhs.List) case *syntax.ListExpr: // [x, y] = rhs fcomp.assignSequence(pos, lhs.List) case *syntax.IndexExpr: // x[y] = rhs fcomp.expr(lhs.X) fcomp.emit(EXCH) fcomp.expr(lhs.Y) fcomp.emit(EXCH) fcomp.setPos(lhs.Lbrack) fcomp.emit(SETINDEX) case *syntax.DotExpr: // x.f = rhs fcomp.expr(lhs.X) fcomp.emit(EXCH) fcomp.setPos(lhs.Dot) fcomp.emit1(SETFIELD, fcomp.pcomp.nameIndex(lhs.Name.Name)) default: panic(lhs) } }
[ "func", "(", "fcomp", "*", "fcomp", ")", "assign", "(", "pos", "syntax", ".", "Position", ",", "lhs", "syntax", ".", "Expr", ")", "{", "switch", "lhs", ":=", "lhs", ".", "(", "type", ")", "{", "case", "*", "syntax", ".", "ParenExpr", ":", "// (lhs) = rhs", "fcomp", ".", "assign", "(", "pos", ",", "lhs", ".", "X", ")", "\n\n", "case", "*", "syntax", ".", "Ident", ":", "// x = rhs", "fcomp", ".", "set", "(", "lhs", ")", "\n\n", "case", "*", "syntax", ".", "TupleExpr", ":", "// x, y = rhs", "fcomp", ".", "assignSequence", "(", "pos", ",", "lhs", ".", "List", ")", "\n\n", "case", "*", "syntax", ".", "ListExpr", ":", "// [x, y] = rhs", "fcomp", ".", "assignSequence", "(", "pos", ",", "lhs", ".", "List", ")", "\n\n", "case", "*", "syntax", ".", "IndexExpr", ":", "// x[y] = rhs", "fcomp", ".", "expr", "(", "lhs", ".", "X", ")", "\n", "fcomp", ".", "emit", "(", "EXCH", ")", "\n", "fcomp", ".", "expr", "(", "lhs", ".", "Y", ")", "\n", "fcomp", ".", "emit", "(", "EXCH", ")", "\n", "fcomp", ".", "setPos", "(", "lhs", ".", "Lbrack", ")", "\n", "fcomp", ".", "emit", "(", "SETINDEX", ")", "\n\n", "case", "*", "syntax", ".", "DotExpr", ":", "// x.f = rhs", "fcomp", ".", "expr", "(", "lhs", ".", "X", ")", "\n", "fcomp", ".", "emit", "(", "EXCH", ")", "\n", "fcomp", ".", "setPos", "(", "lhs", ".", "Dot", ")", "\n", "fcomp", ".", "emit1", "(", "SETFIELD", ",", "fcomp", ".", "pcomp", ".", "nameIndex", "(", "lhs", ".", "Name", ".", "Name", ")", ")", "\n\n", "default", ":", "panic", "(", "lhs", ")", "\n", "}", "\n", "}" ]
// assign implements lhs = rhs for arbitrary expressions lhs. // RHS is on top of stack, consumed.
[ "assign", "implements", "lhs", "=", "rhs", "for", "arbitrary", "expressions", "lhs", ".", "RHS", "is", "on", "top", "of", "stack", "consumed", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L1089-L1126
6,665
google/skylark
internal/compile/compile.go
add
func add(code rune, args []summand) syntax.Expr { switch code { case 's': var buf bytes.Buffer for _, arg := range args { buf.WriteString(arg.x.(*syntax.Literal).Value.(string)) } return &syntax.Literal{Token: syntax.STRING, Value: buf.String()} case 'l': var elems []syntax.Expr for _, arg := range args { elems = append(elems, arg.x.(*syntax.ListExpr).List...) } return &syntax.ListExpr{List: elems} case 't': var elems []syntax.Expr for _, arg := range args { elems = append(elems, arg.x.(*syntax.TupleExpr).List...) } return &syntax.TupleExpr{List: elems} } panic(code) }
go
func add(code rune, args []summand) syntax.Expr { switch code { case 's': var buf bytes.Buffer for _, arg := range args { buf.WriteString(arg.x.(*syntax.Literal).Value.(string)) } return &syntax.Literal{Token: syntax.STRING, Value: buf.String()} case 'l': var elems []syntax.Expr for _, arg := range args { elems = append(elems, arg.x.(*syntax.ListExpr).List...) } return &syntax.ListExpr{List: elems} case 't': var elems []syntax.Expr for _, arg := range args { elems = append(elems, arg.x.(*syntax.TupleExpr).List...) } return &syntax.TupleExpr{List: elems} } panic(code) }
[ "func", "add", "(", "code", "rune", ",", "args", "[", "]", "summand", ")", "syntax", ".", "Expr", "{", "switch", "code", "{", "case", "'s'", ":", "var", "buf", "bytes", ".", "Buffer", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "buf", ".", "WriteString", "(", "arg", ".", "x", ".", "(", "*", "syntax", ".", "Literal", ")", ".", "Value", ".", "(", "string", ")", ")", "\n", "}", "\n", "return", "&", "syntax", ".", "Literal", "{", "Token", ":", "syntax", ".", "STRING", ",", "Value", ":", "buf", ".", "String", "(", ")", "}", "\n", "case", "'l'", ":", "var", "elems", "[", "]", "syntax", ".", "Expr", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "elems", "=", "append", "(", "elems", ",", "arg", ".", "x", ".", "(", "*", "syntax", ".", "ListExpr", ")", ".", "List", "...", ")", "\n", "}", "\n", "return", "&", "syntax", ".", "ListExpr", "{", "List", ":", "elems", "}", "\n", "case", "'t'", ":", "var", "elems", "[", "]", "syntax", ".", "Expr", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "elems", "=", "append", "(", "elems", ",", "arg", ".", "x", ".", "(", "*", "syntax", ".", "TupleExpr", ")", ".", "List", "...", ")", "\n", "}", "\n", "return", "&", "syntax", ".", "TupleExpr", "{", "List", ":", "elems", "}", "\n", "}", "\n", "panic", "(", "code", ")", "\n", "}" ]
// add returns an expression denoting the sum of args, // which are all addable values of the type indicated by code. // The resulting syntax is degenerate, lacking position, etc.
[ "add", "returns", "an", "expression", "denoting", "the", "sum", "of", "args", "which", "are", "all", "addable", "values", "of", "the", "type", "indicated", "by", "code", ".", "The", "resulting", "syntax", "is", "degenerate", "lacking", "position", "etc", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L1404-L1426
6,666
google/skylark
internal/compile/compile.go
ifelse
func (fcomp *fcomp) ifelse(cond syntax.Expr, t, f *block) { switch cond := cond.(type) { case *syntax.UnaryExpr: if cond.Op == syntax.NOT { // if not x then goto t else goto f // => // if x then goto f else goto t fcomp.ifelse(cond.X, f, t) return } case *syntax.BinaryExpr: switch cond.Op { case syntax.AND: // if x and y then goto t else goto f // => // if x then ifelse(y, t, f) else goto f fcomp.expr(cond.X) y := fcomp.newBlock() fcomp.condjump(CJMP, y, f) fcomp.block = y fcomp.ifelse(cond.Y, t, f) return case syntax.OR: // if x or y then goto t else goto f // => // if x then goto t else ifelse(y, t, f) fcomp.expr(cond.X) y := fcomp.newBlock() fcomp.condjump(CJMP, t, y) fcomp.block = y fcomp.ifelse(cond.Y, t, f) return case syntax.NOT_IN: // if x not in y then goto t else goto f // => // if x in y then goto f else goto t copy := *cond copy.Op = syntax.IN fcomp.expr(&copy) fcomp.condjump(CJMP, f, t) return } } // general case fcomp.expr(cond) fcomp.condjump(CJMP, t, f) }
go
func (fcomp *fcomp) ifelse(cond syntax.Expr, t, f *block) { switch cond := cond.(type) { case *syntax.UnaryExpr: if cond.Op == syntax.NOT { // if not x then goto t else goto f // => // if x then goto f else goto t fcomp.ifelse(cond.X, f, t) return } case *syntax.BinaryExpr: switch cond.Op { case syntax.AND: // if x and y then goto t else goto f // => // if x then ifelse(y, t, f) else goto f fcomp.expr(cond.X) y := fcomp.newBlock() fcomp.condjump(CJMP, y, f) fcomp.block = y fcomp.ifelse(cond.Y, t, f) return case syntax.OR: // if x or y then goto t else goto f // => // if x then goto t else ifelse(y, t, f) fcomp.expr(cond.X) y := fcomp.newBlock() fcomp.condjump(CJMP, t, y) fcomp.block = y fcomp.ifelse(cond.Y, t, f) return case syntax.NOT_IN: // if x not in y then goto t else goto f // => // if x in y then goto f else goto t copy := *cond copy.Op = syntax.IN fcomp.expr(&copy) fcomp.condjump(CJMP, f, t) return } } // general case fcomp.expr(cond) fcomp.condjump(CJMP, t, f) }
[ "func", "(", "fcomp", "*", "fcomp", ")", "ifelse", "(", "cond", "syntax", ".", "Expr", ",", "t", ",", "f", "*", "block", ")", "{", "switch", "cond", ":=", "cond", ".", "(", "type", ")", "{", "case", "*", "syntax", ".", "UnaryExpr", ":", "if", "cond", ".", "Op", "==", "syntax", ".", "NOT", "{", "// if not x then goto t else goto f", "// =>", "// if x then goto f else goto t", "fcomp", ".", "ifelse", "(", "cond", ".", "X", ",", "f", ",", "t", ")", "\n", "return", "\n", "}", "\n\n", "case", "*", "syntax", ".", "BinaryExpr", ":", "switch", "cond", ".", "Op", "{", "case", "syntax", ".", "AND", ":", "// if x and y then goto t else goto f", "// =>", "// if x then ifelse(y, t, f) else goto f", "fcomp", ".", "expr", "(", "cond", ".", "X", ")", "\n", "y", ":=", "fcomp", ".", "newBlock", "(", ")", "\n", "fcomp", ".", "condjump", "(", "CJMP", ",", "y", ",", "f", ")", "\n\n", "fcomp", ".", "block", "=", "y", "\n", "fcomp", ".", "ifelse", "(", "cond", ".", "Y", ",", "t", ",", "f", ")", "\n", "return", "\n\n", "case", "syntax", ".", "OR", ":", "// if x or y then goto t else goto f", "// =>", "// if x then goto t else ifelse(y, t, f)", "fcomp", ".", "expr", "(", "cond", ".", "X", ")", "\n", "y", ":=", "fcomp", ".", "newBlock", "(", ")", "\n", "fcomp", ".", "condjump", "(", "CJMP", ",", "t", ",", "y", ")", "\n\n", "fcomp", ".", "block", "=", "y", "\n", "fcomp", ".", "ifelse", "(", "cond", ".", "Y", ",", "t", ",", "f", ")", "\n", "return", "\n", "case", "syntax", ".", "NOT_IN", ":", "// if x not in y then goto t else goto f", "// =>", "// if x in y then goto f else goto t", "copy", ":=", "*", "cond", "\n", "copy", ".", "Op", "=", "syntax", ".", "IN", "\n", "fcomp", ".", "expr", "(", "&", "copy", ")", "\n", "fcomp", ".", "condjump", "(", "CJMP", ",", "f", ",", "t", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// general case", "fcomp", ".", "expr", "(", "cond", ")", "\n", "fcomp", ".", "condjump", "(", "CJMP", ",", "t", ",", "f", ")", "\n", "}" ]
// ifelse emits a Boolean control flow decision. // On return, the current block is unset.
[ "ifelse", "emits", "a", "Boolean", "control", "flow", "decision", ".", "On", "return", "the", "current", "block", "is", "unset", "." ]
a5f7082aabed29c0e429c722292c66ec8ecf9591
https://github.com/google/skylark/blob/a5f7082aabed29c0e429c722292c66ec8ecf9591/internal/compile/compile.go#L1682-L1733
6,667
flosch/pongo2
error.go
Error
func (e *Error) Error() string { s := "[Error" if e.Sender != "" { s += " (where: " + e.Sender + ")" } if e.Filename != "" { s += " in " + e.Filename } if e.Line > 0 { s += fmt.Sprintf(" | Line %d Col %d", e.Line, e.Column) if e.Token != nil { s += fmt.Sprintf(" near '%s'", e.Token.Val) } } s += "] " s += e.OrigError.Error() return s }
go
func (e *Error) Error() string { s := "[Error" if e.Sender != "" { s += " (where: " + e.Sender + ")" } if e.Filename != "" { s += " in " + e.Filename } if e.Line > 0 { s += fmt.Sprintf(" | Line %d Col %d", e.Line, e.Column) if e.Token != nil { s += fmt.Sprintf(" near '%s'", e.Token.Val) } } s += "] " s += e.OrigError.Error() return s }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "s", ":=", "\"", "\"", "\n", "if", "e", ".", "Sender", "!=", "\"", "\"", "{", "s", "+=", "\"", "\"", "+", "e", ".", "Sender", "+", "\"", "\"", "\n", "}", "\n", "if", "e", ".", "Filename", "!=", "\"", "\"", "{", "s", "+=", "\"", "\"", "+", "e", ".", "Filename", "\n", "}", "\n", "if", "e", ".", "Line", ">", "0", "{", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Line", ",", "e", ".", "Column", ")", "\n", "if", "e", ".", "Token", "!=", "nil", "{", "s", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Token", ".", "Val", ")", "\n", "}", "\n", "}", "\n", "s", "+=", "\"", "\"", "\n", "s", "+=", "e", ".", "OrigError", ".", "Error", "(", ")", "\n", "return", "s", "\n", "}" ]
// Returns a nice formatted error string.
[ "Returns", "a", "nice", "formatted", "error", "string", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/error.go#L42-L59
6,668
flosch/pongo2
error.go
RawLine
func (e *Error) RawLine() (line string, available bool, outErr error) { if e.Line <= 0 || e.Filename == "<string>" { return "", false, nil } filename := e.Filename if e.Template != nil { filename = e.Template.set.resolveFilename(e.Template, e.Filename) } file, err := os.Open(filename) if err != nil { return "", false, err } defer func() { err := file.Close() if err != nil && outErr == nil { outErr = err } }() scanner := bufio.NewScanner(file) l := 0 for scanner.Scan() { l++ if l == e.Line { return scanner.Text(), true, nil } } return "", false, nil }
go
func (e *Error) RawLine() (line string, available bool, outErr error) { if e.Line <= 0 || e.Filename == "<string>" { return "", false, nil } filename := e.Filename if e.Template != nil { filename = e.Template.set.resolveFilename(e.Template, e.Filename) } file, err := os.Open(filename) if err != nil { return "", false, err } defer func() { err := file.Close() if err != nil && outErr == nil { outErr = err } }() scanner := bufio.NewScanner(file) l := 0 for scanner.Scan() { l++ if l == e.Line { return scanner.Text(), true, nil } } return "", false, nil }
[ "func", "(", "e", "*", "Error", ")", "RawLine", "(", ")", "(", "line", "string", ",", "available", "bool", ",", "outErr", "error", ")", "{", "if", "e", ".", "Line", "<=", "0", "||", "e", ".", "Filename", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "false", ",", "nil", "\n", "}", "\n\n", "filename", ":=", "e", ".", "Filename", "\n", "if", "e", ".", "Template", "!=", "nil", "{", "filename", "=", "e", ".", "Template", ".", "set", ".", "resolveFilename", "(", "e", ".", "Template", ",", "e", ".", "Filename", ")", "\n", "}", "\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "false", ",", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "err", ":=", "file", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "outErr", "==", "nil", "{", "outErr", "=", "err", "\n", "}", "\n", "}", "(", ")", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "file", ")", "\n", "l", ":=", "0", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "l", "++", "\n", "if", "l", "==", "e", ".", "Line", "{", "return", "scanner", ".", "Text", "(", ")", ",", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "false", ",", "nil", "\n", "}" ]
// RawLine returns the affected line from the original template, if available.
[ "RawLine", "returns", "the", "affected", "line", "from", "the", "original", "template", "if", "available", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/error.go#L62-L91
6,669
flosch/pongo2
parser.go
newParser
func newParser(name string, tokens []*Token, template *Template) *Parser { p := &Parser{ name: name, tokens: tokens, template: template, } if len(tokens) > 0 { p.lastToken = tokens[len(tokens)-1] } return p }
go
func newParser(name string, tokens []*Token, template *Template) *Parser { p := &Parser{ name: name, tokens: tokens, template: template, } if len(tokens) > 0 { p.lastToken = tokens[len(tokens)-1] } return p }
[ "func", "newParser", "(", "name", "string", ",", "tokens", "[", "]", "*", "Token", ",", "template", "*", "Template", ")", "*", "Parser", "{", "p", ":=", "&", "Parser", "{", "name", ":", "name", ",", "tokens", ":", "tokens", ",", "template", ":", "template", ",", "}", "\n", "if", "len", "(", "tokens", ")", ">", "0", "{", "p", ".", "lastToken", "=", "tokens", "[", "len", "(", "tokens", ")", "-", "1", "]", "\n", "}", "\n", "return", "p", "\n", "}" ]
// Creates a new parser to parse tokens. // Used inside pongo2 to parse documents and to provide an easy-to-use // parser for tag authors
[ "Creates", "a", "new", "parser", "to", "parse", "tokens", ".", "Used", "inside", "pongo2", "to", "parse", "documents", "and", "to", "provide", "an", "easy", "-", "to", "-", "use", "parser", "for", "tag", "authors" ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/parser.go#L44-L54
6,670
flosch/pongo2
parser.go
MatchType
func (p *Parser) MatchType(typ TokenType) *Token { if t := p.PeekType(typ); t != nil { p.Consume() return t } return nil }
go
func (p *Parser) MatchType(typ TokenType) *Token { if t := p.PeekType(typ); t != nil { p.Consume() return t } return nil }
[ "func", "(", "p", "*", "Parser", ")", "MatchType", "(", "typ", "TokenType", ")", "*", "Token", "{", "if", "t", ":=", "p", ".", "PeekType", "(", "typ", ")", ";", "t", "!=", "nil", "{", "p", ".", "Consume", "(", ")", "\n", "return", "t", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Returns the CURRENT token if the given type matches. // Consumes this token on success.
[ "Returns", "the", "CURRENT", "token", "if", "the", "given", "type", "matches", ".", "Consumes", "this", "token", "on", "success", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/parser.go#L73-L79
6,671
flosch/pongo2
parser.go
Match
func (p *Parser) Match(typ TokenType, val string) *Token { if t := p.Peek(typ, val); t != nil { p.Consume() return t } return nil }
go
func (p *Parser) Match(typ TokenType, val string) *Token { if t := p.Peek(typ, val); t != nil { p.Consume() return t } return nil }
[ "func", "(", "p", "*", "Parser", ")", "Match", "(", "typ", "TokenType", ",", "val", "string", ")", "*", "Token", "{", "if", "t", ":=", "p", ".", "Peek", "(", "typ", ",", "val", ")", ";", "t", "!=", "nil", "{", "p", ".", "Consume", "(", ")", "\n", "return", "t", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Returns the CURRENT token if the given type AND value matches. // Consumes this token on success.
[ "Returns", "the", "CURRENT", "token", "if", "the", "given", "type", "AND", "value", "matches", ".", "Consumes", "this", "token", "on", "success", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/parser.go#L83-L89
6,672
flosch/pongo2
parser.go
Peek
func (p *Parser) Peek(typ TokenType, val string) *Token { return p.PeekN(0, typ, val) }
go
func (p *Parser) Peek(typ TokenType, val string) *Token { return p.PeekN(0, typ, val) }
[ "func", "(", "p", "*", "Parser", ")", "Peek", "(", "typ", "TokenType", ",", "val", "string", ")", "*", "Token", "{", "return", "p", ".", "PeekN", "(", "0", ",", "typ", ",", "val", ")", "\n", "}" ]
// Returns the CURRENT token if the given type AND value matches. // It DOES NOT consume the token.
[ "Returns", "the", "CURRENT", "token", "if", "the", "given", "type", "AND", "value", "matches", ".", "It", "DOES", "NOT", "consume", "the", "token", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/parser.go#L112-L114
6,673
flosch/pongo2
parser.go
Error
func (p *Parser) Error(msg string, token *Token) *Error { if token == nil { // Set current token token = p.Current() if token == nil { // Set to last token if len(p.tokens) > 0 { token = p.tokens[len(p.tokens)-1] } } } var line, col int if token != nil { line = token.Line col = token.Col } return &Error{ Template: p.template, Filename: p.name, Sender: "parser", Line: line, Column: col, Token: token, OrigError: errors.New(msg), } }
go
func (p *Parser) Error(msg string, token *Token) *Error { if token == nil { // Set current token token = p.Current() if token == nil { // Set to last token if len(p.tokens) > 0 { token = p.tokens[len(p.tokens)-1] } } } var line, col int if token != nil { line = token.Line col = token.Col } return &Error{ Template: p.template, Filename: p.name, Sender: "parser", Line: line, Column: col, Token: token, OrigError: errors.New(msg), } }
[ "func", "(", "p", "*", "Parser", ")", "Error", "(", "msg", "string", ",", "token", "*", "Token", ")", "*", "Error", "{", "if", "token", "==", "nil", "{", "// Set current token", "token", "=", "p", ".", "Current", "(", ")", "\n", "if", "token", "==", "nil", "{", "// Set to last token", "if", "len", "(", "p", ".", "tokens", ")", ">", "0", "{", "token", "=", "p", ".", "tokens", "[", "len", "(", "p", ".", "tokens", ")", "-", "1", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "var", "line", ",", "col", "int", "\n", "if", "token", "!=", "nil", "{", "line", "=", "token", ".", "Line", "\n", "col", "=", "token", ".", "Col", "\n", "}", "\n", "return", "&", "Error", "{", "Template", ":", "p", ".", "template", ",", "Filename", ":", "p", ".", "name", ",", "Sender", ":", "\"", "\"", ",", "Line", ":", "line", ",", "Column", ":", "col", ",", "Token", ":", "token", ",", "OrigError", ":", "errors", ".", "New", "(", "msg", ")", ",", "}", "\n", "}" ]
// Error produces a nice error message and returns an error-object. // The 'token'-argument is optional. If provided, it will take // the token's position information. If not provided, it will // automatically use the CURRENT token's position information.
[ "Error", "produces", "a", "nice", "error", "message", "and", "returns", "an", "error", "-", "object", ".", "The", "token", "-", "argument", "is", "optional", ".", "If", "provided", "it", "will", "take", "the", "token", "s", "position", "information", ".", "If", "not", "provided", "it", "will", "automatically", "use", "the", "CURRENT", "token", "s", "position", "information", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/parser.go#L183-L208
6,674
flosch/pongo2
template.go
ExecuteWriterUnbuffered
func (tpl *Template) ExecuteWriterUnbuffered(context Context, writer io.Writer) error { return tpl.newTemplateWriterAndExecute(context, writer) }
go
func (tpl *Template) ExecuteWriterUnbuffered(context Context, writer io.Writer) error { return tpl.newTemplateWriterAndExecute(context, writer) }
[ "func", "(", "tpl", "*", "Template", ")", "ExecuteWriterUnbuffered", "(", "context", "Context", ",", "writer", "io", ".", "Writer", ")", "error", "{", "return", "tpl", ".", "newTemplateWriterAndExecute", "(", "context", ",", "writer", ")", "\n", "}" ]
// Same as ExecuteWriter. The only difference between both functions is that // this function might already have written parts of the generated template in the // case of an execution error because there's no intermediate buffer involved for // performance reasons. This is handy if you need high performance template // generation or if you want to manage your own pool of buffers.
[ "Same", "as", "ExecuteWriter", ".", "The", "only", "difference", "between", "both", "functions", "is", "that", "this", "function", "might", "already", "have", "written", "parts", "of", "the", "generated", "template", "in", "the", "case", "of", "an", "execution", "error", "because", "there", "s", "no", "intermediate", "buffer", "involved", "for", "performance", "reasons", ".", "This", "is", "handy", "if", "you", "need", "high", "performance", "template", "generation", "or", "if", "you", "want", "to", "manage", "your", "own", "pool", "of", "buffers", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template.go#L170-L172
6,675
flosch/pongo2
template.go
Execute
func (tpl *Template) Execute(context Context) (string, error) { // Execute template buffer, err := tpl.newBufferAndExecute(context) if err != nil { return "", err } return buffer.String(), nil }
go
func (tpl *Template) Execute(context Context) (string, error) { // Execute template buffer, err := tpl.newBufferAndExecute(context) if err != nil { return "", err } return buffer.String(), nil }
[ "func", "(", "tpl", "*", "Template", ")", "Execute", "(", "context", "Context", ")", "(", "string", ",", "error", ")", "{", "// Execute template", "buffer", ",", "err", ":=", "tpl", ".", "newBufferAndExecute", "(", "context", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "buffer", ".", "String", "(", ")", ",", "nil", "\n\n", "}" ]
// Executes the template and returns the rendered template as a string
[ "Executes", "the", "template", "and", "returns", "the", "rendered", "template", "as", "a", "string" ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template.go#L185-L194
6,676
flosch/pongo2
template_loader.go
MustNewLocalFileSystemLoader
func MustNewLocalFileSystemLoader(baseDir string) *LocalFilesystemLoader { fs, err := NewLocalFileSystemLoader(baseDir) if err != nil { log.Panic(err) } return fs }
go
func MustNewLocalFileSystemLoader(baseDir string) *LocalFilesystemLoader { fs, err := NewLocalFileSystemLoader(baseDir) if err != nil { log.Panic(err) } return fs }
[ "func", "MustNewLocalFileSystemLoader", "(", "baseDir", "string", ")", "*", "LocalFilesystemLoader", "{", "fs", ",", "err", ":=", "NewLocalFileSystemLoader", "(", "baseDir", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Panic", "(", "err", ")", "\n", "}", "\n", "return", "fs", "\n", "}" ]
// MustNewLocalFileSystemLoader creates a new LocalFilesystemLoader instance // and panics if there's any error during instantiation. The parameters // are the same like NewLocalFileSystemLoader.
[ "MustNewLocalFileSystemLoader", "creates", "a", "new", "LocalFilesystemLoader", "instance", "and", "panics", "if", "there", "s", "any", "error", "during", "instantiation", ".", "The", "parameters", "are", "the", "same", "like", "NewLocalFileSystemLoader", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_loader.go#L23-L29
6,677
flosch/pongo2
template_loader.go
Get
func (fs *LocalFilesystemLoader) Get(path string) (io.Reader, error) { buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } return bytes.NewReader(buf), nil }
go
func (fs *LocalFilesystemLoader) Get(path string) (io.Reader, error) { buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } return bytes.NewReader(buf), nil }
[ "func", "(", "fs", "*", "LocalFilesystemLoader", ")", "Get", "(", "path", "string", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "buf", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bytes", ".", "NewReader", "(", "buf", ")", ",", "nil", "\n", "}" ]
// Get reads the path's content from your local filesystem.
[ "Get", "reads", "the", "path", "s", "content", "from", "your", "local", "filesystem", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_loader.go#L73-L79
6,678
flosch/pongo2
template_loader.go
NewSandboxedFilesystemLoader
func NewSandboxedFilesystemLoader(baseDir string) (*SandboxedFilesystemLoader, error) { fs, err := NewLocalFileSystemLoader(baseDir) if err != nil { return nil, err } return &SandboxedFilesystemLoader{ LocalFilesystemLoader: fs, }, nil }
go
func NewSandboxedFilesystemLoader(baseDir string) (*SandboxedFilesystemLoader, error) { fs, err := NewLocalFileSystemLoader(baseDir) if err != nil { return nil, err } return &SandboxedFilesystemLoader{ LocalFilesystemLoader: fs, }, nil }
[ "func", "NewSandboxedFilesystemLoader", "(", "baseDir", "string", ")", "(", "*", "SandboxedFilesystemLoader", ",", "error", ")", "{", "fs", ",", "err", ":=", "NewLocalFileSystemLoader", "(", "baseDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "SandboxedFilesystemLoader", "{", "LocalFilesystemLoader", ":", "fs", ",", "}", ",", "nil", "\n", "}" ]
// NewSandboxedFilesystemLoader creates a new sandboxed local file system instance.
[ "NewSandboxedFilesystemLoader", "creates", "a", "new", "sandboxed", "local", "file", "system", "instance", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_loader.go#L115-L123
6,679
flosch/pongo2
template_sets.go
BanTag
func (set *TemplateSet) BanTag(name string) error { _, has := tags[name] if !has { return errors.Errorf("tag '%s' not found", name) } if set.firstTemplateCreated { return errors.New("you cannot ban any tags after you've added your first template to your template set") } _, has = set.bannedTags[name] if has { return errors.Errorf("tag '%s' is already banned", name) } set.bannedTags[name] = true return nil }
go
func (set *TemplateSet) BanTag(name string) error { _, has := tags[name] if !has { return errors.Errorf("tag '%s' not found", name) } if set.firstTemplateCreated { return errors.New("you cannot ban any tags after you've added your first template to your template set") } _, has = set.bannedTags[name] if has { return errors.Errorf("tag '%s' is already banned", name) } set.bannedTags[name] = true return nil }
[ "func", "(", "set", "*", "TemplateSet", ")", "BanTag", "(", "name", "string", ")", "error", "{", "_", ",", "has", ":=", "tags", "[", "name", "]", "\n", "if", "!", "has", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "set", ".", "firstTemplateCreated", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "has", "=", "set", ".", "bannedTags", "[", "name", "]", "\n", "if", "has", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "set", ".", "bannedTags", "[", "name", "]", "=", "true", "\n\n", "return", "nil", "\n", "}" ]
// BanTag bans a specific tag for this template set. See more in the documentation for TemplateSet.
[ "BanTag", "bans", "a", "specific", "tag", "for", "this", "template", "set", ".", "See", "more", "in", "the", "documentation", "for", "TemplateSet", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L83-L98
6,680
flosch/pongo2
template_sets.go
BanFilter
func (set *TemplateSet) BanFilter(name string) error { _, has := filters[name] if !has { return errors.Errorf("filter '%s' not found", name) } if set.firstTemplateCreated { return errors.New("you cannot ban any filters after you've added your first template to your template set") } _, has = set.bannedFilters[name] if has { return errors.Errorf("filter '%s' is already banned", name) } set.bannedFilters[name] = true return nil }
go
func (set *TemplateSet) BanFilter(name string) error { _, has := filters[name] if !has { return errors.Errorf("filter '%s' not found", name) } if set.firstTemplateCreated { return errors.New("you cannot ban any filters after you've added your first template to your template set") } _, has = set.bannedFilters[name] if has { return errors.Errorf("filter '%s' is already banned", name) } set.bannedFilters[name] = true return nil }
[ "func", "(", "set", "*", "TemplateSet", ")", "BanFilter", "(", "name", "string", ")", "error", "{", "_", ",", "has", ":=", "filters", "[", "name", "]", "\n", "if", "!", "has", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "set", ".", "firstTemplateCreated", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "has", "=", "set", ".", "bannedFilters", "[", "name", "]", "\n", "if", "has", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "set", ".", "bannedFilters", "[", "name", "]", "=", "true", "\n\n", "return", "nil", "\n", "}" ]
// BanFilter bans a specific filter for this template set. See more in the documentation for TemplateSet.
[ "BanFilter", "bans", "a", "specific", "filter", "for", "this", "template", "set", ".", "See", "more", "in", "the", "documentation", "for", "TemplateSet", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L101-L116
6,681
flosch/pongo2
template_sets.go
CleanCache
func (set *TemplateSet) CleanCache(filenames ...string) { set.templateCacheMutex.Lock() defer set.templateCacheMutex.Unlock() if len(filenames) == 0 { set.templateCache = make(map[string]*Template, len(set.templateCache)) } for _, filename := range filenames { delete(set.templateCache, set.resolveFilename(nil, filename)) } }
go
func (set *TemplateSet) CleanCache(filenames ...string) { set.templateCacheMutex.Lock() defer set.templateCacheMutex.Unlock() if len(filenames) == 0 { set.templateCache = make(map[string]*Template, len(set.templateCache)) } for _, filename := range filenames { delete(set.templateCache, set.resolveFilename(nil, filename)) } }
[ "func", "(", "set", "*", "TemplateSet", ")", "CleanCache", "(", "filenames", "...", "string", ")", "{", "set", ".", "templateCacheMutex", ".", "Lock", "(", ")", "\n", "defer", "set", ".", "templateCacheMutex", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "filenames", ")", "==", "0", "{", "set", ".", "templateCache", "=", "make", "(", "map", "[", "string", "]", "*", "Template", ",", "len", "(", "set", ".", "templateCache", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "filename", ":=", "range", "filenames", "{", "delete", "(", "set", ".", "templateCache", ",", "set", ".", "resolveFilename", "(", "nil", ",", "filename", ")", ")", "\n", "}", "\n", "}" ]
// CleanCache cleans the template cache. If filenames is not empty, // it will remove the template caches of those filenames. // Or it will empty the whole template cache. It is thread-safe.
[ "CleanCache", "cleans", "the", "template", "cache", ".", "If", "filenames", "is", "not", "empty", "it", "will", "remove", "the", "template", "caches", "of", "those", "filenames", ".", "Or", "it", "will", "empty", "the", "whole", "template", "cache", ".", "It", "is", "thread", "-", "safe", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L121-L132
6,682
flosch/pongo2
template_sets.go
FromString
func (set *TemplateSet) FromString(tpl string) (*Template, error) { set.firstTemplateCreated = true return newTemplateString(set, []byte(tpl)) }
go
func (set *TemplateSet) FromString(tpl string) (*Template, error) { set.firstTemplateCreated = true return newTemplateString(set, []byte(tpl)) }
[ "func", "(", "set", "*", "TemplateSet", ")", "FromString", "(", "tpl", "string", ")", "(", "*", "Template", ",", "error", ")", "{", "set", ".", "firstTemplateCreated", "=", "true", "\n\n", "return", "newTemplateString", "(", "set", ",", "[", "]", "byte", "(", "tpl", ")", ")", "\n", "}" ]
// FromString loads a template from string and returns a Template instance.
[ "FromString", "loads", "a", "template", "from", "string", "and", "returns", "a", "Template", "instance", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L167-L171
6,683
flosch/pongo2
template_sets.go
FromBytes
func (set *TemplateSet) FromBytes(tpl []byte) (*Template, error) { set.firstTemplateCreated = true return newTemplateString(set, tpl) }
go
func (set *TemplateSet) FromBytes(tpl []byte) (*Template, error) { set.firstTemplateCreated = true return newTemplateString(set, tpl) }
[ "func", "(", "set", "*", "TemplateSet", ")", "FromBytes", "(", "tpl", "[", "]", "byte", ")", "(", "*", "Template", ",", "error", ")", "{", "set", ".", "firstTemplateCreated", "=", "true", "\n\n", "return", "newTemplateString", "(", "set", ",", "tpl", ")", "\n", "}" ]
// FromBytes loads a template from bytes and returns a Template instance.
[ "FromBytes", "loads", "a", "template", "from", "bytes", "and", "returns", "a", "Template", "instance", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L174-L178
6,684
flosch/pongo2
template_sets.go
FromFile
func (set *TemplateSet) FromFile(filename string) (*Template, error) { set.firstTemplateCreated = true fd, err := set.loader.Get(set.resolveFilename(nil, filename)) if err != nil { return nil, &Error{ Filename: filename, Sender: "fromfile", OrigError: err, } } buf, err := ioutil.ReadAll(fd) if err != nil { return nil, &Error{ Filename: filename, Sender: "fromfile", OrigError: err, } } return newTemplate(set, filename, false, buf) }
go
func (set *TemplateSet) FromFile(filename string) (*Template, error) { set.firstTemplateCreated = true fd, err := set.loader.Get(set.resolveFilename(nil, filename)) if err != nil { return nil, &Error{ Filename: filename, Sender: "fromfile", OrigError: err, } } buf, err := ioutil.ReadAll(fd) if err != nil { return nil, &Error{ Filename: filename, Sender: "fromfile", OrigError: err, } } return newTemplate(set, filename, false, buf) }
[ "func", "(", "set", "*", "TemplateSet", ")", "FromFile", "(", "filename", "string", ")", "(", "*", "Template", ",", "error", ")", "{", "set", ".", "firstTemplateCreated", "=", "true", "\n\n", "fd", ",", "err", ":=", "set", ".", "loader", ".", "Get", "(", "set", ".", "resolveFilename", "(", "nil", ",", "filename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "Error", "{", "Filename", ":", "filename", ",", "Sender", ":", "\"", "\"", ",", "OrigError", ":", "err", ",", "}", "\n", "}", "\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "fd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "&", "Error", "{", "Filename", ":", "filename", ",", "Sender", ":", "\"", "\"", ",", "OrigError", ":", "err", ",", "}", "\n", "}", "\n\n", "return", "newTemplate", "(", "set", ",", "filename", ",", "false", ",", "buf", ")", "\n", "}" ]
// FromFile loads a template from a filename and returns a Template instance.
[ "FromFile", "loads", "a", "template", "from", "a", "filename", "and", "returns", "a", "Template", "instance", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L181-L202
6,685
flosch/pongo2
template_sets.go
RenderTemplateString
func (set *TemplateSet) RenderTemplateString(s string, ctx Context) (string, error) { set.firstTemplateCreated = true tpl := Must(set.FromString(s)) result, err := tpl.Execute(ctx) if err != nil { return "", err } return result, nil }
go
func (set *TemplateSet) RenderTemplateString(s string, ctx Context) (string, error) { set.firstTemplateCreated = true tpl := Must(set.FromString(s)) result, err := tpl.Execute(ctx) if err != nil { return "", err } return result, nil }
[ "func", "(", "set", "*", "TemplateSet", ")", "RenderTemplateString", "(", "s", "string", ",", "ctx", "Context", ")", "(", "string", ",", "error", ")", "{", "set", ".", "firstTemplateCreated", "=", "true", "\n\n", "tpl", ":=", "Must", "(", "set", ".", "FromString", "(", "s", ")", ")", "\n", "result", ",", "err", ":=", "tpl", ".", "Execute", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// RenderTemplateString is a shortcut and renders a template string directly.
[ "RenderTemplateString", "is", "a", "shortcut", "and", "renders", "a", "template", "string", "directly", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L205-L214
6,686
flosch/pongo2
template_sets.go
RenderTemplateBytes
func (set *TemplateSet) RenderTemplateBytes(b []byte, ctx Context) (string, error) { set.firstTemplateCreated = true tpl := Must(set.FromBytes(b)) result, err := tpl.Execute(ctx) if err != nil { return "", err } return result, nil }
go
func (set *TemplateSet) RenderTemplateBytes(b []byte, ctx Context) (string, error) { set.firstTemplateCreated = true tpl := Must(set.FromBytes(b)) result, err := tpl.Execute(ctx) if err != nil { return "", err } return result, nil }
[ "func", "(", "set", "*", "TemplateSet", ")", "RenderTemplateBytes", "(", "b", "[", "]", "byte", ",", "ctx", "Context", ")", "(", "string", ",", "error", ")", "{", "set", ".", "firstTemplateCreated", "=", "true", "\n\n", "tpl", ":=", "Must", "(", "set", ".", "FromBytes", "(", "b", ")", ")", "\n", "result", ",", "err", ":=", "tpl", ".", "Execute", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// RenderTemplateBytes is a shortcut and renders template bytes directly.
[ "RenderTemplateBytes", "is", "a", "shortcut", "and", "renders", "template", "bytes", "directly", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L217-L226
6,687
flosch/pongo2
template_sets.go
RenderTemplateFile
func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) (string, error) { set.firstTemplateCreated = true tpl := Must(set.FromFile(fn)) result, err := tpl.Execute(ctx) if err != nil { return "", err } return result, nil }
go
func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) (string, error) { set.firstTemplateCreated = true tpl := Must(set.FromFile(fn)) result, err := tpl.Execute(ctx) if err != nil { return "", err } return result, nil }
[ "func", "(", "set", "*", "TemplateSet", ")", "RenderTemplateFile", "(", "fn", "string", ",", "ctx", "Context", ")", "(", "string", ",", "error", ")", "{", "set", ".", "firstTemplateCreated", "=", "true", "\n\n", "tpl", ":=", "Must", "(", "set", ".", "FromFile", "(", "fn", ")", ")", "\n", "result", ",", "err", ":=", "tpl", ".", "Execute", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// RenderTemplateFile is a shortcut and renders a template file directly.
[ "RenderTemplateFile", "is", "a", "shortcut", "and", "renders", "a", "template", "file", "directly", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/template_sets.go#L229-L238
6,688
flosch/pongo2
value.go
AsSafeValue
func AsSafeValue(i interface{}) *Value { return &Value{ val: reflect.ValueOf(i), safe: true, } }
go
func AsSafeValue(i interface{}) *Value { return &Value{ val: reflect.ValueOf(i), safe: true, } }
[ "func", "AsSafeValue", "(", "i", "interface", "{", "}", ")", "*", "Value", "{", "return", "&", "Value", "{", "val", ":", "reflect", ".", "ValueOf", "(", "i", ")", ",", "safe", ":", "true", ",", "}", "\n", "}" ]
// AsSafeValue works like AsValue, but does not apply the 'escape' filter.
[ "AsSafeValue", "works", "like", "AsValue", "but", "does", "not", "apply", "the", "escape", "filter", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L29-L34
6,689
flosch/pongo2
value.go
IsFloat
func (v *Value) IsFloat() bool { return v.getResolvedValue().Kind() == reflect.Float32 || v.getResolvedValue().Kind() == reflect.Float64 }
go
func (v *Value) IsFloat() bool { return v.getResolvedValue().Kind() == reflect.Float32 || v.getResolvedValue().Kind() == reflect.Float64 }
[ "func", "(", "v", "*", "Value", ")", "IsFloat", "(", ")", "bool", "{", "return", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Float32", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Float64", "\n", "}" ]
// IsFloat checks whether the underlying value is a float
[ "IsFloat", "checks", "whether", "the", "underlying", "value", "is", "a", "float" ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L54-L57
6,690
flosch/pongo2
value.go
IsInteger
func (v *Value) IsInteger() bool { return v.getResolvedValue().Kind() == reflect.Int || v.getResolvedValue().Kind() == reflect.Int8 || v.getResolvedValue().Kind() == reflect.Int16 || v.getResolvedValue().Kind() == reflect.Int32 || v.getResolvedValue().Kind() == reflect.Int64 || v.getResolvedValue().Kind() == reflect.Uint || v.getResolvedValue().Kind() == reflect.Uint8 || v.getResolvedValue().Kind() == reflect.Uint16 || v.getResolvedValue().Kind() == reflect.Uint32 || v.getResolvedValue().Kind() == reflect.Uint64 }
go
func (v *Value) IsInteger() bool { return v.getResolvedValue().Kind() == reflect.Int || v.getResolvedValue().Kind() == reflect.Int8 || v.getResolvedValue().Kind() == reflect.Int16 || v.getResolvedValue().Kind() == reflect.Int32 || v.getResolvedValue().Kind() == reflect.Int64 || v.getResolvedValue().Kind() == reflect.Uint || v.getResolvedValue().Kind() == reflect.Uint8 || v.getResolvedValue().Kind() == reflect.Uint16 || v.getResolvedValue().Kind() == reflect.Uint32 || v.getResolvedValue().Kind() == reflect.Uint64 }
[ "func", "(", "v", "*", "Value", ")", "IsInteger", "(", ")", "bool", "{", "return", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Int", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Int8", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Int16", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Int32", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Int64", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint8", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint16", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint32", "||", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint64", "\n", "}" ]
// IsInteger checks whether the underlying value is an integer
[ "IsInteger", "checks", "whether", "the", "underlying", "value", "is", "an", "integer" ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L60-L71
6,691
flosch/pongo2
value.go
Len
func (v *Value) Len() int { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: return v.getResolvedValue().Len() case reflect.String: runes := []rune(v.getResolvedValue().String()) return len(runes) default: logf("Value.Len() not available for type: %s\n", v.getResolvedValue().Kind().String()) return 0 } }
go
func (v *Value) Len() int { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: return v.getResolvedValue().Len() case reflect.String: runes := []rune(v.getResolvedValue().String()) return len(runes) default: logf("Value.Len() not available for type: %s\n", v.getResolvedValue().Kind().String()) return 0 } }
[ "func", "(", "v", "*", "Value", ")", "Len", "(", ")", "int", "{", "switch", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Array", ",", "reflect", ".", "Chan", ",", "reflect", ".", "Map", ",", "reflect", ".", "Slice", ":", "return", "v", ".", "getResolvedValue", "(", ")", ".", "Len", "(", ")", "\n", "case", "reflect", ".", "String", ":", "runes", ":=", "[", "]", "rune", "(", "v", ".", "getResolvedValue", "(", ")", ".", "String", "(", ")", ")", "\n", "return", "len", "(", "runes", ")", "\n", "default", ":", "logf", "(", "\"", "\\n", "\"", ",", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", ".", "String", "(", ")", ")", "\n", "return", "0", "\n", "}", "\n", "}" ]
// Len returns the length for an array, chan, map, slice or string. // Otherwise it will return 0.
[ "Len", "returns", "the", "length", "for", "an", "array", "chan", "map", "slice", "or", "string", ".", "Otherwise", "it", "will", "return", "0", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L253-L264
6,692
flosch/pongo2
value.go
Index
func (v *Value) Index(i int) *Value { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Slice: if i >= v.Len() { return AsValue(nil) } return AsValue(v.getResolvedValue().Index(i).Interface()) case reflect.String: //return AsValue(v.getResolvedValue().Slice(i, i+1).Interface()) s := v.getResolvedValue().String() runes := []rune(s) if i < len(runes) { return AsValue(string(runes[i])) } return AsValue("") default: logf("Value.Slice() not available for type: %s\n", v.getResolvedValue().Kind().String()) return AsValue([]int{}) } }
go
func (v *Value) Index(i int) *Value { switch v.getResolvedValue().Kind() { case reflect.Array, reflect.Slice: if i >= v.Len() { return AsValue(nil) } return AsValue(v.getResolvedValue().Index(i).Interface()) case reflect.String: //return AsValue(v.getResolvedValue().Slice(i, i+1).Interface()) s := v.getResolvedValue().String() runes := []rune(s) if i < len(runes) { return AsValue(string(runes[i])) } return AsValue("") default: logf("Value.Slice() not available for type: %s\n", v.getResolvedValue().Kind().String()) return AsValue([]int{}) } }
[ "func", "(", "v", "*", "Value", ")", "Index", "(", "i", "int", ")", "*", "Value", "{", "switch", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ":", "if", "i", ">=", "v", ".", "Len", "(", ")", "{", "return", "AsValue", "(", "nil", ")", "\n", "}", "\n", "return", "AsValue", "(", "v", ".", "getResolvedValue", "(", ")", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", ")", "\n", "case", "reflect", ".", "String", ":", "//return AsValue(v.getResolvedValue().Slice(i, i+1).Interface())", "s", ":=", "v", ".", "getResolvedValue", "(", ")", ".", "String", "(", ")", "\n", "runes", ":=", "[", "]", "rune", "(", "s", ")", "\n", "if", "i", "<", "len", "(", "runes", ")", "{", "return", "AsValue", "(", "string", "(", "runes", "[", "i", "]", ")", ")", "\n", "}", "\n", "return", "AsValue", "(", "\"", "\"", ")", "\n", "default", ":", "logf", "(", "\"", "\\n", "\"", ",", "v", ".", "getResolvedValue", "(", ")", ".", "Kind", "(", ")", ".", "String", "(", ")", ")", "\n", "return", "AsValue", "(", "[", "]", "int", "{", "}", ")", "\n", "}", "\n", "}" ]
// Index gets the i-th item of an array, slice or string. Otherwise // it will return NIL.
[ "Index", "gets", "the", "i", "-", "th", "item", "of", "an", "array", "slice", "or", "string", ".", "Otherwise", "it", "will", "return", "NIL", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L283-L302
6,693
flosch/pongo2
value.go
Interface
func (v *Value) Interface() interface{} { if v.val.IsValid() { return v.val.Interface() } return nil }
go
func (v *Value) Interface() interface{} { if v.val.IsValid() { return v.val.Interface() } return nil }
[ "func", "(", "v", "*", "Value", ")", "Interface", "(", ")", "interface", "{", "}", "{", "if", "v", ".", "val", ".", "IsValid", "(", ")", "{", "return", "v", ".", "val", ".", "Interface", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Interface gives you access to the underlying value.
[ "Interface", "gives", "you", "access", "to", "the", "underlying", "value", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L460-L465
6,694
flosch/pongo2
value.go
EqualValueTo
func (v *Value) EqualValueTo(other *Value) bool { // comparison of uint with int fails using .Interface()-comparison (see issue #64) if v.IsInteger() && other.IsInteger() { return v.Integer() == other.Integer() } return v.Interface() == other.Interface() }
go
func (v *Value) EqualValueTo(other *Value) bool { // comparison of uint with int fails using .Interface()-comparison (see issue #64) if v.IsInteger() && other.IsInteger() { return v.Integer() == other.Integer() } return v.Interface() == other.Interface() }
[ "func", "(", "v", "*", "Value", ")", "EqualValueTo", "(", "other", "*", "Value", ")", "bool", "{", "// comparison of uint with int fails using .Interface()-comparison (see issue #64)", "if", "v", ".", "IsInteger", "(", ")", "&&", "other", ".", "IsInteger", "(", ")", "{", "return", "v", ".", "Integer", "(", ")", "==", "other", ".", "Integer", "(", ")", "\n", "}", "\n", "return", "v", ".", "Interface", "(", ")", "==", "other", ".", "Interface", "(", ")", "\n", "}" ]
// EqualValueTo checks whether two values are containing the same value or object.
[ "EqualValueTo", "checks", "whether", "two", "values", "are", "containing", "the", "same", "value", "or", "object", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/value.go#L468-L474
6,695
flosch/pongo2
filters.go
MustApplyFilter
func MustApplyFilter(name string, value *Value, param *Value) *Value { val, err := ApplyFilter(name, value, param) if err != nil { panic(err) } return val }
go
func MustApplyFilter(name string, value *Value, param *Value) *Value { val, err := ApplyFilter(name, value, param) if err != nil { panic(err) } return val }
[ "func", "MustApplyFilter", "(", "name", "string", ",", "value", "*", "Value", ",", "param", "*", "Value", ")", "*", "Value", "{", "val", ",", "err", ":=", "ApplyFilter", "(", "name", ",", "value", ",", "param", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "val", "\n", "}" ]
// MustApplyFilter behaves like ApplyFilter, but panics on an error.
[ "MustApplyFilter", "behaves", "like", "ApplyFilter", "but", "panics", "on", "an", "error", "." ]
79872a7b27692599b259dc751bed8b03581dd0de
https://github.com/flosch/pongo2/blob/79872a7b27692599b259dc751bed8b03581dd0de/filters.go#L50-L56
6,696
aporeto-inc/trireme-lib
controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go
NewMockCollectorReader
func NewMockCollectorReader(ctrl *gomock.Controller) *MockCollectorReader { mock := &MockCollectorReader{ctrl: ctrl} mock.recorder = &MockCollectorReaderMockRecorder{mock} return mock }
go
func NewMockCollectorReader(ctrl *gomock.Controller) *MockCollectorReader { mock := &MockCollectorReader{ctrl: ctrl} mock.recorder = &MockCollectorReaderMockRecorder{mock} return mock }
[ "func", "NewMockCollectorReader", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockCollectorReader", "{", "mock", ":=", "&", "MockCollectorReader", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockCollectorReaderMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockCollectorReader creates a new mock instance // nolint
[ "NewMockCollectorReader", "creates", "a", "new", "mock", "instance", "nolint" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go#L29-L33
6,697
aporeto-inc/trireme-lib
controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go
GetAllRecords
func (mr *MockCollectorReaderMockRecorder) GetAllRecords() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllRecords", reflect.TypeOf((*MockCollectorReader)(nil).GetAllRecords)) }
go
func (mr *MockCollectorReaderMockRecorder) GetAllRecords() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllRecords", reflect.TypeOf((*MockCollectorReader)(nil).GetAllRecords)) }
[ "func", "(", "mr", "*", "MockCollectorReaderMockRecorder", ")", "GetAllRecords", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockCollectorReader", ")", "(", "nil", ")", ".", "GetAllRecords", ")", ")", "\n", "}" ]
// GetAllRecords indicates an expected call of GetAllRecords // nolint
[ "GetAllRecords", "indicates", "an", "expected", "call", "of", "GetAllRecords", "nolint" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go#L65-L67
6,698
aporeto-inc/trireme-lib
controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go
GetUserRecords
func (m *MockCollectorReader) GetUserRecords() map[string]*collector.UserRecord { ret := m.ctrl.Call(m, "GetUserRecords") ret0, _ := ret[0].(map[string]*collector.UserRecord) return ret0 }
go
func (m *MockCollectorReader) GetUserRecords() map[string]*collector.UserRecord { ret := m.ctrl.Call(m, "GetUserRecords") ret0, _ := ret[0].(map[string]*collector.UserRecord) return ret0 }
[ "func", "(", "m", "*", "MockCollectorReader", ")", "GetUserRecords", "(", ")", "map", "[", "string", "]", "*", "collector", ".", "UserRecord", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "(", "map", "[", "string", "]", "*", "collector", ".", "UserRecord", ")", "\n", "return", "ret0", "\n", "}" ]
// GetUserRecords mocks base method // nolint
[ "GetUserRecords", "mocks", "base", "method", "nolint" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go#L71-L75
6,699
aporeto-inc/trireme-lib
controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go
NewMockCollector
func NewMockCollector(ctrl *gomock.Controller) *MockCollector { mock := &MockCollector{ctrl: ctrl} mock.recorder = &MockCollectorMockRecorder{mock} return mock }
go
func NewMockCollector(ctrl *gomock.Controller) *MockCollector { mock := &MockCollector{ctrl: ctrl} mock.recorder = &MockCollectorMockRecorder{mock} return mock }
[ "func", "NewMockCollector", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockCollector", "{", "mock", ":=", "&", "MockCollector", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockCollectorMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockCollector creates a new mock instance // nolint
[ "NewMockCollector", "creates", "a", "new", "mock", "instance", "nolint" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/controller/pkg/remoteenforcer/internal/statscollector/mockstatscollector/mockstatscollector.go#L124-L128