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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
open-policy-agent/opa
internal/presentation/presentation.go
Bindings
func Bindings(w io.Writer, r Output) error { if r.Error != nil { return prettyError(w, r.Error) } for _, rs := range r.Result { if err := JSON(w, rs.Bindings); err != nil { return err } } return nil }
go
func Bindings(w io.Writer, r Output) error { if r.Error != nil { return prettyError(w, r.Error) } for _, rs := range r.Result { if err := JSON(w, rs.Bindings); err != nil { return err } } return nil }
[ "func", "Bindings", "(", "w", "io", ".", "Writer", ",", "r", "Output", ")", "error", "{", "if", "r", ".", "Error", "!=", "nil", "{", "return", "prettyError", "(", "w", ",", "r", ".", "Error", ")", "\n", "}", "\n", "for", "_", ",", "rs", ":=", "range", "r", ".", "Result", "{", "if", "err", ":=", "JSON", "(", "w", ",", "rs", ".", "Bindings", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Bindings prints the bindings from r to w.
[ "Bindings", "prints", "the", "bindings", "from", "r", "to", "w", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/internal/presentation/presentation.go#L137-L147
train
open-policy-agent/opa
internal/presentation/presentation.go
Values
func Values(w io.Writer, r Output) error { if r.Error != nil { return prettyError(w, r.Error) } for _, rs := range r.Result { line := make([]interface{}, len(rs.Expressions)) for i := range line { line[i] = rs.Expressions[i].Value } if err := JSON(os.Stdout, line); err != nil { return err } } return nil }
go
func Values(w io.Writer, r Output) error { if r.Error != nil { return prettyError(w, r.Error) } for _, rs := range r.Result { line := make([]interface{}, len(rs.Expressions)) for i := range line { line[i] = rs.Expressions[i].Value } if err := JSON(os.Stdout, line); err != nil { return err } } return nil }
[ "func", "Values", "(", "w", "io", ".", "Writer", ",", "r", "Output", ")", "error", "{", "if", "r", ".", "Error", "!=", "nil", "{", "return", "prettyError", "(", "w", ",", "r", ".", "Error", ")", "\n", "}", "\n", "for", "_", ",", "rs", ":=", "range", "r", ".", "Result", "{", "line", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "rs", ".", "Expressions", ")", ")", "\n", "for", "i", ":=", "range", "line", "{", "line", "[", "i", "]", "=", "rs", ".", "Expressions", "[", "i", "]", ".", "Value", "\n", "}", "\n", "if", "err", ":=", "JSON", "(", "os", ".", "Stdout", ",", "line", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Values prints the values from r to w.
[ "Values", "prints", "the", "values", "from", "r", "to", "w", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/internal/presentation/presentation.go#L150-L164
train
open-policy-agent/opa
internal/presentation/presentation.go
Pretty
func Pretty(w io.Writer, r Output) error { if len(r.Explanation) > 0 { if err := prettyExplanation(w, r.Explanation); err != nil { return err } } if r.Error != nil { if err := prettyError(w, r.Error); err != nil { return err } } else if r.undefined() { fmt.Fprintln(w, "undefined") } else if r.Result != nil { if err := prettyResult(w, r.Result, r.limit); err != nil { return err } } else if r.Partial != nil { if err := prettyPartial(w, r.Partial); err != nil { return err } } if r.Metrics != nil { if err := prettyMetrics(w, r.Metrics, r.limit); err != nil { return err } } if len(r.Profile) > 0 { if err := prettyProfile(w, r.Profile); err != nil { return err } } if r.Coverage != nil { if err := prettyCoverage(w, r.Coverage); err != nil { return err } } return nil }
go
func Pretty(w io.Writer, r Output) error { if len(r.Explanation) > 0 { if err := prettyExplanation(w, r.Explanation); err != nil { return err } } if r.Error != nil { if err := prettyError(w, r.Error); err != nil { return err } } else if r.undefined() { fmt.Fprintln(w, "undefined") } else if r.Result != nil { if err := prettyResult(w, r.Result, r.limit); err != nil { return err } } else if r.Partial != nil { if err := prettyPartial(w, r.Partial); err != nil { return err } } if r.Metrics != nil { if err := prettyMetrics(w, r.Metrics, r.limit); err != nil { return err } } if len(r.Profile) > 0 { if err := prettyProfile(w, r.Profile); err != nil { return err } } if r.Coverage != nil { if err := prettyCoverage(w, r.Coverage); err != nil { return err } } return nil }
[ "func", "Pretty", "(", "w", "io", ".", "Writer", ",", "r", "Output", ")", "error", "{", "if", "len", "(", "r", ".", "Explanation", ")", ">", "0", "{", "if", "err", ":=", "prettyExplanation", "(", "w", ",", "r", ".", "Explanation", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "r", ".", "Error", "!=", "nil", "{", "if", "err", ":=", "prettyError", "(", "w", ",", "r", ".", "Error", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "r", ".", "undefined", "(", ")", "{", "fmt", ".", "Fprintln", "(", "w", ",", "\"", "\"", ")", "\n", "}", "else", "if", "r", ".", "Result", "!=", "nil", "{", "if", "err", ":=", "prettyResult", "(", "w", ",", "r", ".", "Result", ",", "r", ".", "limit", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "r", ".", "Partial", "!=", "nil", "{", "if", "err", ":=", "prettyPartial", "(", "w", ",", "r", ".", "Partial", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "r", ".", "Metrics", "!=", "nil", "{", "if", "err", ":=", "prettyMetrics", "(", "w", ",", "r", ".", "Metrics", ",", "r", ".", "limit", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "r", ".", "Profile", ")", ">", "0", "{", "if", "err", ":=", "prettyProfile", "(", "w", ",", "r", ".", "Profile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "r", ".", "Coverage", "!=", "nil", "{", "if", "err", ":=", "prettyCoverage", "(", "w", ",", "r", ".", "Coverage", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Pretty prints all of r to w in a human-readable format.
[ "Pretty", "prints", "all", "of", "r", "to", "w", "in", "a", "human", "-", "readable", "format", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/internal/presentation/presentation.go#L167-L204
train
open-policy-agent/opa
topdown/http.go
addHeaders
func addHeaders(req *http.Request, headers map[string]interface{}) (bool, error) { for k, v := range headers { // Type assertion header, ok := v.(string) if ok { req.Header.Add(k, header) } else { return false, fmt.Errorf("invalid type for headers value") } } return true, nil }
go
func addHeaders(req *http.Request, headers map[string]interface{}) (bool, error) { for k, v := range headers { // Type assertion header, ok := v.(string) if ok { req.Header.Add(k, header) } else { return false, fmt.Errorf("invalid type for headers value") } } return true, nil }
[ "func", "addHeaders", "(", "req", "*", "http", ".", "Request", ",", "headers", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "bool", ",", "error", ")", "{", "for", "k", ",", "v", ":=", "range", "headers", "{", "// Type assertion", "header", ",", "ok", ":=", "v", ".", "(", "string", ")", "\n", "if", "ok", "{", "req", ".", "Header", ".", "Add", "(", "k", ",", "header", ")", "\n", "}", "else", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// Adds custom headers to a new HTTP request.
[ "Adds", "custom", "headers", "to", "a", "new", "HTTP", "request", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/http.go#L109-L120
train
open-policy-agent/opa
topdown/http.go
checkCache
func checkCache(method string, url string, bctx BuiltinContext) ast.Value { key := getCtxKey(method, url) val, ok := bctx.Cache.Get(key) if ok { return val.(ast.Value) } return nil }
go
func checkCache(method string, url string, bctx BuiltinContext) ast.Value { key := getCtxKey(method, url) val, ok := bctx.Cache.Get(key) if ok { return val.(ast.Value) } return nil }
[ "func", "checkCache", "(", "method", "string", ",", "url", "string", ",", "bctx", "BuiltinContext", ")", "ast", ".", "Value", "{", "key", ":=", "getCtxKey", "(", "method", ",", "url", ")", "\n\n", "val", ",", "ok", ":=", "bctx", ".", "Cache", ".", "Get", "(", "key", ")", "\n", "if", "ok", "{", "return", "val", ".", "(", "ast", ".", "Value", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkCache checks for the given key's value in the cache
[ "checkCache", "checks", "for", "the", "given", "key", "s", "value", "in", "the", "cache" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/http.go#L330-L338
train
open-policy-agent/opa
plugins/discovery/config.go
ParseConfig
func ParseConfig(bs []byte, services []string) (*Config, error) { if bs == nil { return nil, nil } var result Config if err := util.Unmarshal(bs, &result); err != nil { return nil, err } return &result, result.validateAndInjectDefaults(services) }
go
func ParseConfig(bs []byte, services []string) (*Config, error) { if bs == nil { return nil, nil } var result Config if err := util.Unmarshal(bs, &result); err != nil { return nil, err } return &result, result.validateAndInjectDefaults(services) }
[ "func", "ParseConfig", "(", "bs", "[", "]", "byte", ",", "services", "[", "]", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "if", "bs", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "var", "result", "Config", "\n\n", "if", "err", ":=", "util", ".", "Unmarshal", "(", "bs", ",", "&", "result", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "result", ",", "result", ".", "validateAndInjectDefaults", "(", "services", ")", "\n", "}" ]
// ParseConfig returns a valid Config object with defaults injected.
[ "ParseConfig", "returns", "a", "valid", "Config", "object", "with", "defaults", "injected", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/discovery/config.go#L28-L41
train
open-policy-agent/opa
topdown/copypropagation/copypropagation.go
New
func New(livevars ast.VarSet) *CopyPropagator { sorted := make([]ast.Var, 0, len(livevars)) for v := range livevars { sorted = append(sorted, v) } sort.Slice(sorted, func(i, j int) bool { return sorted[i].Compare(sorted[j]) < 0 }) return &CopyPropagator{livevars: livevars, sorted: sorted} }
go
func New(livevars ast.VarSet) *CopyPropagator { sorted := make([]ast.Var, 0, len(livevars)) for v := range livevars { sorted = append(sorted, v) } sort.Slice(sorted, func(i, j int) bool { return sorted[i].Compare(sorted[j]) < 0 }) return &CopyPropagator{livevars: livevars, sorted: sorted} }
[ "func", "New", "(", "livevars", "ast", ".", "VarSet", ")", "*", "CopyPropagator", "{", "sorted", ":=", "make", "(", "[", "]", "ast", ".", "Var", ",", "0", ",", "len", "(", "livevars", ")", ")", "\n", "for", "v", ":=", "range", "livevars", "{", "sorted", "=", "append", "(", "sorted", ",", "v", ")", "\n", "}", "\n\n", "sort", ".", "Slice", "(", "sorted", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "sorted", "[", "i", "]", ".", "Compare", "(", "sorted", "[", "j", "]", ")", "<", "0", "\n", "}", ")", "\n\n", "return", "&", "CopyPropagator", "{", "livevars", ":", "livevars", ",", "sorted", ":", "sorted", "}", "\n", "}" ]
// New returns a new CopyPropagator that optimizes queries while preserving vars // in the livevars set.
[ "New", "returns", "a", "new", "CopyPropagator", "that", "optimizes", "queries", "while", "preserving", "vars", "in", "the", "livevars", "set", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/copypropagation/copypropagation.go#L37-L49
train
open-policy-agent/opa
topdown/copypropagation/copypropagation.go
WithEnsureNonEmptyBody
func (p *CopyPropagator) WithEnsureNonEmptyBody(yes bool) *CopyPropagator { p.ensureNonEmptyBody = yes return p }
go
func (p *CopyPropagator) WithEnsureNonEmptyBody(yes bool) *CopyPropagator { p.ensureNonEmptyBody = yes return p }
[ "func", "(", "p", "*", "CopyPropagator", ")", "WithEnsureNonEmptyBody", "(", "yes", "bool", ")", "*", "CopyPropagator", "{", "p", ".", "ensureNonEmptyBody", "=", "yes", "\n", "return", "p", "\n", "}" ]
// WithEnsureNonEmptyBody configures p to ensure that results are always non-empty.
[ "WithEnsureNonEmptyBody", "configures", "p", "to", "ensure", "that", "results", "are", "always", "non", "-", "empty", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/copypropagation/copypropagation.go#L52-L55
train
open-policy-agent/opa
topdown/copypropagation/copypropagation.go
Apply
func (p *CopyPropagator) Apply(query ast.Body) (result ast.Body) { uf, ok := makeDisjointSets(p.livevars, query) if !ok { return query } // Compute set of vars that appear in the head of refs in the query. If a var // is dereferenced, we cannot plug it with a constant value so the constant on // the union-find root must be unset (e.g., [1][0] is not legal.) headvars := ast.NewVarSet() ast.WalkRefs(query, func(x ast.Ref) bool { if v, ok := x[0].Value.(ast.Var); ok { if root, ok := uf.Find(v); ok { root.constant = nil headvars.Add(root.key) } else { headvars.Add(v) } } return false }) bindings := map[ast.Var]*binding{} for _, expr := range query { // Deep copy the expr as it may be mutated below. The caller that is running // copy propagation may hold references to the expr. expr = expr.Copy() pctx := &plugContext{ bindings: bindings, uf: uf, negated: expr.Negated, headvars: headvars, } if p.plugBindings(pctx, expr) { if p.updateBindings(pctx, expr) { result.Append(expr) } } } // Run post-processing step on the query to ensure that all live vars are bound // in the result. The plugging that happens above substitutes all vars in the // same set with the root. // // This step should run before the next step to prevent unnecessary bindings // from being added to the result. For example: // // - Given the following result: <empty> // - Given the following bindings: x/input.x and y/input // - Given the following liveset: {x} // // If this step were to run AFTER the following step, the output would be: // // x = input.x; y = input // // Even though y = input is not required. for _, v := range p.sorted { if root, ok := uf.Find(v); ok { if root.constant != nil { result.Append(ast.Equality.Expr(ast.NewTerm(v), root.constant)) } else if b, ok := bindings[root.key]; ok { result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(b.v))) } else if root.key != v { result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(root.key))) } } } // Run post-processing step on query to ensure that all killed exprs are // accounted for. If an expr is killed but the binding is never used, the query // must still include the expr. For example, given the query 'input.x = a' and // an empty livevar set, the result must include the ref input.x otherwise the // query could be satisfied without input.x being defined. When exprs are // killed we initialize the binding counter to zero and then increment it each // time the binding is substituted. if the binding was never substituted it // means the binding value must be added back into the query. for _, b := range sortbindings(bindings) { if !b.containedIn(result) { result.Append(ast.Equality.Expr(ast.NewTerm(b.k), ast.NewTerm(b.v))) } } if p.ensureNonEmptyBody && len(result) == 0 { result = append(result, ast.NewExpr(ast.BooleanTerm(true))) } return result }
go
func (p *CopyPropagator) Apply(query ast.Body) (result ast.Body) { uf, ok := makeDisjointSets(p.livevars, query) if !ok { return query } // Compute set of vars that appear in the head of refs in the query. If a var // is dereferenced, we cannot plug it with a constant value so the constant on // the union-find root must be unset (e.g., [1][0] is not legal.) headvars := ast.NewVarSet() ast.WalkRefs(query, func(x ast.Ref) bool { if v, ok := x[0].Value.(ast.Var); ok { if root, ok := uf.Find(v); ok { root.constant = nil headvars.Add(root.key) } else { headvars.Add(v) } } return false }) bindings := map[ast.Var]*binding{} for _, expr := range query { // Deep copy the expr as it may be mutated below. The caller that is running // copy propagation may hold references to the expr. expr = expr.Copy() pctx := &plugContext{ bindings: bindings, uf: uf, negated: expr.Negated, headvars: headvars, } if p.plugBindings(pctx, expr) { if p.updateBindings(pctx, expr) { result.Append(expr) } } } // Run post-processing step on the query to ensure that all live vars are bound // in the result. The plugging that happens above substitutes all vars in the // same set with the root. // // This step should run before the next step to prevent unnecessary bindings // from being added to the result. For example: // // - Given the following result: <empty> // - Given the following bindings: x/input.x and y/input // - Given the following liveset: {x} // // If this step were to run AFTER the following step, the output would be: // // x = input.x; y = input // // Even though y = input is not required. for _, v := range p.sorted { if root, ok := uf.Find(v); ok { if root.constant != nil { result.Append(ast.Equality.Expr(ast.NewTerm(v), root.constant)) } else if b, ok := bindings[root.key]; ok { result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(b.v))) } else if root.key != v { result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(root.key))) } } } // Run post-processing step on query to ensure that all killed exprs are // accounted for. If an expr is killed but the binding is never used, the query // must still include the expr. For example, given the query 'input.x = a' and // an empty livevar set, the result must include the ref input.x otherwise the // query could be satisfied without input.x being defined. When exprs are // killed we initialize the binding counter to zero and then increment it each // time the binding is substituted. if the binding was never substituted it // means the binding value must be added back into the query. for _, b := range sortbindings(bindings) { if !b.containedIn(result) { result.Append(ast.Equality.Expr(ast.NewTerm(b.k), ast.NewTerm(b.v))) } } if p.ensureNonEmptyBody && len(result) == 0 { result = append(result, ast.NewExpr(ast.BooleanTerm(true))) } return result }
[ "func", "(", "p", "*", "CopyPropagator", ")", "Apply", "(", "query", "ast", ".", "Body", ")", "(", "result", "ast", ".", "Body", ")", "{", "uf", ",", "ok", ":=", "makeDisjointSets", "(", "p", ".", "livevars", ",", "query", ")", "\n", "if", "!", "ok", "{", "return", "query", "\n", "}", "\n\n", "// Compute set of vars that appear in the head of refs in the query. If a var", "// is dereferenced, we cannot plug it with a constant value so the constant on", "// the union-find root must be unset (e.g., [1][0] is not legal.)", "headvars", ":=", "ast", ".", "NewVarSet", "(", ")", "\n", "ast", ".", "WalkRefs", "(", "query", ",", "func", "(", "x", "ast", ".", "Ref", ")", "bool", "{", "if", "v", ",", "ok", ":=", "x", "[", "0", "]", ".", "Value", ".", "(", "ast", ".", "Var", ")", ";", "ok", "{", "if", "root", ",", "ok", ":=", "uf", ".", "Find", "(", "v", ")", ";", "ok", "{", "root", ".", "constant", "=", "nil", "\n", "headvars", ".", "Add", "(", "root", ".", "key", ")", "\n", "}", "else", "{", "headvars", ".", "Add", "(", "v", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n\n", "bindings", ":=", "map", "[", "ast", ".", "Var", "]", "*", "binding", "{", "}", "\n\n", "for", "_", ",", "expr", ":=", "range", "query", "{", "// Deep copy the expr as it may be mutated below. The caller that is running", "// copy propagation may hold references to the expr.", "expr", "=", "expr", ".", "Copy", "(", ")", "\n\n", "pctx", ":=", "&", "plugContext", "{", "bindings", ":", "bindings", ",", "uf", ":", "uf", ",", "negated", ":", "expr", ".", "Negated", ",", "headvars", ":", "headvars", ",", "}", "\n\n", "if", "p", ".", "plugBindings", "(", "pctx", ",", "expr", ")", "{", "if", "p", ".", "updateBindings", "(", "pctx", ",", "expr", ")", "{", "result", ".", "Append", "(", "expr", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Run post-processing step on the query to ensure that all live vars are bound", "// in the result. The plugging that happens above substitutes all vars in the", "// same set with the root.", "//", "// This step should run before the next step to prevent unnecessary bindings", "// from being added to the result. For example:", "//", "// - Given the following result: <empty>", "// - Given the following bindings: x/input.x and y/input", "// - Given the following liveset: {x}", "//", "// If this step were to run AFTER the following step, the output would be:", "//", "//\tx = input.x; y = input", "//", "// Even though y = input is not required.", "for", "_", ",", "v", ":=", "range", "p", ".", "sorted", "{", "if", "root", ",", "ok", ":=", "uf", ".", "Find", "(", "v", ")", ";", "ok", "{", "if", "root", ".", "constant", "!=", "nil", "{", "result", ".", "Append", "(", "ast", ".", "Equality", ".", "Expr", "(", "ast", ".", "NewTerm", "(", "v", ")", ",", "root", ".", "constant", ")", ")", "\n", "}", "else", "if", "b", ",", "ok", ":=", "bindings", "[", "root", ".", "key", "]", ";", "ok", "{", "result", ".", "Append", "(", "ast", ".", "Equality", ".", "Expr", "(", "ast", ".", "NewTerm", "(", "v", ")", ",", "ast", ".", "NewTerm", "(", "b", ".", "v", ")", ")", ")", "\n", "}", "else", "if", "root", ".", "key", "!=", "v", "{", "result", ".", "Append", "(", "ast", ".", "Equality", ".", "Expr", "(", "ast", ".", "NewTerm", "(", "v", ")", ",", "ast", ".", "NewTerm", "(", "root", ".", "key", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Run post-processing step on query to ensure that all killed exprs are", "// accounted for. If an expr is killed but the binding is never used, the query", "// must still include the expr. For example, given the query 'input.x = a' and", "// an empty livevar set, the result must include the ref input.x otherwise the", "// query could be satisfied without input.x being defined. When exprs are", "// killed we initialize the binding counter to zero and then increment it each", "// time the binding is substituted. if the binding was never substituted it", "// means the binding value must be added back into the query.", "for", "_", ",", "b", ":=", "range", "sortbindings", "(", "bindings", ")", "{", "if", "!", "b", ".", "containedIn", "(", "result", ")", "{", "result", ".", "Append", "(", "ast", ".", "Equality", ".", "Expr", "(", "ast", ".", "NewTerm", "(", "b", ".", "k", ")", ",", "ast", ".", "NewTerm", "(", "b", ".", "v", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "p", ".", "ensureNonEmptyBody", "&&", "len", "(", "result", ")", "==", "0", "{", "result", "=", "append", "(", "result", ",", "ast", ".", "NewExpr", "(", "ast", ".", "BooleanTerm", "(", "true", ")", ")", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Apply executes the copy propagation optimization and returns a new query.
[ "Apply", "executes", "the", "copy", "propagation", "optimization", "and", "returns", "a", "new", "query", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/copypropagation/copypropagation.go#L58-L150
train
open-policy-agent/opa
topdown/copypropagation/copypropagation.go
plugBindings
func (p *CopyPropagator) plugBindings(pctx *plugContext, x interface{}) bool { // Kill single term expressions that are in the binding list. They will be // re-added during post-processing if needed. if expr, ok := x.(*ast.Expr); ok { if term, ok := expr.Terms.(*ast.Term); ok { if v, ok := term.Value.(ast.Var); ok { if root, ok := pctx.uf.Find(v); ok { if _, ok := pctx.bindings[root.key]; ok { return false } } } } } ast.WalkTerms(x, func(t *ast.Term) bool { // Apply union-find to remove redundant variables from input. switch v := t.Value.(type) { case ast.Var: if root, ok := pctx.uf.Find(v); ok { t.Value = root.Value() } case ast.Ref: if root, ok := pctx.uf.Find(v[0].Value.(ast.Var)); ok { v[0].Value = root.Value() } } // Apply binding list to substitute remaining vars. switch v := t.Value.(type) { case ast.Var: if b, ok := pctx.bindings[v]; ok { if !pctx.negated || b.v.IsGround() { t.Value = b.v } return true } case ast.Ref: // Refs require special handling. If the head of the ref was killed, then the // rest of the ref must be concatenated with the new base. // // Invariant: ref heads can only be replaced by refs (not calls). if b, ok := pctx.bindings[v[0].Value.(ast.Var)]; ok { if !pctx.negated || b.v.IsGround() { t.Value = b.v.(ast.Ref).Concat(v[1:]) } } for i := 1; i < len(v); i++ { p.plugBindings(pctx, v[i]) } return true } return false }) return true }
go
func (p *CopyPropagator) plugBindings(pctx *plugContext, x interface{}) bool { // Kill single term expressions that are in the binding list. They will be // re-added during post-processing if needed. if expr, ok := x.(*ast.Expr); ok { if term, ok := expr.Terms.(*ast.Term); ok { if v, ok := term.Value.(ast.Var); ok { if root, ok := pctx.uf.Find(v); ok { if _, ok := pctx.bindings[root.key]; ok { return false } } } } } ast.WalkTerms(x, func(t *ast.Term) bool { // Apply union-find to remove redundant variables from input. switch v := t.Value.(type) { case ast.Var: if root, ok := pctx.uf.Find(v); ok { t.Value = root.Value() } case ast.Ref: if root, ok := pctx.uf.Find(v[0].Value.(ast.Var)); ok { v[0].Value = root.Value() } } // Apply binding list to substitute remaining vars. switch v := t.Value.(type) { case ast.Var: if b, ok := pctx.bindings[v]; ok { if !pctx.negated || b.v.IsGround() { t.Value = b.v } return true } case ast.Ref: // Refs require special handling. If the head of the ref was killed, then the // rest of the ref must be concatenated with the new base. // // Invariant: ref heads can only be replaced by refs (not calls). if b, ok := pctx.bindings[v[0].Value.(ast.Var)]; ok { if !pctx.negated || b.v.IsGround() { t.Value = b.v.(ast.Ref).Concat(v[1:]) } } for i := 1; i < len(v); i++ { p.plugBindings(pctx, v[i]) } return true } return false }) return true }
[ "func", "(", "p", "*", "CopyPropagator", ")", "plugBindings", "(", "pctx", "*", "plugContext", ",", "x", "interface", "{", "}", ")", "bool", "{", "// Kill single term expressions that are in the binding list. They will be", "// re-added during post-processing if needed.", "if", "expr", ",", "ok", ":=", "x", ".", "(", "*", "ast", ".", "Expr", ")", ";", "ok", "{", "if", "term", ",", "ok", ":=", "expr", ".", "Terms", ".", "(", "*", "ast", ".", "Term", ")", ";", "ok", "{", "if", "v", ",", "ok", ":=", "term", ".", "Value", ".", "(", "ast", ".", "Var", ")", ";", "ok", "{", "if", "root", ",", "ok", ":=", "pctx", ".", "uf", ".", "Find", "(", "v", ")", ";", "ok", "{", "if", "_", ",", "ok", ":=", "pctx", ".", "bindings", "[", "root", ".", "key", "]", ";", "ok", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "ast", ".", "WalkTerms", "(", "x", ",", "func", "(", "t", "*", "ast", ".", "Term", ")", "bool", "{", "// Apply union-find to remove redundant variables from input.", "switch", "v", ":=", "t", ".", "Value", ".", "(", "type", ")", "{", "case", "ast", ".", "Var", ":", "if", "root", ",", "ok", ":=", "pctx", ".", "uf", ".", "Find", "(", "v", ")", ";", "ok", "{", "t", ".", "Value", "=", "root", ".", "Value", "(", ")", "\n", "}", "\n", "case", "ast", ".", "Ref", ":", "if", "root", ",", "ok", ":=", "pctx", ".", "uf", ".", "Find", "(", "v", "[", "0", "]", ".", "Value", ".", "(", "ast", ".", "Var", ")", ")", ";", "ok", "{", "v", "[", "0", "]", ".", "Value", "=", "root", ".", "Value", "(", ")", "\n", "}", "\n", "}", "\n", "// Apply binding list to substitute remaining vars.", "switch", "v", ":=", "t", ".", "Value", ".", "(", "type", ")", "{", "case", "ast", ".", "Var", ":", "if", "b", ",", "ok", ":=", "pctx", ".", "bindings", "[", "v", "]", ";", "ok", "{", "if", "!", "pctx", ".", "negated", "||", "b", ".", "v", ".", "IsGround", "(", ")", "{", "t", ".", "Value", "=", "b", ".", "v", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "case", "ast", ".", "Ref", ":", "// Refs require special handling. If the head of the ref was killed, then the", "// rest of the ref must be concatenated with the new base.", "//", "// Invariant: ref heads can only be replaced by refs (not calls).", "if", "b", ",", "ok", ":=", "pctx", ".", "bindings", "[", "v", "[", "0", "]", ".", "Value", ".", "(", "ast", ".", "Var", ")", "]", ";", "ok", "{", "if", "!", "pctx", ".", "negated", "||", "b", ".", "v", ".", "IsGround", "(", ")", "{", "t", ".", "Value", "=", "b", ".", "v", ".", "(", "ast", ".", "Ref", ")", ".", "Concat", "(", "v", "[", "1", ":", "]", ")", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "v", ")", ";", "i", "++", "{", "p", ".", "plugBindings", "(", "pctx", ",", "v", "[", "i", "]", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n\n", "return", "true", "\n", "}" ]
// plugBindings applies the binding list and union-find to x. This process // removes as many variables as possible.
[ "plugBindings", "applies", "the", "binding", "list", "and", "union", "-", "find", "to", "x", ".", "This", "process", "removes", "as", "many", "variables", "as", "possible", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/copypropagation/copypropagation.go#L154-L210
train
open-policy-agent/opa
topdown/copypropagation/copypropagation.go
updateBindings
func (p *CopyPropagator) updateBindings(pctx *plugContext, expr *ast.Expr) bool { if pctx.negated || len(expr.With) > 0 { return true } if expr.IsEquality() { a, b := expr.Operand(0), expr.Operand(1) if a.Equal(b) { return false } k, v, keep := p.updateBindingsEq(a, b) if !keep { if v != nil { pctx.bindings[k] = newbinding(k, v) } return false } } else if expr.IsCall() { terms := expr.Terms.([]*ast.Term) output := terms[len(terms)-1] if k, ok := output.Value.(ast.Var); ok && !p.livevars.Contains(k) && !pctx.headvars.Contains(k) { pctx.bindings[k] = newbinding(k, ast.CallTerm(terms[:len(terms)-1]...).Value) return false } } return !isNoop(expr) }
go
func (p *CopyPropagator) updateBindings(pctx *plugContext, expr *ast.Expr) bool { if pctx.negated || len(expr.With) > 0 { return true } if expr.IsEquality() { a, b := expr.Operand(0), expr.Operand(1) if a.Equal(b) { return false } k, v, keep := p.updateBindingsEq(a, b) if !keep { if v != nil { pctx.bindings[k] = newbinding(k, v) } return false } } else if expr.IsCall() { terms := expr.Terms.([]*ast.Term) output := terms[len(terms)-1] if k, ok := output.Value.(ast.Var); ok && !p.livevars.Contains(k) && !pctx.headvars.Contains(k) { pctx.bindings[k] = newbinding(k, ast.CallTerm(terms[:len(terms)-1]...).Value) return false } } return !isNoop(expr) }
[ "func", "(", "p", "*", "CopyPropagator", ")", "updateBindings", "(", "pctx", "*", "plugContext", ",", "expr", "*", "ast", ".", "Expr", ")", "bool", "{", "if", "pctx", ".", "negated", "||", "len", "(", "expr", ".", "With", ")", ">", "0", "{", "return", "true", "\n", "}", "\n", "if", "expr", ".", "IsEquality", "(", ")", "{", "a", ",", "b", ":=", "expr", ".", "Operand", "(", "0", ")", ",", "expr", ".", "Operand", "(", "1", ")", "\n", "if", "a", ".", "Equal", "(", "b", ")", "{", "return", "false", "\n", "}", "\n", "k", ",", "v", ",", "keep", ":=", "p", ".", "updateBindingsEq", "(", "a", ",", "b", ")", "\n", "if", "!", "keep", "{", "if", "v", "!=", "nil", "{", "pctx", ".", "bindings", "[", "k", "]", "=", "newbinding", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "}", "else", "if", "expr", ".", "IsCall", "(", ")", "{", "terms", ":=", "expr", ".", "Terms", ".", "(", "[", "]", "*", "ast", ".", "Term", ")", "\n", "output", ":=", "terms", "[", "len", "(", "terms", ")", "-", "1", "]", "\n", "if", "k", ",", "ok", ":=", "output", ".", "Value", ".", "(", "ast", ".", "Var", ")", ";", "ok", "&&", "!", "p", ".", "livevars", ".", "Contains", "(", "k", ")", "&&", "!", "pctx", ".", "headvars", ".", "Contains", "(", "k", ")", "{", "pctx", ".", "bindings", "[", "k", "]", "=", "newbinding", "(", "k", ",", "ast", ".", "CallTerm", "(", "terms", "[", ":", "len", "(", "terms", ")", "-", "1", "]", "...", ")", ".", "Value", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "return", "!", "isNoop", "(", "expr", ")", "\n", "}" ]
// updateBindings returns false if the expression can be killed. If the // expression is killed, the binding list is updated to map a var to value.
[ "updateBindings", "returns", "false", "if", "the", "expression", "can", "be", "killed", ".", "If", "the", "expression", "is", "killed", "the", "binding", "list", "is", "updated", "to", "map", "a", "var", "to", "value", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/copypropagation/copypropagation.go#L214-L239
train
open-policy-agent/opa
ast/compile.go
WithPackage
func (qc *QueryContext) WithPackage(pkg *Package) *QueryContext { if qc == nil { qc = NewQueryContext() } qc.Package = pkg return qc }
go
func (qc *QueryContext) WithPackage(pkg *Package) *QueryContext { if qc == nil { qc = NewQueryContext() } qc.Package = pkg return qc }
[ "func", "(", "qc", "*", "QueryContext", ")", "WithPackage", "(", "pkg", "*", "Package", ")", "*", "QueryContext", "{", "if", "qc", "==", "nil", "{", "qc", "=", "NewQueryContext", "(", ")", "\n", "}", "\n", "qc", ".", "Package", "=", "pkg", "\n", "return", "qc", "\n", "}" ]
// WithPackage sets the pkg on qc.
[ "WithPackage", "sets", "the", "pkg", "on", "qc", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L109-L115
train
open-policy-agent/opa
ast/compile.go
WithImports
func (qc *QueryContext) WithImports(imports []*Import) *QueryContext { if qc == nil { qc = NewQueryContext() } qc.Imports = imports return qc }
go
func (qc *QueryContext) WithImports(imports []*Import) *QueryContext { if qc == nil { qc = NewQueryContext() } qc.Imports = imports return qc }
[ "func", "(", "qc", "*", "QueryContext", ")", "WithImports", "(", "imports", "[", "]", "*", "Import", ")", "*", "QueryContext", "{", "if", "qc", "==", "nil", "{", "qc", "=", "NewQueryContext", "(", ")", "\n", "}", "\n", "qc", ".", "Imports", "=", "imports", "\n", "return", "qc", "\n", "}" ]
// WithImports sets the imports on qc.
[ "WithImports", "sets", "the", "imports", "on", "qc", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L118-L124
train
open-policy-agent/opa
ast/compile.go
Copy
func (qc *QueryContext) Copy() *QueryContext { if qc == nil { return nil } cpy := *qc if cpy.Package != nil { cpy.Package = qc.Package.Copy() } cpy.Imports = make([]*Import, len(qc.Imports)) for i := range qc.Imports { cpy.Imports[i] = qc.Imports[i].Copy() } return &cpy }
go
func (qc *QueryContext) Copy() *QueryContext { if qc == nil { return nil } cpy := *qc if cpy.Package != nil { cpy.Package = qc.Package.Copy() } cpy.Imports = make([]*Import, len(qc.Imports)) for i := range qc.Imports { cpy.Imports[i] = qc.Imports[i].Copy() } return &cpy }
[ "func", "(", "qc", "*", "QueryContext", ")", "Copy", "(", ")", "*", "QueryContext", "{", "if", "qc", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "cpy", ":=", "*", "qc", "\n", "if", "cpy", ".", "Package", "!=", "nil", "{", "cpy", ".", "Package", "=", "qc", ".", "Package", ".", "Copy", "(", ")", "\n", "}", "\n", "cpy", ".", "Imports", "=", "make", "(", "[", "]", "*", "Import", ",", "len", "(", "qc", ".", "Imports", ")", ")", "\n", "for", "i", ":=", "range", "qc", ".", "Imports", "{", "cpy", ".", "Imports", "[", "i", "]", "=", "qc", ".", "Imports", "[", "i", "]", ".", "Copy", "(", ")", "\n", "}", "\n", "return", "&", "cpy", "\n", "}" ]
// Copy returns a deep copy of qc.
[ "Copy", "returns", "a", "deep", "copy", "of", "qc", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L127-L140
train
open-policy-agent/opa
ast/compile.go
NewCompiler
func NewCompiler() *Compiler { c := &Compiler{ Modules: map[string]*Module{}, TypeEnv: NewTypeEnv(), ruleIndices: util.NewHashMap(func(a, b util.T) bool { r1, r2 := a.(Ref), b.(Ref) return r1.Equal(r2) }, func(x util.T) int { return x.(Ref).Hash() }), maxErrs: CompileErrorLimitDefault, after: map[string][]CompilerStage{}, } c.ModuleTree = NewModuleTree(nil) c.RuleTree = NewRuleTree(c.ModuleTree) checker := newTypeChecker() c.TypeEnv = checker.checkLanguageBuiltins() c.stages = []struct { name string f func() }{ // Reference resolution should run first as it may be used to lazily // load additional modules. If any stages run before resolution, they // need to be re-run after resolution. {"ResolveRefs", c.resolveAllRefs}, {"RewriteAssignments", c.rewriteLocalAssignments}, {"RewriteExprTerms", c.rewriteExprTerms}, {"SetModuleTree", c.setModuleTree}, {"SetRuleTree", c.setRuleTree}, {"SetGraph", c.setGraph}, {"RewriteComprehensionTerms", c.rewriteComprehensionTerms}, {"RewriteRefsInHead", c.rewriteRefsInHead}, {"RewriteWithValues", c.rewriteWithModifiers}, {"CheckRuleConflicts", c.checkRuleConflicts}, {"CheckSafetyRuleHeads", c.checkSafetyRuleHeads}, {"CheckSafetyRuleBodies", c.checkSafetyRuleBodies}, {"RewriteEquals", c.rewriteEquals}, {"RewriteDynamicTerms", c.rewriteDynamicTerms}, {"CheckRecursion", c.checkRecursion}, {"CheckTypes", c.checkTypes}, {"BuildRuleIndices", c.buildRuleIndices}, } return c }
go
func NewCompiler() *Compiler { c := &Compiler{ Modules: map[string]*Module{}, TypeEnv: NewTypeEnv(), ruleIndices: util.NewHashMap(func(a, b util.T) bool { r1, r2 := a.(Ref), b.(Ref) return r1.Equal(r2) }, func(x util.T) int { return x.(Ref).Hash() }), maxErrs: CompileErrorLimitDefault, after: map[string][]CompilerStage{}, } c.ModuleTree = NewModuleTree(nil) c.RuleTree = NewRuleTree(c.ModuleTree) checker := newTypeChecker() c.TypeEnv = checker.checkLanguageBuiltins() c.stages = []struct { name string f func() }{ // Reference resolution should run first as it may be used to lazily // load additional modules. If any stages run before resolution, they // need to be re-run after resolution. {"ResolveRefs", c.resolveAllRefs}, {"RewriteAssignments", c.rewriteLocalAssignments}, {"RewriteExprTerms", c.rewriteExprTerms}, {"SetModuleTree", c.setModuleTree}, {"SetRuleTree", c.setRuleTree}, {"SetGraph", c.setGraph}, {"RewriteComprehensionTerms", c.rewriteComprehensionTerms}, {"RewriteRefsInHead", c.rewriteRefsInHead}, {"RewriteWithValues", c.rewriteWithModifiers}, {"CheckRuleConflicts", c.checkRuleConflicts}, {"CheckSafetyRuleHeads", c.checkSafetyRuleHeads}, {"CheckSafetyRuleBodies", c.checkSafetyRuleBodies}, {"RewriteEquals", c.rewriteEquals}, {"RewriteDynamicTerms", c.rewriteDynamicTerms}, {"CheckRecursion", c.checkRecursion}, {"CheckTypes", c.checkTypes}, {"BuildRuleIndices", c.buildRuleIndices}, } return c }
[ "func", "NewCompiler", "(", ")", "*", "Compiler", "{", "c", ":=", "&", "Compiler", "{", "Modules", ":", "map", "[", "string", "]", "*", "Module", "{", "}", ",", "TypeEnv", ":", "NewTypeEnv", "(", ")", ",", "ruleIndices", ":", "util", ".", "NewHashMap", "(", "func", "(", "a", ",", "b", "util", ".", "T", ")", "bool", "{", "r1", ",", "r2", ":=", "a", ".", "(", "Ref", ")", ",", "b", ".", "(", "Ref", ")", "\n", "return", "r1", ".", "Equal", "(", "r2", ")", "\n", "}", ",", "func", "(", "x", "util", ".", "T", ")", "int", "{", "return", "x", ".", "(", "Ref", ")", ".", "Hash", "(", ")", "\n", "}", ")", ",", "maxErrs", ":", "CompileErrorLimitDefault", ",", "after", ":", "map", "[", "string", "]", "[", "]", "CompilerStage", "{", "}", ",", "}", "\n\n", "c", ".", "ModuleTree", "=", "NewModuleTree", "(", "nil", ")", "\n", "c", ".", "RuleTree", "=", "NewRuleTree", "(", "c", ".", "ModuleTree", ")", "\n\n", "checker", ":=", "newTypeChecker", "(", ")", "\n", "c", ".", "TypeEnv", "=", "checker", ".", "checkLanguageBuiltins", "(", ")", "\n\n", "c", ".", "stages", "=", "[", "]", "struct", "{", "name", "string", "\n", "f", "func", "(", ")", "\n", "}", "{", "// Reference resolution should run first as it may be used to lazily", "// load additional modules. If any stages run before resolution, they", "// need to be re-run after resolution.", "{", "\"", "\"", ",", "c", ".", "resolveAllRefs", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteLocalAssignments", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteExprTerms", "}", ",", "{", "\"", "\"", ",", "c", ".", "setModuleTree", "}", ",", "{", "\"", "\"", ",", "c", ".", "setRuleTree", "}", ",", "{", "\"", "\"", ",", "c", ".", "setGraph", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteComprehensionTerms", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteRefsInHead", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteWithModifiers", "}", ",", "{", "\"", "\"", ",", "c", ".", "checkRuleConflicts", "}", ",", "{", "\"", "\"", ",", "c", ".", "checkSafetyRuleHeads", "}", ",", "{", "\"", "\"", ",", "c", ".", "checkSafetyRuleBodies", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteEquals", "}", ",", "{", "\"", "\"", ",", "c", ".", "rewriteDynamicTerms", "}", ",", "{", "\"", "\"", ",", "c", ".", "checkRecursion", "}", ",", "{", "\"", "\"", ",", "c", ".", "checkTypes", "}", ",", "{", "\"", "\"", ",", "c", ".", "buildRuleIndices", "}", ",", "}", "\n\n", "return", "c", "\n", "}" ]
// NewCompiler returns a new empty compiler.
[ "NewCompiler", "returns", "a", "new", "empty", "compiler", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L171-L219
train
open-policy-agent/opa
ast/compile.go
SetErrorLimit
func (c *Compiler) SetErrorLimit(limit int) *Compiler { c.maxErrs = limit return c }
go
func (c *Compiler) SetErrorLimit(limit int) *Compiler { c.maxErrs = limit return c }
[ "func", "(", "c", "*", "Compiler", ")", "SetErrorLimit", "(", "limit", "int", ")", "*", "Compiler", "{", "c", ".", "maxErrs", "=", "limit", "\n", "return", "c", "\n", "}" ]
// SetErrorLimit sets the number of errors the compiler can encounter before it // quits. Zero or a negative number indicates no limit.
[ "SetErrorLimit", "sets", "the", "number", "of", "errors", "the", "compiler", "can", "encounter", "before", "it", "quits", ".", "Zero", "or", "a", "negative", "number", "indicates", "no", "limit", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L223-L226
train
open-policy-agent/opa
ast/compile.go
WithPathConflictsCheck
func (c *Compiler) WithPathConflictsCheck(fn func([]string) (bool, error)) *Compiler { c.pathExists = fn return c }
go
func (c *Compiler) WithPathConflictsCheck(fn func([]string) (bool, error)) *Compiler { c.pathExists = fn return c }
[ "func", "(", "c", "*", "Compiler", ")", "WithPathConflictsCheck", "(", "fn", "func", "(", "[", "]", "string", ")", "(", "bool", ",", "error", ")", ")", "*", "Compiler", "{", "c", ".", "pathExists", "=", "fn", "\n", "return", "c", "\n", "}" ]
// WithPathConflictsCheck enables base-virtual document conflict // detection. The compiler will check that rules don't overlap with // paths that exist as determined by the provided callable.
[ "WithPathConflictsCheck", "enables", "base", "-", "virtual", "document", "conflict", "detection", ".", "The", "compiler", "will", "check", "that", "rules", "don", "t", "overlap", "with", "paths", "that", "exist", "as", "determined", "by", "the", "provided", "callable", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L231-L234
train
open-policy-agent/opa
ast/compile.go
WithStageAfter
func (c *Compiler) WithStageAfter(after string, stage CompilerStage) *Compiler { c.after[after] = append(c.after[after], stage) return c }
go
func (c *Compiler) WithStageAfter(after string, stage CompilerStage) *Compiler { c.after[after] = append(c.after[after], stage) return c }
[ "func", "(", "c", "*", "Compiler", ")", "WithStageAfter", "(", "after", "string", ",", "stage", "CompilerStage", ")", "*", "Compiler", "{", "c", ".", "after", "[", "after", "]", "=", "append", "(", "c", ".", "after", "[", "after", "]", ",", "stage", ")", "\n", "return", "c", "\n", "}" ]
// WithStageAfter registers a stage to run during compilation after // the named stage.
[ "WithStageAfter", "registers", "a", "stage", "to", "run", "during", "compilation", "after", "the", "named", "stage", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L238-L241
train
open-policy-agent/opa
ast/compile.go
Compile
func (c *Compiler) Compile(modules map[string]*Module) { c.Modules = make(map[string]*Module, len(modules)) for k, v := range modules { c.Modules[k] = v.Copy() c.sorted = append(c.sorted, k) } sort.Strings(c.sorted) c.compile() }
go
func (c *Compiler) Compile(modules map[string]*Module) { c.Modules = make(map[string]*Module, len(modules)) for k, v := range modules { c.Modules[k] = v.Copy() c.sorted = append(c.sorted, k) } sort.Strings(c.sorted) c.compile() }
[ "func", "(", "c", "*", "Compiler", ")", "Compile", "(", "modules", "map", "[", "string", "]", "*", "Module", ")", "{", "c", ".", "Modules", "=", "make", "(", "map", "[", "string", "]", "*", "Module", ",", "len", "(", "modules", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "modules", "{", "c", ".", "Modules", "[", "k", "]", "=", "v", ".", "Copy", "(", ")", "\n", "c", ".", "sorted", "=", "append", "(", "c", ".", "sorted", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "c", ".", "sorted", ")", "\n", "c", ".", "compile", "(", ")", "\n", "}" ]
// Compile runs the compilation process on the input modules. The compiled // version of the modules and associated data structures are stored on the // compiler. If the compilation process fails for any reason, the compiler will // contain a slice of errors.
[ "Compile", "runs", "the", "compilation", "process", "on", "the", "input", "modules", ".", "The", "compiled", "version", "of", "the", "modules", "and", "associated", "data", "structures", "are", "stored", "on", "the", "compiler", ".", "If", "the", "compilation", "process", "fails", "for", "any", "reason", "the", "compiler", "will", "contain", "a", "slice", "of", "errors", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L252-L260
train
open-policy-agent/opa
ast/compile.go
GetArity
func (c *Compiler) GetArity(ref Ref) int { if bi := BuiltinMap[ref.String()]; bi != nil { return len(bi.Decl.Args()) } rules := c.GetRulesExact(ref) if len(rules) == 0 { return -1 } return len(rules[0].Head.Args) }
go
func (c *Compiler) GetArity(ref Ref) int { if bi := BuiltinMap[ref.String()]; bi != nil { return len(bi.Decl.Args()) } rules := c.GetRulesExact(ref) if len(rules) == 0 { return -1 } return len(rules[0].Head.Args) }
[ "func", "(", "c", "*", "Compiler", ")", "GetArity", "(", "ref", "Ref", ")", "int", "{", "if", "bi", ":=", "BuiltinMap", "[", "ref", ".", "String", "(", ")", "]", ";", "bi", "!=", "nil", "{", "return", "len", "(", "bi", ".", "Decl", ".", "Args", "(", ")", ")", "\n", "}", "\n", "rules", ":=", "c", ".", "GetRulesExact", "(", "ref", ")", "\n", "if", "len", "(", "rules", ")", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "return", "len", "(", "rules", "[", "0", "]", ".", "Head", ".", "Args", ")", "\n", "}" ]
// GetArity returns the number of args a function referred to by ref takes. If // ref refers to built-in function, the built-in declaration is consulted, // otherwise, the ref is used to perform a ruleset lookup.
[ "GetArity", "returns", "the", "number", "of", "args", "a", "function", "referred", "to", "by", "ref", "takes", ".", "If", "ref", "refers", "to", "built", "-", "in", "function", "the", "built", "-", "in", "declaration", "is", "consulted", "otherwise", "the", "ref", "is", "used", "to", "perform", "a", "ruleset", "lookup", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L270-L279
train
open-policy-agent/opa
ast/compile.go
WithModuleLoader
func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler { c.moduleLoader = f return c }
go
func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler { c.moduleLoader = f return c }
[ "func", "(", "c", "*", "Compiler", ")", "WithModuleLoader", "(", "f", "ModuleLoader", ")", "*", "Compiler", "{", "c", ".", "moduleLoader", "=", "f", "\n", "return", "c", "\n", "}" ]
// WithModuleLoader sets f as the ModuleLoader on the compiler. // // The compiler will invoke the ModuleLoader after resolving all references in // the current set of input modules. The ModuleLoader can return a new // collection of parsed modules that are to be included in the compilation // process. This process will repeat until the ModuleLoader returns an empty // collection or an error. If an error is returned, compilation will stop // immediately.
[ "WithModuleLoader", "sets", "f", "as", "the", "ModuleLoader", "on", "the", "compiler", ".", "The", "compiler", "will", "invoke", "the", "ModuleLoader", "after", "resolving", "all", "references", "in", "the", "current", "set", "of", "input", "modules", ".", "The", "ModuleLoader", "can", "return", "a", "new", "collection", "of", "parsed", "modules", "that", "are", "to", "be", "included", "in", "the", "compilation", "process", ".", "This", "process", "will", "repeat", "until", "the", "ModuleLoader", "returns", "an", "empty", "collection", "or", "an", "error", ".", "If", "an", "error", "is", "returned", "compilation", "will", "stop", "immediately", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L446-L449
train
open-policy-agent/opa
ast/compile.go
buildRuleIndices
func (c *Compiler) buildRuleIndices() { c.RuleTree.DepthFirst(func(node *TreeNode) bool { if len(node.Values) == 0 { return false } index := newBaseDocEqIndex(func(ref Ref) bool { return len(c.GetRules(ref.GroundPrefix())) > 0 }) if rules := extractRules(node.Values); index.Build(rules) { c.ruleIndices.Put(rules[0].Path(), index) } return false }) }
go
func (c *Compiler) buildRuleIndices() { c.RuleTree.DepthFirst(func(node *TreeNode) bool { if len(node.Values) == 0 { return false } index := newBaseDocEqIndex(func(ref Ref) bool { return len(c.GetRules(ref.GroundPrefix())) > 0 }) if rules := extractRules(node.Values); index.Build(rules) { c.ruleIndices.Put(rules[0].Path(), index) } return false }) }
[ "func", "(", "c", "*", "Compiler", ")", "buildRuleIndices", "(", ")", "{", "c", ".", "RuleTree", ".", "DepthFirst", "(", "func", "(", "node", "*", "TreeNode", ")", "bool", "{", "if", "len", "(", "node", ".", "Values", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "index", ":=", "newBaseDocEqIndex", "(", "func", "(", "ref", "Ref", ")", "bool", "{", "return", "len", "(", "c", ".", "GetRules", "(", "ref", ".", "GroundPrefix", "(", ")", ")", ")", ">", "0", "\n", "}", ")", "\n", "if", "rules", ":=", "extractRules", "(", "node", ".", "Values", ")", ";", "index", ".", "Build", "(", "rules", ")", "{", "c", ".", "ruleIndices", ".", "Put", "(", "rules", "[", "0", "]", ".", "Path", "(", ")", ",", "index", ")", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n\n", "}" ]
// buildRuleIndices constructs indices for rules.
[ "buildRuleIndices", "constructs", "indices", "for", "rules", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L452-L467
train
open-policy-agent/opa
ast/compile.go
checkRecursion
func (c *Compiler) checkRecursion() { eq := func(a, b util.T) bool { return a.(*Rule) == b.(*Rule) } c.RuleTree.DepthFirst(func(node *TreeNode) bool { for _, rule := range node.Values { for node := rule.(*Rule); node != nil; node = node.Else { c.checkSelfPath(node.Loc(), eq, node, node) } } return false }) }
go
func (c *Compiler) checkRecursion() { eq := func(a, b util.T) bool { return a.(*Rule) == b.(*Rule) } c.RuleTree.DepthFirst(func(node *TreeNode) bool { for _, rule := range node.Values { for node := rule.(*Rule); node != nil; node = node.Else { c.checkSelfPath(node.Loc(), eq, node, node) } } return false }) }
[ "func", "(", "c", "*", "Compiler", ")", "checkRecursion", "(", ")", "{", "eq", ":=", "func", "(", "a", ",", "b", "util", ".", "T", ")", "bool", "{", "return", "a", ".", "(", "*", "Rule", ")", "==", "b", ".", "(", "*", "Rule", ")", "\n", "}", "\n\n", "c", ".", "RuleTree", ".", "DepthFirst", "(", "func", "(", "node", "*", "TreeNode", ")", "bool", "{", "for", "_", ",", "rule", ":=", "range", "node", ".", "Values", "{", "for", "node", ":=", "rule", ".", "(", "*", "Rule", ")", ";", "node", "!=", "nil", ";", "node", "=", "node", ".", "Else", "{", "c", ".", "checkSelfPath", "(", "node", ".", "Loc", "(", ")", ",", "eq", ",", "node", ",", "node", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}" ]
// checkRecursion ensures that there are no recursive definitions, i.e., there are // no cycles in the Graph.
[ "checkRecursion", "ensures", "that", "there", "are", "no", "recursive", "definitions", "i", ".", "e", ".", "there", "are", "no", "cycles", "in", "the", "Graph", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L471-L484
train
open-policy-agent/opa
ast/compile.go
checkRuleConflicts
func (c *Compiler) checkRuleConflicts() { c.RuleTree.DepthFirst(func(node *TreeNode) bool { if len(node.Values) == 0 { return false } kinds := map[DocKind]struct{}{} defaultRules := 0 arities := map[int]struct{}{} for _, rule := range node.Values { r := rule.(*Rule) kinds[r.Head.DocKind()] = struct{}{} arities[len(r.Head.Args)] = struct{}{} if r.Default { defaultRules++ } } name := Var(node.Key.(String)) if len(kinds) > 1 || len(arities) > 1 { c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "conflicting rules named %v found", name)) } if defaultRules > 1 { c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "multiple default rules named %s found", name)) } return false }) if c.pathExists != nil { for _, err := range CheckPathConflicts(c, c.pathExists) { c.err(err) } } c.ModuleTree.DepthFirst(func(node *ModuleTreeNode) bool { for _, mod := range node.Modules { for _, rule := range mod.Rules { if childNode, ok := node.Children[String(rule.Head.Name)]; ok { for _, childMod := range childNode.Modules { msg := fmt.Sprintf("%v conflicts with rule defined at %v", childMod.Package, rule.Loc()) c.err(NewError(TypeErr, mod.Package.Loc(), msg)) } } } } return false }) }
go
func (c *Compiler) checkRuleConflicts() { c.RuleTree.DepthFirst(func(node *TreeNode) bool { if len(node.Values) == 0 { return false } kinds := map[DocKind]struct{}{} defaultRules := 0 arities := map[int]struct{}{} for _, rule := range node.Values { r := rule.(*Rule) kinds[r.Head.DocKind()] = struct{}{} arities[len(r.Head.Args)] = struct{}{} if r.Default { defaultRules++ } } name := Var(node.Key.(String)) if len(kinds) > 1 || len(arities) > 1 { c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "conflicting rules named %v found", name)) } if defaultRules > 1 { c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "multiple default rules named %s found", name)) } return false }) if c.pathExists != nil { for _, err := range CheckPathConflicts(c, c.pathExists) { c.err(err) } } c.ModuleTree.DepthFirst(func(node *ModuleTreeNode) bool { for _, mod := range node.Modules { for _, rule := range mod.Rules { if childNode, ok := node.Children[String(rule.Head.Name)]; ok { for _, childMod := range childNode.Modules { msg := fmt.Sprintf("%v conflicts with rule defined at %v", childMod.Package, rule.Loc()) c.err(NewError(TypeErr, mod.Package.Loc(), msg)) } } } } return false }) }
[ "func", "(", "c", "*", "Compiler", ")", "checkRuleConflicts", "(", ")", "{", "c", ".", "RuleTree", ".", "DepthFirst", "(", "func", "(", "node", "*", "TreeNode", ")", "bool", "{", "if", "len", "(", "node", ".", "Values", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "kinds", ":=", "map", "[", "DocKind", "]", "struct", "{", "}", "{", "}", "\n", "defaultRules", ":=", "0", "\n", "arities", ":=", "map", "[", "int", "]", "struct", "{", "}", "{", "}", "\n\n", "for", "_", ",", "rule", ":=", "range", "node", ".", "Values", "{", "r", ":=", "rule", ".", "(", "*", "Rule", ")", "\n", "kinds", "[", "r", ".", "Head", ".", "DocKind", "(", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "arities", "[", "len", "(", "r", ".", "Head", ".", "Args", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "if", "r", ".", "Default", "{", "defaultRules", "++", "\n", "}", "\n", "}", "\n\n", "name", ":=", "Var", "(", "node", ".", "Key", ".", "(", "String", ")", ")", "\n\n", "if", "len", "(", "kinds", ")", ">", "1", "||", "len", "(", "arities", ")", ">", "1", "{", "c", ".", "err", "(", "NewError", "(", "TypeErr", ",", "node", ".", "Values", "[", "0", "]", ".", "(", "*", "Rule", ")", ".", "Loc", "(", ")", ",", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n\n", "if", "defaultRules", ">", "1", "{", "c", ".", "err", "(", "NewError", "(", "TypeErr", ",", "node", ".", "Values", "[", "0", "]", ".", "(", "*", "Rule", ")", ".", "Loc", "(", ")", ",", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n\n", "return", "false", "\n", "}", ")", "\n\n", "if", "c", ".", "pathExists", "!=", "nil", "{", "for", "_", ",", "err", ":=", "range", "CheckPathConflicts", "(", "c", ",", "c", ".", "pathExists", ")", "{", "c", ".", "err", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "c", ".", "ModuleTree", ".", "DepthFirst", "(", "func", "(", "node", "*", "ModuleTreeNode", ")", "bool", "{", "for", "_", ",", "mod", ":=", "range", "node", ".", "Modules", "{", "for", "_", ",", "rule", ":=", "range", "mod", ".", "Rules", "{", "if", "childNode", ",", "ok", ":=", "node", ".", "Children", "[", "String", "(", "rule", ".", "Head", ".", "Name", ")", "]", ";", "ok", "{", "for", "_", ",", "childMod", ":=", "range", "childNode", ".", "Modules", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "childMod", ".", "Package", ",", "rule", ".", "Loc", "(", ")", ")", "\n", "c", ".", "err", "(", "NewError", "(", "TypeErr", ",", "mod", ".", "Package", ".", "Loc", "(", ")", ",", "msg", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}" ]
// checkRuleConflicts ensures that rules definitions are not in conflict.
[ "checkRuleConflicts", "ensures", "that", "rules", "definitions", "are", "not", "in", "conflict", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L507-L558
train
open-policy-agent/opa
ast/compile.go
checkSafetyRuleBodies
func (c *Compiler) checkSafetyRuleBodies() { for _, name := range c.sorted { m := c.Modules[name] WalkRules(m, func(r *Rule) bool { safe := ReservedVars.Copy() safe.Update(r.Head.Args.Vars()) r.Body = c.checkBodySafety(safe, m, r.Body, r.Loc()) return false }) } }
go
func (c *Compiler) checkSafetyRuleBodies() { for _, name := range c.sorted { m := c.Modules[name] WalkRules(m, func(r *Rule) bool { safe := ReservedVars.Copy() safe.Update(r.Head.Args.Vars()) r.Body = c.checkBodySafety(safe, m, r.Body, r.Loc()) return false }) } }
[ "func", "(", "c", "*", "Compiler", ")", "checkSafetyRuleBodies", "(", ")", "{", "for", "_", ",", "name", ":=", "range", "c", ".", "sorted", "{", "m", ":=", "c", ".", "Modules", "[", "name", "]", "\n", "WalkRules", "(", "m", ",", "func", "(", "r", "*", "Rule", ")", "bool", "{", "safe", ":=", "ReservedVars", ".", "Copy", "(", ")", "\n", "safe", ".", "Update", "(", "r", ".", "Head", ".", "Args", ".", "Vars", "(", ")", ")", "\n", "r", ".", "Body", "=", "c", ".", "checkBodySafety", "(", "safe", ",", "m", ",", "r", ".", "Body", ",", "r", ".", "Loc", "(", ")", ")", "\n", "return", "false", "\n", "}", ")", "\n", "}", "\n", "}" ]
// checkSafetyRuleBodies ensures that variables appearing in negated expressions or non-target // positions of built-in expressions will be bound when evaluating the rule from left // to right, re-ordering as necessary.
[ "checkSafetyRuleBodies", "ensures", "that", "variables", "appearing", "in", "negated", "expressions", "or", "non", "-", "target", "positions", "of", "built", "-", "in", "expressions", "will", "be", "bound", "when", "evaluating", "the", "rule", "from", "left", "to", "right", "re", "-", "ordering", "as", "necessary", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L563-L573
train
open-policy-agent/opa
ast/compile.go
checkSafetyRuleHeads
func (c *Compiler) checkSafetyRuleHeads() { for _, name := range c.sorted { m := c.Modules[name] WalkRules(m, func(r *Rule) bool { safe := r.Body.Vars(safetyCheckVarVisitorParams) safe.Update(r.Head.Args.Vars()) unsafe := r.Head.Vars().Diff(safe) for v := range unsafe { if !v.IsGenerated() { c.err(NewError(UnsafeVarErr, r.Loc(), "var %v is unsafe", v)) } } return false }) } }
go
func (c *Compiler) checkSafetyRuleHeads() { for _, name := range c.sorted { m := c.Modules[name] WalkRules(m, func(r *Rule) bool { safe := r.Body.Vars(safetyCheckVarVisitorParams) safe.Update(r.Head.Args.Vars()) unsafe := r.Head.Vars().Diff(safe) for v := range unsafe { if !v.IsGenerated() { c.err(NewError(UnsafeVarErr, r.Loc(), "var %v is unsafe", v)) } } return false }) } }
[ "func", "(", "c", "*", "Compiler", ")", "checkSafetyRuleHeads", "(", ")", "{", "for", "_", ",", "name", ":=", "range", "c", ".", "sorted", "{", "m", ":=", "c", ".", "Modules", "[", "name", "]", "\n", "WalkRules", "(", "m", ",", "func", "(", "r", "*", "Rule", ")", "bool", "{", "safe", ":=", "r", ".", "Body", ".", "Vars", "(", "safetyCheckVarVisitorParams", ")", "\n", "safe", ".", "Update", "(", "r", ".", "Head", ".", "Args", ".", "Vars", "(", ")", ")", "\n", "unsafe", ":=", "r", ".", "Head", ".", "Vars", "(", ")", ".", "Diff", "(", "safe", ")", "\n", "for", "v", ":=", "range", "unsafe", "{", "if", "!", "v", ".", "IsGenerated", "(", ")", "{", "c", ".", "err", "(", "NewError", "(", "UnsafeVarErr", ",", "r", ".", "Loc", "(", ")", ",", "\"", "\"", ",", "v", ")", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}", "\n", "}" ]
// checkSafetyRuleHeads ensures that variables appearing in the head of a // rule also appear in the body.
[ "checkSafetyRuleHeads", "ensures", "that", "variables", "appearing", "in", "the", "head", "of", "a", "rule", "also", "appear", "in", "the", "body", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L593-L609
train
open-policy-agent/opa
ast/compile.go
checkTypes
func (c *Compiler) checkTypes() { // Recursion is caught in earlier step, so this cannot fail. sorted, _ := c.Graph.Sort() checker := newTypeChecker() env, errs := checker.CheckTypes(c.TypeEnv, sorted) for _, err := range errs { c.err(err) } c.TypeEnv = env }
go
func (c *Compiler) checkTypes() { // Recursion is caught in earlier step, so this cannot fail. sorted, _ := c.Graph.Sort() checker := newTypeChecker() env, errs := checker.CheckTypes(c.TypeEnv, sorted) for _, err := range errs { c.err(err) } c.TypeEnv = env }
[ "func", "(", "c", "*", "Compiler", ")", "checkTypes", "(", ")", "{", "// Recursion is caught in earlier step, so this cannot fail.", "sorted", ",", "_", ":=", "c", ".", "Graph", ".", "Sort", "(", ")", "\n", "checker", ":=", "newTypeChecker", "(", ")", "\n", "env", ",", "errs", ":=", "checker", ".", "CheckTypes", "(", "c", ".", "TypeEnv", ",", "sorted", ")", "\n", "for", "_", ",", "err", ":=", "range", "errs", "{", "c", ".", "err", "(", "err", ")", "\n", "}", "\n", "c", ".", "TypeEnv", "=", "env", "\n", "}" ]
// checkTypes runs the type checker on all rules. The type checker builds a // TypeEnv that is stored on the compiler.
[ "checkTypes", "runs", "the", "type", "checker", "on", "all", "rules", ".", "The", "type", "checker", "builds", "a", "TypeEnv", "that", "is", "stored", "on", "the", "compiler", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L613-L622
train
open-policy-agent/opa
ast/compile.go
NewModuleTree
func NewModuleTree(mods map[string]*Module) *ModuleTreeNode { root := &ModuleTreeNode{ Children: map[Value]*ModuleTreeNode{}, } for _, m := range mods { node := root for i, x := range m.Package.Path { c, ok := node.Children[x.Value] if !ok { var hide bool if i == 1 && x.Value.Compare(SystemDocumentKey) == 0 { hide = true } c = &ModuleTreeNode{ Key: x.Value, Children: map[Value]*ModuleTreeNode{}, Hide: hide, } node.Children[x.Value] = c } node = c } node.Modules = append(node.Modules, m) } return root }
go
func NewModuleTree(mods map[string]*Module) *ModuleTreeNode { root := &ModuleTreeNode{ Children: map[Value]*ModuleTreeNode{}, } for _, m := range mods { node := root for i, x := range m.Package.Path { c, ok := node.Children[x.Value] if !ok { var hide bool if i == 1 && x.Value.Compare(SystemDocumentKey) == 0 { hide = true } c = &ModuleTreeNode{ Key: x.Value, Children: map[Value]*ModuleTreeNode{}, Hide: hide, } node.Children[x.Value] = c } node = c } node.Modules = append(node.Modules, m) } return root }
[ "func", "NewModuleTree", "(", "mods", "map", "[", "string", "]", "*", "Module", ")", "*", "ModuleTreeNode", "{", "root", ":=", "&", "ModuleTreeNode", "{", "Children", ":", "map", "[", "Value", "]", "*", "ModuleTreeNode", "{", "}", ",", "}", "\n", "for", "_", ",", "m", ":=", "range", "mods", "{", "node", ":=", "root", "\n", "for", "i", ",", "x", ":=", "range", "m", ".", "Package", ".", "Path", "{", "c", ",", "ok", ":=", "node", ".", "Children", "[", "x", ".", "Value", "]", "\n", "if", "!", "ok", "{", "var", "hide", "bool", "\n", "if", "i", "==", "1", "&&", "x", ".", "Value", ".", "Compare", "(", "SystemDocumentKey", ")", "==", "0", "{", "hide", "=", "true", "\n", "}", "\n", "c", "=", "&", "ModuleTreeNode", "{", "Key", ":", "x", ".", "Value", ",", "Children", ":", "map", "[", "Value", "]", "*", "ModuleTreeNode", "{", "}", ",", "Hide", ":", "hide", ",", "}", "\n", "node", ".", "Children", "[", "x", ".", "Value", "]", "=", "c", "\n", "}", "\n", "node", "=", "c", "\n", "}", "\n", "node", ".", "Modules", "=", "append", "(", "node", ".", "Modules", ",", "m", ")", "\n", "}", "\n", "return", "root", "\n", "}" ]
// NewModuleTree returns a new ModuleTreeNode that represents the root // of the module tree populated with the given modules.
[ "NewModuleTree", "returns", "a", "new", "ModuleTreeNode", "that", "represents", "the", "root", "of", "the", "module", "tree", "populated", "with", "the", "given", "modules", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1119-L1144
train
open-policy-agent/opa
ast/compile.go
Size
func (n *ModuleTreeNode) Size() int { s := len(n.Modules) for _, c := range n.Children { s += c.Size() } return s }
go
func (n *ModuleTreeNode) Size() int { s := len(n.Modules) for _, c := range n.Children { s += c.Size() } return s }
[ "func", "(", "n", "*", "ModuleTreeNode", ")", "Size", "(", ")", "int", "{", "s", ":=", "len", "(", "n", ".", "Modules", ")", "\n", "for", "_", ",", "c", ":=", "range", "n", ".", "Children", "{", "s", "+=", "c", ".", "Size", "(", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Size returns the number of modules in the tree.
[ "Size", "returns", "the", "number", "of", "modules", "in", "the", "tree", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1147-L1153
train
open-policy-agent/opa
ast/compile.go
DepthFirst
func (n *ModuleTreeNode) DepthFirst(f func(node *ModuleTreeNode) bool) { if !f(n) { for _, node := range n.Children { node.DepthFirst(f) } } }
go
func (n *ModuleTreeNode) DepthFirst(f func(node *ModuleTreeNode) bool) { if !f(n) { for _, node := range n.Children { node.DepthFirst(f) } } }
[ "func", "(", "n", "*", "ModuleTreeNode", ")", "DepthFirst", "(", "f", "func", "(", "node", "*", "ModuleTreeNode", ")", "bool", ")", "{", "if", "!", "f", "(", "n", ")", "{", "for", "_", ",", "node", ":=", "range", "n", ".", "Children", "{", "node", ".", "DepthFirst", "(", "f", ")", "\n", "}", "\n", "}", "\n", "}" ]
// DepthFirst performs a depth-first traversal of the module tree rooted at n. // If f returns true, traversal will not continue to the children of n.
[ "DepthFirst", "performs", "a", "depth", "-", "first", "traversal", "of", "the", "module", "tree", "rooted", "at", "n", ".", "If", "f", "returns", "true", "traversal", "will", "not", "continue", "to", "the", "children", "of", "n", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1157-L1163
train
open-policy-agent/opa
ast/compile.go
NewRuleTree
func NewRuleTree(mtree *ModuleTreeNode) *TreeNode { ruleSets := map[String][]util.T{} // Build rule sets for this package. for _, mod := range mtree.Modules { for _, rule := range mod.Rules { key := String(rule.Head.Name) ruleSets[key] = append(ruleSets[key], rule) } } // Each rule set becomes a leaf node. children := map[Value]*TreeNode{} for key, rules := range ruleSets { children[key] = &TreeNode{ Key: key, Children: nil, Values: rules, } } // Each module in subpackage becomes child node. for _, child := range mtree.Children { children[child.Key] = NewRuleTree(child) } return &TreeNode{ Key: mtree.Key, Values: nil, Children: children, Hide: mtree.Hide, } }
go
func NewRuleTree(mtree *ModuleTreeNode) *TreeNode { ruleSets := map[String][]util.T{} // Build rule sets for this package. for _, mod := range mtree.Modules { for _, rule := range mod.Rules { key := String(rule.Head.Name) ruleSets[key] = append(ruleSets[key], rule) } } // Each rule set becomes a leaf node. children := map[Value]*TreeNode{} for key, rules := range ruleSets { children[key] = &TreeNode{ Key: key, Children: nil, Values: rules, } } // Each module in subpackage becomes child node. for _, child := range mtree.Children { children[child.Key] = NewRuleTree(child) } return &TreeNode{ Key: mtree.Key, Values: nil, Children: children, Hide: mtree.Hide, } }
[ "func", "NewRuleTree", "(", "mtree", "*", "ModuleTreeNode", ")", "*", "TreeNode", "{", "ruleSets", ":=", "map", "[", "String", "]", "[", "]", "util", ".", "T", "{", "}", "\n\n", "// Build rule sets for this package.", "for", "_", ",", "mod", ":=", "range", "mtree", ".", "Modules", "{", "for", "_", ",", "rule", ":=", "range", "mod", ".", "Rules", "{", "key", ":=", "String", "(", "rule", ".", "Head", ".", "Name", ")", "\n", "ruleSets", "[", "key", "]", "=", "append", "(", "ruleSets", "[", "key", "]", ",", "rule", ")", "\n", "}", "\n", "}", "\n\n", "// Each rule set becomes a leaf node.", "children", ":=", "map", "[", "Value", "]", "*", "TreeNode", "{", "}", "\n\n", "for", "key", ",", "rules", ":=", "range", "ruleSets", "{", "children", "[", "key", "]", "=", "&", "TreeNode", "{", "Key", ":", "key", ",", "Children", ":", "nil", ",", "Values", ":", "rules", ",", "}", "\n", "}", "\n\n", "// Each module in subpackage becomes child node.", "for", "_", ",", "child", ":=", "range", "mtree", ".", "Children", "{", "children", "[", "child", ".", "Key", "]", "=", "NewRuleTree", "(", "child", ")", "\n", "}", "\n\n", "return", "&", "TreeNode", "{", "Key", ":", "mtree", ".", "Key", ",", "Values", ":", "nil", ",", "Children", ":", "children", ",", "Hide", ":", "mtree", ".", "Hide", ",", "}", "\n", "}" ]
// NewRuleTree returns a new TreeNode that represents the root // of the rule tree populated with the given rules.
[ "NewRuleTree", "returns", "a", "new", "TreeNode", "that", "represents", "the", "root", "of", "the", "rule", "tree", "populated", "with", "the", "given", "rules", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1176-L1210
train
open-policy-agent/opa
ast/compile.go
Size
func (n *TreeNode) Size() int { s := len(n.Values) for _, c := range n.Children { s += c.Size() } return s }
go
func (n *TreeNode) Size() int { s := len(n.Values) for _, c := range n.Children { s += c.Size() } return s }
[ "func", "(", "n", "*", "TreeNode", ")", "Size", "(", ")", "int", "{", "s", ":=", "len", "(", "n", ".", "Values", ")", "\n", "for", "_", ",", "c", ":=", "range", "n", ".", "Children", "{", "s", "+=", "c", ".", "Size", "(", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Size returns the number of rules in the tree.
[ "Size", "returns", "the", "number", "of", "rules", "in", "the", "tree", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1213-L1219
train
open-policy-agent/opa
ast/compile.go
Child
func (n *TreeNode) Child(k Value) *TreeNode { switch k.(type) { case String, Var: return n.Children[k] } return nil }
go
func (n *TreeNode) Child(k Value) *TreeNode { switch k.(type) { case String, Var: return n.Children[k] } return nil }
[ "func", "(", "n", "*", "TreeNode", ")", "Child", "(", "k", "Value", ")", "*", "TreeNode", "{", "switch", "k", ".", "(", "type", ")", "{", "case", "String", ",", "Var", ":", "return", "n", ".", "Children", "[", "k", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Child returns n's child with key k.
[ "Child", "returns", "n", "s", "child", "with", "key", "k", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1222-L1228
train
open-policy-agent/opa
ast/compile.go
DepthFirst
func (n *TreeNode) DepthFirst(f func(node *TreeNode) bool) { if !f(n) { for _, node := range n.Children { node.DepthFirst(f) } } }
go
func (n *TreeNode) DepthFirst(f func(node *TreeNode) bool) { if !f(n) { for _, node := range n.Children { node.DepthFirst(f) } } }
[ "func", "(", "n", "*", "TreeNode", ")", "DepthFirst", "(", "f", "func", "(", "node", "*", "TreeNode", ")", "bool", ")", "{", "if", "!", "f", "(", "n", ")", "{", "for", "_", ",", "node", ":=", "range", "n", ".", "Children", "{", "node", ".", "DepthFirst", "(", "f", ")", "\n", "}", "\n", "}", "\n", "}" ]
// DepthFirst performs a depth-first traversal of the rule tree rooted at n. If // f returns true, traversal will not continue to the children of n.
[ "DepthFirst", "performs", "a", "depth", "-", "first", "traversal", "of", "the", "rule", "tree", "rooted", "at", "n", ".", "If", "f", "returns", "true", "traversal", "will", "not", "continue", "to", "the", "children", "of", "n", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1232-L1238
train
open-policy-agent/opa
ast/compile.go
NewGraph
func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph { graph := &Graph{ adj: map[util.T]map[util.T]struct{}{}, nodes: map[util.T]struct{}{}, sorted: nil, } // Create visitor to walk a rule AST and add edges to the rule graph for // each dependency. vis := func(a *Rule) Visitor { stop := false return NewGenericVisitor(func(x interface{}) bool { switch x := x.(type) { case Ref: for _, b := range list(x.GroundPrefix()) { for node := b; node != nil; node = node.Else { graph.addDependency(a, node) } } case *Rule: if stop { // Do not recurse into else clauses (which will be handled // by the outer visitor.) return true } stop = true } return false }) } // Walk over all rules, add them to graph, and build adjencency lists. for _, module := range modules { WalkRules(module, func(a *Rule) bool { graph.addNode(a) Walk(vis(a), a) return false }) } return graph }
go
func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph { graph := &Graph{ adj: map[util.T]map[util.T]struct{}{}, nodes: map[util.T]struct{}{}, sorted: nil, } // Create visitor to walk a rule AST and add edges to the rule graph for // each dependency. vis := func(a *Rule) Visitor { stop := false return NewGenericVisitor(func(x interface{}) bool { switch x := x.(type) { case Ref: for _, b := range list(x.GroundPrefix()) { for node := b; node != nil; node = node.Else { graph.addDependency(a, node) } } case *Rule: if stop { // Do not recurse into else clauses (which will be handled // by the outer visitor.) return true } stop = true } return false }) } // Walk over all rules, add them to graph, and build adjencency lists. for _, module := range modules { WalkRules(module, func(a *Rule) bool { graph.addNode(a) Walk(vis(a), a) return false }) } return graph }
[ "func", "NewGraph", "(", "modules", "map", "[", "string", "]", "*", "Module", ",", "list", "func", "(", "Ref", ")", "[", "]", "*", "Rule", ")", "*", "Graph", "{", "graph", ":=", "&", "Graph", "{", "adj", ":", "map", "[", "util", ".", "T", "]", "map", "[", "util", ".", "T", "]", "struct", "{", "}", "{", "}", ",", "nodes", ":", "map", "[", "util", ".", "T", "]", "struct", "{", "}", "{", "}", ",", "sorted", ":", "nil", ",", "}", "\n\n", "// Create visitor to walk a rule AST and add edges to the rule graph for", "// each dependency.", "vis", ":=", "func", "(", "a", "*", "Rule", ")", "Visitor", "{", "stop", ":=", "false", "\n", "return", "NewGenericVisitor", "(", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "switch", "x", ":=", "x", ".", "(", "type", ")", "{", "case", "Ref", ":", "for", "_", ",", "b", ":=", "range", "list", "(", "x", ".", "GroundPrefix", "(", ")", ")", "{", "for", "node", ":=", "b", ";", "node", "!=", "nil", ";", "node", "=", "node", ".", "Else", "{", "graph", ".", "addDependency", "(", "a", ",", "node", ")", "\n", "}", "\n", "}", "\n", "case", "*", "Rule", ":", "if", "stop", "{", "// Do not recurse into else clauses (which will be handled", "// by the outer visitor.)", "return", "true", "\n", "}", "\n", "stop", "=", "true", "\n", "}", "\n", "return", "false", "\n", "}", ")", "\n", "}", "\n\n", "// Walk over all rules, add them to graph, and build adjencency lists.", "for", "_", ",", "module", ":=", "range", "modules", "{", "WalkRules", "(", "module", ",", "func", "(", "a", "*", "Rule", ")", "bool", "{", "graph", ".", "addNode", "(", "a", ")", "\n", "Walk", "(", "vis", "(", "a", ")", ",", "a", ")", "\n", "return", "false", "\n", "}", ")", "\n", "}", "\n\n", "return", "graph", "\n", "}" ]
// NewGraph returns a new Graph based on modules. The list function must return // the rules referred to directly by the ref.
[ "NewGraph", "returns", "a", "new", "Graph", "based", "on", "modules", ".", "The", "list", "function", "must", "return", "the", "rules", "referred", "to", "directly", "by", "the", "ref", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1249-L1291
train
open-policy-agent/opa
ast/compile.go
Dependencies
func (g *Graph) Dependencies(x util.T) map[util.T]struct{} { return g.adj[x] }
go
func (g *Graph) Dependencies(x util.T) map[util.T]struct{} { return g.adj[x] }
[ "func", "(", "g", "*", "Graph", ")", "Dependencies", "(", "x", "util", ".", "T", ")", "map", "[", "util", ".", "T", "]", "struct", "{", "}", "{", "return", "g", ".", "adj", "[", "x", "]", "\n", "}" ]
// Dependencies returns the set of rules that x depends on.
[ "Dependencies", "returns", "the", "set", "of", "rules", "that", "x", "depends", "on", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1294-L1296
train
open-policy-agent/opa
ast/compile.go
Sort
func (g *Graph) Sort() (sorted []util.T, ok bool) { if g.sorted != nil { return g.sorted, true } sort := &graphSort{ sorted: make([]util.T, 0, len(g.nodes)), deps: g.Dependencies, marked: map[util.T]struct{}{}, temp: map[util.T]struct{}{}, } for node := range g.nodes { if !sort.Visit(node) { return nil, false } } g.sorted = sort.sorted return g.sorted, true }
go
func (g *Graph) Sort() (sorted []util.T, ok bool) { if g.sorted != nil { return g.sorted, true } sort := &graphSort{ sorted: make([]util.T, 0, len(g.nodes)), deps: g.Dependencies, marked: map[util.T]struct{}{}, temp: map[util.T]struct{}{}, } for node := range g.nodes { if !sort.Visit(node) { return nil, false } } g.sorted = sort.sorted return g.sorted, true }
[ "func", "(", "g", "*", "Graph", ")", "Sort", "(", ")", "(", "sorted", "[", "]", "util", ".", "T", ",", "ok", "bool", ")", "{", "if", "g", ".", "sorted", "!=", "nil", "{", "return", "g", ".", "sorted", ",", "true", "\n", "}", "\n\n", "sort", ":=", "&", "graphSort", "{", "sorted", ":", "make", "(", "[", "]", "util", ".", "T", ",", "0", ",", "len", "(", "g", ".", "nodes", ")", ")", ",", "deps", ":", "g", ".", "Dependencies", ",", "marked", ":", "map", "[", "util", ".", "T", "]", "struct", "{", "}", "{", "}", ",", "temp", ":", "map", "[", "util", ".", "T", "]", "struct", "{", "}", "{", "}", ",", "}", "\n\n", "for", "node", ":=", "range", "g", ".", "nodes", "{", "if", "!", "sort", ".", "Visit", "(", "node", ")", "{", "return", "nil", ",", "false", "\n", "}", "\n", "}", "\n\n", "g", ".", "sorted", "=", "sort", ".", "sorted", "\n", "return", "g", ".", "sorted", ",", "true", "\n", "}" ]
// Sort returns a slice of rules sorted by dependencies. If a cycle is found, // ok is set to false.
[ "Sort", "returns", "a", "slice", "of", "rules", "sorted", "by", "dependencies", ".", "If", "a", "cycle", "is", "found", "ok", "is", "set", "to", "false", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1300-L1320
train
open-policy-agent/opa
ast/compile.go
reorderBodyForSafety
func reorderBodyForSafety(arity func(Ref) int, globals VarSet, body Body) (Body, unsafeVars) { body, unsafe := reorderBodyForClosures(arity, globals, body) if len(unsafe) != 0 { return nil, unsafe } reordered := Body{} safe := VarSet{} for _, e := range body { for v := range e.Vars(safetyCheckVarVisitorParams) { if globals.Contains(v) { safe.Add(v) } else { unsafe.Add(e, v) } } } for { n := len(reordered) for _, e := range body { if reordered.Contains(e) { continue } safe.Update(outputVarsForExpr(e, arity, safe)) for v := range unsafe[e] { if safe.Contains(v) { delete(unsafe[e], v) } } if len(unsafe[e]) == 0 { delete(unsafe, e) reordered = append(reordered, e) } } if len(reordered) == n { break } } // Recursively visit closures and perform the safety checks on them. // Update the globals at each expression to include the variables that could // be closed over. g := globals.Copy() for i, e := range reordered { if i > 0 { g.Update(reordered[i-1].Vars(safetyCheckVarVisitorParams)) } vis := &bodySafetyVisitor{ arity: arity, current: e, globals: g, unsafe: unsafe, } Walk(vis, e) } // Need to reset expression indices as re-ordering may have // changed them. setExprIndices(reordered) return reordered, unsafe }
go
func reorderBodyForSafety(arity func(Ref) int, globals VarSet, body Body) (Body, unsafeVars) { body, unsafe := reorderBodyForClosures(arity, globals, body) if len(unsafe) != 0 { return nil, unsafe } reordered := Body{} safe := VarSet{} for _, e := range body { for v := range e.Vars(safetyCheckVarVisitorParams) { if globals.Contains(v) { safe.Add(v) } else { unsafe.Add(e, v) } } } for { n := len(reordered) for _, e := range body { if reordered.Contains(e) { continue } safe.Update(outputVarsForExpr(e, arity, safe)) for v := range unsafe[e] { if safe.Contains(v) { delete(unsafe[e], v) } } if len(unsafe[e]) == 0 { delete(unsafe, e) reordered = append(reordered, e) } } if len(reordered) == n { break } } // Recursively visit closures and perform the safety checks on them. // Update the globals at each expression to include the variables that could // be closed over. g := globals.Copy() for i, e := range reordered { if i > 0 { g.Update(reordered[i-1].Vars(safetyCheckVarVisitorParams)) } vis := &bodySafetyVisitor{ arity: arity, current: e, globals: g, unsafe: unsafe, } Walk(vis, e) } // Need to reset expression indices as re-ordering may have // changed them. setExprIndices(reordered) return reordered, unsafe }
[ "func", "reorderBodyForSafety", "(", "arity", "func", "(", "Ref", ")", "int", ",", "globals", "VarSet", ",", "body", "Body", ")", "(", "Body", ",", "unsafeVars", ")", "{", "body", ",", "unsafe", ":=", "reorderBodyForClosures", "(", "arity", ",", "globals", ",", "body", ")", "\n", "if", "len", "(", "unsafe", ")", "!=", "0", "{", "return", "nil", ",", "unsafe", "\n", "}", "\n\n", "reordered", ":=", "Body", "{", "}", "\n", "safe", ":=", "VarSet", "{", "}", "\n\n", "for", "_", ",", "e", ":=", "range", "body", "{", "for", "v", ":=", "range", "e", ".", "Vars", "(", "safetyCheckVarVisitorParams", ")", "{", "if", "globals", ".", "Contains", "(", "v", ")", "{", "safe", ".", "Add", "(", "v", ")", "\n", "}", "else", "{", "unsafe", ".", "Add", "(", "e", ",", "v", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "{", "n", ":=", "len", "(", "reordered", ")", "\n\n", "for", "_", ",", "e", ":=", "range", "body", "{", "if", "reordered", ".", "Contains", "(", "e", ")", "{", "continue", "\n", "}", "\n\n", "safe", ".", "Update", "(", "outputVarsForExpr", "(", "e", ",", "arity", ",", "safe", ")", ")", "\n\n", "for", "v", ":=", "range", "unsafe", "[", "e", "]", "{", "if", "safe", ".", "Contains", "(", "v", ")", "{", "delete", "(", "unsafe", "[", "e", "]", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "unsafe", "[", "e", "]", ")", "==", "0", "{", "delete", "(", "unsafe", ",", "e", ")", "\n", "reordered", "=", "append", "(", "reordered", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "reordered", ")", "==", "n", "{", "break", "\n", "}", "\n", "}", "\n\n", "// Recursively visit closures and perform the safety checks on them.", "// Update the globals at each expression to include the variables that could", "// be closed over.", "g", ":=", "globals", ".", "Copy", "(", ")", "\n", "for", "i", ",", "e", ":=", "range", "reordered", "{", "if", "i", ">", "0", "{", "g", ".", "Update", "(", "reordered", "[", "i", "-", "1", "]", ".", "Vars", "(", "safetyCheckVarVisitorParams", ")", ")", "\n", "}", "\n", "vis", ":=", "&", "bodySafetyVisitor", "{", "arity", ":", "arity", ",", "current", ":", "e", ",", "globals", ":", "g", ",", "unsafe", ":", "unsafe", ",", "}", "\n", "Walk", "(", "vis", ",", "e", ")", "\n", "}", "\n\n", "// Need to reset expression indices as re-ordering may have", "// changed them.", "setExprIndices", "(", "reordered", ")", "\n\n", "return", "reordered", ",", "unsafe", "\n", "}" ]
// reorderBodyForSafety returns a copy of the body ordered such that // left to right evaluation of the body will not encounter unbound variables // in input positions or negated expressions. // // Expressions are added to the re-ordered body as soon as they are considered // safe. If multiple expressions become safe in the same pass, they are added // in their original order. This results in minimal re-ordering of the body. // // If the body cannot be reordered to ensure safety, the second return value // contains a mapping of expressions to unsafe variables in those expressions.
[ "reorderBodyForSafety", "returns", "a", "copy", "of", "the", "body", "ordered", "such", "that", "left", "to", "right", "evaluation", "of", "the", "body", "will", "not", "encounter", "unbound", "variables", "in", "input", "positions", "or", "negated", "expressions", ".", "Expressions", "are", "added", "to", "the", "re", "-", "ordered", "body", "as", "soon", "as", "they", "are", "considered", "safe", ".", "If", "multiple", "expressions", "become", "safe", "in", "the", "same", "pass", "they", "are", "added", "in", "their", "original", "order", ".", "This", "results", "in", "minimal", "re", "-", "ordering", "of", "the", "body", ".", "If", "the", "body", "cannot", "be", "reordered", "to", "ensure", "safety", "the", "second", "return", "value", "contains", "a", "mapping", "of", "expressions", "to", "unsafe", "variables", "in", "those", "expressions", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1458-L1527
train
open-policy-agent/opa
ast/compile.go
checkComprehensionSafety
func (vis *bodySafetyVisitor) checkComprehensionSafety(tv VarSet, body Body) Body { bv := body.Vars(safetyCheckVarVisitorParams) bv.Update(vis.globals) uv := tv.Diff(bv) for v := range uv { vis.unsafe.Add(vis.current, v) } // Check body for safety, reordering as necessary. r, u := reorderBodyForSafety(vis.arity, vis.globals, body) if len(u) == 0 { return r } vis.unsafe.Update(u) return body }
go
func (vis *bodySafetyVisitor) checkComprehensionSafety(tv VarSet, body Body) Body { bv := body.Vars(safetyCheckVarVisitorParams) bv.Update(vis.globals) uv := tv.Diff(bv) for v := range uv { vis.unsafe.Add(vis.current, v) } // Check body for safety, reordering as necessary. r, u := reorderBodyForSafety(vis.arity, vis.globals, body) if len(u) == 0 { return r } vis.unsafe.Update(u) return body }
[ "func", "(", "vis", "*", "bodySafetyVisitor", ")", "checkComprehensionSafety", "(", "tv", "VarSet", ",", "body", "Body", ")", "Body", "{", "bv", ":=", "body", ".", "Vars", "(", "safetyCheckVarVisitorParams", ")", "\n", "bv", ".", "Update", "(", "vis", ".", "globals", ")", "\n", "uv", ":=", "tv", ".", "Diff", "(", "bv", ")", "\n", "for", "v", ":=", "range", "uv", "{", "vis", ".", "unsafe", ".", "Add", "(", "vis", ".", "current", ",", "v", ")", "\n", "}", "\n\n", "// Check body for safety, reordering as necessary.", "r", ",", "u", ":=", "reorderBodyForSafety", "(", "vis", ".", "arity", ",", "vis", ".", "globals", ",", "body", ")", "\n", "if", "len", "(", "u", ")", "==", "0", "{", "return", "r", "\n", "}", "\n\n", "vis", ".", "unsafe", ".", "Update", "(", "u", ")", "\n", "return", "body", "\n", "}" ]
// Check term for safety. This is analogous to the rule head safety check.
[ "Check", "term", "for", "safety", ".", "This", "is", "analogous", "to", "the", "rule", "head", "safety", "check", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L1556-L1572
train
open-policy-agent/opa
ast/compile.go
rewriteWithModifiersInBody
func rewriteWithModifiersInBody(c *Compiler, f *equalityFactory, body Body) (Body, *Error) { var result Body for i := range body { exprs, err := rewriteWithModifier(c, f, body[i]) if err != nil { return nil, err } if len(exprs) > 0 { for _, expr := range exprs { result.Append(expr) } } else { result.Append(body[i]) } } return result, nil }
go
func rewriteWithModifiersInBody(c *Compiler, f *equalityFactory, body Body) (Body, *Error) { var result Body for i := range body { exprs, err := rewriteWithModifier(c, f, body[i]) if err != nil { return nil, err } if len(exprs) > 0 { for _, expr := range exprs { result.Append(expr) } } else { result.Append(body[i]) } } return result, nil }
[ "func", "rewriteWithModifiersInBody", "(", "c", "*", "Compiler", ",", "f", "*", "equalityFactory", ",", "body", "Body", ")", "(", "Body", ",", "*", "Error", ")", "{", "var", "result", "Body", "\n", "for", "i", ":=", "range", "body", "{", "exprs", ",", "err", ":=", "rewriteWithModifier", "(", "c", ",", "f", ",", "body", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "exprs", ")", ">", "0", "{", "for", "_", ",", "expr", ":=", "range", "exprs", "{", "result", ".", "Append", "(", "expr", ")", "\n", "}", "\n", "}", "else", "{", "result", ".", "Append", "(", "body", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// rewriteWithModifiersInBody will rewrite the body so that with modifiers do // not contain terms that require evaluation as values. If this function // encounters an invalid with modifier target then it will raise an error.
[ "rewriteWithModifiersInBody", "will", "rewrite", "the", "body", "so", "that", "with", "modifiers", "do", "not", "contain", "terms", "that", "require", "evaluation", "as", "values", ".", "If", "this", "function", "encounters", "an", "invalid", "with", "modifier", "target", "then", "it", "will", "raise", "an", "error", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/compile.go#L2680-L2696
train
open-policy-agent/opa
ast/visit.go
Walk
func Walk(v Visitor, x interface{}) { wrapped, ok := v.(BeforeAndAfterVisitor) if !ok { wrapped = noopBeforeAndAfterVisitor{v} } WalkBeforeAndAfter(wrapped, x) }
go
func Walk(v Visitor, x interface{}) { wrapped, ok := v.(BeforeAndAfterVisitor) if !ok { wrapped = noopBeforeAndAfterVisitor{v} } WalkBeforeAndAfter(wrapped, x) }
[ "func", "Walk", "(", "v", "Visitor", ",", "x", "interface", "{", "}", ")", "{", "wrapped", ",", "ok", ":=", "v", ".", "(", "BeforeAndAfterVisitor", ")", "\n", "if", "!", "ok", "{", "wrapped", "=", "noopBeforeAndAfterVisitor", "{", "v", "}", "\n", "}", "\n", "WalkBeforeAndAfter", "(", "wrapped", ",", "x", ")", "\n", "}" ]
// Walk iterates the AST by calling the Visit function on the Visitor // v for x before recursing.
[ "Walk", "iterates", "the", "AST", "by", "calling", "the", "Visit", "function", "on", "the", "Visitor", "v", "for", "x", "before", "recursing", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L25-L31
train
open-policy-agent/opa
ast/visit.go
WalkVars
func WalkVars(x interface{}, f func(Var) bool) { vis := &GenericVisitor{func(x interface{}) bool { if v, ok := x.(Var); ok { return f(v) } return false }} Walk(vis, x) }
go
func WalkVars(x interface{}, f func(Var) bool) { vis := &GenericVisitor{func(x interface{}) bool { if v, ok := x.(Var); ok { return f(v) } return false }} Walk(vis, x) }
[ "func", "WalkVars", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "Var", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "v", ",", "ok", ":=", "x", ".", "(", "Var", ")", ";", "ok", "{", "return", "f", "(", "v", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkVars calls the function f on all vars under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkVars", "calls", "the", "function", "f", "on", "all", "vars", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L135-L143
train
open-policy-agent/opa
ast/visit.go
WalkClosures
func WalkClosures(x interface{}, f func(interface{}) bool) { vis := &GenericVisitor{func(x interface{}) bool { switch x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: return f(x) } return false }} Walk(vis, x) }
go
func WalkClosures(x interface{}, f func(interface{}) bool) { vis := &GenericVisitor{func(x interface{}) bool { switch x.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: return f(x) } return false }} Walk(vis, x) }
[ "func", "WalkClosures", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "interface", "{", "}", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "switch", "x", ".", "(", "type", ")", "{", "case", "*", "ArrayComprehension", ",", "*", "ObjectComprehension", ",", "*", "SetComprehension", ":", "return", "f", "(", "x", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkClosures calls the function f on all closures under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkClosures", "calls", "the", "function", "f", "on", "all", "closures", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L147-L156
train
open-policy-agent/opa
ast/visit.go
WalkRefs
func WalkRefs(x interface{}, f func(Ref) bool) { vis := &GenericVisitor{func(x interface{}) bool { if r, ok := x.(Ref); ok { return f(r) } return false }} Walk(vis, x) }
go
func WalkRefs(x interface{}, f func(Ref) bool) { vis := &GenericVisitor{func(x interface{}) bool { if r, ok := x.(Ref); ok { return f(r) } return false }} Walk(vis, x) }
[ "func", "WalkRefs", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "Ref", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "r", ",", "ok", ":=", "x", ".", "(", "Ref", ")", ";", "ok", "{", "return", "f", "(", "r", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkRefs calls the function f on all references under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkRefs", "calls", "the", "function", "f", "on", "all", "references", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L160-L168
train
open-policy-agent/opa
ast/visit.go
WalkTerms
func WalkTerms(x interface{}, f func(*Term) bool) { vis := &GenericVisitor{func(x interface{}) bool { if term, ok := x.(*Term); ok { return f(term) } return false }} Walk(vis, x) }
go
func WalkTerms(x interface{}, f func(*Term) bool) { vis := &GenericVisitor{func(x interface{}) bool { if term, ok := x.(*Term); ok { return f(term) } return false }} Walk(vis, x) }
[ "func", "WalkTerms", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "*", "Term", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "term", ",", "ok", ":=", "x", ".", "(", "*", "Term", ")", ";", "ok", "{", "return", "f", "(", "term", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkTerms calls the function f on all terms under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkTerms", "calls", "the", "function", "f", "on", "all", "terms", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L172-L180
train
open-policy-agent/opa
ast/visit.go
WalkWiths
func WalkWiths(x interface{}, f func(*With) bool) { vis := &GenericVisitor{func(x interface{}) bool { if w, ok := x.(*With); ok { return f(w) } return false }} Walk(vis, x) }
go
func WalkWiths(x interface{}, f func(*With) bool) { vis := &GenericVisitor{func(x interface{}) bool { if w, ok := x.(*With); ok { return f(w) } return false }} Walk(vis, x) }
[ "func", "WalkWiths", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "*", "With", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "w", ",", "ok", ":=", "x", ".", "(", "*", "With", ")", ";", "ok", "{", "return", "f", "(", "w", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkWiths calls the function f on all with modifiers under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkWiths", "calls", "the", "function", "f", "on", "all", "with", "modifiers", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L184-L192
train
open-policy-agent/opa
ast/visit.go
WalkExprs
func WalkExprs(x interface{}, f func(*Expr) bool) { vis := &GenericVisitor{func(x interface{}) bool { if r, ok := x.(*Expr); ok { return f(r) } return false }} Walk(vis, x) }
go
func WalkExprs(x interface{}, f func(*Expr) bool) { vis := &GenericVisitor{func(x interface{}) bool { if r, ok := x.(*Expr); ok { return f(r) } return false }} Walk(vis, x) }
[ "func", "WalkExprs", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "*", "Expr", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "r", ",", "ok", ":=", "x", ".", "(", "*", "Expr", ")", ";", "ok", "{", "return", "f", "(", "r", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkExprs calls the function f on all expressions under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkExprs", "calls", "the", "function", "f", "on", "all", "expressions", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L196-L204
train
open-policy-agent/opa
ast/visit.go
WalkBodies
func WalkBodies(x interface{}, f func(Body) bool) { vis := &GenericVisitor{func(x interface{}) bool { if b, ok := x.(Body); ok { return f(b) } return false }} Walk(vis, x) }
go
func WalkBodies(x interface{}, f func(Body) bool) { vis := &GenericVisitor{func(x interface{}) bool { if b, ok := x.(Body); ok { return f(b) } return false }} Walk(vis, x) }
[ "func", "WalkBodies", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "Body", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "b", ",", "ok", ":=", "x", ".", "(", "Body", ")", ";", "ok", "{", "return", "f", "(", "b", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkBodies calls the function f on all bodies under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkBodies", "calls", "the", "function", "f", "on", "all", "bodies", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L208-L216
train
open-policy-agent/opa
ast/visit.go
WalkRules
func WalkRules(x interface{}, f func(*Rule) bool) { vis := &GenericVisitor{func(x interface{}) bool { if r, ok := x.(*Rule); ok { return f(r) } return false }} Walk(vis, x) }
go
func WalkRules(x interface{}, f func(*Rule) bool) { vis := &GenericVisitor{func(x interface{}) bool { if r, ok := x.(*Rule); ok { return f(r) } return false }} Walk(vis, x) }
[ "func", "WalkRules", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "*", "Rule", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "r", ",", "ok", ":=", "x", ".", "(", "*", "Rule", ")", ";", "ok", "{", "return", "f", "(", "r", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkRules calls the function f on all rules under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkRules", "calls", "the", "function", "f", "on", "all", "rules", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L220-L228
train
open-policy-agent/opa
ast/visit.go
WalkNodes
func WalkNodes(x interface{}, f func(Node) bool) { vis := &GenericVisitor{func(x interface{}) bool { if n, ok := x.(Node); ok { return f(n) } return false }} Walk(vis, x) }
go
func WalkNodes(x interface{}, f func(Node) bool) { vis := &GenericVisitor{func(x interface{}) bool { if n, ok := x.(Node); ok { return f(n) } return false }} Walk(vis, x) }
[ "func", "WalkNodes", "(", "x", "interface", "{", "}", ",", "f", "func", "(", "Node", ")", "bool", ")", "{", "vis", ":=", "&", "GenericVisitor", "{", "func", "(", "x", "interface", "{", "}", ")", "bool", "{", "if", "n", ",", "ok", ":=", "x", ".", "(", "Node", ")", ";", "ok", "{", "return", "f", "(", "n", ")", "\n", "}", "\n", "return", "false", "\n", "}", "}", "\n", "Walk", "(", "vis", ",", "x", ")", "\n", "}" ]
// WalkNodes calls the function f on all nodes under x. If the function f // returns true, AST nodes under the last node will not be visited.
[ "WalkNodes", "calls", "the", "function", "f", "on", "all", "nodes", "under", "x", ".", "If", "the", "function", "f", "returns", "true", "AST", "nodes", "under", "the", "last", "node", "will", "not", "be", "visited", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L232-L240
train
open-policy-agent/opa
ast/visit.go
Visit
func (vis *GenericVisitor) Visit(x interface{}) Visitor { if vis.f(x) { return nil } return vis }
go
func (vis *GenericVisitor) Visit(x interface{}) Visitor { if vis.f(x) { return nil } return vis }
[ "func", "(", "vis", "*", "GenericVisitor", ")", "Visit", "(", "x", "interface", "{", "}", ")", "Visitor", "{", "if", "vis", ".", "f", "(", "x", ")", "{", "return", "nil", "\n", "}", "\n", "return", "vis", "\n", "}" ]
// Visit calls the function f on the GenericVisitor.
[ "Visit", "calls", "the", "function", "f", "on", "the", "GenericVisitor", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L256-L261
train
open-policy-agent/opa
ast/visit.go
WithParams
func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor { vis.params = params return vis }
go
func (vis *VarVisitor) WithParams(params VarVisitorParams) *VarVisitor { vis.params = params return vis }
[ "func", "(", "vis", "*", "VarVisitor", ")", "WithParams", "(", "params", "VarVisitorParams", ")", "*", "VarVisitor", "{", "vis", ".", "params", "=", "params", "\n", "return", "vis", "\n", "}" ]
// WithParams sets the parameters in params on vis.
[ "WithParams", "sets", "the", "parameters", "in", "params", "on", "vis", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L289-L292
train
open-policy-agent/opa
ast/visit.go
Visit
func (vis *VarVisitor) Visit(v interface{}) Visitor { if vis.params.SkipObjectKeys { if o, ok := v.(Object); ok { o.Foreach(func(_, v *Term) { Walk(vis, v) }) return nil } } if vis.params.SkipRefHead { if r, ok := v.(Ref); ok { for _, t := range r[1:] { Walk(vis, t) } return nil } } if vis.params.SkipClosures { switch v.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: return nil } } if vis.params.SkipWithTarget { if v, ok := v.(*With); ok { Walk(vis, v.Value) return nil } } if vis.params.SkipSets { if _, ok := v.(Set); ok { return nil } } if vis.params.SkipRefCallHead { switch v := v.(type) { case *Expr: if terms, ok := v.Terms.([]*Term); ok { for _, t := range terms[0].Value.(Ref)[1:] { Walk(vis, t) } for i := 1; i < len(terms); i++ { Walk(vis, terms[i]) } for _, w := range v.With { Walk(vis, w) } return nil } case Call: operator := v[0].Value.(Ref) for i := 1; i < len(operator); i++ { Walk(vis, operator[i]) } for i := 1; i < len(v); i++ { Walk(vis, v[i]) } return nil } } if v, ok := v.(Var); ok { vis.vars.Add(v) } return vis }
go
func (vis *VarVisitor) Visit(v interface{}) Visitor { if vis.params.SkipObjectKeys { if o, ok := v.(Object); ok { o.Foreach(func(_, v *Term) { Walk(vis, v) }) return nil } } if vis.params.SkipRefHead { if r, ok := v.(Ref); ok { for _, t := range r[1:] { Walk(vis, t) } return nil } } if vis.params.SkipClosures { switch v.(type) { case *ArrayComprehension, *ObjectComprehension, *SetComprehension: return nil } } if vis.params.SkipWithTarget { if v, ok := v.(*With); ok { Walk(vis, v.Value) return nil } } if vis.params.SkipSets { if _, ok := v.(Set); ok { return nil } } if vis.params.SkipRefCallHead { switch v := v.(type) { case *Expr: if terms, ok := v.Terms.([]*Term); ok { for _, t := range terms[0].Value.(Ref)[1:] { Walk(vis, t) } for i := 1; i < len(terms); i++ { Walk(vis, terms[i]) } for _, w := range v.With { Walk(vis, w) } return nil } case Call: operator := v[0].Value.(Ref) for i := 1; i < len(operator); i++ { Walk(vis, operator[i]) } for i := 1; i < len(v); i++ { Walk(vis, v[i]) } return nil } } if v, ok := v.(Var); ok { vis.vars.Add(v) } return vis }
[ "func", "(", "vis", "*", "VarVisitor", ")", "Visit", "(", "v", "interface", "{", "}", ")", "Visitor", "{", "if", "vis", ".", "params", ".", "SkipObjectKeys", "{", "if", "o", ",", "ok", ":=", "v", ".", "(", "Object", ")", ";", "ok", "{", "o", ".", "Foreach", "(", "func", "(", "_", ",", "v", "*", "Term", ")", "{", "Walk", "(", "vis", ",", "v", ")", "\n", "}", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "vis", ".", "params", ".", "SkipRefHead", "{", "if", "r", ",", "ok", ":=", "v", ".", "(", "Ref", ")", ";", "ok", "{", "for", "_", ",", "t", ":=", "range", "r", "[", "1", ":", "]", "{", "Walk", "(", "vis", ",", "t", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "vis", ".", "params", ".", "SkipClosures", "{", "switch", "v", ".", "(", "type", ")", "{", "case", "*", "ArrayComprehension", ",", "*", "ObjectComprehension", ",", "*", "SetComprehension", ":", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "vis", ".", "params", ".", "SkipWithTarget", "{", "if", "v", ",", "ok", ":=", "v", ".", "(", "*", "With", ")", ";", "ok", "{", "Walk", "(", "vis", ",", "v", ".", "Value", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "vis", ".", "params", ".", "SkipSets", "{", "if", "_", ",", "ok", ":=", "v", ".", "(", "Set", ")", ";", "ok", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "vis", ".", "params", ".", "SkipRefCallHead", "{", "switch", "v", ":=", "v", ".", "(", "type", ")", "{", "case", "*", "Expr", ":", "if", "terms", ",", "ok", ":=", "v", ".", "Terms", ".", "(", "[", "]", "*", "Term", ")", ";", "ok", "{", "for", "_", ",", "t", ":=", "range", "terms", "[", "0", "]", ".", "Value", ".", "(", "Ref", ")", "[", "1", ":", "]", "{", "Walk", "(", "vis", ",", "t", ")", "\n", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "terms", ")", ";", "i", "++", "{", "Walk", "(", "vis", ",", "terms", "[", "i", "]", ")", "\n", "}", "\n", "for", "_", ",", "w", ":=", "range", "v", ".", "With", "{", "Walk", "(", "vis", ",", "w", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "case", "Call", ":", "operator", ":=", "v", "[", "0", "]", ".", "Value", ".", "(", "Ref", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "operator", ")", ";", "i", "++", "{", "Walk", "(", "vis", ",", "operator", "[", "i", "]", ")", "\n", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "v", ")", ";", "i", "++", "{", "Walk", "(", "vis", ",", "v", "[", "i", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "v", ".", "(", "Var", ")", ";", "ok", "{", "vis", ".", "vars", ".", "Add", "(", "v", ")", "\n", "}", "\n", "return", "vis", "\n", "}" ]
// Visit is called to walk the AST node v.
[ "Visit", "is", "called", "to", "walk", "the", "AST", "node", "v", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/visit.go#L300-L364
train
open-policy-agent/opa
ast/strings.go
TypeName
func TypeName(x interface{}) string { return strings.ToLower(reflect.Indirect(reflect.ValueOf(x)).Type().Name()) }
go
func TypeName(x interface{}) string { return strings.ToLower(reflect.Indirect(reflect.ValueOf(x)).Type().Name()) }
[ "func", "TypeName", "(", "x", "interface", "{", "}", ")", "string", "{", "return", "strings", ".", "ToLower", "(", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "x", ")", ")", ".", "Type", "(", ")", ".", "Name", "(", ")", ")", "\n", "}" ]
// TypeName returns a human readable name for the AST element type.
[ "TypeName", "returns", "a", "human", "readable", "name", "for", "the", "AST", "element", "type", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/ast/strings.go#L13-L15
train
open-policy-agent/opa
watch/watch.go
New
func New(ctx context.Context, s storage.Store, c *ast.Compiler, txn storage.Transaction) (w *Watcher, err error) { w = create(ctx, s, c) w.trigger, err = s.Register(ctx, txn, storage.TriggerConfig{OnCommit: w.notify}) return w, err }
go
func New(ctx context.Context, s storage.Store, c *ast.Compiler, txn storage.Transaction) (w *Watcher, err error) { w = create(ctx, s, c) w.trigger, err = s.Register(ctx, txn, storage.TriggerConfig{OnCommit: w.notify}) return w, err }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "s", "storage", ".", "Store", ",", "c", "*", "ast", ".", "Compiler", ",", "txn", "storage", ".", "Transaction", ")", "(", "w", "*", "Watcher", ",", "err", "error", ")", "{", "w", "=", "create", "(", "ctx", ",", "s", ",", "c", ")", "\n", "w", ".", "trigger", ",", "err", "=", "s", ".", "Register", "(", "ctx", ",", "txn", ",", "storage", ".", "TriggerConfig", "{", "OnCommit", ":", "w", ".", "notify", "}", ")", "\n", "return", "w", ",", "err", "\n", "}" ]
// New creates and returns a new Watcher on the store using the compiler provided. // Once a compiler is provided to create a Watcher, it must not be modified, or else // the results produced by the Watcher are undefined.
[ "New", "creates", "and", "returns", "a", "new", "Watcher", "on", "the", "store", "using", "the", "compiler", "provided", ".", "Once", "a", "compiler", "is", "provided", "to", "create", "a", "Watcher", "it", "must", "not", "be", "modified", "or", "else", "the", "results", "produced", "by", "the", "Watcher", "are", "undefined", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L74-L78
train
open-policy-agent/opa
watch/watch.go
NewQuery
func (w *Watcher) NewQuery(query string) *Handle { out := make(chan Event) h := &Handle{ C: out, query: query, out: out, notify: make(signal, 1), done: make(signal), ack: make(signal), watcher: w, } return h }
go
func (w *Watcher) NewQuery(query string) *Handle { out := make(chan Event) h := &Handle{ C: out, query: query, out: out, notify: make(signal, 1), done: make(signal), ack: make(signal), watcher: w, } return h }
[ "func", "(", "w", "*", "Watcher", ")", "NewQuery", "(", "query", "string", ")", "*", "Handle", "{", "out", ":=", "make", "(", "chan", "Event", ")", "\n", "h", ":=", "&", "Handle", "{", "C", ":", "out", ",", "query", ":", "query", ",", "out", ":", "out", ",", "notify", ":", "make", "(", "signal", ",", "1", ")", ",", "done", ":", "make", "(", "signal", ")", ",", "ack", ":", "make", "(", "signal", ")", ",", "watcher", ":", "w", ",", "}", "\n", "return", "h", "\n", "}" ]
// NewQuery returns a new watch Handle that can be run. Callers must invoke the // Run function on the handle to start the watch.
[ "NewQuery", "returns", "a", "new", "watch", "Handle", "that", "can", "be", "run", ".", "Callers", "must", "invoke", "the", "Run", "function", "on", "the", "handle", "to", "start", "the", "watch", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L82-L94
train
open-policy-agent/opa
watch/watch.go
Query
func (w *Watcher) Query(query string) (*Handle, error) { h := w.NewQuery(query) return h, h.Start() }
go
func (w *Watcher) Query(query string) (*Handle, error) { h := w.NewQuery(query) return h, h.Start() }
[ "func", "(", "w", "*", "Watcher", ")", "Query", "(", "query", "string", ")", "(", "*", "Handle", ",", "error", ")", "{", "h", ":=", "w", ".", "NewQuery", "(", "query", ")", "\n", "return", "h", ",", "h", ".", "Start", "(", ")", "\n", "}" ]
// Query registers a watch on the provided Rego query. Whenever changes are made to a // base or virtual document that the query depends on, an Event describing the new result // of the query will be sent through the Handle. // // Query will return an error if registering the watch fails for any reason.
[ "Query", "registers", "a", "watch", "on", "the", "provided", "Rego", "query", ".", "Whenever", "changes", "are", "made", "to", "a", "base", "or", "virtual", "document", "that", "the", "query", "depends", "on", "an", "Event", "describing", "the", "new", "result", "of", "the", "query", "will", "be", "sent", "through", "the", "Handle", ".", "Query", "will", "return", "an", "error", "if", "registering", "the", "watch", "fails", "for", "any", "reason", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L101-L104
train
open-policy-agent/opa
watch/watch.go
WithInstrumentation
func (h *Handle) WithInstrumentation(yes bool) *Handle { h.instrument = yes return h }
go
func (h *Handle) WithInstrumentation(yes bool) *Handle { h.instrument = yes return h }
[ "func", "(", "h", "*", "Handle", ")", "WithInstrumentation", "(", "yes", "bool", ")", "*", "Handle", "{", "h", ".", "instrument", "=", "yes", "\n", "return", "h", "\n", "}" ]
// WithInstrumentation enables instrumentation on the query to diagnose // performance issues.
[ "WithInstrumentation", "enables", "instrumentation", "on", "the", "query", "to", "diagnose", "performance", "issues", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L108-L111
train
open-policy-agent/opa
watch/watch.go
Start
func (h *Handle) Start() error { if err := h.watcher.registerHandle(h); err != nil { return err } go h.deliver() return nil }
go
func (h *Handle) Start() error { if err := h.watcher.registerHandle(h); err != nil { return err } go h.deliver() return nil }
[ "func", "(", "h", "*", "Handle", ")", "Start", "(", ")", "error", "{", "if", "err", ":=", "h", ".", "watcher", ".", "registerHandle", "(", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "go", "h", ".", "deliver", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start registers and starts the watch.
[ "Start", "registers", "and", "starts", "the", "watch", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L120-L126
train
open-policy-agent/opa
watch/watch.go
Stop
func (h *Handle) Stop() { h.l.Lock() defer h.l.Unlock() h.watcher.endQuery(h) }
go
func (h *Handle) Stop() { h.l.Lock() defer h.l.Unlock() h.watcher.endQuery(h) }
[ "func", "(", "h", "*", "Handle", ")", "Stop", "(", ")", "{", "h", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "l", ".", "Unlock", "(", ")", "\n\n", "h", ".", "watcher", ".", "endQuery", "(", "h", ")", "\n", "}" ]
// Stop ends the watch on the query associated with the Handle. It will close the channel // that was delivering notifications through the Handle. This may happen before or after // Stop returns.
[ "Stop", "ends", "the", "watch", "on", "the", "query", "associated", "with", "the", "Handle", ".", "It", "will", "close", "the", "channel", "that", "was", "delivering", "notifications", "through", "the", "Handle", ".", "This", "may", "happen", "before", "or", "after", "Stop", "returns", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L131-L136
train
open-policy-agent/opa
watch/watch.go
Migrate
func (w *Watcher) Migrate(c *ast.Compiler, txn storage.Transaction) (*Watcher, error) { w.l.Lock() defer w.l.Unlock() if w.closed { return w, errors.New("cannot migrate a closed Watcher") } m, err := New(w.ctx, w.store, c, txn) if err != nil { return w, err } var handles []*Handle for h := range w.handles { handles = append(handles, h) } w.close(txn, true) for _, h := range handles { if err := m.registerHandle(h); err != nil { h.shutDown(newInvalidatedWatchError(err)) } } return m, nil }
go
func (w *Watcher) Migrate(c *ast.Compiler, txn storage.Transaction) (*Watcher, error) { w.l.Lock() defer w.l.Unlock() if w.closed { return w, errors.New("cannot migrate a closed Watcher") } m, err := New(w.ctx, w.store, c, txn) if err != nil { return w, err } var handles []*Handle for h := range w.handles { handles = append(handles, h) } w.close(txn, true) for _, h := range handles { if err := m.registerHandle(h); err != nil { h.shutDown(newInvalidatedWatchError(err)) } } return m, nil }
[ "func", "(", "w", "*", "Watcher", ")", "Migrate", "(", "c", "*", "ast", ".", "Compiler", ",", "txn", "storage", ".", "Transaction", ")", "(", "*", "Watcher", ",", "error", ")", "{", "w", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "l", ".", "Unlock", "(", ")", "\n", "if", "w", ".", "closed", "{", "return", "w", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "m", ",", "err", ":=", "New", "(", "w", ".", "ctx", ",", "w", ".", "store", ",", "c", ",", "txn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "w", ",", "err", "\n", "}", "\n\n", "var", "handles", "[", "]", "*", "Handle", "\n", "for", "h", ":=", "range", "w", ".", "handles", "{", "handles", "=", "append", "(", "handles", ",", "h", ")", "\n", "}", "\n", "w", ".", "close", "(", "txn", ",", "true", ")", "\n\n", "for", "_", ",", "h", ":=", "range", "handles", "{", "if", "err", ":=", "m", ".", "registerHandle", "(", "h", ")", ";", "err", "!=", "nil", "{", "h", ".", "shutDown", "(", "newInvalidatedWatchError", "(", "err", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// Migrate creates a new Watcher with the same watches as w, but using the new // compiler. Like when creating a Watcher with New, the provided compiler must not // be modified after being passed to Migrate, or else behavior is undefined. // // After Migrate returns, the old watcher will be closed, and the new will be ready for // use. All Handles from the old watcher will still be active, via the returned Watcher, // with the exception of those Handles who's query is no longer valid with the new // compiler. Such Handles will be shutdown and a final Event sent along their channel // indicating the cause of the error. // // If an error occurs creating the new Watcher, the state of the old Watcher will not be // changed.
[ "Migrate", "creates", "a", "new", "Watcher", "with", "the", "same", "watches", "as", "w", "but", "using", "the", "new", "compiler", ".", "Like", "when", "creating", "a", "Watcher", "with", "New", "the", "provided", "compiler", "must", "not", "be", "modified", "after", "being", "passed", "to", "Migrate", "or", "else", "behavior", "is", "undefined", ".", "After", "Migrate", "returns", "the", "old", "watcher", "will", "be", "closed", "and", "the", "new", "will", "be", "ready", "for", "use", ".", "All", "Handles", "from", "the", "old", "watcher", "will", "still", "be", "active", "via", "the", "returned", "Watcher", "with", "the", "exception", "of", "those", "Handles", "who", "s", "query", "is", "no", "longer", "valid", "with", "the", "new", "compiler", ".", "Such", "Handles", "will", "be", "shutdown", "and", "a", "final", "Event", "sent", "along", "their", "channel", "indicating", "the", "cause", "of", "the", "error", ".", "If", "an", "error", "occurs", "creating", "the", "new", "Watcher", "the", "state", "of", "the", "old", "Watcher", "will", "not", "be", "changed", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L163-L188
train
open-policy-agent/opa
watch/watch.go
close
func (w *Watcher) close(txn storage.Transaction, migrating bool) { w.trigger.Unregister(w.ctx, txn) if !migrating { for h := range w.handles { h.shutDown(nil) } } w.handles = map[*Handle]struct{}{} w.dataWatch = map[string]map[signal]struct{}{} w.closed = true }
go
func (w *Watcher) close(txn storage.Transaction, migrating bool) { w.trigger.Unregister(w.ctx, txn) if !migrating { for h := range w.handles { h.shutDown(nil) } } w.handles = map[*Handle]struct{}{} w.dataWatch = map[string]map[signal]struct{}{} w.closed = true }
[ "func", "(", "w", "*", "Watcher", ")", "close", "(", "txn", "storage", ".", "Transaction", ",", "migrating", "bool", ")", "{", "w", ".", "trigger", ".", "Unregister", "(", "w", ".", "ctx", ",", "txn", ")", "\n", "if", "!", "migrating", "{", "for", "h", ":=", "range", "w", ".", "handles", "{", "h", ".", "shutDown", "(", "nil", ")", "\n", "}", "\n", "}", "\n", "w", ".", "handles", "=", "map", "[", "*", "Handle", "]", "struct", "{", "}", "{", "}", "\n", "w", ".", "dataWatch", "=", "map", "[", "string", "]", "map", "[", "signal", "]", "struct", "{", "}", "{", "}", "\n", "w", ".", "closed", "=", "true", "\n", "}" ]
// close assumes that the Watcher is locked. It will not unlock it.
[ "close", "assumes", "that", "the", "Watcher", "is", "locked", ".", "It", "will", "not", "unlock", "it", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/watch/watch.go#L306-L316
train
open-policy-agent/opa
plugins/logs/plugin.go
ParseConfig
func ParseConfig(config []byte, services []string, plugins []string) (*Config, error) { if config == nil { return nil, nil } var parsedConfig Config if err := util.Unmarshal(config, &parsedConfig); err != nil { return nil, err } if err := parsedConfig.validateAndInjectDefaults(services, plugins); err != nil { return nil, err } return &parsedConfig, nil }
go
func ParseConfig(config []byte, services []string, plugins []string) (*Config, error) { if config == nil { return nil, nil } var parsedConfig Config if err := util.Unmarshal(config, &parsedConfig); err != nil { return nil, err } if err := parsedConfig.validateAndInjectDefaults(services, plugins); err != nil { return nil, err } return &parsedConfig, nil }
[ "func", "ParseConfig", "(", "config", "[", "]", "byte", ",", "services", "[", "]", "string", ",", "plugins", "[", "]", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "var", "parsedConfig", "Config", "\n\n", "if", "err", ":=", "util", ".", "Unmarshal", "(", "config", ",", "&", "parsedConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "parsedConfig", ".", "validateAndInjectDefaults", "(", "services", ",", "plugins", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "parsedConfig", ",", "nil", "\n", "}" ]
// ParseConfig validates the config and injects default values.
[ "ParseConfig", "validates", "the", "config", "and", "injects", "default", "values", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/logs/plugin.go#L157-L173
train
open-policy-agent/opa
plugins/logs/plugin.go
Lookup
func Lookup(manager *plugins.Manager) *Plugin { if p := manager.Plugin(Name); p != nil { return p.(*Plugin) } return nil }
go
func Lookup(manager *plugins.Manager) *Plugin { if p := manager.Plugin(Name); p != nil { return p.(*Plugin) } return nil }
[ "func", "Lookup", "(", "manager", "*", "plugins", ".", "Manager", ")", "*", "Plugin", "{", "if", "p", ":=", "manager", ".", "Plugin", "(", "Name", ")", ";", "p", "!=", "nil", "{", "return", "p", ".", "(", "*", "Plugin", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Lookup returns the decision logs plugin registered with the manager.
[ "Lookup", "returns", "the", "decision", "logs", "plugin", "registered", "with", "the", "manager", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/logs/plugin.go#L194-L199
train
open-policy-agent/opa
plugins/logs/plugin.go
Start
func (p *Plugin) Start(ctx context.Context) error { p.logInfo("Starting decision log uploader.") go p.loop() return nil }
go
func (p *Plugin) Start(ctx context.Context) error { p.logInfo("Starting decision log uploader.") go p.loop() return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Start", "(", "ctx", "context", ".", "Context", ")", "error", "{", "p", ".", "logInfo", "(", "\"", "\"", ")", "\n", "go", "p", ".", "loop", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Start starts the plugin.
[ "Start", "starts", "the", "plugin", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/logs/plugin.go#L202-L206
train
open-policy-agent/opa
plugins/logs/plugin.go
Log
func (p *Plugin) Log(ctx context.Context, decision *server.Info) error { path := strings.Replace(strings.TrimPrefix(decision.Path, "data."), ".", "/", -1) event := EventV1{ Labels: p.manager.Labels(), DecisionID: decision.DecisionID, Revision: decision.Revision, Path: path, Query: decision.Query, Input: decision.Input, Result: decision.Results, RequestedBy: decision.RemoteAddr, Timestamp: decision.Timestamp, } if decision.Metrics != nil { event.Metrics = decision.Metrics.All() } if decision.Error != nil { event.Error = decision.Error } if p.config.Plugin != nil { proxy, ok := p.manager.Plugin(*p.config.Plugin).(Logger) if !ok { return fmt.Errorf("plugin does not implement Logger interface") } return proxy.Log(ctx, event) } p.mtx.Lock() defer p.mtx.Unlock() result, err := p.enc.Write(event) if err != nil { // TODO(tsandall): revisit this now that we have an API that // can return an error. Should the default behaviour be to // fail-closed as we do for plugins? p.logError("Log encoding failed: %v.", err) return nil } if result != nil { p.bufferChunk(p.buffer, result) } return nil }
go
func (p *Plugin) Log(ctx context.Context, decision *server.Info) error { path := strings.Replace(strings.TrimPrefix(decision.Path, "data."), ".", "/", -1) event := EventV1{ Labels: p.manager.Labels(), DecisionID: decision.DecisionID, Revision: decision.Revision, Path: path, Query: decision.Query, Input: decision.Input, Result: decision.Results, RequestedBy: decision.RemoteAddr, Timestamp: decision.Timestamp, } if decision.Metrics != nil { event.Metrics = decision.Metrics.All() } if decision.Error != nil { event.Error = decision.Error } if p.config.Plugin != nil { proxy, ok := p.manager.Plugin(*p.config.Plugin).(Logger) if !ok { return fmt.Errorf("plugin does not implement Logger interface") } return proxy.Log(ctx, event) } p.mtx.Lock() defer p.mtx.Unlock() result, err := p.enc.Write(event) if err != nil { // TODO(tsandall): revisit this now that we have an API that // can return an error. Should the default behaviour be to // fail-closed as we do for plugins? p.logError("Log encoding failed: %v.", err) return nil } if result != nil { p.bufferChunk(p.buffer, result) } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Log", "(", "ctx", "context", ".", "Context", ",", "decision", "*", "server", ".", "Info", ")", "error", "{", "path", ":=", "strings", ".", "Replace", "(", "strings", ".", "TrimPrefix", "(", "decision", ".", "Path", ",", "\"", "\"", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "event", ":=", "EventV1", "{", "Labels", ":", "p", ".", "manager", ".", "Labels", "(", ")", ",", "DecisionID", ":", "decision", ".", "DecisionID", ",", "Revision", ":", "decision", ".", "Revision", ",", "Path", ":", "path", ",", "Query", ":", "decision", ".", "Query", ",", "Input", ":", "decision", ".", "Input", ",", "Result", ":", "decision", ".", "Results", ",", "RequestedBy", ":", "decision", ".", "RemoteAddr", ",", "Timestamp", ":", "decision", ".", "Timestamp", ",", "}", "\n\n", "if", "decision", ".", "Metrics", "!=", "nil", "{", "event", ".", "Metrics", "=", "decision", ".", "Metrics", ".", "All", "(", ")", "\n", "}", "\n\n", "if", "decision", ".", "Error", "!=", "nil", "{", "event", ".", "Error", "=", "decision", ".", "Error", "\n", "}", "\n\n", "if", "p", ".", "config", ".", "Plugin", "!=", "nil", "{", "proxy", ",", "ok", ":=", "p", ".", "manager", ".", "Plugin", "(", "*", "p", ".", "config", ".", "Plugin", ")", ".", "(", "Logger", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "proxy", ".", "Log", "(", "ctx", ",", "event", ")", "\n", "}", "\n\n", "p", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "result", ",", "err", ":=", "p", ".", "enc", ".", "Write", "(", "event", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO(tsandall): revisit this now that we have an API that", "// can return an error. Should the default behaviour be to", "// fail-closed as we do for plugins?", "p", ".", "logError", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "result", "!=", "nil", "{", "p", ".", "bufferChunk", "(", "p", ".", "buffer", ",", "result", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Log appends a decision log event to the buffer for uploading.
[ "Log", "appends", "a", "decision", "log", "event", "to", "the", "buffer", "for", "uploading", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/logs/plugin.go#L217-L266
train
open-policy-agent/opa
plugins/logs/plugin.go
Reconfigure
func (p *Plugin) Reconfigure(_ context.Context, config interface{}) { p.reconfig <- config }
go
func (p *Plugin) Reconfigure(_ context.Context, config interface{}) { p.reconfig <- config }
[ "func", "(", "p", "*", "Plugin", ")", "Reconfigure", "(", "_", "context", ".", "Context", ",", "config", "interface", "{", "}", ")", "{", "p", ".", "reconfig", "<-", "config", "\n", "}" ]
// Reconfigure notifies the plugin with a new configuration.
[ "Reconfigure", "notifies", "the", "plugin", "with", "a", "new", "configuration", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/logs/plugin.go#L269-L271
train
open-policy-agent/opa
loader/merge.go
mergeInterfaces
func mergeInterfaces(a map[string]interface{}, b map[string]interface{}) (c map[string]interface{}, ok bool) { c = map[string]interface{}{} for k := range a { c[k] = a[k] } for k := range b { add := b[k] exist, ok := c[k] if !ok { c[k] = add continue } existObj, existOk := exist.(map[string]interface{}) addObj, addOk := add.(map[string]interface{}) if !existOk || !addOk { return nil, false } c[k], ok = mergeInterfaces(existObj, addObj) if !ok { return nil, false } } return c, true }
go
func mergeInterfaces(a map[string]interface{}, b map[string]interface{}) (c map[string]interface{}, ok bool) { c = map[string]interface{}{} for k := range a { c[k] = a[k] } for k := range b { add := b[k] exist, ok := c[k] if !ok { c[k] = add continue } existObj, existOk := exist.(map[string]interface{}) addObj, addOk := add.(map[string]interface{}) if !existOk || !addOk { return nil, false } c[k], ok = mergeInterfaces(existObj, addObj) if !ok { return nil, false } } return c, true }
[ "func", "mergeInterfaces", "(", "a", "map", "[", "string", "]", "interface", "{", "}", ",", "b", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "c", "map", "[", "string", "]", "interface", "{", "}", ",", "ok", "bool", ")", "{", "c", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "for", "k", ":=", "range", "a", "{", "c", "[", "k", "]", "=", "a", "[", "k", "]", "\n", "}", "\n\n", "for", "k", ":=", "range", "b", "{", "add", ":=", "b", "[", "k", "]", "\n", "exist", ",", "ok", ":=", "c", "[", "k", "]", "\n", "if", "!", "ok", "{", "c", "[", "k", "]", "=", "add", "\n", "continue", "\n", "}", "\n\n", "existObj", ",", "existOk", ":=", "exist", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "addObj", ",", "addOk", ":=", "add", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "existOk", "||", "!", "addOk", "{", "return", "nil", ",", "false", "\n", "}", "\n\n", "c", "[", "k", "]", ",", "ok", "=", "mergeInterfaces", "(", "existObj", ",", "addObj", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "false", "\n", "}", "\n", "}", "\n\n", "return", "c", ",", "true", "\n", "}" ]
// mergeInterfaces returns the result of merging a and b. If a and b cannot be // merged because of conflicting key-value pairs, ok is false.
[ "mergeInterfaces", "returns", "the", "result", "of", "merging", "a", "and", "b", ".", "If", "a", "and", "b", "cannot", "be", "merged", "because", "of", "conflicting", "key", "-", "value", "pairs", "ok", "is", "false", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/loader/merge.go#L9-L38
train
open-policy-agent/opa
topdown/tokens.go
decodeHeader
func (token *JSONWebToken) decodeHeader() (err error) { var h ast.Value if h, err = builtinBase64UrlDecode(ast.String(token.header)); err != nil { return fmt.Errorf("JWT header had invalid encoding: %v", err) } if token.decodedHeader, err = validateJWTHeader(string(h.(ast.String))); err != nil { return err } return }
go
func (token *JSONWebToken) decodeHeader() (err error) { var h ast.Value if h, err = builtinBase64UrlDecode(ast.String(token.header)); err != nil { return fmt.Errorf("JWT header had invalid encoding: %v", err) } if token.decodedHeader, err = validateJWTHeader(string(h.(ast.String))); err != nil { return err } return }
[ "func", "(", "token", "*", "JSONWebToken", ")", "decodeHeader", "(", ")", "(", "err", "error", ")", "{", "var", "h", "ast", ".", "Value", "\n", "if", "h", ",", "err", "=", "builtinBase64UrlDecode", "(", "ast", ".", "String", "(", "token", ".", "header", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "token", ".", "decodedHeader", ",", "err", "=", "validateJWTHeader", "(", "string", "(", "h", ".", "(", "ast", ".", "String", ")", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "\n", "}" ]
// decodeHeader populates the decodedHeader field.
[ "decodeHeader", "populates", "the", "decodedHeader", "field", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L48-L57
train
open-policy-agent/opa
topdown/tokens.go
builtinJWTVerifyRS256
func builtinJWTVerifyRS256(a ast.Value, b ast.Value) (ast.Value, error) { return builtinJWTVerifyRSA(a, b, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPKCS1v15( publicKey, crypto.SHA256, digest, signature) }) }
go
func builtinJWTVerifyRS256(a ast.Value, b ast.Value) (ast.Value, error) { return builtinJWTVerifyRSA(a, b, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPKCS1v15( publicKey, crypto.SHA256, digest, signature) }) }
[ "func", "builtinJWTVerifyRS256", "(", "a", "ast", ".", "Value", ",", "b", "ast", ".", "Value", ")", "(", "ast", ".", "Value", ",", "error", ")", "{", "return", "builtinJWTVerifyRSA", "(", "a", ",", "b", ",", "func", "(", "publicKey", "*", "rsa", ".", "PublicKey", ",", "digest", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "error", "{", "return", "rsa", ".", "VerifyPKCS1v15", "(", "publicKey", ",", "crypto", ".", "SHA256", ",", "digest", ",", "signature", ")", "\n", "}", ")", "\n", "}" ]
// Implements RS256 JWT signature verification
[ "Implements", "RS256", "JWT", "signature", "verification" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L118-L126
train
open-policy-agent/opa
topdown/tokens.go
builtinJWTVerifyPS256
func builtinJWTVerifyPS256(a ast.Value, b ast.Value) (ast.Value, error) { return builtinJWTVerifyRSA(a, b, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPSS( publicKey, crypto.SHA256, digest, signature, nil) }) }
go
func builtinJWTVerifyPS256(a ast.Value, b ast.Value) (ast.Value, error) { return builtinJWTVerifyRSA(a, b, func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error { return rsa.VerifyPSS( publicKey, crypto.SHA256, digest, signature, nil) }) }
[ "func", "builtinJWTVerifyPS256", "(", "a", "ast", ".", "Value", ",", "b", "ast", ".", "Value", ")", "(", "ast", ".", "Value", ",", "error", ")", "{", "return", "builtinJWTVerifyRSA", "(", "a", ",", "b", ",", "func", "(", "publicKey", "*", "rsa", ".", "PublicKey", ",", "digest", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "error", "{", "return", "rsa", ".", "VerifyPSS", "(", "publicKey", ",", "crypto", ".", "SHA256", ",", "digest", ",", "signature", ",", "nil", ")", "\n", "}", ")", "\n", "}" ]
// Implements PS256 JWT signature verification
[ "Implements", "PS256", "JWT", "signature", "verification" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L129-L138
train
open-policy-agent/opa
topdown/tokens.go
builtinJWTVerifyRSA
func builtinJWTVerifyRSA(a ast.Value, b ast.Value, verify func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error) (ast.Value, error) { return builtinJWTVerify(a, b, func(publicKey interface{}, digest []byte, signature []byte) error { publicKeyRsa, ok := publicKey.(*rsa.PublicKey) if !ok { return fmt.Errorf("incorrect public key type") } return verify(publicKeyRsa, digest, signature) }) }
go
func builtinJWTVerifyRSA(a ast.Value, b ast.Value, verify func(publicKey *rsa.PublicKey, digest []byte, signature []byte) error) (ast.Value, error) { return builtinJWTVerify(a, b, func(publicKey interface{}, digest []byte, signature []byte) error { publicKeyRsa, ok := publicKey.(*rsa.PublicKey) if !ok { return fmt.Errorf("incorrect public key type") } return verify(publicKeyRsa, digest, signature) }) }
[ "func", "builtinJWTVerifyRSA", "(", "a", "ast", ".", "Value", ",", "b", "ast", ".", "Value", ",", "verify", "func", "(", "publicKey", "*", "rsa", ".", "PublicKey", ",", "digest", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "error", ")", "(", "ast", ".", "Value", ",", "error", ")", "{", "return", "builtinJWTVerify", "(", "a", ",", "b", ",", "func", "(", "publicKey", "interface", "{", "}", ",", "digest", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "error", "{", "publicKeyRsa", ",", "ok", ":=", "publicKey", ".", "(", "*", "rsa", ".", "PublicKey", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "verify", "(", "publicKeyRsa", ",", "digest", ",", "signature", ")", "\n", "}", ")", "\n", "}" ]
// Implements RSA JWT signature verification.
[ "Implements", "RSA", "JWT", "signature", "verification", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L141-L149
train
open-policy-agent/opa
topdown/tokens.go
builtinJWTVerifyES256
func builtinJWTVerifyES256(a ast.Value, b ast.Value) (ast.Value, error) { return builtinJWTVerify(a, b, func(publicKey interface{}, digest []byte, signature []byte) error { publicKeyEcdsa, ok := publicKey.(*ecdsa.PublicKey) if !ok { return fmt.Errorf("incorrect public key type") } r, s := &big.Int{}, &big.Int{} n := len(signature) / 2 r.SetBytes(signature[:n]) s.SetBytes(signature[n:]) if ecdsa.Verify(publicKeyEcdsa, digest, r, s) { return nil } return fmt.Errorf("ECDSA signature verification error") }) }
go
func builtinJWTVerifyES256(a ast.Value, b ast.Value) (ast.Value, error) { return builtinJWTVerify(a, b, func(publicKey interface{}, digest []byte, signature []byte) error { publicKeyEcdsa, ok := publicKey.(*ecdsa.PublicKey) if !ok { return fmt.Errorf("incorrect public key type") } r, s := &big.Int{}, &big.Int{} n := len(signature) / 2 r.SetBytes(signature[:n]) s.SetBytes(signature[n:]) if ecdsa.Verify(publicKeyEcdsa, digest, r, s) { return nil } return fmt.Errorf("ECDSA signature verification error") }) }
[ "func", "builtinJWTVerifyES256", "(", "a", "ast", ".", "Value", ",", "b", "ast", ".", "Value", ")", "(", "ast", ".", "Value", ",", "error", ")", "{", "return", "builtinJWTVerify", "(", "a", ",", "b", ",", "func", "(", "publicKey", "interface", "{", "}", ",", "digest", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "error", "{", "publicKeyEcdsa", ",", "ok", ":=", "publicKey", ".", "(", "*", "ecdsa", ".", "PublicKey", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "r", ",", "s", ":=", "&", "big", ".", "Int", "{", "}", ",", "&", "big", ".", "Int", "{", "}", "\n", "n", ":=", "len", "(", "signature", ")", "/", "2", "\n", "r", ".", "SetBytes", "(", "signature", "[", ":", "n", "]", ")", "\n", "s", ".", "SetBytes", "(", "signature", "[", "n", ":", "]", ")", "\n", "if", "ecdsa", ".", "Verify", "(", "publicKeyEcdsa", ",", "digest", ",", "r", ",", "s", ")", "{", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", ")", "\n", "}" ]
// Implements ES256 JWT signature verification.
[ "Implements", "ES256", "JWT", "signature", "verification", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L152-L167
train
open-policy-agent/opa
topdown/tokens.go
getKeyFromCert
func getKeyFromCert(certificate string) (key interface{}, err error) { block, rest := pem.Decode([]byte(certificate)) if block == nil || block.Type != "CERTIFICATE" || len(rest) > 0 { return nil, fmt.Errorf("failed to decode PEM block containing certificate") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, errors.Wrap(err, "PEM parse error") } key = cert.PublicKey return }
go
func getKeyFromCert(certificate string) (key interface{}, err error) { block, rest := pem.Decode([]byte(certificate)) if block == nil || block.Type != "CERTIFICATE" || len(rest) > 0 { return nil, fmt.Errorf("failed to decode PEM block containing certificate") } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, errors.Wrap(err, "PEM parse error") } key = cert.PublicKey return }
[ "func", "getKeyFromCert", "(", "certificate", "string", ")", "(", "key", "interface", "{", "}", ",", "err", "error", ")", "{", "block", ",", "rest", ":=", "pem", ".", "Decode", "(", "[", "]", "byte", "(", "certificate", ")", ")", "\n", "if", "block", "==", "nil", "||", "block", ".", "Type", "!=", "\"", "\"", "||", "len", "(", "rest", ")", ">", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "block", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "key", "=", "cert", ".", "PublicKey", "\n", "return", "\n", "}" ]
// getKeyFromCert returns the public key found in a X.509 certificate.
[ "getKeyFromCert", "returns", "the", "public", "key", "found", "in", "a", "X", ".", "509", "certificate", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L170-L182
train
open-policy-agent/opa
topdown/tokens.go
builtinJWTVerify
func builtinJWTVerify(a ast.Value, b ast.Value, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) { // Decode the JSON Web Token token, err := decodeJWT(a) if err != nil { return nil, err } // Process PEM encoded certificate input astCertificate, err := builtins.StringOperand(b, 2) if err != nil { return nil, err } key, err := getKeyFromCert(string(astCertificate)) if err != nil { return nil, err } signature, err := token.decodeSignature() if err != nil { return nil, err } // Validate the JWT signature err = verify(key, getInputSHA([]byte(token.header+"."+token.payload)), []byte(signature)) if err != nil { return ast.Boolean(false), nil } return ast.Boolean(true), nil }
go
func builtinJWTVerify(a ast.Value, b ast.Value, verify func(publicKey interface{}, digest []byte, signature []byte) error) (ast.Value, error) { // Decode the JSON Web Token token, err := decodeJWT(a) if err != nil { return nil, err } // Process PEM encoded certificate input astCertificate, err := builtins.StringOperand(b, 2) if err != nil { return nil, err } key, err := getKeyFromCert(string(astCertificate)) if err != nil { return nil, err } signature, err := token.decodeSignature() if err != nil { return nil, err } // Validate the JWT signature err = verify(key, getInputSHA([]byte(token.header+"."+token.payload)), []byte(signature)) if err != nil { return ast.Boolean(false), nil } return ast.Boolean(true), nil }
[ "func", "builtinJWTVerify", "(", "a", "ast", ".", "Value", ",", "b", "ast", ".", "Value", ",", "verify", "func", "(", "publicKey", "interface", "{", "}", ",", "digest", "[", "]", "byte", ",", "signature", "[", "]", "byte", ")", "error", ")", "(", "ast", ".", "Value", ",", "error", ")", "{", "// Decode the JSON Web Token", "token", ",", "err", ":=", "decodeJWT", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Process PEM encoded certificate input", "astCertificate", ",", "err", ":=", "builtins", ".", "StringOperand", "(", "b", ",", "2", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "key", ",", "err", ":=", "getKeyFromCert", "(", "string", "(", "astCertificate", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "signature", ",", "err", ":=", "token", ".", "decodeSignature", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Validate the JWT signature", "err", "=", "verify", "(", "key", ",", "getInputSHA", "(", "[", "]", "byte", "(", "token", ".", "header", "+", "\"", "\"", "+", "token", ".", "payload", ")", ")", ",", "[", "]", "byte", "(", "signature", ")", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "ast", ".", "Boolean", "(", "false", ")", ",", "nil", "\n", "}", "\n", "return", "ast", ".", "Boolean", "(", "true", ")", ",", "nil", "\n", "}" ]
// Implements JWT signature verification.
[ "Implements", "JWT", "signature", "verification", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L185-L216
train
open-policy-agent/opa
topdown/tokens.go
tokenConstraintCert
func tokenConstraintCert(value ast.Value, constraints *tokenConstraints) (err error) { var cert ast.String var ok bool if cert, ok = value.(ast.String); !ok { err = fmt.Errorf("cert constraint: must be a string") return } if constraints.key, err = getKeyFromCert(string(cert)); err != nil { return } return }
go
func tokenConstraintCert(value ast.Value, constraints *tokenConstraints) (err error) { var cert ast.String var ok bool if cert, ok = value.(ast.String); !ok { err = fmt.Errorf("cert constraint: must be a string") return } if constraints.key, err = getKeyFromCert(string(cert)); err != nil { return } return }
[ "func", "tokenConstraintCert", "(", "value", "ast", ".", "Value", ",", "constraints", "*", "tokenConstraints", ")", "(", "err", "error", ")", "{", "var", "cert", "ast", ".", "String", "\n", "var", "ok", "bool", "\n", "if", "cert", ",", "ok", "=", "value", ".", "(", "ast", ".", "String", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "constraints", ".", "key", ",", "err", "=", "getKeyFromCert", "(", "string", "(", "cert", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "\n", "}" ]
// tokenConstraintCert handles the `cert` constraint.
[ "tokenConstraintCert", "handles", "the", "cert", "constraint", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L298-L309
train
open-policy-agent/opa
topdown/tokens.go
tokenConstraintTime
func tokenConstraintTime(value ast.Value, constraints *tokenConstraints) (err error) { var time ast.Number var ok bool if time, ok = value.(ast.Number); !ok { err = fmt.Errorf("token time constraint: must be a number") return } var timeFloat float64 if timeFloat, err = strconv.ParseFloat(string(time), 64); err != nil { err = fmt.Errorf("token time constraint: %v", err) return } if timeFloat < 0 { err = fmt.Errorf("token time constraint: must not be negative") return } constraints.time = int64(timeFloat) return }
go
func tokenConstraintTime(value ast.Value, constraints *tokenConstraints) (err error) { var time ast.Number var ok bool if time, ok = value.(ast.Number); !ok { err = fmt.Errorf("token time constraint: must be a number") return } var timeFloat float64 if timeFloat, err = strconv.ParseFloat(string(time), 64); err != nil { err = fmt.Errorf("token time constraint: %v", err) return } if timeFloat < 0 { err = fmt.Errorf("token time constraint: must not be negative") return } constraints.time = int64(timeFloat) return }
[ "func", "tokenConstraintTime", "(", "value", "ast", ".", "Value", ",", "constraints", "*", "tokenConstraints", ")", "(", "err", "error", ")", "{", "var", "time", "ast", ".", "Number", "\n", "var", "ok", "bool", "\n", "if", "time", ",", "ok", "=", "value", ".", "(", "ast", ".", "Number", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "var", "timeFloat", "float64", "\n", "if", "timeFloat", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "string", "(", "time", ")", ",", "64", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "timeFloat", "<", "0", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "constraints", ".", "time", "=", "int64", "(", "timeFloat", ")", "\n", "return", "\n", "}" ]
// tokenConstraintTime handles the `time` constraint.
[ "tokenConstraintTime", "handles", "the", "time", "constraint", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L312-L330
train
open-policy-agent/opa
topdown/tokens.go
tokenConstraintString
func tokenConstraintString(name string, value ast.Value, where *string) (err error) { var av ast.String var ok bool if av, ok = value.(ast.String); !ok { err = fmt.Errorf("%s constraint: must be a string", name) return } *where = string(av) return }
go
func tokenConstraintString(name string, value ast.Value, where *string) (err error) { var av ast.String var ok bool if av, ok = value.(ast.String); !ok { err = fmt.Errorf("%s constraint: must be a string", name) return } *where = string(av) return }
[ "func", "tokenConstraintString", "(", "name", "string", ",", "value", "ast", ".", "Value", ",", "where", "*", "string", ")", "(", "err", "error", ")", "{", "var", "av", "ast", ".", "String", "\n", "var", "ok", "bool", "\n", "if", "av", ",", "ok", "=", "value", ".", "(", "ast", ".", "String", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "\n", "}", "\n", "*", "where", "=", "string", "(", "av", ")", "\n", "return", "\n", "}" ]
// tokenConstraintString handles string constraints.
[ "tokenConstraintString", "handles", "string", "constraints", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L333-L342
train
open-policy-agent/opa
topdown/tokens.go
parseTokenConstraints
func parseTokenConstraints(a ast.Value) (constraints tokenConstraints, err error) { constraints.time = -1 var o ast.Object var ok bool if o, ok = a.(ast.Object); !ok { err = fmt.Errorf("token constraints must be object") return } if err = o.Iter(func(k *ast.Term, v *ast.Term) (err error) { var handler tokenConstraintHandler var ok bool name := string(k.Value.(ast.String)) if handler, ok = tokenConstraintTypes[name]; ok { if err = handler(v.Value, &constraints); err != nil { return } } else { // Anything unknown is rejected. err = fmt.Errorf("unknown token validation constraint: %s", name) return } return }); err != nil { return } return }
go
func parseTokenConstraints(a ast.Value) (constraints tokenConstraints, err error) { constraints.time = -1 var o ast.Object var ok bool if o, ok = a.(ast.Object); !ok { err = fmt.Errorf("token constraints must be object") return } if err = o.Iter(func(k *ast.Term, v *ast.Term) (err error) { var handler tokenConstraintHandler var ok bool name := string(k.Value.(ast.String)) if handler, ok = tokenConstraintTypes[name]; ok { if err = handler(v.Value, &constraints); err != nil { return } } else { // Anything unknown is rejected. err = fmt.Errorf("unknown token validation constraint: %s", name) return } return }); err != nil { return } return }
[ "func", "parseTokenConstraints", "(", "a", "ast", ".", "Value", ")", "(", "constraints", "tokenConstraints", ",", "err", "error", ")", "{", "constraints", ".", "time", "=", "-", "1", "\n", "var", "o", "ast", ".", "Object", "\n", "var", "ok", "bool", "\n", "if", "o", ",", "ok", "=", "a", ".", "(", "ast", ".", "Object", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "err", "=", "o", ".", "Iter", "(", "func", "(", "k", "*", "ast", ".", "Term", ",", "v", "*", "ast", ".", "Term", ")", "(", "err", "error", ")", "{", "var", "handler", "tokenConstraintHandler", "\n", "var", "ok", "bool", "\n", "name", ":=", "string", "(", "k", ".", "Value", ".", "(", "ast", ".", "String", ")", ")", "\n", "if", "handler", ",", "ok", "=", "tokenConstraintTypes", "[", "name", "]", ";", "ok", "{", "if", "err", "=", "handler", "(", "v", ".", "Value", ",", "&", "constraints", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "// Anything unknown is rejected.", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "\n", "}", "\n", "return", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "\n", "}" ]
// parseTokenConstraints parses the constraints argument.
[ "parseTokenConstraints", "parses", "the", "constraints", "argument", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L345-L371
train
open-policy-agent/opa
topdown/tokens.go
validate
func (constraints *tokenConstraints) validate() (err error) { keys := 0 if constraints.key != nil { keys++ } if constraints.secret != "" { keys++ } if keys > 1 { err = fmt.Errorf("duplicate key constraints") return } if keys < 1 { err = fmt.Errorf("no key constraint") return } return }
go
func (constraints *tokenConstraints) validate() (err error) { keys := 0 if constraints.key != nil { keys++ } if constraints.secret != "" { keys++ } if keys > 1 { err = fmt.Errorf("duplicate key constraints") return } if keys < 1 { err = fmt.Errorf("no key constraint") return } return }
[ "func", "(", "constraints", "*", "tokenConstraints", ")", "validate", "(", ")", "(", "err", "error", ")", "{", "keys", ":=", "0", "\n", "if", "constraints", ".", "key", "!=", "nil", "{", "keys", "++", "\n", "}", "\n", "if", "constraints", ".", "secret", "!=", "\"", "\"", "{", "keys", "++", "\n", "}", "\n", "if", "keys", ">", "1", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "keys", "<", "1", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "return", "\n", "}" ]
// validate validates the constraints argument.
[ "validate", "validates", "the", "constraints", "argument", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L374-L391
train
open-policy-agent/opa
topdown/tokens.go
verify
func (constraints *tokenConstraints) verify(kid, alg, header, payload, signature string) (err error) { // Construct the payload plaintext := []byte(header) plaintext = append(plaintext, []byte(".")...) plaintext = append(plaintext, payload...) // Look up the algorithm var ok bool var a tokenAlgorithm a, ok = tokenAlgorithms[alg] if !ok { err = fmt.Errorf("unknown JWS algorithm: %s", alg) return } // If we're configured with a single key then only trust that if constraints.key != nil { return a.verify(constraints.key, a.hash, plaintext, []byte(signature)) } if constraints.secret != "" { return a.verify([]byte(constraints.secret), a.hash, plaintext, []byte(signature)) } // (*tokenConstraints)validate() should prevent this happening err = errors.New("unexpectedly found no keys to trust") return }
go
func (constraints *tokenConstraints) verify(kid, alg, header, payload, signature string) (err error) { // Construct the payload plaintext := []byte(header) plaintext = append(plaintext, []byte(".")...) plaintext = append(plaintext, payload...) // Look up the algorithm var ok bool var a tokenAlgorithm a, ok = tokenAlgorithms[alg] if !ok { err = fmt.Errorf("unknown JWS algorithm: %s", alg) return } // If we're configured with a single key then only trust that if constraints.key != nil { return a.verify(constraints.key, a.hash, plaintext, []byte(signature)) } if constraints.secret != "" { return a.verify([]byte(constraints.secret), a.hash, plaintext, []byte(signature)) } // (*tokenConstraints)validate() should prevent this happening err = errors.New("unexpectedly found no keys to trust") return }
[ "func", "(", "constraints", "*", "tokenConstraints", ")", "verify", "(", "kid", ",", "alg", ",", "header", ",", "payload", ",", "signature", "string", ")", "(", "err", "error", ")", "{", "// Construct the payload", "plaintext", ":=", "[", "]", "byte", "(", "header", ")", "\n", "plaintext", "=", "append", "(", "plaintext", ",", "[", "]", "byte", "(", "\"", "\"", ")", "...", ")", "\n", "plaintext", "=", "append", "(", "plaintext", ",", "payload", "...", ")", "\n", "// Look up the algorithm", "var", "ok", "bool", "\n", "var", "a", "tokenAlgorithm", "\n", "a", ",", "ok", "=", "tokenAlgorithms", "[", "alg", "]", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "alg", ")", "\n", "return", "\n", "}", "\n", "// If we're configured with a single key then only trust that", "if", "constraints", ".", "key", "!=", "nil", "{", "return", "a", ".", "verify", "(", "constraints", ".", "key", ",", "a", ".", "hash", ",", "plaintext", ",", "[", "]", "byte", "(", "signature", ")", ")", "\n", "}", "\n", "if", "constraints", ".", "secret", "!=", "\"", "\"", "{", "return", "a", ".", "verify", "(", "[", "]", "byte", "(", "constraints", ".", "secret", ")", ",", "a", ".", "hash", ",", "plaintext", ",", "[", "]", "byte", "(", "signature", ")", ")", "\n", "}", "\n", "// (*tokenConstraints)validate() should prevent this happening", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}" ]
// verify verifies a JWT using the constraints and the algorithm from the header
[ "verify", "verifies", "a", "JWT", "using", "the", "constraints", "and", "the", "algorithm", "from", "the", "header" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L394-L417
train
open-policy-agent/opa
topdown/tokens.go
validAudience
func (constraints *tokenConstraints) validAudience(aud ast.Value) (valid bool) { var ok bool var s ast.String if s, ok = aud.(ast.String); ok { return string(s) == constraints.aud } var a ast.Array if a, ok = aud.(ast.Array); ok { for _, t := range a { if s, ok = t.Value.(ast.String); ok { if string(s) == constraints.aud { return true } } else { // Ill-formed aud claim return false } } } return false }
go
func (constraints *tokenConstraints) validAudience(aud ast.Value) (valid bool) { var ok bool var s ast.String if s, ok = aud.(ast.String); ok { return string(s) == constraints.aud } var a ast.Array if a, ok = aud.(ast.Array); ok { for _, t := range a { if s, ok = t.Value.(ast.String); ok { if string(s) == constraints.aud { return true } } else { // Ill-formed aud claim return false } } } return false }
[ "func", "(", "constraints", "*", "tokenConstraints", ")", "validAudience", "(", "aud", "ast", ".", "Value", ")", "(", "valid", "bool", ")", "{", "var", "ok", "bool", "\n", "var", "s", "ast", ".", "String", "\n", "if", "s", ",", "ok", "=", "aud", ".", "(", "ast", ".", "String", ")", ";", "ok", "{", "return", "string", "(", "s", ")", "==", "constraints", ".", "aud", "\n", "}", "\n", "var", "a", "ast", ".", "Array", "\n", "if", "a", ",", "ok", "=", "aud", ".", "(", "ast", ".", "Array", ")", ";", "ok", "{", "for", "_", ",", "t", ":=", "range", "a", "{", "if", "s", ",", "ok", "=", "t", ".", "Value", ".", "(", "ast", ".", "String", ")", ";", "ok", "{", "if", "string", "(", "s", ")", "==", "constraints", ".", "aud", "{", "return", "true", "\n", "}", "\n", "}", "else", "{", "// Ill-formed aud claim", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// validAudience checks the audience of the JWT. // It returns true if it meets the constraints and false otherwise.
[ "validAudience", "checks", "the", "audience", "of", "the", "JWT", ".", "It", "returns", "true", "if", "it", "meets", "the", "constraints", "and", "false", "otherwise", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L421-L441
train
open-policy-agent/opa
topdown/tokens.go
tokenHeaderCrit
func tokenHeaderCrit(header *tokenHeader, value ast.Value) (err error) { var ok bool var v ast.Array if v, ok = value.(ast.Array); !ok { err = fmt.Errorf("crit: must be a list") return } header.crit = map[string]bool{} for _, t := range v { var tv ast.String if tv, ok = t.Value.(ast.String); !ok { err = fmt.Errorf("crit: must be a list of strings") return } header.crit[string(tv)] = true } if len(header.crit) == 0 { err = fmt.Errorf("crit: must be a nonempty list") // 'MUST NOT' use the empty list return } return }
go
func tokenHeaderCrit(header *tokenHeader, value ast.Value) (err error) { var ok bool var v ast.Array if v, ok = value.(ast.Array); !ok { err = fmt.Errorf("crit: must be a list") return } header.crit = map[string]bool{} for _, t := range v { var tv ast.String if tv, ok = t.Value.(ast.String); !ok { err = fmt.Errorf("crit: must be a list of strings") return } header.crit[string(tv)] = true } if len(header.crit) == 0 { err = fmt.Errorf("crit: must be a nonempty list") // 'MUST NOT' use the empty list return } return }
[ "func", "tokenHeaderCrit", "(", "header", "*", "tokenHeader", ",", "value", "ast", ".", "Value", ")", "(", "err", "error", ")", "{", "var", "ok", "bool", "\n", "var", "v", "ast", ".", "Array", "\n", "if", "v", ",", "ok", "=", "value", ".", "(", "ast", ".", "Array", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "header", ".", "crit", "=", "map", "[", "string", "]", "bool", "{", "}", "\n", "for", "_", ",", "t", ":=", "range", "v", "{", "var", "tv", "ast", ".", "String", "\n", "if", "tv", ",", "ok", "=", "t", ".", "Value", ".", "(", "ast", ".", "String", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "header", ".", "crit", "[", "string", "(", "tv", ")", "]", "=", "true", "\n", "}", "\n", "if", "len", "(", "header", ".", "crit", ")", "==", "0", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "// 'MUST NOT' use the empty list", "\n", "return", "\n", "}", "\n", "return", "\n", "}" ]
// tokenHeaderCrit handles the 'crit' header parameter
[ "tokenHeaderCrit", "handles", "the", "crit", "header", "parameter" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L567-L588
train
open-policy-agent/opa
topdown/tokens.go
tokenHeaderString
func tokenHeaderString(name string, where *string, value ast.Value) (err error) { var ok bool var v ast.String if v, ok = value.(ast.String); !ok { err = fmt.Errorf("%s: must be a string", name) return } *where = string(v) return }
go
func tokenHeaderString(name string, where *string, value ast.Value) (err error) { var ok bool var v ast.String if v, ok = value.(ast.String); !ok { err = fmt.Errorf("%s: must be a string", name) return } *where = string(v) return }
[ "func", "tokenHeaderString", "(", "name", "string", ",", "where", "*", "string", ",", "value", "ast", ".", "Value", ")", "(", "err", "error", ")", "{", "var", "ok", "bool", "\n", "var", "v", "ast", ".", "String", "\n", "if", "v", ",", "ok", "=", "value", ".", "(", "ast", ".", "String", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "\n", "}", "\n", "*", "where", "=", "string", "(", "v", ")", "\n", "return", "\n", "}" ]
// tokenHeaderString handles string-format JWT header parameters
[ "tokenHeaderString", "handles", "string", "-", "format", "JWT", "header", "parameters" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L591-L600
train
open-policy-agent/opa
topdown/tokens.go
parseTokenHeader
func parseTokenHeader(token *JSONWebToken) (header tokenHeader, err error) { header.unknown = []string{} if err = token.decodedHeader.Iter(func(k *ast.Term, v *ast.Term) (err error) { ks := string(k.Value.(ast.String)) var ok bool var handler tokenHeaderHandler if handler, ok = tokenHeaderTypes[ks]; ok { if err = handler(&header, v.Value); err != nil { return } } else { header.unknown = append(header.unknown, ks) } return }); err != nil { return } return }
go
func parseTokenHeader(token *JSONWebToken) (header tokenHeader, err error) { header.unknown = []string{} if err = token.decodedHeader.Iter(func(k *ast.Term, v *ast.Term) (err error) { ks := string(k.Value.(ast.String)) var ok bool var handler tokenHeaderHandler if handler, ok = tokenHeaderTypes[ks]; ok { if err = handler(&header, v.Value); err != nil { return } } else { header.unknown = append(header.unknown, ks) } return }); err != nil { return } return }
[ "func", "parseTokenHeader", "(", "token", "*", "JSONWebToken", ")", "(", "header", "tokenHeader", ",", "err", "error", ")", "{", "header", ".", "unknown", "=", "[", "]", "string", "{", "}", "\n", "if", "err", "=", "token", ".", "decodedHeader", ".", "Iter", "(", "func", "(", "k", "*", "ast", ".", "Term", ",", "v", "*", "ast", ".", "Term", ")", "(", "err", "error", ")", "{", "ks", ":=", "string", "(", "k", ".", "Value", ".", "(", "ast", ".", "String", ")", ")", "\n", "var", "ok", "bool", "\n", "var", "handler", "tokenHeaderHandler", "\n", "if", "handler", ",", "ok", "=", "tokenHeaderTypes", "[", "ks", "]", ";", "ok", "{", "if", "err", "=", "handler", "(", "&", "header", ",", "v", ".", "Value", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "else", "{", "header", ".", "unknown", "=", "append", "(", "header", ".", "unknown", ",", "ks", ")", "\n", "}", "\n", "return", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "\n", "}" ]
// parseTokenHeader parses the JWT header.
[ "parseTokenHeader", "parses", "the", "JWT", "header", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L603-L621
train
open-policy-agent/opa
topdown/tokens.go
valid
func (header *tokenHeader) valid() bool { // RFC7515 s4.1.1 alg MUST be present if header.alg == "" { return false } // RFC7515 4.1.11 JWS is invalid if there is a critical parameter that we did not recognize for _, u := range header.unknown { if header.crit[u] { return false } } return true }
go
func (header *tokenHeader) valid() bool { // RFC7515 s4.1.1 alg MUST be present if header.alg == "" { return false } // RFC7515 4.1.11 JWS is invalid if there is a critical parameter that we did not recognize for _, u := range header.unknown { if header.crit[u] { return false } } return true }
[ "func", "(", "header", "*", "tokenHeader", ")", "valid", "(", ")", "bool", "{", "// RFC7515 s4.1.1 alg MUST be present", "if", "header", ".", "alg", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "// RFC7515 4.1.11 JWS is invalid if there is a critical parameter that we did not recognize", "for", "_", ",", "u", ":=", "range", "header", ".", "unknown", "{", "if", "header", ".", "crit", "[", "u", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// validTokenHeader returns true if the JOSE header is valid, otherwise false.
[ "validTokenHeader", "returns", "true", "if", "the", "JOSE", "header", "is", "valid", "otherwise", "false", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L624-L636
train
open-policy-agent/opa
topdown/tokens.go
validateJWTHeader
func validateJWTHeader(h string) (ast.Object, error) { header, err := extractJSONObject(h) if err != nil { return nil, fmt.Errorf("bad JWT header: %v", err) } // There are two kinds of JWT tokens, a JSON Web Signature (JWS) and // a JSON Web Encryption (JWE). The latter is very involved, and we // won't support it for now. // This code checks which kind of JWT we are dealing with according to // RFC 7516 Section 9: https://tools.ietf.org/html/rfc7516#section-9 if header.Get(jwtEncKey) != nil { return nil, errors.New("JWT is a JWE object, which is not supported") } return header, nil }
go
func validateJWTHeader(h string) (ast.Object, error) { header, err := extractJSONObject(h) if err != nil { return nil, fmt.Errorf("bad JWT header: %v", err) } // There are two kinds of JWT tokens, a JSON Web Signature (JWS) and // a JSON Web Encryption (JWE). The latter is very involved, and we // won't support it for now. // This code checks which kind of JWT we are dealing with according to // RFC 7516 Section 9: https://tools.ietf.org/html/rfc7516#section-9 if header.Get(jwtEncKey) != nil { return nil, errors.New("JWT is a JWE object, which is not supported") } return header, nil }
[ "func", "validateJWTHeader", "(", "h", "string", ")", "(", "ast", ".", "Object", ",", "error", ")", "{", "header", ",", "err", ":=", "extractJSONObject", "(", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// There are two kinds of JWT tokens, a JSON Web Signature (JWS) and", "// a JSON Web Encryption (JWE). The latter is very involved, and we", "// won't support it for now.", "// This code checks which kind of JWT we are dealing with according to", "// RFC 7516 Section 9: https://tools.ietf.org/html/rfc7516#section-9", "if", "header", ".", "Get", "(", "jwtEncKey", ")", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "header", ",", "nil", "\n", "}" ]
// Extract, validate and return the JWT header as an ast.Object.
[ "Extract", "validate", "and", "return", "the", "JWT", "header", "as", "an", "ast", ".", "Object", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L805-L821
train
open-policy-agent/opa
topdown/tokens.go
getInputSHA
func getInputSHA(input []byte) (hash []byte) { hasher := sha256.New() hasher.Write(input) return hasher.Sum(nil) }
go
func getInputSHA(input []byte) (hash []byte) { hasher := sha256.New() hasher.Write(input) return hasher.Sum(nil) }
[ "func", "getInputSHA", "(", "input", "[", "]", "byte", ")", "(", "hash", "[", "]", "byte", ")", "{", "hasher", ":=", "sha256", ".", "New", "(", ")", "\n", "hasher", ".", "Write", "(", "input", ")", "\n", "return", "hasher", ".", "Sum", "(", "nil", ")", "\n", "}" ]
// getInputSha returns the SHA256 checksum of the input
[ "getInputSha", "returns", "the", "SHA256", "checksum", "of", "the", "input" ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/topdown/tokens.go#L845-L849
train
open-policy-agent/opa
util/enumflag.go
NewEnumFlag
func NewEnumFlag(defaultValue string, vs []string) *EnumFlag { f := &EnumFlag{ i: -1, vs: vs, defaultValue: defaultValue, } return f }
go
func NewEnumFlag(defaultValue string, vs []string) *EnumFlag { f := &EnumFlag{ i: -1, vs: vs, defaultValue: defaultValue, } return f }
[ "func", "NewEnumFlag", "(", "defaultValue", "string", ",", "vs", "[", "]", "string", ")", "*", "EnumFlag", "{", "f", ":=", "&", "EnumFlag", "{", "i", ":", "-", "1", ",", "vs", ":", "vs", ",", "defaultValue", ":", "defaultValue", ",", "}", "\n", "return", "f", "\n", "}" ]
// NewEnumFlag returns a new EnumFlag that has a defaultValue and vs enumerated // values.
[ "NewEnumFlag", "returns", "a", "new", "EnumFlag", "that", "has", "a", "defaultValue", "and", "vs", "enumerated", "values", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/util/enumflag.go#L22-L29
train
open-policy-agent/opa
util/enumflag.go
String
func (f *EnumFlag) String() string { if f.i == -1 { return f.defaultValue } return f.vs[f.i] }
go
func (f *EnumFlag) String() string { if f.i == -1 { return f.defaultValue } return f.vs[f.i] }
[ "func", "(", "f", "*", "EnumFlag", ")", "String", "(", ")", "string", "{", "if", "f", ".", "i", "==", "-", "1", "{", "return", "f", ".", "defaultValue", "\n", "}", "\n", "return", "f", ".", "vs", "[", "f", ".", "i", "]", "\n", "}" ]
// String returns the EnumValue's value as string.
[ "String", "returns", "the", "EnumValue", "s", "value", "as", "string", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/util/enumflag.go#L37-L42
train
open-policy-agent/opa
util/enumflag.go
Set
func (f *EnumFlag) Set(s string) error { for i := range f.vs { if f.vs[i] == s { f.i = i return nil } } return fmt.Errorf("must be one of %v", f.Type()) }
go
func (f *EnumFlag) Set(s string) error { for i := range f.vs { if f.vs[i] == s { f.i = i return nil } } return fmt.Errorf("must be one of %v", f.Type()) }
[ "func", "(", "f", "*", "EnumFlag", ")", "Set", "(", "s", "string", ")", "error", "{", "for", "i", ":=", "range", "f", ".", "vs", "{", "if", "f", ".", "vs", "[", "i", "]", "==", "s", "{", "f", ".", "i", "=", "i", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Type", "(", ")", ")", "\n", "}" ]
// Set sets the enum value. If s is not a valid enum value, an error is // returned.
[ "Set", "sets", "the", "enum", "value", ".", "If", "s", "is", "not", "a", "valid", "enum", "value", "an", "error", "is", "returned", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/util/enumflag.go#L46-L54
train
open-policy-agent/opa
internal/wasm/encoding/writer.go
WriteModule
func WriteModule(w io.Writer, module *module.Module) error { if err := writeMagic(w); err != nil { return err } if err := writeVersion(w); err != nil { return err } if module == nil { return nil } if err := writeTypeSection(w, module.Type); err != nil { return err } if err := writeImportSection(w, module.Import); err != nil { return err } if err := writeFunctionSection(w, module.Function); err != nil { return err } if err := writeTableSection(w, module.Table); err != nil { return err } if err := writeGlobalSection(w, module.Global); err != nil { return err } if err := writeExportSection(w, module.Export); err != nil { return err } if err := writeRawCodeSection(w, module.Code); err != nil { return err } if err := writeDataSection(w, module.Data); err != nil { return err } return nil }
go
func WriteModule(w io.Writer, module *module.Module) error { if err := writeMagic(w); err != nil { return err } if err := writeVersion(w); err != nil { return err } if module == nil { return nil } if err := writeTypeSection(w, module.Type); err != nil { return err } if err := writeImportSection(w, module.Import); err != nil { return err } if err := writeFunctionSection(w, module.Function); err != nil { return err } if err := writeTableSection(w, module.Table); err != nil { return err } if err := writeGlobalSection(w, module.Global); err != nil { return err } if err := writeExportSection(w, module.Export); err != nil { return err } if err := writeRawCodeSection(w, module.Code); err != nil { return err } if err := writeDataSection(w, module.Data); err != nil { return err } return nil }
[ "func", "WriteModule", "(", "w", "io", ".", "Writer", ",", "module", "*", "module", ".", "Module", ")", "error", "{", "if", "err", ":=", "writeMagic", "(", "w", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeVersion", "(", "w", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "module", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "writeTypeSection", "(", "w", ",", "module", ".", "Type", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeImportSection", "(", "w", ",", "module", ".", "Import", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeFunctionSection", "(", "w", ",", "module", ".", "Function", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeTableSection", "(", "w", ",", "module", ".", "Table", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeGlobalSection", "(", "w", ",", "module", ".", "Global", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeExportSection", "(", "w", ",", "module", ".", "Export", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeRawCodeSection", "(", "w", ",", "module", ".", "Code", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeDataSection", "(", "w", ",", "module", ".", "Data", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// WriteModule writes a binary-encoded representation of module to w.
[ "WriteModule", "writes", "a", "binary", "-", "encoded", "representation", "of", "module", "to", "w", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/internal/wasm/encoding/writer.go#L23-L70
train
open-policy-agent/opa
internal/wasm/encoding/writer.go
WriteCodeEntry
func WriteCodeEntry(w io.Writer, entry *module.CodeEntry) error { if err := leb128.WriteVarUint32(w, uint32(len(entry.Func.Locals))); err != nil { return err } for _, local := range entry.Func.Locals { if err := leb128.WriteVarUint32(w, local.Count); err != nil { return err } if err := writeValueType(w, local.Type); err != nil { return err } } return writeInstructions(w, entry.Func.Expr.Instrs) }
go
func WriteCodeEntry(w io.Writer, entry *module.CodeEntry) error { if err := leb128.WriteVarUint32(w, uint32(len(entry.Func.Locals))); err != nil { return err } for _, local := range entry.Func.Locals { if err := leb128.WriteVarUint32(w, local.Count); err != nil { return err } if err := writeValueType(w, local.Type); err != nil { return err } } return writeInstructions(w, entry.Func.Expr.Instrs) }
[ "func", "WriteCodeEntry", "(", "w", "io", ".", "Writer", ",", "entry", "*", "module", ".", "CodeEntry", ")", "error", "{", "if", "err", ":=", "leb128", ".", "WriteVarUint32", "(", "w", ",", "uint32", "(", "len", "(", "entry", ".", "Func", ".", "Locals", ")", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "local", ":=", "range", "entry", ".", "Func", ".", "Locals", "{", "if", "err", ":=", "leb128", ".", "WriteVarUint32", "(", "w", ",", "local", ".", "Count", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "writeValueType", "(", "w", ",", "local", ".", "Type", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "writeInstructions", "(", "w", ",", "entry", ".", "Func", ".", "Expr", ".", "Instrs", ")", "\n", "}" ]
// WriteCodeEntry writes a binary encoded representation of entry to w.
[ "WriteCodeEntry", "writes", "a", "binary", "encoded", "representation", "of", "entry", "to", "w", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/internal/wasm/encoding/writer.go#L73-L91
train
open-policy-agent/opa
config/config.go
ParseConfig
func ParseConfig(raw []byte, id string) (*Config, error) { var result Config if err := util.Unmarshal(raw, &result); err != nil { return nil, err } return &result, result.validateAndInjectDefaults(id) }
go
func ParseConfig(raw []byte, id string) (*Config, error) { var result Config if err := util.Unmarshal(raw, &result); err != nil { return nil, err } return &result, result.validateAndInjectDefaults(id) }
[ "func", "ParseConfig", "(", "raw", "[", "]", "byte", ",", "id", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "var", "result", "Config", "\n", "if", "err", ":=", "util", ".", "Unmarshal", "(", "raw", ",", "&", "result", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "result", ",", "result", ".", "validateAndInjectDefaults", "(", "id", ")", "\n", "}" ]
// ParseConfig returns a valid Config object with defaults injected. The id // and version parameters will be set in the labels map.
[ "ParseConfig", "returns", "a", "valid", "Config", "object", "with", "defaults", "injected", ".", "The", "id", "and", "version", "parameters", "will", "be", "set", "in", "the", "labels", "map", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/config/config.go#L33-L39
train
open-policy-agent/opa
config/config.go
PluginsEnabled
func (c Config) PluginsEnabled() bool { return c.Bundle != nil || c.DecisionLogs != nil || c.Status != nil || len(c.Plugins) > 0 }
go
func (c Config) PluginsEnabled() bool { return c.Bundle != nil || c.DecisionLogs != nil || c.Status != nil || len(c.Plugins) > 0 }
[ "func", "(", "c", "Config", ")", "PluginsEnabled", "(", ")", "bool", "{", "return", "c", ".", "Bundle", "!=", "nil", "||", "c", ".", "DecisionLogs", "!=", "nil", "||", "c", ".", "Status", "!=", "nil", "||", "len", "(", "c", ".", "Plugins", ")", ">", "0", "\n", "}" ]
// PluginsEnabled returns true if one or more plugin features are enabled.
[ "PluginsEnabled", "returns", "true", "if", "one", "or", "more", "plugin", "features", "are", "enabled", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/config/config.go#L42-L44
train
open-policy-agent/opa
config/config.go
DefaultDecisionRef
func (c Config) DefaultDecisionRef() ast.Ref { ref, _ := parsePathToRef(*c.DefaultDecision) return ref }
go
func (c Config) DefaultDecisionRef() ast.Ref { ref, _ := parsePathToRef(*c.DefaultDecision) return ref }
[ "func", "(", "c", "Config", ")", "DefaultDecisionRef", "(", ")", "ast", ".", "Ref", "{", "ref", ",", "_", ":=", "parsePathToRef", "(", "*", "c", ".", "DefaultDecision", ")", "\n", "return", "ref", "\n", "}" ]
// DefaultDecisionRef returns the default decision as a reference.
[ "DefaultDecisionRef", "returns", "the", "default", "decision", "as", "a", "reference", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/config/config.go#L47-L50
train
open-policy-agent/opa
config/config.go
DefaultAuthorizationDecisionRef
func (c Config) DefaultAuthorizationDecisionRef() ast.Ref { ref, _ := parsePathToRef(*c.DefaultAuthorizationDecision) return ref }
go
func (c Config) DefaultAuthorizationDecisionRef() ast.Ref { ref, _ := parsePathToRef(*c.DefaultAuthorizationDecision) return ref }
[ "func", "(", "c", "Config", ")", "DefaultAuthorizationDecisionRef", "(", ")", "ast", ".", "Ref", "{", "ref", ",", "_", ":=", "parsePathToRef", "(", "*", "c", ".", "DefaultAuthorizationDecision", ")", "\n", "return", "ref", "\n", "}" ]
// DefaultAuthorizationDecisionRef returns the default authorization decision // as a reference.
[ "DefaultAuthorizationDecisionRef", "returns", "the", "default", "authorization", "decision", "as", "a", "reference", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/config/config.go#L54-L57
train
open-policy-agent/opa
plugins/bundle/plugin.go
Start
func (p *Plugin) Start(ctx context.Context) error { p.logInfo("Starting bundle downloader.") p.mtx.Lock() defer p.mtx.Unlock() p.downloader.Start(ctx) return nil }
go
func (p *Plugin) Start(ctx context.Context) error { p.logInfo("Starting bundle downloader.") p.mtx.Lock() defer p.mtx.Unlock() p.downloader.Start(ctx) return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Start", "(", "ctx", "context", ".", "Context", ")", "error", "{", "p", ".", "logInfo", "(", "\"", "\"", ")", "\n", "p", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n", "p", ".", "downloader", ".", "Start", "(", "ctx", ")", "\n", "return", "nil", "\n", "}" ]
// Start runs the plugin. The plugin will periodically try to download bundles // from the configured service. When a new bundle is downloaded, the data and // policies are extracted and inserted into storage.
[ "Start", "runs", "the", "plugin", ".", "The", "plugin", "will", "periodically", "try", "to", "download", "bundles", "from", "the", "configured", "service", ".", "When", "a", "new", "bundle", "is", "downloaded", "the", "data", "and", "policies", "are", "extracted", "and", "inserted", "into", "storage", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/bundle/plugin.go#L62-L68
train
open-policy-agent/opa
plugins/bundle/plugin.go
Reconfigure
func (p *Plugin) Reconfigure(ctx context.Context, config interface{}) { p.mtx.Lock() defer p.mtx.Unlock() newConfig := config.(*Config) if reflect.DeepEqual(p.config, *newConfig) { p.logDebug("Bundle downloader configuration unchanged.") return } p.logInfo("Bundle downloader configuration changed. Restarting bundle downloader.") p.config = *config.(*Config) p.downloader.Stop(ctx) p.initDownloader() p.downloader.Start(ctx) }
go
func (p *Plugin) Reconfigure(ctx context.Context, config interface{}) { p.mtx.Lock() defer p.mtx.Unlock() newConfig := config.(*Config) if reflect.DeepEqual(p.config, *newConfig) { p.logDebug("Bundle downloader configuration unchanged.") return } p.logInfo("Bundle downloader configuration changed. Restarting bundle downloader.") p.config = *config.(*Config) p.downloader.Stop(ctx) p.initDownloader() p.downloader.Start(ctx) }
[ "func", "(", "p", "*", "Plugin", ")", "Reconfigure", "(", "ctx", "context", ".", "Context", ",", "config", "interface", "{", "}", ")", "{", "p", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "newConfig", ":=", "config", ".", "(", "*", "Config", ")", "\n", "if", "reflect", ".", "DeepEqual", "(", "p", ".", "config", ",", "*", "newConfig", ")", "{", "p", ".", "logDebug", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "p", ".", "logInfo", "(", "\"", "\"", ")", "\n", "p", ".", "config", "=", "*", "config", ".", "(", "*", "Config", ")", "\n", "p", ".", "downloader", ".", "Stop", "(", "ctx", ")", "\n", "p", ".", "initDownloader", "(", ")", "\n", "p", ".", "downloader", ".", "Start", "(", "ctx", ")", "\n", "}" ]
// Reconfigure notifies the plugin that it's configuration has changed.
[ "Reconfigure", "notifies", "the", "plugin", "that", "it", "s", "configuration", "has", "changed", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/bundle/plugin.go#L79-L94
train
open-policy-agent/opa
plugins/bundle/plugin.go
Register
func (p *Plugin) Register(name interface{}, listener func(Status)) { p.mtx.Lock() defer p.mtx.Unlock() if p.listeners == nil { p.listeners = map[interface{}]func(Status){} } p.listeners[name] = listener }
go
func (p *Plugin) Register(name interface{}, listener func(Status)) { p.mtx.Lock() defer p.mtx.Unlock() if p.listeners == nil { p.listeners = map[interface{}]func(Status){} } p.listeners[name] = listener }
[ "func", "(", "p", "*", "Plugin", ")", "Register", "(", "name", "interface", "{", "}", ",", "listener", "func", "(", "Status", ")", ")", "{", "p", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mtx", ".", "Unlock", "(", ")", "\n\n", "if", "p", ".", "listeners", "==", "nil", "{", "p", ".", "listeners", "=", "map", "[", "interface", "{", "}", "]", "func", "(", "Status", ")", "{", "}", "\n", "}", "\n\n", "p", ".", "listeners", "[", "name", "]", "=", "listener", "\n", "}" ]
// Register a listener to receive status updates. The name must be comparable.
[ "Register", "a", "listener", "to", "receive", "status", "updates", ".", "The", "name", "must", "be", "comparable", "." ]
589105aff580587c1b27b87df7123105af3e212a
https://github.com/open-policy-agent/opa/blob/589105aff580587c1b27b87df7123105af3e212a/plugins/bundle/plugin.go#L97-L106
train