id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
8,900
matryer/moq
pkg/moq/moq.go
New
func New(src, packageName string) (*Mocker, error) { srcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax) if err != nil { return nil, fmt.Errorf("Couldn't load source package: %s", err) } pkgPath := srcPkg.PkgPath if len(packageName) == 0 { packageName = srcPkg.Name } else { mockPkgPath := filepath.Join(src, packageName) if _, err := os.Stat(mockPkgPath); os.IsNotExist(err) { os.Mkdir(mockPkgPath, os.ModePerm) } mockPkg, err := pkgInfoFromPath(mockPkgPath, packages.LoadFiles) if err != nil { return nil, fmt.Errorf("Couldn't load mock package: %s", err) } pkgPath = mockPkg.PkgPath } tmpl, err := template.New("moq").Funcs(templateFuncs).Parse(moqTemplate) if err != nil { return nil, err } return &Mocker{ tmpl: tmpl, srcPkg: srcPkg, pkgName: packageName, pkgPath: pkgPath, imports: make(map[string]bool), }, nil }
go
func New(src, packageName string) (*Mocker, error) { srcPkg, err := pkgInfoFromPath(src, packages.LoadSyntax) if err != nil { return nil, fmt.Errorf("Couldn't load source package: %s", err) } pkgPath := srcPkg.PkgPath if len(packageName) == 0 { packageName = srcPkg.Name } else { mockPkgPath := filepath.Join(src, packageName) if _, err := os.Stat(mockPkgPath); os.IsNotExist(err) { os.Mkdir(mockPkgPath, os.ModePerm) } mockPkg, err := pkgInfoFromPath(mockPkgPath, packages.LoadFiles) if err != nil { return nil, fmt.Errorf("Couldn't load mock package: %s", err) } pkgPath = mockPkg.PkgPath } tmpl, err := template.New("moq").Funcs(templateFuncs).Parse(moqTemplate) if err != nil { return nil, err } return &Mocker{ tmpl: tmpl, srcPkg: srcPkg, pkgName: packageName, pkgPath: pkgPath, imports: make(map[string]bool), }, nil }
[ "func", "New", "(", "src", ",", "packageName", "string", ")", "(", "*", "Mocker", ",", "error", ")", "{", "srcPkg", ",", "err", ":=", "pkgInfoFromPath", "(", "src", ",", "packages", ".", "LoadSyntax", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "pkgPath", ":=", "srcPkg", ".", "PkgPath", "\n\n", "if", "len", "(", "packageName", ")", "==", "0", "{", "packageName", "=", "srcPkg", ".", "Name", "\n", "}", "else", "{", "mockPkgPath", ":=", "filepath", ".", "Join", "(", "src", ",", "packageName", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "mockPkgPath", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "os", ".", "Mkdir", "(", "mockPkgPath", ",", "os", ".", "ModePerm", ")", "\n", "}", "\n", "mockPkg", ",", "err", ":=", "pkgInfoFromPath", "(", "mockPkgPath", ",", "packages", ".", "LoadFiles", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "pkgPath", "=", "mockPkg", ".", "PkgPath", "\n", "}", "\n\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "templateFuncs", ")", ".", "Parse", "(", "moqTemplate", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Mocker", "{", "tmpl", ":", "tmpl", ",", "srcPkg", ":", "srcPkg", ",", "pkgName", ":", "packageName", ",", "pkgPath", ":", "pkgPath", ",", "imports", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "}", ",", "nil", "\n", "}" ]
// New makes a new Mocker for the specified package directory.
[ "New", "makes", "a", "new", "Mocker", "for", "the", "specified", "package", "directory", "." ]
6cfb0558e1bd81d19c9909483c39e199634fed29
https://github.com/matryer/moq/blob/6cfb0558e1bd81d19c9909483c39e199634fed29/pkg/moq/moq.go#L73-L105
8,901
matryer/moq
pkg/moq/moq.go
Mock
func (m *Mocker) Mock(w io.Writer, name ...string) error { if len(name) == 0 { return errors.New("must specify one interface") } doc := doc{ PackageName: m.pkgName, Imports: moqImports, } mocksMethods := false tpkg := m.srcPkg.Types for _, n := range name { iface := tpkg.Scope().Lookup(n) if iface == nil { return fmt.Errorf("cannot find interface %s", n) } if !types.IsInterface(iface.Type()) { return fmt.Errorf("%s (%s) not an interface", n, iface.Type().String()) } iiface := iface.Type().Underlying().(*types.Interface).Complete() obj := obj{ InterfaceName: n, } for i := 0; i < iiface.NumMethods(); i++ { mocksMethods = true meth := iiface.Method(i) sig := meth.Type().(*types.Signature) method := &method{ Name: meth.Name(), } obj.Methods = append(obj.Methods, method) method.Params = m.extractArgs(sig, sig.Params(), "in%d") method.Returns = m.extractArgs(sig, sig.Results(), "out%d") } doc.Objects = append(doc.Objects, obj) } if mocksMethods { doc.Imports = append(doc.Imports, "sync") } for pkgToImport := range m.imports { doc.Imports = append(doc.Imports, stripVendorPath(pkgToImport)) } if tpkg.Name() != m.pkgName { doc.SourcePackagePrefix = tpkg.Name() + "." doc.Imports = append(doc.Imports, tpkg.Path()) } var buf bytes.Buffer err := m.tmpl.Execute(&buf, doc) if err != nil { return err } formatted, err := format.Source(buf.Bytes()) if err != nil { return fmt.Errorf("go/format: %s", err) } if _, err := w.Write(formatted); err != nil { return err } return nil }
go
func (m *Mocker) Mock(w io.Writer, name ...string) error { if len(name) == 0 { return errors.New("must specify one interface") } doc := doc{ PackageName: m.pkgName, Imports: moqImports, } mocksMethods := false tpkg := m.srcPkg.Types for _, n := range name { iface := tpkg.Scope().Lookup(n) if iface == nil { return fmt.Errorf("cannot find interface %s", n) } if !types.IsInterface(iface.Type()) { return fmt.Errorf("%s (%s) not an interface", n, iface.Type().String()) } iiface := iface.Type().Underlying().(*types.Interface).Complete() obj := obj{ InterfaceName: n, } for i := 0; i < iiface.NumMethods(); i++ { mocksMethods = true meth := iiface.Method(i) sig := meth.Type().(*types.Signature) method := &method{ Name: meth.Name(), } obj.Methods = append(obj.Methods, method) method.Params = m.extractArgs(sig, sig.Params(), "in%d") method.Returns = m.extractArgs(sig, sig.Results(), "out%d") } doc.Objects = append(doc.Objects, obj) } if mocksMethods { doc.Imports = append(doc.Imports, "sync") } for pkgToImport := range m.imports { doc.Imports = append(doc.Imports, stripVendorPath(pkgToImport)) } if tpkg.Name() != m.pkgName { doc.SourcePackagePrefix = tpkg.Name() + "." doc.Imports = append(doc.Imports, tpkg.Path()) } var buf bytes.Buffer err := m.tmpl.Execute(&buf, doc) if err != nil { return err } formatted, err := format.Source(buf.Bytes()) if err != nil { return fmt.Errorf("go/format: %s", err) } if _, err := w.Write(formatted); err != nil { return err } return nil }
[ "func", "(", "m", "*", "Mocker", ")", "Mock", "(", "w", "io", ".", "Writer", ",", "name", "...", "string", ")", "error", "{", "if", "len", "(", "name", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "doc", ":=", "doc", "{", "PackageName", ":", "m", ".", "pkgName", ",", "Imports", ":", "moqImports", ",", "}", "\n\n", "mocksMethods", ":=", "false", "\n\n", "tpkg", ":=", "m", ".", "srcPkg", ".", "Types", "\n", "for", "_", ",", "n", ":=", "range", "name", "{", "iface", ":=", "tpkg", ".", "Scope", "(", ")", ".", "Lookup", "(", "n", ")", "\n", "if", "iface", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "\n", "if", "!", "types", ".", "IsInterface", "(", "iface", ".", "Type", "(", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ",", "iface", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "iiface", ":=", "iface", ".", "Type", "(", ")", ".", "Underlying", "(", ")", ".", "(", "*", "types", ".", "Interface", ")", ".", "Complete", "(", ")", "\n", "obj", ":=", "obj", "{", "InterfaceName", ":", "n", ",", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "iiface", ".", "NumMethods", "(", ")", ";", "i", "++", "{", "mocksMethods", "=", "true", "\n", "meth", ":=", "iiface", ".", "Method", "(", "i", ")", "\n", "sig", ":=", "meth", ".", "Type", "(", ")", ".", "(", "*", "types", ".", "Signature", ")", "\n", "method", ":=", "&", "method", "{", "Name", ":", "meth", ".", "Name", "(", ")", ",", "}", "\n", "obj", ".", "Methods", "=", "append", "(", "obj", ".", "Methods", ",", "method", ")", "\n", "method", ".", "Params", "=", "m", ".", "extractArgs", "(", "sig", ",", "sig", ".", "Params", "(", ")", ",", "\"", "\"", ")", "\n", "method", ".", "Returns", "=", "m", ".", "extractArgs", "(", "sig", ",", "sig", ".", "Results", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "doc", ".", "Objects", "=", "append", "(", "doc", ".", "Objects", ",", "obj", ")", "\n", "}", "\n\n", "if", "mocksMethods", "{", "doc", ".", "Imports", "=", "append", "(", "doc", ".", "Imports", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "pkgToImport", ":=", "range", "m", ".", "imports", "{", "doc", ".", "Imports", "=", "append", "(", "doc", ".", "Imports", ",", "stripVendorPath", "(", "pkgToImport", ")", ")", "\n", "}", "\n\n", "if", "tpkg", ".", "Name", "(", ")", "!=", "m", ".", "pkgName", "{", "doc", ".", "SourcePackagePrefix", "=", "tpkg", ".", "Name", "(", ")", "+", "\"", "\"", "\n", "doc", ".", "Imports", "=", "append", "(", "doc", ".", "Imports", ",", "tpkg", ".", "Path", "(", ")", ")", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n", "err", ":=", "m", ".", "tmpl", ".", "Execute", "(", "&", "buf", ",", "doc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "formatted", ",", "err", ":=", "format", ".", "Source", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "w", ".", "Write", "(", "formatted", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Mock generates a mock for the specified interface name.
[ "Mock", "generates", "a", "mock", "for", "the", "specified", "interface", "name", "." ]
6cfb0558e1bd81d19c9909483c39e199634fed29
https://github.com/matryer/moq/blob/6cfb0558e1bd81d19c9909483c39e199634fed29/pkg/moq/moq.go#L108-L173
8,902
thejerf/suture
supervisor.go
Stop
func (s *Supervisor) Stop() { s.Lock() if s.state == notRunning { s.state = terminated s.Unlock() return } s.state = terminated s.Unlock() done := make(chan struct{}) if s.sendControl(stopSupervisor{done}) { <-done } }
go
func (s *Supervisor) Stop() { s.Lock() if s.state == notRunning { s.state = terminated s.Unlock() return } s.state = terminated s.Unlock() done := make(chan struct{}) if s.sendControl(stopSupervisor{done}) { <-done } }
[ "func", "(", "s", "*", "Supervisor", ")", "Stop", "(", ")", "{", "s", ".", "Lock", "(", ")", "\n", "if", "s", ".", "state", "==", "notRunning", "{", "s", ".", "state", "=", "terminated", "\n", "s", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "s", ".", "state", "=", "terminated", "\n", "s", ".", "Unlock", "(", ")", "\n\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "if", "s", ".", "sendControl", "(", "stopSupervisor", "{", "done", "}", ")", "{", "<-", "done", "\n", "}", "\n", "}" ]
// Stop stops the Supervisor. // // This function will not return until either all Services have stopped, or // they timeout after the timeout value given to the Supervisor at // creation.
[ "Stop", "stops", "the", "Supervisor", ".", "This", "function", "will", "not", "return", "until", "either", "all", "Services", "have", "stopped", "or", "they", "timeout", "after", "the", "timeout", "value", "given", "to", "the", "Supervisor", "at", "creation", "." ]
e97a74fdc74a2ddc29931e289bf419891b491712
https://github.com/thejerf/suture/blob/e97a74fdc74a2ddc29931e289bf419891b491712/supervisor.go#L526-L540
8,903
ericchiang/k8s
client.go
NewClient
func NewClient(config *Config) (*Client, error) { if len(config.Contexts) == 0 { if config.CurrentContext != "" { return nil, fmt.Errorf("no contexts with name %q", config.CurrentContext) } if n := len(config.Clusters); n == 0 { return nil, errors.New("no clusters provided") } else if n > 1 { return nil, errors.New("multiple clusters but no current context") } if n := len(config.AuthInfos); n == 0 { return nil, errors.New("no users provided") } else if n > 1 { return nil, errors.New("multiple users but no current context") } return newClient(config.Clusters[0].Cluster, config.AuthInfos[0].AuthInfo, namespaceDefault) } var ctx Context if config.CurrentContext == "" { if n := len(config.Contexts); n == 0 { return nil, errors.New("no contexts provided") } else if n > 1 { return nil, errors.New("multiple contexts but no current context") } ctx = config.Contexts[0].Context } else { for _, c := range config.Contexts { if c.Name == config.CurrentContext { ctx = c.Context goto configFound } } return nil, fmt.Errorf("no config named %q", config.CurrentContext) configFound: } if ctx.Cluster == "" { return nil, fmt.Errorf("context doesn't have a cluster") } if ctx.AuthInfo == "" { return nil, fmt.Errorf("context doesn't have a user") } var ( user AuthInfo cluster Cluster ) for _, u := range config.AuthInfos { if u.Name == ctx.AuthInfo { user = u.AuthInfo goto userFound } } return nil, fmt.Errorf("no user named %q", ctx.AuthInfo) userFound: for _, c := range config.Clusters { if c.Name == ctx.Cluster { cluster = c.Cluster goto clusterFound } } return nil, fmt.Errorf("no cluster named %q", ctx.Cluster) clusterFound: namespace := ctx.Namespace if namespace == "" { namespace = namespaceDefault } return newClient(cluster, user, namespace) }
go
func NewClient(config *Config) (*Client, error) { if len(config.Contexts) == 0 { if config.CurrentContext != "" { return nil, fmt.Errorf("no contexts with name %q", config.CurrentContext) } if n := len(config.Clusters); n == 0 { return nil, errors.New("no clusters provided") } else if n > 1 { return nil, errors.New("multiple clusters but no current context") } if n := len(config.AuthInfos); n == 0 { return nil, errors.New("no users provided") } else if n > 1 { return nil, errors.New("multiple users but no current context") } return newClient(config.Clusters[0].Cluster, config.AuthInfos[0].AuthInfo, namespaceDefault) } var ctx Context if config.CurrentContext == "" { if n := len(config.Contexts); n == 0 { return nil, errors.New("no contexts provided") } else if n > 1 { return nil, errors.New("multiple contexts but no current context") } ctx = config.Contexts[0].Context } else { for _, c := range config.Contexts { if c.Name == config.CurrentContext { ctx = c.Context goto configFound } } return nil, fmt.Errorf("no config named %q", config.CurrentContext) configFound: } if ctx.Cluster == "" { return nil, fmt.Errorf("context doesn't have a cluster") } if ctx.AuthInfo == "" { return nil, fmt.Errorf("context doesn't have a user") } var ( user AuthInfo cluster Cluster ) for _, u := range config.AuthInfos { if u.Name == ctx.AuthInfo { user = u.AuthInfo goto userFound } } return nil, fmt.Errorf("no user named %q", ctx.AuthInfo) userFound: for _, c := range config.Clusters { if c.Name == ctx.Cluster { cluster = c.Cluster goto clusterFound } } return nil, fmt.Errorf("no cluster named %q", ctx.Cluster) clusterFound: namespace := ctx.Namespace if namespace == "" { namespace = namespaceDefault } return newClient(cluster, user, namespace) }
[ "func", "NewClient", "(", "config", "*", "Config", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "len", "(", "config", ".", "Contexts", ")", "==", "0", "{", "if", "config", ".", "CurrentContext", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "CurrentContext", ")", "\n", "}", "\n\n", "if", "n", ":=", "len", "(", "config", ".", "Clusters", ")", ";", "n", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "if", "n", ">", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "n", ":=", "len", "(", "config", ".", "AuthInfos", ")", ";", "n", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "if", "n", ">", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "newClient", "(", "config", ".", "Clusters", "[", "0", "]", ".", "Cluster", ",", "config", ".", "AuthInfos", "[", "0", "]", ".", "AuthInfo", ",", "namespaceDefault", ")", "\n", "}", "\n\n", "var", "ctx", "Context", "\n", "if", "config", ".", "CurrentContext", "==", "\"", "\"", "{", "if", "n", ":=", "len", "(", "config", ".", "Contexts", ")", ";", "n", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "if", "n", ">", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "ctx", "=", "config", ".", "Contexts", "[", "0", "]", ".", "Context", "\n", "}", "else", "{", "for", "_", ",", "c", ":=", "range", "config", ".", "Contexts", "{", "if", "c", ".", "Name", "==", "config", ".", "CurrentContext", "{", "ctx", "=", "c", ".", "Context", "\n", "goto", "configFound", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "CurrentContext", ")", "\n", "configFound", ":", "}", "\n\n", "if", "ctx", ".", "Cluster", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "ctx", ".", "AuthInfo", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "(", "user", "AuthInfo", "\n", "cluster", "Cluster", "\n", ")", "\n\n", "for", "_", ",", "u", ":=", "range", "config", ".", "AuthInfos", "{", "if", "u", ".", "Name", "==", "ctx", ".", "AuthInfo", "{", "user", "=", "u", ".", "AuthInfo", "\n", "goto", "userFound", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctx", ".", "AuthInfo", ")", "\n", "userFound", ":", "for", "_", ",", "c", ":=", "range", "config", ".", "Clusters", "{", "if", "c", ".", "Name", "==", "ctx", ".", "Cluster", "{", "cluster", "=", "c", ".", "Cluster", "\n", "goto", "clusterFound", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctx", ".", "Cluster", ")", "\n", "clusterFound", ":", "namespace", ":=", "ctx", ".", "Namespace", "\n", "if", "namespace", "==", "\"", "\"", "{", "namespace", "=", "namespaceDefault", "\n", "}", "\n\n", "return", "newClient", "(", "cluster", ",", "user", ",", "namespace", ")", "\n", "}" ]
// NewClient initializes a client from a client config.
[ "NewClient", "initializes", "a", "client", "from", "a", "client", "config", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/client.go#L137-L211
8,904
ericchiang/k8s
client.go
NewInClusterClient
func NewInClusterClient() (*Client, error) { host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") if len(host) == 0 || len(port) == 0 { return nil, errors.New("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined") } namespace, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace") if err != nil { return nil, err } server := url.URL{ Scheme: "https", Host: net.JoinHostPort(host, port), } cluster := Cluster{ Server: server.String(), CertificateAuthority: "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt", } user := AuthInfo{TokenFile: "/var/run/secrets/kubernetes.io/serviceaccount/token"} return newClient(cluster, user, string(namespace)) }
go
func NewInClusterClient() (*Client, error) { host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") if len(host) == 0 || len(port) == 0 { return nil, errors.New("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined") } namespace, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace") if err != nil { return nil, err } server := url.URL{ Scheme: "https", Host: net.JoinHostPort(host, port), } cluster := Cluster{ Server: server.String(), CertificateAuthority: "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt", } user := AuthInfo{TokenFile: "/var/run/secrets/kubernetes.io/serviceaccount/token"} return newClient(cluster, user, string(namespace)) }
[ "func", "NewInClusterClient", "(", ")", "(", "*", "Client", ",", "error", ")", "{", "host", ",", "port", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "len", "(", "host", ")", "==", "0", "||", "len", "(", "port", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "namespace", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "server", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "net", ".", "JoinHostPort", "(", "host", ",", "port", ")", ",", "}", "\n", "cluster", ":=", "Cluster", "{", "Server", ":", "server", ".", "String", "(", ")", ",", "CertificateAuthority", ":", "\"", "\"", ",", "}", "\n", "user", ":=", "AuthInfo", "{", "TokenFile", ":", "\"", "\"", "}", "\n", "return", "newClient", "(", "cluster", ",", "user", ",", "string", "(", "namespace", ")", ")", "\n", "}" ]
// NewInClusterClient returns a client that uses the service account bearer token mounted // into Kubernetes pods.
[ "NewInClusterClient", "returns", "a", "client", "that", "uses", "the", "service", "account", "bearer", "token", "mounted", "into", "Kubernetes", "pods", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/client.go#L215-L235
8,905
ericchiang/k8s
examples/api-errors.go
createConfigMap
func createConfigMap(client *k8s.Client, name string, values map[string]string) error { cm := &v1.ConfigMap{ Metadata: &metav1.ObjectMeta{ Name: &name, Namespace: &client.Namespace, }, Data: values, } err := client.Create(context.Background(), cm) // If an HTTP error was returned by the API server, it will be of type // *k8s.APIError. This can be used to inspect the status code. if apiErr, ok := err.(*k8s.APIError); ok { // Resource already exists. Carry on. if apiErr.Code == http.StatusConflict { return nil } } return fmt.Errorf("create configmap: %v", err) }
go
func createConfigMap(client *k8s.Client, name string, values map[string]string) error { cm := &v1.ConfigMap{ Metadata: &metav1.ObjectMeta{ Name: &name, Namespace: &client.Namespace, }, Data: values, } err := client.Create(context.Background(), cm) // If an HTTP error was returned by the API server, it will be of type // *k8s.APIError. This can be used to inspect the status code. if apiErr, ok := err.(*k8s.APIError); ok { // Resource already exists. Carry on. if apiErr.Code == http.StatusConflict { return nil } } return fmt.Errorf("create configmap: %v", err) }
[ "func", "createConfigMap", "(", "client", "*", "k8s", ".", "Client", ",", "name", "string", ",", "values", "map", "[", "string", "]", "string", ")", "error", "{", "cm", ":=", "&", "v1", ".", "ConfigMap", "{", "Metadata", ":", "&", "metav1", ".", "ObjectMeta", "{", "Name", ":", "&", "name", ",", "Namespace", ":", "&", "client", ".", "Namespace", ",", "}", ",", "Data", ":", "values", ",", "}", "\n\n", "err", ":=", "client", ".", "Create", "(", "context", ".", "Background", "(", ")", ",", "cm", ")", "\n\n", "// If an HTTP error was returned by the API server, it will be of type", "// *k8s.APIError. This can be used to inspect the status code.", "if", "apiErr", ",", "ok", ":=", "err", ".", "(", "*", "k8s", ".", "APIError", ")", ";", "ok", "{", "// Resource already exists. Carry on.", "if", "apiErr", ".", "Code", "==", "http", ".", "StatusConflict", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}" ]
// createConfigMap creates a configmap in the client's default namespace // but does not return an error if a configmap of the same name already // exists.
[ "createConfigMap", "creates", "a", "configmap", "in", "the", "client", "s", "default", "namespace", "but", "does", "not", "return", "an", "error", "if", "a", "configmap", "of", "the", "same", "name", "already", "exists", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/examples/api-errors.go#L18-L38
8,906
ericchiang/k8s
labels.go
Eq
func (l *LabelSelector) Eq(key, val string) { if !validLabelValue(key) || !validLabelValue(val) { return } l.stmts = append(l.stmts, key+"="+val) }
go
func (l *LabelSelector) Eq(key, val string) { if !validLabelValue(key) || !validLabelValue(val) { return } l.stmts = append(l.stmts, key+"="+val) }
[ "func", "(", "l", "*", "LabelSelector", ")", "Eq", "(", "key", ",", "val", "string", ")", "{", "if", "!", "validLabelValue", "(", "key", ")", "||", "!", "validLabelValue", "(", "val", ")", "{", "return", "\n", "}", "\n", "l", ".", "stmts", "=", "append", "(", "l", ".", "stmts", ",", "key", "+", "\"", "\"", "+", "val", ")", "\n", "}" ]
// Eq selects labels which have the key and the key has the provide value.
[ "Eq", "selects", "labels", "which", "have", "the", "key", "and", "the", "key", "has", "the", "provide", "value", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/labels.go#L47-L52
8,907
ericchiang/k8s
labels.go
In
func (l *LabelSelector) In(key string, vals ...string) { if !validLabelValue(key) || len(vals) == 0 { return } for _, val := range vals { if !validLabelValue(val) { return } } l.stmts = append(l.stmts, key+" in ("+strings.Join(vals, ", ")+")") }
go
func (l *LabelSelector) In(key string, vals ...string) { if !validLabelValue(key) || len(vals) == 0 { return } for _, val := range vals { if !validLabelValue(val) { return } } l.stmts = append(l.stmts, key+" in ("+strings.Join(vals, ", ")+")") }
[ "func", "(", "l", "*", "LabelSelector", ")", "In", "(", "key", "string", ",", "vals", "...", "string", ")", "{", "if", "!", "validLabelValue", "(", "key", ")", "||", "len", "(", "vals", ")", "==", "0", "{", "return", "\n", "}", "\n", "for", "_", ",", "val", ":=", "range", "vals", "{", "if", "!", "validLabelValue", "(", "val", ")", "{", "return", "\n", "}", "\n", "}", "\n", "l", ".", "stmts", "=", "append", "(", "l", ".", "stmts", ",", "key", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "vals", ",", "\"", "\"", ")", "+", "\"", "\"", ")", "\n", "}" ]
// In selects labels which have the key and the key has one of the provided values.
[ "In", "selects", "labels", "which", "have", "the", "key", "and", "the", "key", "has", "one", "of", "the", "provided", "values", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/labels.go#L64-L74
8,908
ericchiang/k8s
resource.go
QueryParam
func QueryParam(name, value string) Option { return optionFunc(func(base string, v url.Values) string { v.Set(name, value) return base }) }
go
func QueryParam(name, value string) Option { return optionFunc(func(base string, v url.Values) string { v.Set(name, value) return base }) }
[ "func", "QueryParam", "(", "name", ",", "value", "string", ")", "Option", "{", "return", "optionFunc", "(", "func", "(", "base", "string", ",", "v", "url", ".", "Values", ")", "string", "{", "v", ".", "Set", "(", "name", ",", "value", ")", "\n", "return", "base", "\n", "}", ")", "\n", "}" ]
// QueryParam can be used to manually set a URL query parameter by name.
[ "QueryParam", "can", "be", "used", "to", "manually", "set", "a", "URL", "query", "parameter", "by", "name", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/resource.go#L39-L44
8,909
ericchiang/k8s
resource.go
Timeout
func Timeout(d time.Duration) Option { return QueryParam( "timeoutSeconds", strconv.FormatInt(int64(d/time.Second), 10), ) }
go
func Timeout(d time.Duration) Option { return QueryParam( "timeoutSeconds", strconv.FormatInt(int64(d/time.Second), 10), ) }
[ "func", "Timeout", "(", "d", "time", ".", "Duration", ")", "Option", "{", "return", "QueryParam", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "int64", "(", "d", "/", "time", ".", "Second", ")", ",", "10", ")", ",", ")", "\n", "}" ]
// Timeout declares the timeout for list and watch operations. Timeout // is only accurate to the second.
[ "Timeout", "declares", "the", "timeout", "for", "list", "and", "watch", "operations", ".", "Timeout", "is", "only", "accurate", "to", "the", "second", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/resource.go#L98-L103
8,910
ericchiang/k8s
examples/out-of-cluster-client.go
loadClient
func loadClient(kubeconfigPath string) (*k8s.Client, error) { data, err := ioutil.ReadFile(kubeconfigPath) if err != nil { return nil, fmt.Errorf("read kubeconfig: %v", err) } // Unmarshal YAML into a Kubernetes config object. var config k8s.Config if err := yaml.Unmarshal(data, &config); err != nil { return nil, fmt.Errorf("unmarshal kubeconfig: %v", err) } return k8s.NewClient(&config) }
go
func loadClient(kubeconfigPath string) (*k8s.Client, error) { data, err := ioutil.ReadFile(kubeconfigPath) if err != nil { return nil, fmt.Errorf("read kubeconfig: %v", err) } // Unmarshal YAML into a Kubernetes config object. var config k8s.Config if err := yaml.Unmarshal(data, &config); err != nil { return nil, fmt.Errorf("unmarshal kubeconfig: %v", err) } return k8s.NewClient(&config) }
[ "func", "loadClient", "(", "kubeconfigPath", "string", ")", "(", "*", "k8s", ".", "Client", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "kubeconfigPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Unmarshal YAML into a Kubernetes config object.", "var", "config", "k8s", ".", "Config", "\n", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "data", ",", "&", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "k8s", ".", "NewClient", "(", "&", "config", ")", "\n", "}" ]
// loadClient parses a kubeconfig from a file and returns a Kubernetes // client. It does not support extensions or client auth providers.
[ "loadClient", "parses", "a", "kubeconfig", "from", "a", "file", "and", "returns", "a", "Kubernetes", "client", ".", "It", "does", "not", "support", "extensions", "or", "client", "auth", "providers", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/examples/out-of-cluster-client.go#L16-L28
8,911
ericchiang/k8s
codec.go
marshal
func marshal(i interface{}) (string, []byte, error) { if _, ok := i.(proto.Message); ok { data, err := marshalPB(i) return contentTypePB, data, err } data, err := json.Marshal(i) return contentTypeJSON, data, err }
go
func marshal(i interface{}) (string, []byte, error) { if _, ok := i.(proto.Message); ok { data, err := marshalPB(i) return contentTypePB, data, err } data, err := json.Marshal(i) return contentTypeJSON, data, err }
[ "func", "marshal", "(", "i", "interface", "{", "}", ")", "(", "string", ",", "[", "]", "byte", ",", "error", ")", "{", "if", "_", ",", "ok", ":=", "i", ".", "(", "proto", ".", "Message", ")", ";", "ok", "{", "data", ",", "err", ":=", "marshalPB", "(", "i", ")", "\n", "return", "contentTypePB", ",", "data", ",", "err", "\n", "}", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "i", ")", "\n", "return", "contentTypeJSON", ",", "data", ",", "err", "\n", "}" ]
// marshal encodes an object and returns the content type of that resource // and the marshaled representation. // // marshal prefers protobuf encoding, but falls back to JSON.
[ "marshal", "encodes", "an", "object", "and", "returns", "the", "content", "type", "of", "that", "resource", "and", "the", "marshaled", "representation", ".", "marshal", "prefers", "protobuf", "encoding", "but", "falls", "back", "to", "JSON", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/codec.go#L29-L36
8,912
ericchiang/k8s
codec.go
unmarshal
func unmarshal(data []byte, contentType string, i interface{}) error { msg, isPBMsg := i.(proto.Message) if contentType == contentTypePB && isPBMsg { if err := unmarshalPB(data, msg); err != nil { return fmt.Errorf("decode protobuf: %v", err) } return nil } if isPBMsg { // only decode into JSON of a protobuf message if the type // explicitly implements json.Unmarshaler if _, ok := i.(json.Unmarshaler); !ok { return fmt.Errorf("cannot decode json payload into protobuf object %T", i) } } if err := json.Unmarshal(data, i); err != nil { return fmt.Errorf("decode json: %v", err) } return nil }
go
func unmarshal(data []byte, contentType string, i interface{}) error { msg, isPBMsg := i.(proto.Message) if contentType == contentTypePB && isPBMsg { if err := unmarshalPB(data, msg); err != nil { return fmt.Errorf("decode protobuf: %v", err) } return nil } if isPBMsg { // only decode into JSON of a protobuf message if the type // explicitly implements json.Unmarshaler if _, ok := i.(json.Unmarshaler); !ok { return fmt.Errorf("cannot decode json payload into protobuf object %T", i) } } if err := json.Unmarshal(data, i); err != nil { return fmt.Errorf("decode json: %v", err) } return nil }
[ "func", "unmarshal", "(", "data", "[", "]", "byte", ",", "contentType", "string", ",", "i", "interface", "{", "}", ")", "error", "{", "msg", ",", "isPBMsg", ":=", "i", ".", "(", "proto", ".", "Message", ")", "\n", "if", "contentType", "==", "contentTypePB", "&&", "isPBMsg", "{", "if", "err", ":=", "unmarshalPB", "(", "data", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "isPBMsg", "{", "// only decode into JSON of a protobuf message if the type", "// explicitly implements json.Unmarshaler", "if", "_", ",", "ok", ":=", "i", ".", "(", "json", ".", "Unmarshaler", ")", ";", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "i", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// unmarshal decoded an object given the content type of the encoded form.
[ "unmarshal", "decoded", "an", "object", "given", "the", "content", "type", "of", "the", "encoded", "form", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/codec.go#L39-L58
8,913
ericchiang/k8s
watch.go
Next
func (w *Watcher) Next(r Resource) (string, error) { return w.watcher.Next(r) }
go
func (w *Watcher) Next(r Resource) (string, error) { return w.watcher.Next(r) }
[ "func", "(", "w", "*", "Watcher", ")", "Next", "(", "r", "Resource", ")", "(", "string", ",", "error", ")", "{", "return", "w", ".", "watcher", ".", "Next", "(", "r", ")", "\n", "}" ]
// Next decodes the next event from the watch stream. Errors are fatal, and // indicate that the watcher should no longer be used, and must be recreated.
[ "Next", "decodes", "the", "next", "event", "from", "the", "watch", "stream", ".", "Errors", "are", "fatal", "and", "indicate", "that", "the", "watcher", "should", "no", "longer", "be", "used", "and", "must", "be", "recreated", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/watch.go#L36-L38
8,914
ericchiang/k8s
apis/meta/v1/json.go
MarshalJSON
func (t Time) MarshalJSON() ([]byte, error) { var seconds, nanos int64 if t.Seconds != nil { seconds = *t.Seconds } if t.Nanos != nil { nanos = int64(*t.Nanos) } return json.Marshal(time.Unix(seconds, nanos)) }
go
func (t Time) MarshalJSON() ([]byte, error) { var seconds, nanos int64 if t.Seconds != nil { seconds = *t.Seconds } if t.Nanos != nil { nanos = int64(*t.Nanos) } return json.Marshal(time.Unix(seconds, nanos)) }
[ "func", "(", "t", "Time", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "seconds", ",", "nanos", "int64", "\n", "if", "t", ".", "Seconds", "!=", "nil", "{", "seconds", "=", "*", "t", ".", "Seconds", "\n", "}", "\n", "if", "t", ".", "Nanos", "!=", "nil", "{", "nanos", "=", "int64", "(", "*", "t", ".", "Nanos", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "time", ".", "Unix", "(", "seconds", ",", "nanos", ")", ")", "\n", "}" ]
// JSON marshaling logic for the Time type so it can be used for custom // resources, which serialize to JSON.
[ "JSON", "marshaling", "logic", "for", "the", "Time", "type", "so", "it", "can", "be", "used", "for", "custom", "resources", "which", "serialize", "to", "JSON", "." ]
68fb2168bedf77759577a56e44f2ccfaf7229673
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/apis/meta/v1/json.go#L11-L20
8,915
petar/GoLLRB
llrb/llrb.go
Has
func (t *LLRB) Has(key Item) bool { return t.Get(key) != nil }
go
func (t *LLRB) Has(key Item) bool { return t.Get(key) != nil }
[ "func", "(", "t", "*", "LLRB", ")", "Has", "(", "key", "Item", ")", "bool", "{", "return", "t", ".", "Get", "(", "key", ")", "!=", "nil", "\n", "}" ]
// Has returns true if the tree contains an element whose order is the same as that of key.
[ "Has", "returns", "true", "if", "the", "tree", "contains", "an", "element", "whose", "order", "is", "the", "same", "as", "that", "of", "key", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L97-L99
8,916
petar/GoLLRB
llrb/llrb.go
Get
func (t *LLRB) Get(key Item) Item { h := t.root for h != nil { switch { case less(key, h.Item): h = h.Left case less(h.Item, key): h = h.Right default: return h.Item } } return nil }
go
func (t *LLRB) Get(key Item) Item { h := t.root for h != nil { switch { case less(key, h.Item): h = h.Left case less(h.Item, key): h = h.Right default: return h.Item } } return nil }
[ "func", "(", "t", "*", "LLRB", ")", "Get", "(", "key", "Item", ")", "Item", "{", "h", ":=", "t", ".", "root", "\n", "for", "h", "!=", "nil", "{", "switch", "{", "case", "less", "(", "key", ",", "h", ".", "Item", ")", ":", "h", "=", "h", ".", "Left", "\n", "case", "less", "(", "h", ".", "Item", ",", "key", ")", ":", "h", "=", "h", ".", "Right", "\n", "default", ":", "return", "h", ".", "Item", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Get retrieves an element from the tree whose order is the same as that of key.
[ "Get", "retrieves", "an", "element", "from", "the", "tree", "whose", "order", "is", "the", "same", "as", "that", "of", "key", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L102-L115
8,917
petar/GoLLRB
llrb/llrb.go
Min
func (t *LLRB) Min() Item { h := t.root if h == nil { return nil } for h.Left != nil { h = h.Left } return h.Item }
go
func (t *LLRB) Min() Item { h := t.root if h == nil { return nil } for h.Left != nil { h = h.Left } return h.Item }
[ "func", "(", "t", "*", "LLRB", ")", "Min", "(", ")", "Item", "{", "h", ":=", "t", ".", "root", "\n", "if", "h", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "h", ".", "Left", "!=", "nil", "{", "h", "=", "h", ".", "Left", "\n", "}", "\n", "return", "h", ".", "Item", "\n", "}" ]
// Min returns the minimum element in the tree.
[ "Min", "returns", "the", "minimum", "element", "in", "the", "tree", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L118-L127
8,918
petar/GoLLRB
llrb/llrb.go
Max
func (t *LLRB) Max() Item { h := t.root if h == nil { return nil } for h.Right != nil { h = h.Right } return h.Item }
go
func (t *LLRB) Max() Item { h := t.root if h == nil { return nil } for h.Right != nil { h = h.Right } return h.Item }
[ "func", "(", "t", "*", "LLRB", ")", "Max", "(", ")", "Item", "{", "h", ":=", "t", ".", "root", "\n", "if", "h", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "h", ".", "Right", "!=", "nil", "{", "h", "=", "h", ".", "Right", "\n", "}", "\n", "return", "h", ".", "Item", "\n", "}" ]
// Max returns the maximum element in the tree.
[ "Max", "returns", "the", "maximum", "element", "in", "the", "tree", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L130-L139
8,919
petar/GoLLRB
llrb/llrb.go
ReplaceOrInsert
func (t *LLRB) ReplaceOrInsert(item Item) Item { if item == nil { panic("inserting nil item") } var replaced Item t.root, replaced = t.replaceOrInsert(t.root, item) t.root.Black = true if replaced == nil { t.count++ } return replaced }
go
func (t *LLRB) ReplaceOrInsert(item Item) Item { if item == nil { panic("inserting nil item") } var replaced Item t.root, replaced = t.replaceOrInsert(t.root, item) t.root.Black = true if replaced == nil { t.count++ } return replaced }
[ "func", "(", "t", "*", "LLRB", ")", "ReplaceOrInsert", "(", "item", "Item", ")", "Item", "{", "if", "item", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "replaced", "Item", "\n", "t", ".", "root", ",", "replaced", "=", "t", ".", "replaceOrInsert", "(", "t", ".", "root", ",", "item", ")", "\n", "t", ".", "root", ".", "Black", "=", "true", "\n", "if", "replaced", "==", "nil", "{", "t", ".", "count", "++", "\n", "}", "\n", "return", "replaced", "\n", "}" ]
// ReplaceOrInsert inserts item into the tree. If an existing // element has the same order, it is removed from the tree and returned.
[ "ReplaceOrInsert", "inserts", "item", "into", "the", "tree", ".", "If", "an", "existing", "element", "has", "the", "same", "order", "it", "is", "removed", "from", "the", "tree", "and", "returned", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L155-L166
8,920
petar/GoLLRB
llrb/llrb.go
InsertNoReplace
func (t *LLRB) InsertNoReplace(item Item) { if item == nil { panic("inserting nil item") } t.root = t.insertNoReplace(t.root, item) t.root.Black = true t.count++ }
go
func (t *LLRB) InsertNoReplace(item Item) { if item == nil { panic("inserting nil item") } t.root = t.insertNoReplace(t.root, item) t.root.Black = true t.count++ }
[ "func", "(", "t", "*", "LLRB", ")", "InsertNoReplace", "(", "item", "Item", ")", "{", "if", "item", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "t", ".", "root", "=", "t", ".", "insertNoReplace", "(", "t", ".", "root", ",", "item", ")", "\n", "t", ".", "root", ".", "Black", "=", "true", "\n", "t", ".", "count", "++", "\n", "}" ]
// InsertNoReplace inserts item into the tree. If an existing // element has the same order, both elements remain in the tree.
[ "InsertNoReplace", "inserts", "item", "into", "the", "tree", ".", "If", "an", "existing", "element", "has", "the", "same", "order", "both", "elements", "remain", "in", "the", "tree", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L191-L198
8,921
petar/GoLLRB
llrb/llrb.go
walkDownRot234
func walkDownRot234(h *Node) *Node { if isRed(h.Left) && isRed(h.Right) { flip(h) } return h }
go
func walkDownRot234(h *Node) *Node { if isRed(h.Left) && isRed(h.Right) { flip(h) } return h }
[ "func", "walkDownRot234", "(", "h", "*", "Node", ")", "*", "Node", "{", "if", "isRed", "(", "h", ".", "Left", ")", "&&", "isRed", "(", "h", ".", "Right", ")", "{", "flip", "(", "h", ")", "\n", "}", "\n\n", "return", "h", "\n", "}" ]
// Rotation driver routines for 2-3-4 algorithm
[ "Rotation", "driver", "routines", "for", "2", "-", "3", "-", "4", "algorithm" ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L238-L244
8,922
petar/GoLLRB
llrb/llrb.go
DeleteMin
func (t *LLRB) DeleteMin() Item { var deleted Item t.root, deleted = deleteMin(t.root) if t.root != nil { t.root.Black = true } if deleted != nil { t.count-- } return deleted }
go
func (t *LLRB) DeleteMin() Item { var deleted Item t.root, deleted = deleteMin(t.root) if t.root != nil { t.root.Black = true } if deleted != nil { t.count-- } return deleted }
[ "func", "(", "t", "*", "LLRB", ")", "DeleteMin", "(", ")", "Item", "{", "var", "deleted", "Item", "\n", "t", ".", "root", ",", "deleted", "=", "deleteMin", "(", "t", ".", "root", ")", "\n", "if", "t", ".", "root", "!=", "nil", "{", "t", ".", "root", ".", "Black", "=", "true", "\n", "}", "\n", "if", "deleted", "!=", "nil", "{", "t", ".", "count", "--", "\n", "}", "\n", "return", "deleted", "\n", "}" ]
// DeleteMin deletes the minimum element in the tree and returns the // deleted item or nil otherwise.
[ "DeleteMin", "deletes", "the", "minimum", "element", "in", "the", "tree", "and", "returns", "the", "deleted", "item", "or", "nil", "otherwise", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L260-L270
8,923
petar/GoLLRB
llrb/llrb.go
deleteMin
func deleteMin(h *Node) (*Node, Item) { if h == nil { return nil, nil } if h.Left == nil { return nil, h.Item } if !isRed(h.Left) && !isRed(h.Left.Left) { h = moveRedLeft(h) } var deleted Item h.Left, deleted = deleteMin(h.Left) return fixUp(h), deleted }
go
func deleteMin(h *Node) (*Node, Item) { if h == nil { return nil, nil } if h.Left == nil { return nil, h.Item } if !isRed(h.Left) && !isRed(h.Left.Left) { h = moveRedLeft(h) } var deleted Item h.Left, deleted = deleteMin(h.Left) return fixUp(h), deleted }
[ "func", "deleteMin", "(", "h", "*", "Node", ")", "(", "*", "Node", ",", "Item", ")", "{", "if", "h", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "h", ".", "Left", "==", "nil", "{", "return", "nil", ",", "h", ".", "Item", "\n", "}", "\n\n", "if", "!", "isRed", "(", "h", ".", "Left", ")", "&&", "!", "isRed", "(", "h", ".", "Left", ".", "Left", ")", "{", "h", "=", "moveRedLeft", "(", "h", ")", "\n", "}", "\n\n", "var", "deleted", "Item", "\n", "h", ".", "Left", ",", "deleted", "=", "deleteMin", "(", "h", ".", "Left", ")", "\n\n", "return", "fixUp", "(", "h", ")", ",", "deleted", "\n", "}" ]
// deleteMin code for LLRB 2-3 trees
[ "deleteMin", "code", "for", "LLRB", "2", "-", "3", "trees" ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L273-L289
8,924
petar/GoLLRB
llrb/llrb.go
DeleteMax
func (t *LLRB) DeleteMax() Item { var deleted Item t.root, deleted = deleteMax(t.root) if t.root != nil { t.root.Black = true } if deleted != nil { t.count-- } return deleted }
go
func (t *LLRB) DeleteMax() Item { var deleted Item t.root, deleted = deleteMax(t.root) if t.root != nil { t.root.Black = true } if deleted != nil { t.count-- } return deleted }
[ "func", "(", "t", "*", "LLRB", ")", "DeleteMax", "(", ")", "Item", "{", "var", "deleted", "Item", "\n", "t", ".", "root", ",", "deleted", "=", "deleteMax", "(", "t", ".", "root", ")", "\n", "if", "t", ".", "root", "!=", "nil", "{", "t", ".", "root", ".", "Black", "=", "true", "\n", "}", "\n", "if", "deleted", "!=", "nil", "{", "t", ".", "count", "--", "\n", "}", "\n", "return", "deleted", "\n", "}" ]
// DeleteMax deletes the maximum element in the tree and returns // the deleted item or nil otherwise
[ "DeleteMax", "deletes", "the", "maximum", "element", "in", "the", "tree", "and", "returns", "the", "deleted", "item", "or", "nil", "otherwise" ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L293-L303
8,925
petar/GoLLRB
llrb/llrb.go
Delete
func (t *LLRB) Delete(key Item) Item { var deleted Item t.root, deleted = t.delete(t.root, key) if t.root != nil { t.root.Black = true } if deleted != nil { t.count-- } return deleted }
go
func (t *LLRB) Delete(key Item) Item { var deleted Item t.root, deleted = t.delete(t.root, key) if t.root != nil { t.root.Black = true } if deleted != nil { t.count-- } return deleted }
[ "func", "(", "t", "*", "LLRB", ")", "Delete", "(", "key", "Item", ")", "Item", "{", "var", "deleted", "Item", "\n", "t", ".", "root", ",", "deleted", "=", "t", ".", "delete", "(", "t", ".", "root", ",", "key", ")", "\n", "if", "t", ".", "root", "!=", "nil", "{", "t", ".", "root", ".", "Black", "=", "true", "\n", "}", "\n", "if", "deleted", "!=", "nil", "{", "t", ".", "count", "--", "\n", "}", "\n", "return", "deleted", "\n", "}" ]
// Delete deletes an item from the tree whose key equals key. // The deleted item is return, otherwise nil is returned.
[ "Delete", "deletes", "an", "item", "from", "the", "tree", "whose", "key", "equals", "key", ".", "The", "deleted", "item", "is", "return", "otherwise", "nil", "is", "returned", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/llrb.go#L326-L336
8,926
petar/GoLLRB
llrb/iterator.go
AscendGreaterOrEqual
func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) { t.ascendGreaterOrEqual(t.root, pivot, iterator) }
go
func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) { t.ascendGreaterOrEqual(t.root, pivot, iterator) }
[ "func", "(", "t", "*", "LLRB", ")", "AscendGreaterOrEqual", "(", "pivot", "Item", ",", "iterator", "ItemIterator", ")", "{", "t", ".", "ascendGreaterOrEqual", "(", "t", ".", "root", ",", "pivot", ",", "iterator", ")", "\n", "}" ]
// AscendGreaterOrEqual will call iterator once for each element greater or equal to // pivot in ascending order. It will stop whenever the iterator returns false.
[ "AscendGreaterOrEqual", "will", "call", "iterator", "once", "for", "each", "element", "greater", "or", "equal", "to", "pivot", "in", "ascending", "order", ".", "It", "will", "stop", "whenever", "the", "iterator", "returns", "false", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/iterator.go#L35-L37
8,927
petar/GoLLRB
llrb/iterator.go
DescendLessOrEqual
func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) { t.descendLessOrEqual(t.root, pivot, iterator) }
go
func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) { t.descendLessOrEqual(t.root, pivot, iterator) }
[ "func", "(", "t", "*", "LLRB", ")", "DescendLessOrEqual", "(", "pivot", "Item", ",", "iterator", "ItemIterator", ")", "{", "t", ".", "descendLessOrEqual", "(", "t", ".", "root", ",", "pivot", ",", "iterator", ")", "\n", "}" ]
// DescendLessOrEqual will call iterator once for each element less than the // pivot in descending order. It will stop whenever the iterator returns false.
[ "DescendLessOrEqual", "will", "call", "iterator", "once", "for", "each", "element", "less", "than", "the", "pivot", "in", "descending", "order", ".", "It", "will", "stop", "whenever", "the", "iterator", "returns", "false", "." ]
53be0d36a84c2a886ca057d34b6aa4468df9ccb4
https://github.com/petar/GoLLRB/blob/53be0d36a84c2a886ca057d34b6aa4468df9ccb4/llrb/iterator.go#L76-L78
8,928
google/jsonapi
runtime.go
WithValue
func (r *Runtime) WithValue(key string, value interface{}) *Runtime { r.ctx[key] = value return r }
go
func (r *Runtime) WithValue(key string, value interface{}) *Runtime { r.ctx[key] = value return r }
[ "func", "(", "r", "*", "Runtime", ")", "WithValue", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "*", "Runtime", "{", "r", ".", "ctx", "[", "key", "]", "=", "value", "\n\n", "return", "r", "\n", "}" ]
// WithValue adds custom state variables to the runtime context.
[ "WithValue", "adds", "custom", "state", "variables", "to", "the", "runtime", "context", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/runtime.go#L51-L55
8,929
google/jsonapi
runtime.go
UnmarshalPayload
func (r *Runtime) UnmarshalPayload(reader io.Reader, model interface{}) error { return r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error { return UnmarshalPayload(reader, model) }) }
go
func (r *Runtime) UnmarshalPayload(reader io.Reader, model interface{}) error { return r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error { return UnmarshalPayload(reader, model) }) }
[ "func", "(", "r", "*", "Runtime", ")", "UnmarshalPayload", "(", "reader", "io", ".", "Reader", ",", "model", "interface", "{", "}", ")", "error", "{", "return", "r", ".", "instrumentCall", "(", "UnmarshalStart", ",", "UnmarshalStop", ",", "func", "(", ")", "error", "{", "return", "UnmarshalPayload", "(", "reader", ",", "model", ")", "\n", "}", ")", "\n", "}" ]
// UnmarshalPayload has docs in request.go for UnmarshalPayload.
[ "UnmarshalPayload", "has", "docs", "in", "request", ".", "go", "for", "UnmarshalPayload", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/runtime.go#L72-L76
8,930
google/jsonapi
runtime.go
UnmarshalManyPayload
func (r *Runtime) UnmarshalManyPayload(reader io.Reader, kind reflect.Type) (elems []interface{}, err error) { r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error { elems, err = UnmarshalManyPayload(reader, kind) return err }) return }
go
func (r *Runtime) UnmarshalManyPayload(reader io.Reader, kind reflect.Type) (elems []interface{}, err error) { r.instrumentCall(UnmarshalStart, UnmarshalStop, func() error { elems, err = UnmarshalManyPayload(reader, kind) return err }) return }
[ "func", "(", "r", "*", "Runtime", ")", "UnmarshalManyPayload", "(", "reader", "io", ".", "Reader", ",", "kind", "reflect", ".", "Type", ")", "(", "elems", "[", "]", "interface", "{", "}", ",", "err", "error", ")", "{", "r", ".", "instrumentCall", "(", "UnmarshalStart", ",", "UnmarshalStop", ",", "func", "(", ")", "error", "{", "elems", ",", "err", "=", "UnmarshalManyPayload", "(", "reader", ",", "kind", ")", "\n", "return", "err", "\n", "}", ")", "\n\n", "return", "\n", "}" ]
// UnmarshalManyPayload has docs in request.go for UnmarshalManyPayload.
[ "UnmarshalManyPayload", "has", "docs", "in", "request", ".", "go", "for", "UnmarshalManyPayload", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/runtime.go#L79-L86
8,931
google/jsonapi
request.go
UnmarshalManyPayload
func UnmarshalManyPayload(in io.Reader, t reflect.Type) ([]interface{}, error) { payload := new(ManyPayload) if err := json.NewDecoder(in).Decode(payload); err != nil { return nil, err } models := []interface{}{} // will be populated from the "data" includedMap := map[string]*Node{} // will be populate from the "included" if payload.Included != nil { for _, included := range payload.Included { key := fmt.Sprintf("%s,%s", included.Type, included.ID) includedMap[key] = included } } for _, data := range payload.Data { model := reflect.New(t.Elem()) err := unmarshalNode(data, model, &includedMap) if err != nil { return nil, err } models = append(models, model.Interface()) } return models, nil }
go
func UnmarshalManyPayload(in io.Reader, t reflect.Type) ([]interface{}, error) { payload := new(ManyPayload) if err := json.NewDecoder(in).Decode(payload); err != nil { return nil, err } models := []interface{}{} // will be populated from the "data" includedMap := map[string]*Node{} // will be populate from the "included" if payload.Included != nil { for _, included := range payload.Included { key := fmt.Sprintf("%s,%s", included.Type, included.ID) includedMap[key] = included } } for _, data := range payload.Data { model := reflect.New(t.Elem()) err := unmarshalNode(data, model, &includedMap) if err != nil { return nil, err } models = append(models, model.Interface()) } return models, nil }
[ "func", "UnmarshalManyPayload", "(", "in", "io", ".", "Reader", ",", "t", "reflect", ".", "Type", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "payload", ":=", "new", "(", "ManyPayload", ")", "\n\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "in", ")", ".", "Decode", "(", "payload", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "models", ":=", "[", "]", "interface", "{", "}", "{", "}", "// will be populated from the \"data\"", "\n", "includedMap", ":=", "map", "[", "string", "]", "*", "Node", "{", "}", "// will be populate from the \"included\"", "\n\n", "if", "payload", ".", "Included", "!=", "nil", "{", "for", "_", ",", "included", ":=", "range", "payload", ".", "Included", "{", "key", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "included", ".", "Type", ",", "included", ".", "ID", ")", "\n", "includedMap", "[", "key", "]", "=", "included", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "data", ":=", "range", "payload", ".", "Data", "{", "model", ":=", "reflect", ".", "New", "(", "t", ".", "Elem", "(", ")", ")", "\n", "err", ":=", "unmarshalNode", "(", "data", ",", "model", ",", "&", "includedMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "models", "=", "append", "(", "models", ",", "model", ".", "Interface", "(", ")", ")", "\n", "}", "\n\n", "return", "models", ",", "nil", "\n", "}" ]
// UnmarshalManyPayload converts an io into a set of struct instances using // jsonapi tags on the type's struct fields.
[ "UnmarshalManyPayload", "converts", "an", "io", "into", "a", "set", "of", "struct", "instances", "using", "jsonapi", "tags", "on", "the", "type", "s", "struct", "fields", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/request.go#L113-L140
8,932
google/jsonapi
request.go
assign
func assign(field, value reflect.Value) { value = reflect.Indirect(value) if field.Kind() == reflect.Ptr { // initialize pointer so it's value // can be set by assignValue field.Set(reflect.New(field.Type().Elem())) field = field.Elem() } assignValue(field, value) }
go
func assign(field, value reflect.Value) { value = reflect.Indirect(value) if field.Kind() == reflect.Ptr { // initialize pointer so it's value // can be set by assignValue field.Set(reflect.New(field.Type().Elem())) field = field.Elem() } assignValue(field, value) }
[ "func", "assign", "(", "field", ",", "value", "reflect", ".", "Value", ")", "{", "value", "=", "reflect", ".", "Indirect", "(", "value", ")", "\n\n", "if", "field", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "// initialize pointer so it's value", "// can be set by assignValue", "field", ".", "Set", "(", "reflect", ".", "New", "(", "field", ".", "Type", "(", ")", ".", "Elem", "(", ")", ")", ")", "\n", "field", "=", "field", ".", "Elem", "(", ")", "\n\n", "}", "\n\n", "assignValue", "(", "field", ",", "value", ")", "\n", "}" ]
// assign will take the value specified and assign it to the field; if // field is expecting a ptr assign will assign a ptr.
[ "assign", "will", "take", "the", "value", "specified", "and", "assign", "it", "to", "the", "field", ";", "if", "field", "is", "expecting", "a", "ptr", "assign", "will", "assign", "a", "ptr", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/request.go#L347-L359
8,933
google/jsonapi
request.go
assignValue
func assignValue(field, value reflect.Value) { switch field.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: field.SetInt(value.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: field.SetUint(value.Uint()) case reflect.Float32, reflect.Float64: field.SetFloat(value.Float()) case reflect.String: field.SetString(value.String()) case reflect.Bool: field.SetBool(value.Bool()) default: field.Set(value) } }
go
func assignValue(field, value reflect.Value) { switch field.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: field.SetInt(value.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: field.SetUint(value.Uint()) case reflect.Float32, reflect.Float64: field.SetFloat(value.Float()) case reflect.String: field.SetString(value.String()) case reflect.Bool: field.SetBool(value.Bool()) default: field.Set(value) } }
[ "func", "assignValue", "(", "field", ",", "value", "reflect", ".", "Value", ")", "{", "switch", "field", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "field", ".", "SetInt", "(", "value", ".", "Int", "(", ")", ")", "\n", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint8", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ",", "reflect", ".", "Uintptr", ":", "field", ".", "SetUint", "(", "value", ".", "Uint", "(", ")", ")", "\n", "case", "reflect", ".", "Float32", ",", "reflect", ".", "Float64", ":", "field", ".", "SetFloat", "(", "value", ".", "Float", "(", ")", ")", "\n", "case", "reflect", ".", "String", ":", "field", ".", "SetString", "(", "value", ".", "String", "(", ")", ")", "\n", "case", "reflect", ".", "Bool", ":", "field", ".", "SetBool", "(", "value", ".", "Bool", "(", ")", ")", "\n", "default", ":", "field", ".", "Set", "(", "value", ")", "\n", "}", "\n", "}" ]
// assign assigns the specified value to the field, // expecting both values not to be pointer types.
[ "assign", "assigns", "the", "specified", "value", "to", "the", "field", "expecting", "both", "values", "not", "to", "be", "pointer", "types", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/request.go#L363-L380
8,934
google/jsonapi
response.go
Marshal
func Marshal(models interface{}) (Payloader, error) { switch vals := reflect.ValueOf(models); vals.Kind() { case reflect.Slice: m, err := convertToSliceInterface(&models) if err != nil { return nil, err } payload, err := marshalMany(m) if err != nil { return nil, err } if linkableModels, isLinkable := models.(Linkable); isLinkable { jl := linkableModels.JSONAPILinks() if er := jl.validate(); er != nil { return nil, er } payload.Links = linkableModels.JSONAPILinks() } if metableModels, ok := models.(Metable); ok { payload.Meta = metableModels.JSONAPIMeta() } return payload, nil case reflect.Ptr: // Check that the pointer was to a struct if reflect.Indirect(vals).Kind() != reflect.Struct { return nil, ErrUnexpectedType } return marshalOne(models) default: return nil, ErrUnexpectedType } }
go
func Marshal(models interface{}) (Payloader, error) { switch vals := reflect.ValueOf(models); vals.Kind() { case reflect.Slice: m, err := convertToSliceInterface(&models) if err != nil { return nil, err } payload, err := marshalMany(m) if err != nil { return nil, err } if linkableModels, isLinkable := models.(Linkable); isLinkable { jl := linkableModels.JSONAPILinks() if er := jl.validate(); er != nil { return nil, er } payload.Links = linkableModels.JSONAPILinks() } if metableModels, ok := models.(Metable); ok { payload.Meta = metableModels.JSONAPIMeta() } return payload, nil case reflect.Ptr: // Check that the pointer was to a struct if reflect.Indirect(vals).Kind() != reflect.Struct { return nil, ErrUnexpectedType } return marshalOne(models) default: return nil, ErrUnexpectedType } }
[ "func", "Marshal", "(", "models", "interface", "{", "}", ")", "(", "Payloader", ",", "error", ")", "{", "switch", "vals", ":=", "reflect", ".", "ValueOf", "(", "models", ")", ";", "vals", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Slice", ":", "m", ",", "err", ":=", "convertToSliceInterface", "(", "&", "models", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "payload", ",", "err", ":=", "marshalMany", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "linkableModels", ",", "isLinkable", ":=", "models", ".", "(", "Linkable", ")", ";", "isLinkable", "{", "jl", ":=", "linkableModels", ".", "JSONAPILinks", "(", ")", "\n", "if", "er", ":=", "jl", ".", "validate", "(", ")", ";", "er", "!=", "nil", "{", "return", "nil", ",", "er", "\n", "}", "\n", "payload", ".", "Links", "=", "linkableModels", ".", "JSONAPILinks", "(", ")", "\n", "}", "\n\n", "if", "metableModels", ",", "ok", ":=", "models", ".", "(", "Metable", ")", ";", "ok", "{", "payload", ".", "Meta", "=", "metableModels", ".", "JSONAPIMeta", "(", ")", "\n", "}", "\n\n", "return", "payload", ",", "nil", "\n", "case", "reflect", ".", "Ptr", ":", "// Check that the pointer was to a struct", "if", "reflect", ".", "Indirect", "(", "vals", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "nil", ",", "ErrUnexpectedType", "\n", "}", "\n", "return", "marshalOne", "(", "models", ")", "\n", "default", ":", "return", "nil", ",", "ErrUnexpectedType", "\n", "}", "\n", "}" ]
// Marshal does the same as MarshalPayload except it just returns the payload // and doesn't write out results. Useful if you use your own JSON rendering // library.
[ "Marshal", "does", "the", "same", "as", "MarshalPayload", "except", "it", "just", "returns", "the", "payload", "and", "doesn", "t", "write", "out", "results", ".", "Useful", "if", "you", "use", "your", "own", "JSON", "rendering", "library", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/response.go#L77-L112
8,935
google/jsonapi
response.go
marshalOne
func marshalOne(model interface{}) (*OnePayload, error) { included := make(map[string]*Node) rootNode, err := visitModelNode(model, &included, true) if err != nil { return nil, err } payload := &OnePayload{Data: rootNode} payload.Included = nodeMapValues(&included) return payload, nil }
go
func marshalOne(model interface{}) (*OnePayload, error) { included := make(map[string]*Node) rootNode, err := visitModelNode(model, &included, true) if err != nil { return nil, err } payload := &OnePayload{Data: rootNode} payload.Included = nodeMapValues(&included) return payload, nil }
[ "func", "marshalOne", "(", "model", "interface", "{", "}", ")", "(", "*", "OnePayload", ",", "error", ")", "{", "included", ":=", "make", "(", "map", "[", "string", "]", "*", "Node", ")", "\n\n", "rootNode", ",", "err", ":=", "visitModelNode", "(", "model", ",", "&", "included", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "payload", ":=", "&", "OnePayload", "{", "Data", ":", "rootNode", "}", "\n\n", "payload", ".", "Included", "=", "nodeMapValues", "(", "&", "included", ")", "\n\n", "return", "payload", ",", "nil", "\n", "}" ]
// marshalOne does the same as MarshalOnePayload except it just returns the // payload and doesn't write out results. Useful is you use your JSON rendering // library.
[ "marshalOne", "does", "the", "same", "as", "MarshalOnePayload", "except", "it", "just", "returns", "the", "payload", "and", "doesn", "t", "write", "out", "results", ".", "Useful", "is", "you", "use", "your", "JSON", "rendering", "library", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/response.go#L134-L146
8,936
google/jsonapi
response.go
marshalMany
func marshalMany(models []interface{}) (*ManyPayload, error) { payload := &ManyPayload{ Data: []*Node{}, } included := map[string]*Node{} for _, model := range models { node, err := visitModelNode(model, &included, true) if err != nil { return nil, err } payload.Data = append(payload.Data, node) } payload.Included = nodeMapValues(&included) return payload, nil }
go
func marshalMany(models []interface{}) (*ManyPayload, error) { payload := &ManyPayload{ Data: []*Node{}, } included := map[string]*Node{} for _, model := range models { node, err := visitModelNode(model, &included, true) if err != nil { return nil, err } payload.Data = append(payload.Data, node) } payload.Included = nodeMapValues(&included) return payload, nil }
[ "func", "marshalMany", "(", "models", "[", "]", "interface", "{", "}", ")", "(", "*", "ManyPayload", ",", "error", ")", "{", "payload", ":=", "&", "ManyPayload", "{", "Data", ":", "[", "]", "*", "Node", "{", "}", ",", "}", "\n", "included", ":=", "map", "[", "string", "]", "*", "Node", "{", "}", "\n\n", "for", "_", ",", "model", ":=", "range", "models", "{", "node", ",", "err", ":=", "visitModelNode", "(", "model", ",", "&", "included", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "payload", ".", "Data", "=", "append", "(", "payload", ".", "Data", ",", "node", ")", "\n", "}", "\n", "payload", ".", "Included", "=", "nodeMapValues", "(", "&", "included", ")", "\n\n", "return", "payload", ",", "nil", "\n", "}" ]
// marshalMany does the same as MarshalManyPayload except it just returns the // payload and doesn't write out results. Useful is you use your JSON rendering // library.
[ "marshalMany", "does", "the", "same", "as", "MarshalManyPayload", "except", "it", "just", "returns", "the", "payload", "and", "doesn", "t", "write", "out", "results", ".", "Useful", "is", "you", "use", "your", "JSON", "rendering", "library", "." ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/response.go#L151-L167
8,937
google/jsonapi
examples/models.go
JSONAPILinks
func (blog Blog) JSONAPILinks() *jsonapi.Links { return &jsonapi.Links{ "self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID), } }
go
func (blog Blog) JSONAPILinks() *jsonapi.Links { return &jsonapi.Links{ "self": fmt.Sprintf("https://example.com/blogs/%d", blog.ID), } }
[ "func", "(", "blog", "Blog", ")", "JSONAPILinks", "(", ")", "*", "jsonapi", ".", "Links", "{", "return", "&", "jsonapi", ".", "Links", "{", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "blog", ".", "ID", ")", ",", "}", "\n", "}" ]
// JSONAPILinks implements the Linkable interface for a blog
[ "JSONAPILinks", "implements", "the", "Linkable", "interface", "for", "a", "blog" ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/examples/models.go#L38-L42
8,938
google/jsonapi
examples/models.go
JSONAPIRelationshipLinks
func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links { if relation == "posts" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID), } } if relation == "current_post" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/current_post", blog.ID), } } return nil }
go
func (blog Blog) JSONAPIRelationshipLinks(relation string) *jsonapi.Links { if relation == "posts" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/posts", blog.ID), } } if relation == "current_post" { return &jsonapi.Links{ "related": fmt.Sprintf("https://example.com/blogs/%d/current_post", blog.ID), } } return nil }
[ "func", "(", "blog", "Blog", ")", "JSONAPIRelationshipLinks", "(", "relation", "string", ")", "*", "jsonapi", ".", "Links", "{", "if", "relation", "==", "\"", "\"", "{", "return", "&", "jsonapi", ".", "Links", "{", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "blog", ".", "ID", ")", ",", "}", "\n", "}", "\n", "if", "relation", "==", "\"", "\"", "{", "return", "&", "jsonapi", ".", "Links", "{", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "blog", ".", "ID", ")", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// JSONAPIRelationshipLinks implements the RelationshipLinkable interface for a blog
[ "JSONAPIRelationshipLinks", "implements", "the", "RelationshipLinkable", "interface", "for", "a", "blog" ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/examples/models.go#L45-L57
8,939
google/jsonapi
examples/models.go
JSONAPIRelationshipMeta
func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta { if relation == "posts" { return &jsonapi.Meta{ "detail": "posts meta information", } } if relation == "current_post" { return &jsonapi.Meta{ "detail": "current post meta information", } } return nil }
go
func (blog Blog) JSONAPIRelationshipMeta(relation string) *jsonapi.Meta { if relation == "posts" { return &jsonapi.Meta{ "detail": "posts meta information", } } if relation == "current_post" { return &jsonapi.Meta{ "detail": "current post meta information", } } return nil }
[ "func", "(", "blog", "Blog", ")", "JSONAPIRelationshipMeta", "(", "relation", "string", ")", "*", "jsonapi", ".", "Meta", "{", "if", "relation", "==", "\"", "\"", "{", "return", "&", "jsonapi", ".", "Meta", "{", "\"", "\"", ":", "\"", "\"", ",", "}", "\n", "}", "\n", "if", "relation", "==", "\"", "\"", "{", "return", "&", "jsonapi", ".", "Meta", "{", "\"", "\"", ":", "\"", "\"", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// JSONAPIRelationshipMeta implements the RelationshipMetable interface for a blog
[ "JSONAPIRelationshipMeta", "implements", "the", "RelationshipMetable", "interface", "for", "a", "blog" ]
d0428f63eb511f08685bda2d0a6af1d7532fb1c0
https://github.com/google/jsonapi/blob/d0428f63eb511f08685bda2d0a6af1d7532fb1c0/examples/models.go#L67-L79
8,940
buger/goterm
terminal.go
applyTransform
func applyTransform(str string, transform sf) (out string) { out = "" for idx, line := range strings.Split(str, "\n") { out += transform(idx, line) } return }
go
func applyTransform(str string, transform sf) (out string) { out = "" for idx, line := range strings.Split(str, "\n") { out += transform(idx, line) } return }
[ "func", "applyTransform", "(", "str", "string", ",", "transform", "sf", ")", "(", "out", "string", ")", "{", "out", "=", "\"", "\"", "\n\n", "for", "idx", ",", "line", ":=", "range", "strings", ".", "Split", "(", "str", ",", "\"", "\\n", "\"", ")", "{", "out", "+=", "transform", "(", "idx", ",", "line", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// Apply given transformation func for each line in string
[ "Apply", "given", "transformation", "func", "for", "each", "line", "in", "string" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L99-L107
8,941
buger/goterm
terminal.go
MoveCursor
func MoveCursor(x int, y int) { fmt.Fprintf(Screen, "\033[%d;%dH", y, x) }
go
func MoveCursor(x int, y int) { fmt.Fprintf(Screen, "\033[%d;%dH", y, x) }
[ "func", "MoveCursor", "(", "x", "int", ",", "y", "int", ")", "{", "fmt", ".", "Fprintf", "(", "Screen", ",", "\"", "\\033", "\"", ",", "y", ",", "x", ")", "\n", "}" ]
// Move cursor to given position
[ "Move", "cursor", "to", "given", "position" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L115-L117
8,942
buger/goterm
terminal.go
MoveTo
func MoveTo(str string, x int, y int) (out string) { x, y = GetXY(x, y) return applyTransform(str, func(idx int, line string) string { return fmt.Sprintf("\033[%d;%dH%s", y+idx, x, line) }) }
go
func MoveTo(str string, x int, y int) (out string) { x, y = GetXY(x, y) return applyTransform(str, func(idx int, line string) string { return fmt.Sprintf("\033[%d;%dH%s", y+idx, x, line) }) }
[ "func", "MoveTo", "(", "str", "string", ",", "x", "int", ",", "y", "int", ")", "(", "out", "string", ")", "{", "x", ",", "y", "=", "GetXY", "(", "x", ",", "y", ")", "\n\n", "return", "applyTransform", "(", "str", ",", "func", "(", "idx", "int", ",", "line", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\033", "\"", ",", "y", "+", "idx", ",", "x", ",", "line", ")", "\n", "}", ")", "\n", "}" ]
// Move string to possition
[ "Move", "string", "to", "possition" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L140-L146
8,943
buger/goterm
terminal.go
ResetLine
func ResetLine(str string) (out string) { return applyTransform(str, func(idx int, line string) string { return fmt.Sprintf("%s%s", RESET_LINE, line) }) }
go
func ResetLine(str string) (out string) { return applyTransform(str, func(idx int, line string) string { return fmt.Sprintf("%s%s", RESET_LINE, line) }) }
[ "func", "ResetLine", "(", "str", "string", ")", "(", "out", "string", ")", "{", "return", "applyTransform", "(", "str", ",", "func", "(", "idx", "int", ",", "line", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "RESET_LINE", ",", "line", ")", "\n", "}", ")", "\n", "}" ]
// Return carrier to start of line
[ "Return", "carrier", "to", "start", "of", "line" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L149-L153
8,944
buger/goterm
terminal.go
Width
func Width() int { ws, err := getWinsize() if err != nil { return -1 } return int(ws.Col) }
go
func Width() int { ws, err := getWinsize() if err != nil { return -1 } return int(ws.Col) }
[ "func", "Width", "(", ")", "int", "{", "ws", ",", "err", ":=", "getWinsize", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "-", "1", "\n", "}", "\n\n", "return", "int", "(", "ws", ".", "Col", ")", "\n", "}" ]
// Get console width
[ "Get", "console", "width" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L192-L200
8,945
buger/goterm
terminal.go
Height
func Height() int { ws, err := getWinsize() if err != nil { return -1 } return int(ws.Row) }
go
func Height() int { ws, err := getWinsize() if err != nil { return -1 } return int(ws.Row) }
[ "func", "Height", "(", ")", "int", "{", "ws", ",", "err", ":=", "getWinsize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", "\n", "}", "\n", "return", "int", "(", "ws", ".", "Row", ")", "\n", "}" ]
// Get console height
[ "Get", "console", "height" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L203-L209
8,946
buger/goterm
terminal.go
Flush
func Flush() { for idx, str := range strings.SplitAfter(Screen.String(), "\n") { if idx > Height() { return } Output.WriteString(str) } Output.Flush() Screen.Reset() }
go
func Flush() { for idx, str := range strings.SplitAfter(Screen.String(), "\n") { if idx > Height() { return } Output.WriteString(str) } Output.Flush() Screen.Reset() }
[ "func", "Flush", "(", ")", "{", "for", "idx", ",", "str", ":=", "range", "strings", ".", "SplitAfter", "(", "Screen", ".", "String", "(", ")", ",", "\"", "\\n", "\"", ")", "{", "if", "idx", ">", "Height", "(", ")", "{", "return", "\n", "}", "\n\n", "Output", ".", "WriteString", "(", "str", ")", "\n", "}", "\n\n", "Output", ".", "Flush", "(", ")", "\n", "Screen", ".", "Reset", "(", ")", "\n", "}" ]
// Flush buffer and ensure that it will not overflow screen
[ "Flush", "buffer", "and", "ensure", "that", "it", "will", "not", "overflow", "screen" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/terminal.go#L217-L228
8,947
buger/goterm
plot.go
getChartData
func getChartData(data *DataTable, index int) (out [][]float64) { for _, r := range data.rows { out = append(out, []float64{r[0], r[index]}) } return }
go
func getChartData(data *DataTable, index int) (out [][]float64) { for _, r := range data.rows { out = append(out, []float64{r[0], r[index]}) } return }
[ "func", "getChartData", "(", "data", "*", "DataTable", ",", "index", "int", ")", "(", "out", "[", "]", "[", "]", "float64", ")", "{", "for", "_", ",", "r", ":=", "range", "data", ".", "rows", "{", "out", "=", "append", "(", "out", ",", "[", "]", "float64", "{", "r", "[", "0", "]", ",", "r", "[", "index", "]", "}", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// DataTable can contain data for multiple graphs, we need to extract only 1
[ "DataTable", "can", "contain", "data", "for", "multiple", "graphs", "we", "need", "to", "extract", "only", "1" ]
c206103e1f37c0c6c5c039706305ea2aa6e8ad3b
https://github.com/buger/goterm/blob/c206103e1f37c0c6c5c039706305ea2aa6e8ad3b/plot.go#L280-L286
8,948
gorilla/csrf
store.go
Save
func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error { // Generate an encoded cookie value with the CSRF token. encoded, err := cs.sc.Encode(cs.name, token) if err != nil { return err } cookie := &http.Cookie{ Name: cs.name, Value: encoded, MaxAge: cs.maxAge, HttpOnly: cs.httpOnly, Secure: cs.secure, Path: cs.path, Domain: cs.domain, } // Set the Expires field on the cookie based on the MaxAge // If MaxAge <= 0, we don't set the Expires attribute, making the cookie // session-only. if cs.maxAge > 0 { cookie.Expires = time.Now().Add( time.Duration(cs.maxAge) * time.Second) } // Write the authenticated cookie to the response. http.SetCookie(w, cookie) return nil }
go
func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error { // Generate an encoded cookie value with the CSRF token. encoded, err := cs.sc.Encode(cs.name, token) if err != nil { return err } cookie := &http.Cookie{ Name: cs.name, Value: encoded, MaxAge: cs.maxAge, HttpOnly: cs.httpOnly, Secure: cs.secure, Path: cs.path, Domain: cs.domain, } // Set the Expires field on the cookie based on the MaxAge // If MaxAge <= 0, we don't set the Expires attribute, making the cookie // session-only. if cs.maxAge > 0 { cookie.Expires = time.Now().Add( time.Duration(cs.maxAge) * time.Second) } // Write the authenticated cookie to the response. http.SetCookie(w, cookie) return nil }
[ "func", "(", "cs", "*", "cookieStore", ")", "Save", "(", "token", "[", "]", "byte", ",", "w", "http", ".", "ResponseWriter", ")", "error", "{", "// Generate an encoded cookie value with the CSRF token.", "encoded", ",", "err", ":=", "cs", ".", "sc", ".", "Encode", "(", "cs", ".", "name", ",", "token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cookie", ":=", "&", "http", ".", "Cookie", "{", "Name", ":", "cs", ".", "name", ",", "Value", ":", "encoded", ",", "MaxAge", ":", "cs", ".", "maxAge", ",", "HttpOnly", ":", "cs", ".", "httpOnly", ",", "Secure", ":", "cs", ".", "secure", ",", "Path", ":", "cs", ".", "path", ",", "Domain", ":", "cs", ".", "domain", ",", "}", "\n\n", "// Set the Expires field on the cookie based on the MaxAge", "// If MaxAge <= 0, we don't set the Expires attribute, making the cookie", "// session-only.", "if", "cs", ".", "maxAge", ">", "0", "{", "cookie", ".", "Expires", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Duration", "(", "cs", ".", "maxAge", ")", "*", "time", ".", "Second", ")", "\n", "}", "\n\n", "// Write the authenticated cookie to the response.", "http", ".", "SetCookie", "(", "w", ",", "cookie", ")", "\n\n", "return", "nil", "\n", "}" ]
// Save stores the CSRF token in the session cookie.
[ "Save", "stores", "the", "CSRF", "token", "in", "the", "session", "cookie", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/store.go#L53-L82
8,949
gorilla/csrf
options.go
RequestHeader
func RequestHeader(header string) Option { return func(cs *csrf) { cs.opts.RequestHeader = header } }
go
func RequestHeader(header string) Option { return func(cs *csrf) { cs.opts.RequestHeader = header } }
[ "func", "RequestHeader", "(", "header", "string", ")", "Option", "{", "return", "func", "(", "cs", "*", "csrf", ")", "{", "cs", ".", "opts", ".", "RequestHeader", "=", "header", "\n", "}", "\n", "}" ]
// RequestHeader allows you to change the request header the CSRF middleware // inspects. The default is X-CSRF-Token.
[ "RequestHeader", "allows", "you", "to", "change", "the", "request", "header", "the", "CSRF", "middleware", "inspects", ".", "The", "default", "is", "X", "-", "CSRF", "-", "Token", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/options.go#L76-L80
8,950
gorilla/csrf
options.go
CookieName
func CookieName(name string) Option { return func(cs *csrf) { cs.opts.CookieName = name } }
go
func CookieName(name string) Option { return func(cs *csrf) { cs.opts.CookieName = name } }
[ "func", "CookieName", "(", "name", "string", ")", "Option", "{", "return", "func", "(", "cs", "*", "csrf", ")", "{", "cs", ".", "opts", ".", "CookieName", "=", "name", "\n", "}", "\n", "}" ]
// CookieName changes the name of the CSRF cookie issued to clients. // // Note that cookie names should not contain whitespace, commas, semicolons, // backslashes or control characters as per RFC6265.
[ "CookieName", "changes", "the", "name", "of", "the", "CSRF", "cookie", "issued", "to", "clients", ".", "Note", "that", "cookie", "names", "should", "not", "contain", "whitespace", "commas", "semicolons", "backslashes", "or", "control", "characters", "as", "per", "RFC6265", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/options.go#L94-L98
8,951
gorilla/csrf
options.go
parseOptions
func parseOptions(h http.Handler, opts ...Option) *csrf { // Set the handler to call after processing. cs := &csrf{ h: h, } // Default to true. See Secure & HttpOnly function comments for rationale. // Set here to allow package users to override the default. cs.opts.Secure = true cs.opts.HttpOnly = true // Range over each options function and apply it // to our csrf type to configure it. Options functions are // applied in order, with any conflicting options overriding // earlier calls. for _, option := range opts { option(cs) } return cs }
go
func parseOptions(h http.Handler, opts ...Option) *csrf { // Set the handler to call after processing. cs := &csrf{ h: h, } // Default to true. See Secure & HttpOnly function comments for rationale. // Set here to allow package users to override the default. cs.opts.Secure = true cs.opts.HttpOnly = true // Range over each options function and apply it // to our csrf type to configure it. Options functions are // applied in order, with any conflicting options overriding // earlier calls. for _, option := range opts { option(cs) } return cs }
[ "func", "parseOptions", "(", "h", "http", ".", "Handler", ",", "opts", "...", "Option", ")", "*", "csrf", "{", "// Set the handler to call after processing.", "cs", ":=", "&", "csrf", "{", "h", ":", "h", ",", "}", "\n\n", "// Default to true. See Secure & HttpOnly function comments for rationale.", "// Set here to allow package users to override the default.", "cs", ".", "opts", ".", "Secure", "=", "true", "\n", "cs", ".", "opts", ".", "HttpOnly", "=", "true", "\n\n", "// Range over each options function and apply it", "// to our csrf type to configure it. Options functions are", "// applied in order, with any conflicting options overriding", "// earlier calls.", "for", "_", ",", "option", ":=", "range", "opts", "{", "option", "(", "cs", ")", "\n", "}", "\n\n", "return", "cs", "\n", "}" ]
// parseOptions parses the supplied options functions and returns a configured // csrf handler.
[ "parseOptions", "parses", "the", "supplied", "options", "functions", "and", "returns", "a", "configured", "csrf", "handler", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/options.go#L110-L130
8,952
gorilla/csrf
helpers.go
FailureReason
func FailureReason(r *http.Request) error { if val, err := contextGet(r, errorKey); err == nil { if err, ok := val.(error); ok { return err } } return nil }
go
func FailureReason(r *http.Request) error { if val, err := contextGet(r, errorKey); err == nil { if err, ok := val.(error); ok { return err } } return nil }
[ "func", "FailureReason", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "if", "val", ",", "err", ":=", "contextGet", "(", "r", ",", "errorKey", ")", ";", "err", "==", "nil", "{", "if", "err", ",", "ok", ":=", "val", ".", "(", "error", ")", ";", "ok", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// FailureReason makes CSRF validation errors available in the request context. // This is useful when you want to log the cause of the error or report it to // client.
[ "FailureReason", "makes", "CSRF", "validation", "errors", "available", "in", "the", "request", "context", ".", "This", "is", "useful", "when", "you", "want", "to", "log", "the", "cause", "of", "the", "error", "or", "report", "it", "to", "client", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/helpers.go#L29-L37
8,953
gorilla/csrf
helpers.go
envError
func envError(r *http.Request, err error) *http.Request { return contextSave(r, errorKey, err) }
go
func envError(r *http.Request, err error) *http.Request { return contextSave(r, errorKey, err) }
[ "func", "envError", "(", "r", "*", "http", ".", "Request", ",", "err", "error", ")", "*", "http", ".", "Request", "{", "return", "contextSave", "(", "r", ",", "errorKey", ",", "err", ")", "\n", "}" ]
// envError stores a CSRF error in the request context.
[ "envError", "stores", "a", "CSRF", "error", "in", "the", "request", "context", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/helpers.go#L201-L203
8,954
gorilla/csrf
csrf.go
ServeHTTP
func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Skip the check if directed to. This should always be a bool. if val, err := contextGet(r, skipCheckKey); err == nil { if skip, ok := val.(bool); ok { if skip { cs.h.ServeHTTP(w, r) return } } } // Retrieve the token from the session. // An error represents either a cookie that failed HMAC validation // or that doesn't exist. realToken, err := cs.st.Get(r) if err != nil || len(realToken) != tokenLength { // If there was an error retrieving the token, the token doesn't exist // yet, or it's the wrong length, generate a new token. // Note that the new token will (correctly) fail validation downstream // as it will no longer match the request token. realToken, err = generateRandomBytes(tokenLength) if err != nil { r = envError(r, err) cs.opts.ErrorHandler.ServeHTTP(w, r) return } // Save the new (real) token in the session store. err = cs.st.Save(realToken, w) if err != nil { r = envError(r, err) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // Save the masked token to the request context r = contextSave(r, tokenKey, mask(realToken, r)) // Save the field name to the request context r = contextSave(r, formKey, cs.opts.FieldName) // HTTP methods not defined as idempotent ("safe") under RFC7231 require // inspection. if !contains(safeMethods, r.Method) { // Enforce an origin check for HTTPS connections. As per the Django CSRF // implementation (https://goo.gl/vKA7GE) the Referer header is almost // always present for same-domain HTTP requests. if r.URL.Scheme == "https" { // Fetch the Referer value. Call the error handler if it's empty or // otherwise fails to parse. referer, err := url.Parse(r.Referer()) if err != nil || referer.String() == "" { r = envError(r, ErrNoReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return } if sameOrigin(r.URL, referer) == false { r = envError(r, ErrBadReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // If the token returned from the session store is nil for non-idempotent // ("unsafe") methods, call the error handler. if realToken == nil { r = envError(r, ErrNoToken) cs.opts.ErrorHandler.ServeHTTP(w, r) return } // Retrieve the combined token (pad + masked) token and unmask it. requestToken := unmask(cs.requestToken(r)) // Compare the request token against the real token if !compareTokens(requestToken, realToken) { r = envError(r, ErrBadToken) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // Set the Vary: Cookie header to protect clients from caching the response. w.Header().Add("Vary", "Cookie") // Call the wrapped handler/router on success. cs.h.ServeHTTP(w, r) // Clear the request context after the handler has completed. contextClear(r) }
go
func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Skip the check if directed to. This should always be a bool. if val, err := contextGet(r, skipCheckKey); err == nil { if skip, ok := val.(bool); ok { if skip { cs.h.ServeHTTP(w, r) return } } } // Retrieve the token from the session. // An error represents either a cookie that failed HMAC validation // or that doesn't exist. realToken, err := cs.st.Get(r) if err != nil || len(realToken) != tokenLength { // If there was an error retrieving the token, the token doesn't exist // yet, or it's the wrong length, generate a new token. // Note that the new token will (correctly) fail validation downstream // as it will no longer match the request token. realToken, err = generateRandomBytes(tokenLength) if err != nil { r = envError(r, err) cs.opts.ErrorHandler.ServeHTTP(w, r) return } // Save the new (real) token in the session store. err = cs.st.Save(realToken, w) if err != nil { r = envError(r, err) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // Save the masked token to the request context r = contextSave(r, tokenKey, mask(realToken, r)) // Save the field name to the request context r = contextSave(r, formKey, cs.opts.FieldName) // HTTP methods not defined as idempotent ("safe") under RFC7231 require // inspection. if !contains(safeMethods, r.Method) { // Enforce an origin check for HTTPS connections. As per the Django CSRF // implementation (https://goo.gl/vKA7GE) the Referer header is almost // always present for same-domain HTTP requests. if r.URL.Scheme == "https" { // Fetch the Referer value. Call the error handler if it's empty or // otherwise fails to parse. referer, err := url.Parse(r.Referer()) if err != nil || referer.String() == "" { r = envError(r, ErrNoReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return } if sameOrigin(r.URL, referer) == false { r = envError(r, ErrBadReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // If the token returned from the session store is nil for non-idempotent // ("unsafe") methods, call the error handler. if realToken == nil { r = envError(r, ErrNoToken) cs.opts.ErrorHandler.ServeHTTP(w, r) return } // Retrieve the combined token (pad + masked) token and unmask it. requestToken := unmask(cs.requestToken(r)) // Compare the request token against the real token if !compareTokens(requestToken, realToken) { r = envError(r, ErrBadToken) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // Set the Vary: Cookie header to protect clients from caching the response. w.Header().Add("Vary", "Cookie") // Call the wrapped handler/router on success. cs.h.ServeHTTP(w, r) // Clear the request context after the handler has completed. contextClear(r) }
[ "func", "(", "cs", "*", "csrf", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Skip the check if directed to. This should always be a bool.", "if", "val", ",", "err", ":=", "contextGet", "(", "r", ",", "skipCheckKey", ")", ";", "err", "==", "nil", "{", "if", "skip", ",", "ok", ":=", "val", ".", "(", "bool", ")", ";", "ok", "{", "if", "skip", "{", "cs", ".", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Retrieve the token from the session.", "// An error represents either a cookie that failed HMAC validation", "// or that doesn't exist.", "realToken", ",", "err", ":=", "cs", ".", "st", ".", "Get", "(", "r", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "realToken", ")", "!=", "tokenLength", "{", "// If there was an error retrieving the token, the token doesn't exist", "// yet, or it's the wrong length, generate a new token.", "// Note that the new token will (correctly) fail validation downstream", "// as it will no longer match the request token.", "realToken", ",", "err", "=", "generateRandomBytes", "(", "tokenLength", ")", "\n", "if", "err", "!=", "nil", "{", "r", "=", "envError", "(", "r", ",", "err", ")", "\n", "cs", ".", "opts", ".", "ErrorHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "// Save the new (real) token in the session store.", "err", "=", "cs", ".", "st", ".", "Save", "(", "realToken", ",", "w", ")", "\n", "if", "err", "!=", "nil", "{", "r", "=", "envError", "(", "r", ",", "err", ")", "\n", "cs", ".", "opts", ".", "ErrorHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Save the masked token to the request context", "r", "=", "contextSave", "(", "r", ",", "tokenKey", ",", "mask", "(", "realToken", ",", "r", ")", ")", "\n", "// Save the field name to the request context", "r", "=", "contextSave", "(", "r", ",", "formKey", ",", "cs", ".", "opts", ".", "FieldName", ")", "\n\n", "// HTTP methods not defined as idempotent (\"safe\") under RFC7231 require", "// inspection.", "if", "!", "contains", "(", "safeMethods", ",", "r", ".", "Method", ")", "{", "// Enforce an origin check for HTTPS connections. As per the Django CSRF", "// implementation (https://goo.gl/vKA7GE) the Referer header is almost", "// always present for same-domain HTTP requests.", "if", "r", ".", "URL", ".", "Scheme", "==", "\"", "\"", "{", "// Fetch the Referer value. Call the error handler if it's empty or", "// otherwise fails to parse.", "referer", ",", "err", ":=", "url", ".", "Parse", "(", "r", ".", "Referer", "(", ")", ")", "\n", "if", "err", "!=", "nil", "||", "referer", ".", "String", "(", ")", "==", "\"", "\"", "{", "r", "=", "envError", "(", "r", ",", "ErrNoReferer", ")", "\n", "cs", ".", "opts", ".", "ErrorHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "if", "sameOrigin", "(", "r", ".", "URL", ",", "referer", ")", "==", "false", "{", "r", "=", "envError", "(", "r", ",", "ErrBadReferer", ")", "\n", "cs", ".", "opts", ".", "ErrorHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// If the token returned from the session store is nil for non-idempotent", "// (\"unsafe\") methods, call the error handler.", "if", "realToken", "==", "nil", "{", "r", "=", "envError", "(", "r", ",", "ErrNoToken", ")", "\n", "cs", ".", "opts", ".", "ErrorHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "// Retrieve the combined token (pad + masked) token and unmask it.", "requestToken", ":=", "unmask", "(", "cs", ".", "requestToken", "(", "r", ")", ")", "\n\n", "// Compare the request token against the real token", "if", "!", "compareTokens", "(", "requestToken", ",", "realToken", ")", "{", "r", "=", "envError", "(", "r", ",", "ErrBadToken", ")", "\n", "cs", ".", "opts", ".", "ErrorHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "}", "\n\n", "// Set the Vary: Cookie header to protect clients from caching the response.", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Call the wrapped handler/router on success.", "cs", ".", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "// Clear the request context after the handler has completed.", "contextClear", "(", "r", ")", "\n", "}" ]
// Implements http.Handler for the csrf type.
[ "Implements", "http", ".", "Handler", "for", "the", "csrf", "type", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/csrf.go#L179-L270
8,955
gorilla/csrf
csrf.go
unauthorizedHandler
func unauthorizedHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, fmt.Sprintf("%s - %s", http.StatusText(http.StatusForbidden), FailureReason(r)), http.StatusForbidden) return }
go
func unauthorizedHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, fmt.Sprintf("%s - %s", http.StatusText(http.StatusForbidden), FailureReason(r)), http.StatusForbidden) return }
[ "func", "unauthorizedHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "http", ".", "Error", "(", "w", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "http", ".", "StatusText", "(", "http", ".", "StatusForbidden", ")", ",", "FailureReason", "(", "r", ")", ")", ",", "http", ".", "StatusForbidden", ")", "\n", "return", "\n", "}" ]
// unauthorizedhandler sets a HTTP 403 Forbidden status and writes the // CSRF failure reason to the response.
[ "unauthorizedhandler", "sets", "a", "HTTP", "403", "Forbidden", "status", "and", "writes", "the", "CSRF", "failure", "reason", "to", "the", "response", "." ]
d1620373958b3d521d88c063d1c9b678e734e9df
https://github.com/gorilla/csrf/blob/d1620373958b3d521d88c063d1c9b678e734e9df/csrf.go#L274-L279
8,956
glycerine/zygomys
zygo/jsonmsgp.go
JsonToSexp
func JsonToSexp(json []byte, env *Zlisp) (Sexp, error) { iface, err := JsonToGo(json) if err != nil { return nil, err } return GoToSexp(iface, env) }
go
func JsonToSexp(json []byte, env *Zlisp) (Sexp, error) { iface, err := JsonToGo(json) if err != nil { return nil, err } return GoToSexp(iface, env) }
[ "func", "JsonToSexp", "(", "json", "[", "]", "byte", ",", "env", "*", "Zlisp", ")", "(", "Sexp", ",", "error", ")", "{", "iface", ",", "err", ":=", "JsonToGo", "(", "json", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "GoToSexp", "(", "iface", ",", "env", ")", "\n", "}" ]
// json -> sexp. env is needed to handle symbols correctly
[ "json", "-", ">", "sexp", ".", "env", "is", "needed", "to", "handle", "symbols", "correctly" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/jsonmsgp.go#L82-L88
8,957
glycerine/zygomys
zygo/jsonmsgp.go
SexpToJson
func SexpToJson(exp Sexp) string { switch e := exp.(type) { case *SexpHash: return e.jsonHashHelper() case *SexpArray: return e.jsonArrayHelper() case *SexpSymbol: return `"` + e.name + `"` default: return exp.SexpString(nil) } }
go
func SexpToJson(exp Sexp) string { switch e := exp.(type) { case *SexpHash: return e.jsonHashHelper() case *SexpArray: return e.jsonArrayHelper() case *SexpSymbol: return `"` + e.name + `"` default: return exp.SexpString(nil) } }
[ "func", "SexpToJson", "(", "exp", "Sexp", ")", "string", "{", "switch", "e", ":=", "exp", ".", "(", "type", ")", "{", "case", "*", "SexpHash", ":", "return", "e", ".", "jsonHashHelper", "(", ")", "\n", "case", "*", "SexpArray", ":", "return", "e", ".", "jsonArrayHelper", "(", ")", "\n", "case", "*", "SexpSymbol", ":", "return", "`\"`", "+", "e", ".", "name", "+", "`\"`", "\n", "default", ":", "return", "exp", ".", "SexpString", "(", "nil", ")", "\n", "}", "\n", "}" ]
// sexp -> json
[ "sexp", "-", ">", "json" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/jsonmsgp.go#L91-L102
8,958
glycerine/zygomys
zygo/jsonmsgp.go
JsonToGo
func JsonToGo(json []byte) (interface{}, error) { var iface interface{} decoder := codec.NewDecoderBytes(json, &msgpHelper.jh) err := decoder.Decode(&iface) if err != nil { panic(err) } VPrintf("\n decoded type : %T\n", iface) VPrintf("\n decoded value: %#v\n", iface) return iface, nil }
go
func JsonToGo(json []byte) (interface{}, error) { var iface interface{} decoder := codec.NewDecoderBytes(json, &msgpHelper.jh) err := decoder.Decode(&iface) if err != nil { panic(err) } VPrintf("\n decoded type : %T\n", iface) VPrintf("\n decoded value: %#v\n", iface) return iface, nil }
[ "func", "JsonToGo", "(", "json", "[", "]", "byte", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "iface", "interface", "{", "}", "\n\n", "decoder", ":=", "codec", ".", "NewDecoderBytes", "(", "json", ",", "&", "msgpHelper", ".", "jh", ")", "\n", "err", ":=", "decoder", ".", "Decode", "(", "&", "iface", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "VPrintf", "(", "\"", "\\n", "\\n", "\"", ",", "iface", ")", "\n", "VPrintf", "(", "\"", "\\n", "\\n", "\"", ",", "iface", ")", "\n", "return", "iface", ",", "nil", "\n", "}" ]
// json -> go
[ "json", "-", ">", "go" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/jsonmsgp.go#L198-L209
8,959
glycerine/zygomys
zygo/jsonmsgp.go
GoToJson
func GoToJson(iface interface{}) []byte { var w bytes.Buffer encoder := codec.NewEncoder(&w, &msgpHelper.jh) err := encoder.Encode(&iface) if err != nil { panic(err) } return w.Bytes() }
go
func GoToJson(iface interface{}) []byte { var w bytes.Buffer encoder := codec.NewEncoder(&w, &msgpHelper.jh) err := encoder.Encode(&iface) if err != nil { panic(err) } return w.Bytes() }
[ "func", "GoToJson", "(", "iface", "interface", "{", "}", ")", "[", "]", "byte", "{", "var", "w", "bytes", ".", "Buffer", "\n", "encoder", ":=", "codec", ".", "NewEncoder", "(", "&", "w", ",", "&", "msgpHelper", ".", "jh", ")", "\n", "err", ":=", "encoder", ".", "Encode", "(", "&", "iface", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "w", ".", "Bytes", "(", ")", "\n", "}" ]
// go -> json
[ "go", "-", ">", "json" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/jsonmsgp.go#L222-L230
8,960
glycerine/zygomys
zygo/jsonmsgp.go
MsgpackToSexp
func MsgpackToSexp(msgp []byte, env *Zlisp) (Sexp, error) { iface, err := MsgpackToGo(msgp) if err != nil { return nil, fmt.Errorf("MsgpackToSexp failed at MsgpackToGo step: '%s", err) } sexp, err := GoToSexp(iface, env) if err != nil { return nil, fmt.Errorf("MsgpackToSexp failed at GoToSexp step: '%s", err) } return sexp, nil }
go
func MsgpackToSexp(msgp []byte, env *Zlisp) (Sexp, error) { iface, err := MsgpackToGo(msgp) if err != nil { return nil, fmt.Errorf("MsgpackToSexp failed at MsgpackToGo step: '%s", err) } sexp, err := GoToSexp(iface, env) if err != nil { return nil, fmt.Errorf("MsgpackToSexp failed at GoToSexp step: '%s", err) } return sexp, nil }
[ "func", "MsgpackToSexp", "(", "msgp", "[", "]", "byte", ",", "env", "*", "Zlisp", ")", "(", "Sexp", ",", "error", ")", "{", "iface", ",", "err", ":=", "MsgpackToGo", "(", "msgp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "sexp", ",", "err", ":=", "GoToSexp", "(", "iface", ",", "env", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "sexp", ",", "nil", "\n", "}" ]
// msgpack -> sexp
[ "msgpack", "-", ">", "sexp" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/jsonmsgp.go#L233-L243
8,961
glycerine/zygomys
zygo/jsonmsgp.go
MsgpackToGo
func MsgpackToGo(msgp []byte) (interface{}, error) { var iface interface{} dec := codec.NewDecoderBytes(msgp, &msgpHelper.mh) err := dec.Decode(&iface) if err != nil { return nil, err } //fmt.Printf("\n decoded type : %T\n", iface) //fmt.Printf("\n decoded value: %#v\n", iface) return iface, nil }
go
func MsgpackToGo(msgp []byte) (interface{}, error) { var iface interface{} dec := codec.NewDecoderBytes(msgp, &msgpHelper.mh) err := dec.Decode(&iface) if err != nil { return nil, err } //fmt.Printf("\n decoded type : %T\n", iface) //fmt.Printf("\n decoded value: %#v\n", iface) return iface, nil }
[ "func", "MsgpackToGo", "(", "msgp", "[", "]", "byte", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "iface", "interface", "{", "}", "\n", "dec", ":=", "codec", ".", "NewDecoderBytes", "(", "msgp", ",", "&", "msgpHelper", ".", "mh", ")", "\n", "err", ":=", "dec", ".", "Decode", "(", "&", "iface", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "//fmt.Printf(\"\\n decoded type : %T\\n\", iface)", "//fmt.Printf(\"\\n decoded value: %#v\\n\", iface)", "return", "iface", ",", "nil", "\n", "}" ]
// msgpack -> go
[ "msgpack", "-", ">", "go" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/jsonmsgp.go#L246-L258
8,962
glycerine/zygomys
slides/coro/lexer.go
dumpComment
func (lexer *Lexer) dumpComment() { str := lexer.buffer.String() lexer.buffer.Reset() lexer.AppendToken(lexer.Token(TokenComment, str)) }
go
func (lexer *Lexer) dumpComment() { str := lexer.buffer.String() lexer.buffer.Reset() lexer.AppendToken(lexer.Token(TokenComment, str)) }
[ "func", "(", "lexer", "*", "Lexer", ")", "dumpComment", "(", ")", "{", "str", ":=", "lexer", ".", "buffer", ".", "String", "(", ")", "\n", "lexer", ".", "buffer", ".", "Reset", "(", ")", "\n", "lexer", ".", "AppendToken", "(", "lexer", ".", "Token", "(", "TokenComment", ",", "str", ")", ")", "\n", "}" ]
// with block comments, we've got to tell // the parser about them, so it can recognize // when another line is needed to finish a // block comment.
[ "with", "block", "comments", "we", "ve", "got", "to", "tell", "the", "parser", "about", "them", "so", "it", "can", "recognize", "when", "another", "line", "is", "needed", "to", "finish", "a", "block", "comment", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/slides/coro/lexer.go#L332-L336
8,963
glycerine/zygomys
zygo/scopes.go
SexpString
func (s *Scope) SexpString(ps *PrintState) string { var label string head := "" if s.IsPackage { head = "(package " + s.PackageName } else { label = "scope " + s.Name if s.IsGlobal { label += " (global)" } } str, err := s.Show(s.env, ps, s.Name) if err != nil { return "(" + label + ")" } return head + " " + str + " )" }
go
func (s *Scope) SexpString(ps *PrintState) string { var label string head := "" if s.IsPackage { head = "(package " + s.PackageName } else { label = "scope " + s.Name if s.IsGlobal { label += " (global)" } } str, err := s.Show(s.env, ps, s.Name) if err != nil { return "(" + label + ")" } return head + " " + str + " )" }
[ "func", "(", "s", "*", "Scope", ")", "SexpString", "(", "ps", "*", "PrintState", ")", "string", "{", "var", "label", "string", "\n", "head", ":=", "\"", "\"", "\n", "if", "s", ".", "IsPackage", "{", "head", "=", "\"", "\"", "+", "s", ".", "PackageName", "\n", "}", "else", "{", "label", "=", "\"", "\"", "+", "s", ".", "Name", "\n", "if", "s", ".", "IsGlobal", "{", "label", "+=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "str", ",", "err", ":=", "s", ".", "Show", "(", "s", ".", "env", ",", "ps", ",", "s", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "+", "label", "+", "\"", "\"", "\n", "}", "\n\n", "return", "head", "+", "\"", "\"", "+", "str", "+", "\"", "\"", "\n", "}" ]
// SexpString satisfies the Sexp interface, producing a string presentation of the value.
[ "SexpString", "satisfies", "the", "Sexp", "interface", "producing", "a", "string", "presentation", "of", "the", "value", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/scopes.go#L27-L45
8,964
glycerine/zygomys
zygo/scopes.go
LookupSymbolNonGlobal
func (stack *Stack) LookupSymbolNonGlobal(sym *SexpSymbol) (Sexp, error, *Scope) { return stack.lookupSymbol(sym, 1, nil) }
go
func (stack *Stack) LookupSymbolNonGlobal(sym *SexpSymbol) (Sexp, error, *Scope) { return stack.lookupSymbol(sym, 1, nil) }
[ "func", "(", "stack", "*", "Stack", ")", "LookupSymbolNonGlobal", "(", "sym", "*", "SexpSymbol", ")", "(", "Sexp", ",", "error", ",", "*", "Scope", ")", "{", "return", "stack", ".", "lookupSymbol", "(", "sym", ",", "1", ",", "nil", ")", "\n", "}" ]
// LookupSymbolNonGlobal - closures use this to only find symbols below the global scope, to avoid copying globals it'll always be-able to ref
[ "LookupSymbolNonGlobal", "-", "closures", "use", "this", "to", "only", "find", "symbols", "below", "the", "global", "scope", "to", "avoid", "copying", "globals", "it", "ll", "always", "be", "-", "able", "to", "ref" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/scopes.go#L129-L131
8,965
glycerine/zygomys
zygo/msgpackmap.go
MsgpackMapMacro
func MsgpackMapMacro(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) < 1 { return SexpNull, fmt.Errorf("struct-name is missing. use: " + "(msgpack-map struct-name)\n") } return MakeList([]Sexp{ env.MakeSymbol("def"), args[0], MakeList([]Sexp{ env.MakeSymbol("quote"), env.MakeSymbol("msgmap"), &SexpStr{S: args[0].(*SexpSymbol).name}, }), }), nil }
go
func MsgpackMapMacro(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) < 1 { return SexpNull, fmt.Errorf("struct-name is missing. use: " + "(msgpack-map struct-name)\n") } return MakeList([]Sexp{ env.MakeSymbol("def"), args[0], MakeList([]Sexp{ env.MakeSymbol("quote"), env.MakeSymbol("msgmap"), &SexpStr{S: args[0].(*SexpSymbol).name}, }), }), nil }
[ "func", "MsgpackMapMacro", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "<", "1", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "return", "MakeList", "(", "[", "]", "Sexp", "{", "env", ".", "MakeSymbol", "(", "\"", "\"", ")", ",", "args", "[", "0", "]", ",", "MakeList", "(", "[", "]", "Sexp", "{", "env", ".", "MakeSymbol", "(", "\"", "\"", ")", ",", "env", ".", "MakeSymbol", "(", "\"", "\"", ")", ",", "&", "SexpStr", "{", "S", ":", "args", "[", "0", "]", ".", "(", "*", "SexpSymbol", ")", ".", "name", "}", ",", "}", ")", ",", "}", ")", ",", "nil", "\n", "}" ]
// declare a new record type
[ "declare", "a", "new", "record", "type" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/msgpackmap.go#L14-L31
8,966
glycerine/zygomys
zygo/comment.go
RemoveEndsFilter
func RemoveEndsFilter(x Sexp) bool { switch n := x.(type) { case *SexpSentinel: if n.Val == SexpEnd.Val { return false } } return true }
go
func RemoveEndsFilter(x Sexp) bool { switch n := x.(type) { case *SexpSentinel: if n.Val == SexpEnd.Val { return false } } return true }
[ "func", "RemoveEndsFilter", "(", "x", "Sexp", ")", "bool", "{", "switch", "n", ":=", "x", ".", "(", "type", ")", "{", "case", "*", "SexpSentinel", ":", "if", "n", ".", "Val", "==", "SexpEnd", ".", "Val", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// detect SexpEnd values and return false on them to filter them out.
[ "detect", "SexpEnd", "values", "and", "return", "false", "on", "them", "to", "filter", "them", "out", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/comment.go#L31-L39
8,967
glycerine/zygomys
zygo/functions.go
MergeFuncMap
func MergeFuncMap(funcs ...map[string]ZlispUserFunction) map[string]ZlispUserFunction { n := make(map[string]ZlispUserFunction) for _, f := range funcs { for k, v := range f { // disallow dups, avoiding possible security implications and confusion generally. if _, dup := n[k]; dup { panic(fmt.Sprintf(" duplicate function '%s' not allowed", k)) } n[k] = v } } return n }
go
func MergeFuncMap(funcs ...map[string]ZlispUserFunction) map[string]ZlispUserFunction { n := make(map[string]ZlispUserFunction) for _, f := range funcs { for k, v := range f { // disallow dups, avoiding possible security implications and confusion generally. if _, dup := n[k]; dup { panic(fmt.Sprintf(" duplicate function '%s' not allowed", k)) } n[k] = v } } return n }
[ "func", "MergeFuncMap", "(", "funcs", "...", "map", "[", "string", "]", "ZlispUserFunction", ")", "map", "[", "string", "]", "ZlispUserFunction", "{", "n", ":=", "make", "(", "map", "[", "string", "]", "ZlispUserFunction", ")", "\n\n", "for", "_", ",", "f", ":=", "range", "funcs", "{", "for", "k", ",", "v", ":=", "range", "f", "{", "// disallow dups, avoiding possible security implications and confusion generally.", "if", "_", ",", "dup", ":=", "n", "[", "k", "]", ";", "dup", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ")", ")", "\n", "}", "\n", "n", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "return", "n", "\n", "}" ]
// MergeFuncMap returns the union of the two given maps
[ "MergeFuncMap", "returns", "the", "union", "of", "the", "two", "given", "maps" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L903-L916
8,968
glycerine/zygomys
zygo/functions.go
CoreFunctions
func CoreFunctions() map[string]ZlispUserFunction { return map[string]ZlispUserFunction{ "pretty": SetPrettyPrintFlag, "<": CompareFunction, ">": CompareFunction, "<=": CompareFunction, ">=": CompareFunction, "==": CompareFunction, "!=": CompareFunction, "isnan": IsNaNFunction, "isNaN": IsNaNFunction, "sll": BinaryIntFunction, "sra": BinaryIntFunction, "srl": BinaryIntFunction, "mod": BinaryIntFunction, "+": NumericFunction, "-": NumericFunction, "*": PointerOrNumericFunction, "**": NumericFunction, "/": NumericFunction, "bitAnd": BitwiseFunction, "bitOr": BitwiseFunction, "bitXor": BitwiseFunction, "bitNot": ComplementFunction, "read": ReadFunction, "cons": ConsFunction, "first": FirstFunction, "second": SecondFunction, "rest": RestFunction, "car": FirstFunction, "cdr": RestFunction, "type?": TypeQueryFunction, "list?": TypeQueryFunction, "null?": TypeQueryFunction, "array?": TypeQueryFunction, "hash?": TypeQueryFunction, "number?": TypeQueryFunction, "int?": TypeQueryFunction, "float?": TypeQueryFunction, "char?": TypeQueryFunction, "symbol?": TypeQueryFunction, "string?": TypeQueryFunction, "zero?": TypeQueryFunction, "empty?": TypeQueryFunction, "func?": TypeQueryFunction, "not": NotFunction, "apply": ApplyFunction, "map": MapFunction, "makeArray": MakeArrayFunction, "aget": ArrayAccessFunction, "aset": ArrayAccessFunction, "sget": SgetFunction, "hget": GenericAccessFunction, // handles arrays or hashes //":": ColonAccessFunction, "hset": HashAccessFunction, "hdel": HashAccessFunction, "keys": HashAccessFunction, "hpair": GenericHpairFunction, "slice": SliceFunction, "len": LenFunction, "append": AppendFunction, "appendslice": AppendFunction, "concat": ConcatFunction, "field": ConstructorFunction, "struct": ConstructorFunction, "array": ConstructorFunction, "list": ConstructorFunction, "hash": ConstructorFunction, "raw": ConstructorFunction, "str": StringifyFunction, "->": ThreadMapFunction, "flatten": FlattenToWordsFunction, "quotelist": QuoteListFunction, "=": AssignmentFunction, ":=": AssignmentFunction, "fieldls": GoFieldListFunction, "defined?": DefinedFunction, "stop": StopFunction, "joinsym": JoinSymFunction, "GOOS": GOOSFunction, "&": AddressOfFunction, "derefSet": DerefFunction, "deref": DerefFunction, ".": DotFunction, "arrayidx": ArrayIndexFunction, "hashidx": HashIndexFunction, "asUint64": AsUint64Function, } }
go
func CoreFunctions() map[string]ZlispUserFunction { return map[string]ZlispUserFunction{ "pretty": SetPrettyPrintFlag, "<": CompareFunction, ">": CompareFunction, "<=": CompareFunction, ">=": CompareFunction, "==": CompareFunction, "!=": CompareFunction, "isnan": IsNaNFunction, "isNaN": IsNaNFunction, "sll": BinaryIntFunction, "sra": BinaryIntFunction, "srl": BinaryIntFunction, "mod": BinaryIntFunction, "+": NumericFunction, "-": NumericFunction, "*": PointerOrNumericFunction, "**": NumericFunction, "/": NumericFunction, "bitAnd": BitwiseFunction, "bitOr": BitwiseFunction, "bitXor": BitwiseFunction, "bitNot": ComplementFunction, "read": ReadFunction, "cons": ConsFunction, "first": FirstFunction, "second": SecondFunction, "rest": RestFunction, "car": FirstFunction, "cdr": RestFunction, "type?": TypeQueryFunction, "list?": TypeQueryFunction, "null?": TypeQueryFunction, "array?": TypeQueryFunction, "hash?": TypeQueryFunction, "number?": TypeQueryFunction, "int?": TypeQueryFunction, "float?": TypeQueryFunction, "char?": TypeQueryFunction, "symbol?": TypeQueryFunction, "string?": TypeQueryFunction, "zero?": TypeQueryFunction, "empty?": TypeQueryFunction, "func?": TypeQueryFunction, "not": NotFunction, "apply": ApplyFunction, "map": MapFunction, "makeArray": MakeArrayFunction, "aget": ArrayAccessFunction, "aset": ArrayAccessFunction, "sget": SgetFunction, "hget": GenericAccessFunction, // handles arrays or hashes //":": ColonAccessFunction, "hset": HashAccessFunction, "hdel": HashAccessFunction, "keys": HashAccessFunction, "hpair": GenericHpairFunction, "slice": SliceFunction, "len": LenFunction, "append": AppendFunction, "appendslice": AppendFunction, "concat": ConcatFunction, "field": ConstructorFunction, "struct": ConstructorFunction, "array": ConstructorFunction, "list": ConstructorFunction, "hash": ConstructorFunction, "raw": ConstructorFunction, "str": StringifyFunction, "->": ThreadMapFunction, "flatten": FlattenToWordsFunction, "quotelist": QuoteListFunction, "=": AssignmentFunction, ":=": AssignmentFunction, "fieldls": GoFieldListFunction, "defined?": DefinedFunction, "stop": StopFunction, "joinsym": JoinSymFunction, "GOOS": GOOSFunction, "&": AddressOfFunction, "derefSet": DerefFunction, "deref": DerefFunction, ".": DotFunction, "arrayidx": ArrayIndexFunction, "hashidx": HashIndexFunction, "asUint64": AsUint64Function, } }
[ "func", "CoreFunctions", "(", ")", "map", "[", "string", "]", "ZlispUserFunction", "{", "return", "map", "[", "string", "]", "ZlispUserFunction", "{", "\"", "\"", ":", "SetPrettyPrintFlag", ",", "\"", "\"", ":", "CompareFunction", ",", "\"", "\"", ":", "CompareFunction", ",", "\"", "\"", ":", "CompareFunction", ",", "\"", "\"", ":", "CompareFunction", ",", "\"", "\"", ":", "CompareFunction", ",", "\"", "\"", ":", "CompareFunction", ",", "\"", "\"", ":", "IsNaNFunction", ",", "\"", "\"", ":", "IsNaNFunction", ",", "\"", "\"", ":", "BinaryIntFunction", ",", "\"", "\"", ":", "BinaryIntFunction", ",", "\"", "\"", ":", "BinaryIntFunction", ",", "\"", "\"", ":", "BinaryIntFunction", ",", "\"", "\"", ":", "NumericFunction", ",", "\"", "\"", ":", "NumericFunction", ",", "\"", "\"", ":", "PointerOrNumericFunction", ",", "\"", "\"", ":", "NumericFunction", ",", "\"", "\"", ":", "NumericFunction", ",", "\"", "\"", ":", "BitwiseFunction", ",", "\"", "\"", ":", "BitwiseFunction", ",", "\"", "\"", ":", "BitwiseFunction", ",", "\"", "\"", ":", "ComplementFunction", ",", "\"", "\"", ":", "ReadFunction", ",", "\"", "\"", ":", "ConsFunction", ",", "\"", "\"", ":", "FirstFunction", ",", "\"", "\"", ":", "SecondFunction", ",", "\"", "\"", ":", "RestFunction", ",", "\"", "\"", ":", "FirstFunction", ",", "\"", "\"", ":", "RestFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "TypeQueryFunction", ",", "\"", "\"", ":", "NotFunction", ",", "\"", "\"", ":", "ApplyFunction", ",", "\"", "\"", ":", "MapFunction", ",", "\"", "\"", ":", "MakeArrayFunction", ",", "\"", "\"", ":", "ArrayAccessFunction", ",", "\"", "\"", ":", "ArrayAccessFunction", ",", "\"", "\"", ":", "SgetFunction", ",", "\"", "\"", ":", "GenericAccessFunction", ",", "// handles arrays or hashes", "//\":\": ColonAccessFunction,", "\"", "\"", ":", "HashAccessFunction", ",", "\"", "\"", ":", "HashAccessFunction", ",", "\"", "\"", ":", "HashAccessFunction", ",", "\"", "\"", ":", "GenericHpairFunction", ",", "\"", "\"", ":", "SliceFunction", ",", "\"", "\"", ":", "LenFunction", ",", "\"", "\"", ":", "AppendFunction", ",", "\"", "\"", ":", "AppendFunction", ",", "\"", "\"", ":", "ConcatFunction", ",", "\"", "\"", ":", "ConstructorFunction", ",", "\"", "\"", ":", "ConstructorFunction", ",", "\"", "\"", ":", "ConstructorFunction", ",", "\"", "\"", ":", "ConstructorFunction", ",", "\"", "\"", ":", "ConstructorFunction", ",", "\"", "\"", ":", "ConstructorFunction", ",", "\"", "\"", ":", "StringifyFunction", ",", "\"", "\"", ":", "ThreadMapFunction", ",", "\"", "\"", ":", "FlattenToWordsFunction", ",", "\"", "\"", ":", "QuoteListFunction", ",", "\"", "\"", ":", "AssignmentFunction", ",", "\"", "\"", ":", "AssignmentFunction", ",", "\"", "\"", ":", "GoFieldListFunction", ",", "\"", "\"", ":", "DefinedFunction", ",", "\"", "\"", ":", "StopFunction", ",", "\"", "\"", ":", "JoinSymFunction", ",", "\"", "\"", ":", "GOOSFunction", ",", "\"", "\"", ":", "AddressOfFunction", ",", "\"", "\"", ":", "DerefFunction", ",", "\"", "\"", ":", "DerefFunction", ",", "\"", "\"", ":", "DotFunction", ",", "\"", "\"", ":", "ArrayIndexFunction", ",", "\"", "\"", ":", "HashIndexFunction", ",", "\"", "\"", ":", "AsUint64Function", ",", "}", "\n", "}" ]
// CoreFunctions returns all of the core logic
[ "CoreFunctions", "returns", "all", "of", "the", "core", "logic" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L939-L1027
8,969
glycerine/zygomys
zygo/functions.go
GenericAccessFunction
func GenericAccessFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) < 1 || len(args) > 3 { return SexpNull, WrongNargs } // handle *SexpSelector container := args[0] var err error if ptr, isPtrLike := container.(Selector); isPtrLike { container, err = ptr.RHS(env) if err != nil { return SexpNull, err } } switch container.(type) { case *SexpHash: return HashAccessFunction(env, name, args) case *SexpArray: return ArrayAccessFunction(env, name, args) } return SexpNull, fmt.Errorf("first argument to hget function must be hash or array") }
go
func GenericAccessFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) < 1 || len(args) > 3 { return SexpNull, WrongNargs } // handle *SexpSelector container := args[0] var err error if ptr, isPtrLike := container.(Selector); isPtrLike { container, err = ptr.RHS(env) if err != nil { return SexpNull, err } } switch container.(type) { case *SexpHash: return HashAccessFunction(env, name, args) case *SexpArray: return ArrayAccessFunction(env, name, args) } return SexpNull, fmt.Errorf("first argument to hget function must be hash or array") }
[ "func", "GenericAccessFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "<", "1", "||", "len", "(", "args", ")", ">", "3", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "// handle *SexpSelector", "container", ":=", "args", "[", "0", "]", "\n", "var", "err", "error", "\n", "if", "ptr", ",", "isPtrLike", ":=", "container", ".", "(", "Selector", ")", ";", "isPtrLike", "{", "container", ",", "err", "=", "ptr", ".", "RHS", "(", "env", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n", "}", "\n\n", "switch", "container", ".", "(", "type", ")", "{", "case", "*", "SexpHash", ":", "return", "HashAccessFunction", "(", "env", ",", "name", ",", "args", ")", "\n", "case", "*", "SexpArray", ":", "return", "ArrayAccessFunction", "(", "env", ",", "name", ",", "args", ")", "\n", "}", "\n", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// handles arrays or hashes
[ "handles", "arrays", "or", "hashes" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L1190-L1212
8,970
glycerine/zygomys
zygo/functions.go
AssignmentFunction
func AssignmentFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { Q("\n AssignmentFunction called with name ='%s'. args='%s'\n", name, env.NewSexpArray(args).SexpString(nil)) narg := len(args) if narg != 2 { return SexpNull, fmt.Errorf("assignment requires two arguments: a left-hand-side and a right-hand-side argument") } var sym *SexpSymbol switch s := args[0].(type) { case *SexpSymbol: sym = s case Selector: err := s.AssignToSelection(env, args[1]) return args[1], err default: return SexpNull, fmt.Errorf("assignment needs left-hand-side"+ " argument to be a symbol; we got %T", s) } if !sym.isDot { Q("assignment sees LHS symbol but is not dot, binding '%s' to '%s'\n", sym.name, args[1].SexpString(nil)) err := env.LexicalBindSymbol(sym, args[1]) if err != nil { return SexpNull, err } return args[1], nil } Q("assignment calling dotGetSetHelper()\n") return dotGetSetHelper(env, sym.name, &args[1]) }
go
func AssignmentFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { Q("\n AssignmentFunction called with name ='%s'. args='%s'\n", name, env.NewSexpArray(args).SexpString(nil)) narg := len(args) if narg != 2 { return SexpNull, fmt.Errorf("assignment requires two arguments: a left-hand-side and a right-hand-side argument") } var sym *SexpSymbol switch s := args[0].(type) { case *SexpSymbol: sym = s case Selector: err := s.AssignToSelection(env, args[1]) return args[1], err default: return SexpNull, fmt.Errorf("assignment needs left-hand-side"+ " argument to be a symbol; we got %T", s) } if !sym.isDot { Q("assignment sees LHS symbol but is not dot, binding '%s' to '%s'\n", sym.name, args[1].SexpString(nil)) err := env.LexicalBindSymbol(sym, args[1]) if err != nil { return SexpNull, err } return args[1], nil } Q("assignment calling dotGetSetHelper()\n") return dotGetSetHelper(env, sym.name, &args[1]) }
[ "func", "AssignmentFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "Q", "(", "\"", "\\n", "\\n", "\"", ",", "name", ",", "env", ".", "NewSexpArray", "(", "args", ")", ".", "SexpString", "(", "nil", ")", ")", "\n\n", "narg", ":=", "len", "(", "args", ")", "\n", "if", "narg", "!=", "2", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "sym", "*", "SexpSymbol", "\n", "switch", "s", ":=", "args", "[", "0", "]", ".", "(", "type", ")", "{", "case", "*", "SexpSymbol", ":", "sym", "=", "s", "\n", "case", "Selector", ":", "err", ":=", "s", ".", "AssignToSelection", "(", "env", ",", "args", "[", "1", "]", ")", "\n", "return", "args", "[", "1", "]", ",", "err", "\n\n", "default", ":", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "if", "!", "sym", ".", "isDot", "{", "Q", "(", "\"", "\\n", "\"", ",", "sym", ".", "name", ",", "args", "[", "1", "]", ".", "SexpString", "(", "nil", ")", ")", "\n", "err", ":=", "env", ".", "LexicalBindSymbol", "(", "sym", ",", "args", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n", "return", "args", "[", "1", "]", ",", "nil", "\n", "}", "\n\n", "Q", "(", "\"", "\\n", "\"", ")", "\n", "return", "dotGetSetHelper", "(", "env", ",", "sym", ".", "name", ",", "&", "args", "[", "1", "]", ")", "\n", "}" ]
// the assignment function, =
[ "the", "assignment", "function", "=" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L1234-L1268
8,971
glycerine/zygomys
zygo/functions.go
errIfPrivate
func errIfPrivate(pathPart string, pkg *Stack) error { noDot := stripAnyDotPrefix(pathPart) // references through a package must be Public if !unicode.IsUpper([]rune(noDot)[0]) { return fmt.Errorf("Cannot access private member '%s' of package '%s'", noDot, pkg.PackageName) } return nil }
go
func errIfPrivate(pathPart string, pkg *Stack) error { noDot := stripAnyDotPrefix(pathPart) // references through a package must be Public if !unicode.IsUpper([]rune(noDot)[0]) { return fmt.Errorf("Cannot access private member '%s' of package '%s'", noDot, pkg.PackageName) } return nil }
[ "func", "errIfPrivate", "(", "pathPart", "string", ",", "pkg", "*", "Stack", ")", "error", "{", "noDot", ":=", "stripAnyDotPrefix", "(", "pathPart", ")", "\n\n", "// references through a package must be Public", "if", "!", "unicode", ".", "IsUpper", "(", "[", "]", "rune", "(", "noDot", ")", "[", "0", "]", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "noDot", ",", "pkg", ".", "PackageName", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// helper used by dotGetSetHelper and sub-calls to check for private
[ "helper", "used", "by", "dotGetSetHelper", "and", "sub", "-", "calls", "to", "check", "for", "private" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L1350-L1359
8,972
glycerine/zygomys
zygo/functions.go
DotFunction
func DotFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 2 { return SexpNull, WrongNargs } P("in DotFunction(), name='%v', args[0] = '%v', args[1]= '%v'", name, args[0].SexpString(nil), args[1].SexpString(nil)) return SexpNull, nil /* var ret Sexp = SexpNull var err error lenpath := len(path) if lenpath == 1 && setVal != nil { // single path element set, bind it now. a := path[0][1:] // strip off the dot asym := env.MakeSymbol(a) // check conflict //Q("asym = %#v\n", asym) builtin, typ := env.IsBuiltinSym(asym) if builtin { return SexpNull, fmt.Errorf("'%s' is a %s, cannot assign to it with dot-symbol", asym.name, typ) } err := env.LexicalBindSymbol(asym, *setVal) if err != nil { return SexpNull, err } return *setVal, nil } // handle multiple paths that index into hashes after the // the first key := path[0][1:] // strip off the dot //Q("\n in dotGetSetHelper(), looking up '%s'\n", key) ret, err, _ = env.LexicalLookupSymbol(env.MakeSymbol(key), false) if err != nil { Q("\n in dotGetSetHelper(), '%s' not found\n", key) return SexpNull, err } return ret, err */ }
go
func DotFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 2 { return SexpNull, WrongNargs } P("in DotFunction(), name='%v', args[0] = '%v', args[1]= '%v'", name, args[0].SexpString(nil), args[1].SexpString(nil)) return SexpNull, nil /* var ret Sexp = SexpNull var err error lenpath := len(path) if lenpath == 1 && setVal != nil { // single path element set, bind it now. a := path[0][1:] // strip off the dot asym := env.MakeSymbol(a) // check conflict //Q("asym = %#v\n", asym) builtin, typ := env.IsBuiltinSym(asym) if builtin { return SexpNull, fmt.Errorf("'%s' is a %s, cannot assign to it with dot-symbol", asym.name, typ) } err := env.LexicalBindSymbol(asym, *setVal) if err != nil { return SexpNull, err } return *setVal, nil } // handle multiple paths that index into hashes after the // the first key := path[0][1:] // strip off the dot //Q("\n in dotGetSetHelper(), looking up '%s'\n", key) ret, err, _ = env.LexicalLookupSymbol(env.MakeSymbol(key), false) if err != nil { Q("\n in dotGetSetHelper(), '%s' not found\n", key) return SexpNull, err } return ret, err */ }
[ "func", "DotFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n", "P", "(", "\"", "\"", ",", "name", ",", "args", "[", "0", "]", ".", "SexpString", "(", "nil", ")", ",", "args", "[", "1", "]", ".", "SexpString", "(", "nil", ")", ")", "\n", "return", "SexpNull", ",", "nil", "\n", "/*\n\t\tvar ret Sexp = SexpNull\n\t\tvar err error\n\t\tlenpath := len(path)\n\n\t\tif lenpath == 1 && setVal != nil {\n\t\t\t// single path element set, bind it now.\n\t\t\ta := path[0][1:] // strip off the dot\n\t\t\tasym := env.MakeSymbol(a)\n\n\t\t\t// check conflict\n\t\t\t//Q(\"asym = %#v\\n\", asym)\n\t\t\tbuiltin, typ := env.IsBuiltinSym(asym)\n\t\t\tif builtin {\n\t\t\t\treturn SexpNull, fmt.Errorf(\"'%s' is a %s, cannot assign to it with dot-symbol\", asym.name, typ)\n\t\t\t}\n\n\t\t\terr := env.LexicalBindSymbol(asym, *setVal)\n\t\t\tif err != nil {\n\t\t\t\treturn SexpNull, err\n\t\t\t}\n\t\t\treturn *setVal, nil\n\t\t}\n\n\t\t// handle multiple paths that index into hashes after the\n\t\t// the first\n\n\t\tkey := path[0][1:] // strip off the dot\n\t\t//Q(\"\\n in dotGetSetHelper(), looking up '%s'\\n\", key)\n\t\tret, err, _ = env.LexicalLookupSymbol(env.MakeSymbol(key), false)\n\t\tif err != nil {\n\t\t\tQ(\"\\n in dotGetSetHelper(), '%s' not found\\n\", key)\n\t\t\treturn SexpNull, err\n\t\t}\n\t\treturn ret, err\n\t*/", "}" ]
// "." dot operator
[ ".", "dot", "operator" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L1659-L1704
8,973
glycerine/zygomys
zygo/functions.go
AsUint64Function
func AsUint64Function(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 1 { return SexpNull, WrongNargs } var val uint64 switch x := args[0].(type) { case *SexpInt: val = uint64(x.Val) case *SexpFloat: val = uint64(x.Val) default: return SexpNull, fmt.Errorf("Cannot convert %s to uint64", TypeOf(args[0]).SexpString(nil)) } return &SexpUint64{Val: val}, nil }
go
func AsUint64Function(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 1 { return SexpNull, WrongNargs } var val uint64 switch x := args[0].(type) { case *SexpInt: val = uint64(x.Val) case *SexpFloat: val = uint64(x.Val) default: return SexpNull, fmt.Errorf("Cannot convert %s to uint64", TypeOf(args[0]).SexpString(nil)) } return &SexpUint64{Val: val}, nil }
[ "func", "AsUint64Function", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "var", "val", "uint64", "\n", "switch", "x", ":=", "args", "[", "0", "]", ".", "(", "type", ")", "{", "case", "*", "SexpInt", ":", "val", "=", "uint64", "(", "x", ".", "Val", ")", "\n", "case", "*", "SexpFloat", ":", "val", "=", "uint64", "(", "x", ".", "Val", ")", "\n", "default", ":", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "TypeOf", "(", "args", "[", "0", "]", ")", ".", "SexpString", "(", "nil", ")", ")", "\n\n", "}", "\n", "return", "&", "SexpUint64", "{", "Val", ":", "val", "}", ",", "nil", "\n", "}" ]
// coerce numbers to uint64
[ "coerce", "numbers", "to", "uint64" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L1771-L1787
8,974
glycerine/zygomys
zygo/hashutils.go
GenericHpairFunction
func GenericHpairFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 2 { return SexpNull, WrongNargs } posreq, isInt := args[1].(*SexpInt) if !isInt { return SexpNull, fmt.Errorf("hpair position request must be an integer") } pos := int(posreq.Val) switch seq := args[0].(type) { case *SexpHash: if pos < 0 || pos >= len(seq.KeyOrder) { return SexpNull, fmt.Errorf("hpair position request %d out of bounds", pos) } return seq.HashPairi(pos) case *SexpArray: if pos < 0 || pos >= len(seq.Val) { return SexpNull, fmt.Errorf("hpair position request %d out of bounds", pos) } return Cons(&SexpInt{Val: int64(pos)}, Cons(seq.Val[pos], SexpNull)), nil default: return SexpNull, errors.New("first argument of to hpair function must be hash, list, or array") } //return SexpNull, nil }
go
func GenericHpairFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 2 { return SexpNull, WrongNargs } posreq, isInt := args[1].(*SexpInt) if !isInt { return SexpNull, fmt.Errorf("hpair position request must be an integer") } pos := int(posreq.Val) switch seq := args[0].(type) { case *SexpHash: if pos < 0 || pos >= len(seq.KeyOrder) { return SexpNull, fmt.Errorf("hpair position request %d out of bounds", pos) } return seq.HashPairi(pos) case *SexpArray: if pos < 0 || pos >= len(seq.Val) { return SexpNull, fmt.Errorf("hpair position request %d out of bounds", pos) } return Cons(&SexpInt{Val: int64(pos)}, Cons(seq.Val[pos], SexpNull)), nil default: return SexpNull, errors.New("first argument of to hpair function must be hash, list, or array") } //return SexpNull, nil }
[ "func", "GenericHpairFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "posreq", ",", "isInt", ":=", "args", "[", "1", "]", ".", "(", "*", "SexpInt", ")", "\n", "if", "!", "isInt", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "pos", ":=", "int", "(", "posreq", ".", "Val", ")", "\n\n", "switch", "seq", ":=", "args", "[", "0", "]", ".", "(", "type", ")", "{", "case", "*", "SexpHash", ":", "if", "pos", "<", "0", "||", "pos", ">=", "len", "(", "seq", ".", "KeyOrder", ")", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pos", ")", "\n", "}", "\n", "return", "seq", ".", "HashPairi", "(", "pos", ")", "\n", "case", "*", "SexpArray", ":", "if", "pos", "<", "0", "||", "pos", ">=", "len", "(", "seq", ".", "Val", ")", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pos", ")", "\n", "}", "\n", "return", "Cons", "(", "&", "SexpInt", "{", "Val", ":", "int64", "(", "pos", ")", "}", ",", "Cons", "(", "seq", ".", "Val", "[", "pos", "]", ",", "SexpNull", ")", ")", ",", "nil", "\n", "default", ":", "return", "SexpNull", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "//return SexpNull, nil", "}" ]
// works over hashes and arrays
[ "works", "over", "hashes", "and", "arrays" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/hashutils.go#L618-L644
8,975
glycerine/zygomys
zygo/hashutils.go
CloneFrom
func (p *SexpHash) CloneFrom(src *SexpHash) { p.TypeName = src.TypeName p.Map = *(src.CopyMap()) p.KeyOrder = src.KeyOrder p.GoStructFactory = src.GoStructFactory p.NumKeys = src.NumKeys p.GoMethods = src.GoMethods p.GoFields = src.GoFields p.GoMethSx = src.GoMethSx p.GoFieldSx = src.GoFieldSx p.GoType = src.GoType p.NumMethod = src.NumMethod p.GoShadowStruct = src.GoShadowStruct p.GoShadowStructVa = src.GoShadowStructVa p.ShadowSet = src.ShadowSet // json tag name -> pointers to example values, as factories for SexpToGoStructs() p.JsonTagMap = make(map[string]*HashFieldDet) for k, v := range src.JsonTagMap { p.JsonTagMap[k] = v } p.DetOrder = src.DetOrder // for using these as a scoping model p.DefnEnv = src.DefnEnv p.SuperClass = src.SuperClass p.ZMain = src.ZMain p.ZMethods = make(map[string]*SexpFunction) for k, v := range src.ZMethods { p.ZMethods[k] = v } p.Env = src.Env }
go
func (p *SexpHash) CloneFrom(src *SexpHash) { p.TypeName = src.TypeName p.Map = *(src.CopyMap()) p.KeyOrder = src.KeyOrder p.GoStructFactory = src.GoStructFactory p.NumKeys = src.NumKeys p.GoMethods = src.GoMethods p.GoFields = src.GoFields p.GoMethSx = src.GoMethSx p.GoFieldSx = src.GoFieldSx p.GoType = src.GoType p.NumMethod = src.NumMethod p.GoShadowStruct = src.GoShadowStruct p.GoShadowStructVa = src.GoShadowStructVa p.ShadowSet = src.ShadowSet // json tag name -> pointers to example values, as factories for SexpToGoStructs() p.JsonTagMap = make(map[string]*HashFieldDet) for k, v := range src.JsonTagMap { p.JsonTagMap[k] = v } p.DetOrder = src.DetOrder // for using these as a scoping model p.DefnEnv = src.DefnEnv p.SuperClass = src.SuperClass p.ZMain = src.ZMain p.ZMethods = make(map[string]*SexpFunction) for k, v := range src.ZMethods { p.ZMethods[k] = v } p.Env = src.Env }
[ "func", "(", "p", "*", "SexpHash", ")", "CloneFrom", "(", "src", "*", "SexpHash", ")", "{", "p", ".", "TypeName", "=", "src", ".", "TypeName", "\n", "p", ".", "Map", "=", "*", "(", "src", ".", "CopyMap", "(", ")", ")", "\n\n", "p", ".", "KeyOrder", "=", "src", ".", "KeyOrder", "\n", "p", ".", "GoStructFactory", "=", "src", ".", "GoStructFactory", "\n", "p", ".", "NumKeys", "=", "src", ".", "NumKeys", "\n", "p", ".", "GoMethods", "=", "src", ".", "GoMethods", "\n", "p", ".", "GoFields", "=", "src", ".", "GoFields", "\n", "p", ".", "GoMethSx", "=", "src", ".", "GoMethSx", "\n", "p", ".", "GoFieldSx", "=", "src", ".", "GoFieldSx", "\n", "p", ".", "GoType", "=", "src", ".", "GoType", "\n", "p", ".", "NumMethod", "=", "src", ".", "NumMethod", "\n", "p", ".", "GoShadowStruct", "=", "src", ".", "GoShadowStruct", "\n", "p", ".", "GoShadowStructVa", "=", "src", ".", "GoShadowStructVa", "\n", "p", ".", "ShadowSet", "=", "src", ".", "ShadowSet", "\n\n", "// json tag name -> pointers to example values, as factories for SexpToGoStructs()", "p", ".", "JsonTagMap", "=", "make", "(", "map", "[", "string", "]", "*", "HashFieldDet", ")", "\n", "for", "k", ",", "v", ":=", "range", "src", ".", "JsonTagMap", "{", "p", ".", "JsonTagMap", "[", "k", "]", "=", "v", "\n", "}", "\n", "p", ".", "DetOrder", "=", "src", ".", "DetOrder", "\n\n", "// for using these as a scoping model", "p", ".", "DefnEnv", "=", "src", ".", "DefnEnv", "\n", "p", ".", "SuperClass", "=", "src", ".", "SuperClass", "\n", "p", ".", "ZMain", "=", "src", ".", "ZMain", "\n", "p", ".", "ZMethods", "=", "make", "(", "map", "[", "string", "]", "*", "SexpFunction", ")", "\n", "for", "k", ",", "v", ":=", "range", "src", ".", "ZMethods", "{", "p", ".", "ZMethods", "[", "k", "]", "=", "v", "\n", "}", "\n", "p", ".", "Env", "=", "src", ".", "Env", "\n", "}" ]
// CloneFrom copys all the internals of src into p, effectively // blanking out whatever p held and replacing it with a copy of src.
[ "CloneFrom", "copys", "all", "the", "internals", "of", "src", "into", "p", "effectively", "blanking", "out", "whatever", "p", "held", "and", "replacing", "it", "with", "a", "copy", "of", "src", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/hashutils.go#L925-L959
8,976
glycerine/zygomys
zygo/parser.go
Start
func (p *Parser) Start() { go func() { defer close(p.Done) expressions := make([]Sexp, 0, SliceDefaultCap) // maybe we already have input, be optimistic! // no need to call p.GetMoreInput() before staring // our loop. for { expr, err := p.ParseExpression(0) if err != nil || expr == SexpEnd { if err == ParserHaltRequested { return } err = p.GetMoreInput(expressions, err) if err == ParserHaltRequested { return } // GetMoreInput will have delivered what we gave them. Reset since we // don't own that memory any more. expressions = make([]Sexp, 0, SliceDefaultCap) } else { // INVAR: err == nil && expr is not SexpEnd expressions = append(expressions, expr) } } }() }
go
func (p *Parser) Start() { go func() { defer close(p.Done) expressions := make([]Sexp, 0, SliceDefaultCap) // maybe we already have input, be optimistic! // no need to call p.GetMoreInput() before staring // our loop. for { expr, err := p.ParseExpression(0) if err != nil || expr == SexpEnd { if err == ParserHaltRequested { return } err = p.GetMoreInput(expressions, err) if err == ParserHaltRequested { return } // GetMoreInput will have delivered what we gave them. Reset since we // don't own that memory any more. expressions = make([]Sexp, 0, SliceDefaultCap) } else { // INVAR: err == nil && expr is not SexpEnd expressions = append(expressions, expr) } } }() }
[ "func", "(", "p", "*", "Parser", ")", "Start", "(", ")", "{", "go", "func", "(", ")", "{", "defer", "close", "(", "p", ".", "Done", ")", "\n", "expressions", ":=", "make", "(", "[", "]", "Sexp", ",", "0", ",", "SliceDefaultCap", ")", "\n\n", "// maybe we already have input, be optimistic!", "// no need to call p.GetMoreInput() before staring", "// our loop.", "for", "{", "expr", ",", "err", ":=", "p", ".", "ParseExpression", "(", "0", ")", "\n", "if", "err", "!=", "nil", "||", "expr", "==", "SexpEnd", "{", "if", "err", "==", "ParserHaltRequested", "{", "return", "\n", "}", "\n", "err", "=", "p", ".", "GetMoreInput", "(", "expressions", ",", "err", ")", "\n", "if", "err", "==", "ParserHaltRequested", "{", "return", "\n", "}", "\n", "// GetMoreInput will have delivered what we gave them. Reset since we", "// don't own that memory any more.", "expressions", "=", "make", "(", "[", "]", "Sexp", ",", "0", ",", "SliceDefaultCap", ")", "\n", "}", "else", "{", "// INVAR: err == nil && expr is not SexpEnd", "expressions", "=", "append", "(", "expressions", ",", "expr", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Starts launches a background goroutine that runs an // infinite parsing loop.
[ "Starts", "launches", "a", "background", "goroutine", "that", "runs", "an", "infinite", "parsing", "loop", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/parser.go#L70-L98
8,977
glycerine/zygomys
slides/coro/repl.go
getExpressionWithLiner
func (pr *Prompter) getExpressionWithLiner(env *Glisp) (readin string, xs []Sexp, err error) { line, err := pr.Getline(nil) if err != nil { return "", nil, err } err = UnexpectedEnd var x []Sexp // parse and pause the parser if we need more input. env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\n"))) x, err = env.parser.ParseTokens() if len(x) > 0 { xs = append(xs, x...) } for err == ErrMoreInputNeeded || err == UnexpectedEnd || err == ResetRequested { nextline, err := pr.Getline(&continuationPrompt) if err != nil { return "", nil, err } // provide more input env.parser.NewInput(bytes.NewBuffer([]byte(nextline + "\n"))) // get parsed expression tree(s) back in x x, err = env.parser.ParseTokens() if len(x) > 0 { for i := range x { if x[i] == SexpEnd { P("found an SexpEnd token, omitting it") continue } xs = append(xs, x[i]) } } switch err { case nil: line += "\n" + nextline // no problem, parsing went fine. return line, xs, nil case ResetRequested: continue case ErrMoreInputNeeded: continue default: return "", nil, fmt.Errorf("Error on line %d: %v\n", env.parser.lexer.Linenum(), err) } } return line, xs, nil }
go
func (pr *Prompter) getExpressionWithLiner(env *Glisp) (readin string, xs []Sexp, err error) { line, err := pr.Getline(nil) if err != nil { return "", nil, err } err = UnexpectedEnd var x []Sexp // parse and pause the parser if we need more input. env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\n"))) x, err = env.parser.ParseTokens() if len(x) > 0 { xs = append(xs, x...) } for err == ErrMoreInputNeeded || err == UnexpectedEnd || err == ResetRequested { nextline, err := pr.Getline(&continuationPrompt) if err != nil { return "", nil, err } // provide more input env.parser.NewInput(bytes.NewBuffer([]byte(nextline + "\n"))) // get parsed expression tree(s) back in x x, err = env.parser.ParseTokens() if len(x) > 0 { for i := range x { if x[i] == SexpEnd { P("found an SexpEnd token, omitting it") continue } xs = append(xs, x[i]) } } switch err { case nil: line += "\n" + nextline // no problem, parsing went fine. return line, xs, nil case ResetRequested: continue case ErrMoreInputNeeded: continue default: return "", nil, fmt.Errorf("Error on line %d: %v\n", env.parser.lexer.Linenum(), err) } } return line, xs, nil }
[ "func", "(", "pr", "*", "Prompter", ")", "getExpressionWithLiner", "(", "env", "*", "Glisp", ")", "(", "readin", "string", ",", "xs", "[", "]", "Sexp", ",", "err", "error", ")", "{", "line", ",", "err", ":=", "pr", ".", "Getline", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "UnexpectedEnd", "\n", "var", "x", "[", "]", "Sexp", "\n\n", "// parse and pause the parser if we need more input.", "env", ".", "parser", ".", "ResetAddNewInput", "(", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "line", "+", "\"", "\\n", "\"", ")", ")", ")", "\n", "x", ",", "err", "=", "env", ".", "parser", ".", "ParseTokens", "(", ")", "\n\n", "if", "len", "(", "x", ")", ">", "0", "{", "xs", "=", "append", "(", "xs", ",", "x", "...", ")", "\n", "}", "\n\n", "for", "err", "==", "ErrMoreInputNeeded", "||", "err", "==", "UnexpectedEnd", "||", "err", "==", "ResetRequested", "{", "nextline", ",", "err", ":=", "pr", ".", "Getline", "(", "&", "continuationPrompt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "err", "\n", "}", "\n", "// provide more input", "env", ".", "parser", ".", "NewInput", "(", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "nextline", "+", "\"", "\\n", "\"", ")", ")", ")", "\n\n", "// get parsed expression tree(s) back in x", "x", ",", "err", "=", "env", ".", "parser", ".", "ParseTokens", "(", ")", "\n", "if", "len", "(", "x", ")", ">", "0", "{", "for", "i", ":=", "range", "x", "{", "if", "x", "[", "i", "]", "==", "SexpEnd", "{", "P", "(", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n", "xs", "=", "append", "(", "xs", ",", "x", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "switch", "err", "{", "case", "nil", ":", "line", "+=", "\"", "\\n", "\"", "+", "nextline", "\n", "// no problem, parsing went fine.", "return", "line", ",", "xs", ",", "nil", "\n", "case", "ResetRequested", ":", "continue", "\n", "case", "ErrMoreInputNeeded", ":", "continue", "\n", "default", ":", "return", "\"", "\"", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "env", ".", "parser", ".", "lexer", ".", "Linenum", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "line", ",", "xs", ",", "nil", "\n", "}" ]
// reads Stdin only
[ "reads", "Stdin", "only" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/slides/coro/repl.go#L74-L125
8,978
glycerine/zygomys
zygo/vprint.go
TSPrintf
func TSPrintf(format string, a ...interface{}) { fmt.Printf("%s ", ts()) fmt.Printf(format, a...) }
go
func TSPrintf(format string, a ...interface{}) { fmt.Printf("%s ", ts()) fmt.Printf(format, a...) }
[ "func", "TSPrintf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Printf", "(", "\"", "\"", ",", "ts", "(", ")", ")", "\n", "fmt", ".", "Printf", "(", "format", ",", "a", "...", ")", "\n", "}" ]
// time-stamped printf
[ "time", "-", "stamped", "printf" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/vprint.go#L27-L30
8,979
glycerine/zygomys
zygo/liner.go
MyWordCompleter
func MyWordCompleter(line string, pos int) (head string, c []string, tail string) { beg := []rune(line[:pos]) end := line[pos:] Q("\nline = '%s' pos=%v\n", line, pos) Q("\nbeg = '%v'\nend = '%s'\n", string(beg), end) // find most recent paren in beg n := len(beg) last := n - 1 var i int var p int = -1 outer: for i = last; i >= 0; i-- { Q("\nbeg[i=%v] is '%v'\n", i, string(beg[i])) switch beg[i] { case ' ': break outer case '(': p = i Q("\n found paren at p = %v\n", i) break outer } } Q("p=%d\n", p) prefix := string(beg) extendme := "" if p == 0 { prefix = "" extendme = string(beg) } else if p > 0 { prefix = string(beg[:p]) extendme = string(beg[p:]) } Q("prefix = '%s'\nextendme = '%s'\n", prefix, extendme) for _, n := range completion_keywords { if strings.HasPrefix(n, strings.ToLower(extendme)) { Q("n='%s' has prefix = '%s'\n", n, extendme) c = append(c, n) } } return prefix, c, end }
go
func MyWordCompleter(line string, pos int) (head string, c []string, tail string) { beg := []rune(line[:pos]) end := line[pos:] Q("\nline = '%s' pos=%v\n", line, pos) Q("\nbeg = '%v'\nend = '%s'\n", string(beg), end) // find most recent paren in beg n := len(beg) last := n - 1 var i int var p int = -1 outer: for i = last; i >= 0; i-- { Q("\nbeg[i=%v] is '%v'\n", i, string(beg[i])) switch beg[i] { case ' ': break outer case '(': p = i Q("\n found paren at p = %v\n", i) break outer } } Q("p=%d\n", p) prefix := string(beg) extendme := "" if p == 0 { prefix = "" extendme = string(beg) } else if p > 0 { prefix = string(beg[:p]) extendme = string(beg[p:]) } Q("prefix = '%s'\nextendme = '%s'\n", prefix, extendme) for _, n := range completion_keywords { if strings.HasPrefix(n, strings.ToLower(extendme)) { Q("n='%s' has prefix = '%s'\n", n, extendme) c = append(c, n) } } return prefix, c, end }
[ "func", "MyWordCompleter", "(", "line", "string", ",", "pos", "int", ")", "(", "head", "string", ",", "c", "[", "]", "string", ",", "tail", "string", ")", "{", "beg", ":=", "[", "]", "rune", "(", "line", "[", ":", "pos", "]", ")", "\n", "end", ":=", "line", "[", "pos", ":", "]", "\n", "Q", "(", "\"", "\\n", "\\n", "\"", ",", "line", ",", "pos", ")", "\n", "Q", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "string", "(", "beg", ")", ",", "end", ")", "\n", "// find most recent paren in beg", "n", ":=", "len", "(", "beg", ")", "\n", "last", ":=", "n", "-", "1", "\n", "var", "i", "int", "\n", "var", "p", "int", "=", "-", "1", "\n", "outer", ":", "for", "i", "=", "last", ";", "i", ">=", "0", ";", "i", "--", "{", "Q", "(", "\"", "\\n", "\\n", "\"", ",", "i", ",", "string", "(", "beg", "[", "i", "]", ")", ")", "\n", "switch", "beg", "[", "i", "]", "{", "case", "' '", ":", "break", "outer", "\n", "case", "'('", ":", "p", "=", "i", "\n", "Q", "(", "\"", "\\n", "\\n", "\"", ",", "i", ")", "\n", "break", "outer", "\n", "}", "\n", "}", "\n", "Q", "(", "\"", "\\n", "\"", ",", "p", ")", "\n", "prefix", ":=", "string", "(", "beg", ")", "\n", "extendme", ":=", "\"", "\"", "\n", "if", "p", "==", "0", "{", "prefix", "=", "\"", "\"", "\n", "extendme", "=", "string", "(", "beg", ")", "\n", "}", "else", "if", "p", ">", "0", "{", "prefix", "=", "string", "(", "beg", "[", ":", "p", "]", ")", "\n", "extendme", "=", "string", "(", "beg", "[", "p", ":", "]", ")", "\n", "}", "\n", "Q", "(", "\"", "\\n", "\\n", "\"", ",", "prefix", ",", "extendme", ")", "\n\n", "for", "_", ",", "n", ":=", "range", "completion_keywords", "{", "if", "strings", ".", "HasPrefix", "(", "n", ",", "strings", ".", "ToLower", "(", "extendme", ")", ")", "{", "Q", "(", "\"", "\\n", "\"", ",", "n", ",", "extendme", ")", "\n", "c", "=", "append", "(", "c", ",", "n", ")", "\n", "}", "\n", "}", "\n\n", "return", "prefix", ",", "c", ",", "end", "\n", "}" ]
// complete phrases that start with '('
[ "complete", "phrases", "that", "start", "with", "(" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/liner.go#L39-L82
8,980
glycerine/zygomys
zygo/pratt.go
Assignment
func (env *Zlisp) Assignment(op string, bp int) *InfixOp { oper := env.MakeSymbol(op) operSet := env.MakeSymbol("set") iop := &InfixOp{ Sym: oper, Bp: bp, MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) { // TODO: check that left is okay as an LVALUE. right, err := pr.Expression(env, bp-1) if err != nil { return SexpNull, err } if op == "=" || op == ":=" { oper = operSet } list := MakeList([]Sexp{ oper, left, right, }) Q("assignment returning list: '%v'", list.SexpString(nil)) return list, nil }, IsAssign: true, } env.infixOps[op] = iop return iop }
go
func (env *Zlisp) Assignment(op string, bp int) *InfixOp { oper := env.MakeSymbol(op) operSet := env.MakeSymbol("set") iop := &InfixOp{ Sym: oper, Bp: bp, MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) { // TODO: check that left is okay as an LVALUE. right, err := pr.Expression(env, bp-1) if err != nil { return SexpNull, err } if op == "=" || op == ":=" { oper = operSet } list := MakeList([]Sexp{ oper, left, right, }) Q("assignment returning list: '%v'", list.SexpString(nil)) return list, nil }, IsAssign: true, } env.infixOps[op] = iop return iop }
[ "func", "(", "env", "*", "Zlisp", ")", "Assignment", "(", "op", "string", ",", "bp", "int", ")", "*", "InfixOp", "{", "oper", ":=", "env", ".", "MakeSymbol", "(", "op", ")", "\n", "operSet", ":=", "env", ".", "MakeSymbol", "(", "\"", "\"", ")", "\n", "iop", ":=", "&", "InfixOp", "{", "Sym", ":", "oper", ",", "Bp", ":", "bp", ",", "MunchLeft", ":", "func", "(", "env", "*", "Zlisp", ",", "pr", "*", "Pratt", ",", "left", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "// TODO: check that left is okay as an LVALUE.", "right", ",", "err", ":=", "pr", ".", "Expression", "(", "env", ",", "bp", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n", "if", "op", "==", "\"", "\"", "||", "op", "==", "\"", "\"", "{", "oper", "=", "operSet", "\n", "}", "\n\n", "list", ":=", "MakeList", "(", "[", "]", "Sexp", "{", "oper", ",", "left", ",", "right", ",", "}", ")", "\n", "Q", "(", "\"", "\"", ",", "list", ".", "SexpString", "(", "nil", ")", ")", "\n", "return", "list", ",", "nil", "\n", "}", ",", "IsAssign", ":", "true", ",", "}", "\n", "env", ".", "infixOps", "[", "op", "]", "=", "iop", "\n", "return", "iop", "\n", "}" ]
// Assignment creates a new assignment operator for infix // processing.
[ "Assignment", "creates", "a", "new", "assignment", "operator", "for", "infix", "processing", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/pratt.go#L113-L140
8,981
glycerine/zygomys
zygo/pratt.go
PostfixAssign
func (env *Zlisp) PostfixAssign(op string, bp int) *InfixOp { oper := env.MakeSymbol(op) iop := &InfixOp{ Sym: oper, Bp: bp, MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) { // TODO: check that left is okay as an LVALUE list := MakeList([]Sexp{ oper, left, }) Q("postfix assignment returning list: '%v'", list.SexpString(nil)) return list, nil }, } env.infixOps[op] = iop return iop }
go
func (env *Zlisp) PostfixAssign(op string, bp int) *InfixOp { oper := env.MakeSymbol(op) iop := &InfixOp{ Sym: oper, Bp: bp, MunchLeft: func(env *Zlisp, pr *Pratt, left Sexp) (Sexp, error) { // TODO: check that left is okay as an LVALUE list := MakeList([]Sexp{ oper, left, }) Q("postfix assignment returning list: '%v'", list.SexpString(nil)) return list, nil }, } env.infixOps[op] = iop return iop }
[ "func", "(", "env", "*", "Zlisp", ")", "PostfixAssign", "(", "op", "string", ",", "bp", "int", ")", "*", "InfixOp", "{", "oper", ":=", "env", ".", "MakeSymbol", "(", "op", ")", "\n", "iop", ":=", "&", "InfixOp", "{", "Sym", ":", "oper", ",", "Bp", ":", "bp", ",", "MunchLeft", ":", "func", "(", "env", "*", "Zlisp", ",", "pr", "*", "Pratt", ",", "left", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "// TODO: check that left is okay as an LVALUE", "list", ":=", "MakeList", "(", "[", "]", "Sexp", "{", "oper", ",", "left", ",", "}", ")", "\n", "Q", "(", "\"", "\"", ",", "list", ".", "SexpString", "(", "nil", ")", ")", "\n", "return", "list", ",", "nil", "\n", "}", ",", "}", "\n", "env", ".", "infixOps", "[", "op", "]", "=", "iop", "\n", "return", "iop", "\n", "}" ]
// PostfixAssign creates a new postfix assignment operator for infix // processing.
[ "PostfixAssign", "creates", "a", "new", "postfix", "assignment", "operator", "for", "infix", "processing", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/pratt.go#L144-L160
8,982
glycerine/zygomys
zygo/pratt.go
Advance
func (p *Pratt) Advance() error { p.Pos++ if p.Pos >= len(p.Stream) { return io.EOF } p.NextToken = p.Stream[p.Pos] Q("end of Advance, p.NextToken = '%v'", p.NextToken.SexpString(nil)) return nil }
go
func (p *Pratt) Advance() error { p.Pos++ if p.Pos >= len(p.Stream) { return io.EOF } p.NextToken = p.Stream[p.Pos] Q("end of Advance, p.NextToken = '%v'", p.NextToken.SexpString(nil)) return nil }
[ "func", "(", "p", "*", "Pratt", ")", "Advance", "(", ")", "error", "{", "p", ".", "Pos", "++", "\n", "if", "p", ".", "Pos", ">=", "len", "(", "p", ".", "Stream", ")", "{", "return", "io", ".", "EOF", "\n", "}", "\n", "p", ".", "NextToken", "=", "p", ".", "Stream", "[", "p", ".", "Pos", "]", "\n", "Q", "(", "\"", "\"", ",", "p", ".", "NextToken", ".", "SexpString", "(", "nil", ")", ")", "\n", "return", "nil", "\n", "}" ]
// Advance sets p.NextToken
[ "Advance", "sets", "p", ".", "NextToken" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/pratt.go#L591-L599
8,983
glycerine/zygomys
zygo/expressions.go
LookupSymbolInParentChainOfClosures
func (sf *SexpFunction) LookupSymbolInParentChainOfClosures(sym *SexpSymbol, setVal *Sexp, env *Zlisp) (Sexp, error, *Scope) { cur := sf par := sf.parent for par != nil { //fmt.Printf(" parent chain: cur:%v -> parent:%v\n", cur.name, par.name) //fmt.Printf(" cur.closures = %s", ClosureToString(cur, env)) exp, err, scope := cur.ClosingLookupSymbolUntilFunc(sym, setVal, 1, false) if err == nil { //P("LookupSymbolInParentChainOfClosures(sym='%s') found in scope '%s'\n", sym.name, scope.Name) return exp, err, scope } cur = par par = par.parent } return SexpNull, SymNotFound, nil }
go
func (sf *SexpFunction) LookupSymbolInParentChainOfClosures(sym *SexpSymbol, setVal *Sexp, env *Zlisp) (Sexp, error, *Scope) { cur := sf par := sf.parent for par != nil { //fmt.Printf(" parent chain: cur:%v -> parent:%v\n", cur.name, par.name) //fmt.Printf(" cur.closures = %s", ClosureToString(cur, env)) exp, err, scope := cur.ClosingLookupSymbolUntilFunc(sym, setVal, 1, false) if err == nil { //P("LookupSymbolInParentChainOfClosures(sym='%s') found in scope '%s'\n", sym.name, scope.Name) return exp, err, scope } cur = par par = par.parent } return SexpNull, SymNotFound, nil }
[ "func", "(", "sf", "*", "SexpFunction", ")", "LookupSymbolInParentChainOfClosures", "(", "sym", "*", "SexpSymbol", ",", "setVal", "*", "Sexp", ",", "env", "*", "Zlisp", ")", "(", "Sexp", ",", "error", ",", "*", "Scope", ")", "{", "cur", ":=", "sf", "\n", "par", ":=", "sf", ".", "parent", "\n", "for", "par", "!=", "nil", "{", "//fmt.Printf(\" parent chain: cur:%v -> parent:%v\\n\", cur.name, par.name)", "//fmt.Printf(\" cur.closures = %s\", ClosureToString(cur, env))", "exp", ",", "err", ",", "scope", ":=", "cur", ".", "ClosingLookupSymbolUntilFunc", "(", "sym", ",", "setVal", ",", "1", ",", "false", ")", "\n", "if", "err", "==", "nil", "{", "//P(\"LookupSymbolInParentChainOfClosures(sym='%s') found in scope '%s'\\n\", sym.name, scope.Name)", "return", "exp", ",", "err", ",", "scope", "\n", "}", "\n\n", "cur", "=", "par", "\n", "par", "=", "par", ".", "parent", "\n", "}", "\n\n", "return", "SexpNull", ",", "SymNotFound", ",", "nil", "\n", "}" ]
// chase parent pointers up the chain and check each of their immediate closures.
[ "chase", "parent", "pointers", "up", "the", "chain", "and", "check", "each", "of", "their", "immediate", "closures", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/expressions.go#L632-L651
8,984
glycerine/zygomys
zygo/callgo.go
NilOrHoldsNil
func NilOrHoldsNil(iface interface{}) bool { if iface == nil { return true } return reflect.ValueOf(iface).IsNil() }
go
func NilOrHoldsNil(iface interface{}) bool { if iface == nil { return true } return reflect.ValueOf(iface).IsNil() }
[ "func", "NilOrHoldsNil", "(", "iface", "interface", "{", "}", ")", "bool", "{", "if", "iface", "==", "nil", "{", "return", "true", "\n", "}", "\n", "return", "reflect", ".", "ValueOf", "(", "iface", ")", ".", "IsNil", "(", ")", "\n", "}" ]
// detect if inteface is holding anything
[ "detect", "if", "inteface", "is", "holding", "anything" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/callgo.go#L204-L209
8,985
glycerine/zygomys
zygo/import.go
ImportPackageBuilder
func ImportPackageBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) { //P("starting ImportPackageBuilder") n := len(args) if n != 1 && n != 2 { return SexpNull, WrongNargs } var path Sexp var alias string switch n { case 1: path = args[0] case 2: path = args[1] //P("import debug: alias position at args[0] is '%#v'", args[0]) switch sy := args[0].(type) { case *SexpSymbol: //P("import debug: alias is symbol, ok: '%v'", sy.name) alias = sy.name default: return SexpNull, fmt.Errorf("import error: alias was not a symbol name") } } var pth string switch x := path.(type) { case *SexpStr: pth = x.S default: return SexpNull, fmt.Errorf("import error: path argument must be string") } if !FileExists(pth) { return SexpNull, fmt.Errorf("import error: path '%s' does not exist", pth) } pkg, err := SourceFileFunction(env, "source", []Sexp{path}) if err != nil { return SexpNull, fmt.Errorf("import error: attempt to import path '%s' resulted in: '%s'", pth, err) } //P("pkg = '%#v'", pkg) asPkg, isPkg := pkg.(*Stack) if !isPkg || !asPkg.IsPackage { return SexpNull, fmt.Errorf("import error: attempt to import path '%s' resulted value that was not a package, but rather '%T'", pth, pkg) } if n == 1 { alias = asPkg.PackageName } //P("using alias = '%s'", alias) // now set alias in the current env err = env.LexicalBindSymbol(env.MakeSymbol(alias), asPkg) if err != nil { return SexpNull, err } return pkg, nil }
go
func ImportPackageBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) { //P("starting ImportPackageBuilder") n := len(args) if n != 1 && n != 2 { return SexpNull, WrongNargs } var path Sexp var alias string switch n { case 1: path = args[0] case 2: path = args[1] //P("import debug: alias position at args[0] is '%#v'", args[0]) switch sy := args[0].(type) { case *SexpSymbol: //P("import debug: alias is symbol, ok: '%v'", sy.name) alias = sy.name default: return SexpNull, fmt.Errorf("import error: alias was not a symbol name") } } var pth string switch x := path.(type) { case *SexpStr: pth = x.S default: return SexpNull, fmt.Errorf("import error: path argument must be string") } if !FileExists(pth) { return SexpNull, fmt.Errorf("import error: path '%s' does not exist", pth) } pkg, err := SourceFileFunction(env, "source", []Sexp{path}) if err != nil { return SexpNull, fmt.Errorf("import error: attempt to import path '%s' resulted in: '%s'", pth, err) } //P("pkg = '%#v'", pkg) asPkg, isPkg := pkg.(*Stack) if !isPkg || !asPkg.IsPackage { return SexpNull, fmt.Errorf("import error: attempt to import path '%s' resulted value that was not a package, but rather '%T'", pth, pkg) } if n == 1 { alias = asPkg.PackageName } //P("using alias = '%s'", alias) // now set alias in the current env err = env.LexicalBindSymbol(env.MakeSymbol(alias), asPkg) if err != nil { return SexpNull, err } return pkg, nil }
[ "func", "ImportPackageBuilder", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "//P(\"starting ImportPackageBuilder\")", "n", ":=", "len", "(", "args", ")", "\n", "if", "n", "!=", "1", "&&", "n", "!=", "2", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "var", "path", "Sexp", "\n", "var", "alias", "string", "\n\n", "switch", "n", "{", "case", "1", ":", "path", "=", "args", "[", "0", "]", "\n", "case", "2", ":", "path", "=", "args", "[", "1", "]", "\n", "//P(\"import debug: alias position at args[0] is '%#v'\", args[0])", "switch", "sy", ":=", "args", "[", "0", "]", ".", "(", "type", ")", "{", "case", "*", "SexpSymbol", ":", "//P(\"import debug: alias is symbol, ok: '%v'\", sy.name)", "alias", "=", "sy", ".", "name", "\n", "default", ":", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "var", "pth", "string", "\n", "switch", "x", ":=", "path", ".", "(", "type", ")", "{", "case", "*", "SexpStr", ":", "pth", "=", "x", ".", "S", "\n", "default", ":", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "FileExists", "(", "pth", ")", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pth", ")", "\n", "}", "\n\n", "pkg", ",", "err", ":=", "SourceFileFunction", "(", "env", ",", "\"", "\"", ",", "[", "]", "Sexp", "{", "path", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pth", ",", "err", ")", "\n", "}", "\n", "//P(\"pkg = '%#v'\", pkg)", "asPkg", ",", "isPkg", ":=", "pkg", ".", "(", "*", "Stack", ")", "\n", "if", "!", "isPkg", "||", "!", "asPkg", ".", "IsPackage", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pth", ",", "pkg", ")", "\n", "}", "\n\n", "if", "n", "==", "1", "{", "alias", "=", "asPkg", ".", "PackageName", "\n", "}", "\n", "//P(\"using alias = '%s'\", alias)", "// now set alias in the current env", "err", "=", "env", ".", "LexicalBindSymbol", "(", "env", ".", "MakeSymbol", "(", "alias", ")", ",", "asPkg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n\n", "return", "pkg", ",", "nil", "\n", "}" ]
// import a package, analagous to Golang.
[ "import", "a", "package", "analagous", "to", "Golang", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/import.go#L8-L67
8,986
glycerine/zygomys
zygo/generator.go
GenerateNewScope
func (gen *Generator) GenerateNewScope(expressions []Sexp) error { size := len(expressions) oldtail := gen.Tail gen.Tail = false if size == 0 { return nil //return NoExpressionsFound } gen.AddInstruction(AddScopeInstr{Name: "newScope"}) for _, expr := range expressions[:size-1] { err := gen.Generate(expr) if err != nil { return err } // insert pops after all but the last instruction // that way the stack remains clean... Q: how does this extra popping not mess up the expressions? gen.AddInstruction(PopInstr(0)) } gen.Tail = oldtail err := gen.Generate(expressions[size-1]) if err != nil { return err } gen.AddInstruction(RemoveScopeInstr{}) return nil }
go
func (gen *Generator) GenerateNewScope(expressions []Sexp) error { size := len(expressions) oldtail := gen.Tail gen.Tail = false if size == 0 { return nil //return NoExpressionsFound } gen.AddInstruction(AddScopeInstr{Name: "newScope"}) for _, expr := range expressions[:size-1] { err := gen.Generate(expr) if err != nil { return err } // insert pops after all but the last instruction // that way the stack remains clean... Q: how does this extra popping not mess up the expressions? gen.AddInstruction(PopInstr(0)) } gen.Tail = oldtail err := gen.Generate(expressions[size-1]) if err != nil { return err } gen.AddInstruction(RemoveScopeInstr{}) return nil }
[ "func", "(", "gen", "*", "Generator", ")", "GenerateNewScope", "(", "expressions", "[", "]", "Sexp", ")", "error", "{", "size", ":=", "len", "(", "expressions", ")", "\n", "oldtail", ":=", "gen", ".", "Tail", "\n", "gen", ".", "Tail", "=", "false", "\n", "if", "size", "==", "0", "{", "return", "nil", "\n", "//return NoExpressionsFound", "}", "\n\n", "gen", ".", "AddInstruction", "(", "AddScopeInstr", "{", "Name", ":", "\"", "\"", "}", ")", "\n", "for", "_", ",", "expr", ":=", "range", "expressions", "[", ":", "size", "-", "1", "]", "{", "err", ":=", "gen", ".", "Generate", "(", "expr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// insert pops after all but the last instruction", "// that way the stack remains clean... Q: how does this extra popping not mess up the expressions?", "gen", ".", "AddInstruction", "(", "PopInstr", "(", "0", ")", ")", "\n", "}", "\n", "gen", ".", "Tail", "=", "oldtail", "\n", "err", ":=", "gen", ".", "Generate", "(", "expressions", "[", "size", "-", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "gen", ".", "AddInstruction", "(", "RemoveScopeInstr", "{", "}", ")", "\n", "return", "nil", "\n", "}" ]
// like begin, but puts its contents in a new scope
[ "like", "begin", "but", "puts", "its", "contents", "in", "a", "new", "scope" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/generator.go#L1370-L1396
8,987
glycerine/zygomys
zygo/system.go
SetShellCmd
func SetShellCmd() { if runtime.GOOS == "windows" { ShellCmd = os.Getenv("COMSPEC") return } try := []string{"/usr/bin/bash"} if !FileExists(ShellCmd) { for i := range try { b := try[i] if FileExists(b) { ShellCmd = b return } } } }
go
func SetShellCmd() { if runtime.GOOS == "windows" { ShellCmd = os.Getenv("COMSPEC") return } try := []string{"/usr/bin/bash"} if !FileExists(ShellCmd) { for i := range try { b := try[i] if FileExists(b) { ShellCmd = b return } } } }
[ "func", "SetShellCmd", "(", ")", "{", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "ShellCmd", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "try", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "if", "!", "FileExists", "(", "ShellCmd", ")", "{", "for", "i", ":=", "range", "try", "{", "b", ":=", "try", "[", "i", "]", "\n", "if", "FileExists", "(", "b", ")", "{", "ShellCmd", "=", "b", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// set ShellCmd as used by SystemFunction
[ "set", "ShellCmd", "as", "used", "by", "SystemFunction" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/system.go#L18-L33
8,988
glycerine/zygomys
zygo/system.go
SystemBuilder
func SystemBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) { //P("SystemBuilder called with args='%#v'", args) return SystemFunction(env, name, args) }
go
func SystemBuilder(env *Zlisp, name string, args []Sexp) (Sexp, error) { //P("SystemBuilder called with args='%#v'", args) return SystemFunction(env, name, args) }
[ "func", "SystemBuilder", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "//P(\"SystemBuilder called with args='%#v'\", args)", "return", "SystemFunction", "(", "env", ",", "name", ",", "args", ")", "\n", "}" ]
// sys is a builder. shell out, return the combined output.
[ "sys", "is", "a", "builder", ".", "shell", "out", "return", "the", "combined", "output", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/system.go#L36-L39
8,989
glycerine/zygomys
zygo/environment.go
DumpFunction
func DumpFunction(fun ZlispFunction, pc int) { blank := " " extra := blank for i, instr := range fun { if i == pc { extra = " PC-> " } else { extra = blank } fmt.Printf("%s %d: %s\n", extra, i, instr.InstrString()) } if pc == len(fun) { fmt.Printf(" PC just past end at %d -----\n\n", pc) } }
go
func DumpFunction(fun ZlispFunction, pc int) { blank := " " extra := blank for i, instr := range fun { if i == pc { extra = " PC-> " } else { extra = blank } fmt.Printf("%s %d: %s\n", extra, i, instr.InstrString()) } if pc == len(fun) { fmt.Printf(" PC just past end at %d -----\n\n", pc) } }
[ "func", "DumpFunction", "(", "fun", "ZlispFunction", ",", "pc", "int", ")", "{", "blank", ":=", "\"", "\"", "\n", "extra", ":=", "blank", "\n", "for", "i", ",", "instr", ":=", "range", "fun", "{", "if", "i", "==", "pc", "{", "extra", "=", "\"", "\"", "\n", "}", "else", "{", "extra", "=", "blank", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "extra", ",", "i", ",", "instr", ".", "InstrString", "(", ")", ")", "\n", "}", "\n", "if", "pc", "==", "len", "(", "fun", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ",", "pc", ")", "\n", "}", "\n", "}" ]
// if pc is -1, don't show it.
[ "if", "pc", "is", "-", "1", "don", "t", "show", "it", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/environment.go#L536-L550
8,990
glycerine/zygomys
zygo/environment.go
FindLoop
func (env *Zlisp) FindLoop(target *Loop) (int, error) { if env.curfunc.user { panic(fmt.Errorf("impossible in user-defined-function to find a loop '%s'", target.stmtname.name)) } instruc := env.curfunc.fun for i := range instruc { switch loop := instruc[i].(type) { case LoopStartInstr: if loop.loop == target { return i, nil } } } return -1, fmt.Errorf("could not find loop target '%s'", target.stmtname.name) }
go
func (env *Zlisp) FindLoop(target *Loop) (int, error) { if env.curfunc.user { panic(fmt.Errorf("impossible in user-defined-function to find a loop '%s'", target.stmtname.name)) } instruc := env.curfunc.fun for i := range instruc { switch loop := instruc[i].(type) { case LoopStartInstr: if loop.loop == target { return i, nil } } } return -1, fmt.Errorf("could not find loop target '%s'", target.stmtname.name) }
[ "func", "(", "env", "*", "Zlisp", ")", "FindLoop", "(", "target", "*", "Loop", ")", "(", "int", ",", "error", ")", "{", "if", "env", ".", "curfunc", ".", "user", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ".", "stmtname", ".", "name", ")", ")", "\n", "}", "\n", "instruc", ":=", "env", ".", "curfunc", ".", "fun", "\n", "for", "i", ":=", "range", "instruc", "{", "switch", "loop", ":=", "instruc", "[", "i", "]", ".", "(", "type", ")", "{", "case", "LoopStartInstr", ":", "if", "loop", ".", "loop", "==", "target", "{", "return", "i", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ".", "stmtname", ".", "name", ")", "\n", "}" ]
// scan the instruction stream to locate loop start
[ "scan", "the", "instruction", "stream", "to", "locate", "loop", "start" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/environment.go#L665-L679
8,991
glycerine/zygomys
zygo/slurp.go
SplitStringFunction
func SplitStringFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 2 { return SexpNull, WrongNargs } // make sure the two args are strings s1, ok := args[0].(*SexpStr) if !ok { return SexpNull, fmt.Errorf("split requires a string to split, got %T", args[0]) } s2, ok := args[1].(*SexpStr) if !ok { return SexpNull, fmt.Errorf("split requires a string as a delimiter, got %T", args[1]) } toSplit := s1.S splitter := s2.S s := strings.Split(toSplit, splitter) split := make([]Sexp, len(s)) for i := range split { split[i] = &SexpStr{S: s[i]} } return env.NewSexpArray(split), nil }
go
func SplitStringFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 2 { return SexpNull, WrongNargs } // make sure the two args are strings s1, ok := args[0].(*SexpStr) if !ok { return SexpNull, fmt.Errorf("split requires a string to split, got %T", args[0]) } s2, ok := args[1].(*SexpStr) if !ok { return SexpNull, fmt.Errorf("split requires a string as a delimiter, got %T", args[1]) } toSplit := s1.S splitter := s2.S s := strings.Split(toSplit, splitter) split := make([]Sexp, len(s)) for i := range split { split[i] = &SexpStr{S: s[i]} } return env.NewSexpArray(split), nil }
[ "func", "SplitStringFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "// make sure the two args are strings", "s1", ",", "ok", ":=", "args", "[", "0", "]", ".", "(", "*", "SexpStr", ")", "\n", "if", "!", "ok", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "args", "[", "0", "]", ")", "\n", "}", "\n", "s2", ",", "ok", ":=", "args", "[", "1", "]", ".", "(", "*", "SexpStr", ")", "\n", "if", "!", "ok", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "args", "[", "1", "]", ")", "\n", "}", "\n\n", "toSplit", ":=", "s1", ".", "S", "\n", "splitter", ":=", "s2", ".", "S", "\n", "s", ":=", "strings", ".", "Split", "(", "toSplit", ",", "splitter", ")", "\n\n", "split", ":=", "make", "(", "[", "]", "Sexp", ",", "len", "(", "s", ")", ")", "\n", "for", "i", ":=", "range", "split", "{", "split", "[", "i", "]", "=", "&", "SexpStr", "{", "S", ":", "s", "[", "i", "]", "}", "\n", "}", "\n\n", "return", "env", ".", "NewSexpArray", "(", "split", ")", ",", "nil", "\n", "}" ]
// SplitStringFunction splits a string based on an arbitrary delimiter
[ "SplitStringFunction", "splits", "a", "string", "based", "on", "an", "arbitrary", "delimiter" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/slurp.go#L134-L159
8,992
glycerine/zygomys
zygo/repl.go
isBalanced
func isBalanced(str string) bool { parens := 0 squares := 0 for _, c := range str { switch c { case '(': parens++ case ')': parens-- case '[': squares++ case ']': squares-- } } return parens == 0 && squares == 0 }
go
func isBalanced(str string) bool { parens := 0 squares := 0 for _, c := range str { switch c { case '(': parens++ case ')': parens-- case '[': squares++ case ']': squares-- } } return parens == 0 && squares == 0 }
[ "func", "isBalanced", "(", "str", "string", ")", "bool", "{", "parens", ":=", "0", "\n", "squares", ":=", "0", "\n\n", "for", "_", ",", "c", ":=", "range", "str", "{", "switch", "c", "{", "case", "'('", ":", "parens", "++", "\n", "case", "')'", ":", "parens", "--", "\n", "case", "'['", ":", "squares", "++", "\n", "case", "']'", ":", "squares", "--", "\n", "}", "\n", "}", "\n\n", "return", "parens", "==", "0", "&&", "squares", "==", "0", "\n", "}" ]
// NB at the moment this doesn't track comment and strings state, // so it will fail if unbalanced '(' are found in either.
[ "NB", "at", "the", "moment", "this", "doesn", "t", "track", "comment", "and", "strings", "state", "so", "it", "will", "fail", "if", "unbalanced", "(", "are", "found", "in", "either", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/repl.go#L43-L61
8,993
glycerine/zygomys
zygo/repl.go
getExpressionWithLiner
func (pr *Prompter) getExpressionWithLiner(env *Zlisp, reader *bufio.Reader, noLiner bool) (readin string, xs []Sexp, err error) { var line, nextline string if noLiner { fmt.Printf(pr.prompt) line, err = getLine(reader) } else { line, err = pr.Getline(nil) } if err != nil { return "", nil, err } err = UnexpectedEnd var x []Sexp // test parse, but don't load or generate bytecode env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\n"))) x, err = env.parser.ParseTokens() //P("\n after ResetAddNewInput, err = %v. x = '%s'\n", err, SexpArray(x).SexpString()) if len(x) > 0 { xs = append(xs, x...) } for err == ErrMoreInputNeeded || err == UnexpectedEnd || err == ResetRequested { if noLiner { fmt.Printf(continuationPrompt) nextline, err = getLine(reader) } else { nextline, err = pr.Getline(&continuationPrompt) } if err != nil { return "", nil, err } env.parser.NewInput(bytes.NewBuffer([]byte(nextline + "\n"))) x, err = env.parser.ParseTokens() if len(x) > 0 { for i := range x { if x[i] == SexpEnd { P("found an SexpEnd token, omitting it") continue } xs = append(xs, x[i]) } } switch err { case nil: line += "\n" + nextline Q("no problem parsing line '%s' into '%s', proceeding...\n", line, (&SexpArray{Val: x, Env: env}).SexpString(nil)) return line, xs, nil case ResetRequested: continue case ErrMoreInputNeeded: continue default: return "", nil, fmt.Errorf("Error on line %d: %v\n", env.parser.lexer.Linenum(), err) } } return line, xs, nil }
go
func (pr *Prompter) getExpressionWithLiner(env *Zlisp, reader *bufio.Reader, noLiner bool) (readin string, xs []Sexp, err error) { var line, nextline string if noLiner { fmt.Printf(pr.prompt) line, err = getLine(reader) } else { line, err = pr.Getline(nil) } if err != nil { return "", nil, err } err = UnexpectedEnd var x []Sexp // test parse, but don't load or generate bytecode env.parser.ResetAddNewInput(bytes.NewBuffer([]byte(line + "\n"))) x, err = env.parser.ParseTokens() //P("\n after ResetAddNewInput, err = %v. x = '%s'\n", err, SexpArray(x).SexpString()) if len(x) > 0 { xs = append(xs, x...) } for err == ErrMoreInputNeeded || err == UnexpectedEnd || err == ResetRequested { if noLiner { fmt.Printf(continuationPrompt) nextline, err = getLine(reader) } else { nextline, err = pr.Getline(&continuationPrompt) } if err != nil { return "", nil, err } env.parser.NewInput(bytes.NewBuffer([]byte(nextline + "\n"))) x, err = env.parser.ParseTokens() if len(x) > 0 { for i := range x { if x[i] == SexpEnd { P("found an SexpEnd token, omitting it") continue } xs = append(xs, x[i]) } } switch err { case nil: line += "\n" + nextline Q("no problem parsing line '%s' into '%s', proceeding...\n", line, (&SexpArray{Val: x, Env: env}).SexpString(nil)) return line, xs, nil case ResetRequested: continue case ErrMoreInputNeeded: continue default: return "", nil, fmt.Errorf("Error on line %d: %v\n", env.parser.lexer.Linenum(), err) } } return line, xs, nil }
[ "func", "(", "pr", "*", "Prompter", ")", "getExpressionWithLiner", "(", "env", "*", "Zlisp", ",", "reader", "*", "bufio", ".", "Reader", ",", "noLiner", "bool", ")", "(", "readin", "string", ",", "xs", "[", "]", "Sexp", ",", "err", "error", ")", "{", "var", "line", ",", "nextline", "string", "\n\n", "if", "noLiner", "{", "fmt", ".", "Printf", "(", "pr", ".", "prompt", ")", "\n", "line", ",", "err", "=", "getLine", "(", "reader", ")", "\n", "}", "else", "{", "line", ",", "err", "=", "pr", ".", "Getline", "(", "nil", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "UnexpectedEnd", "\n", "var", "x", "[", "]", "Sexp", "\n\n", "// test parse, but don't load or generate bytecode", "env", ".", "parser", ".", "ResetAddNewInput", "(", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "line", "+", "\"", "\\n", "\"", ")", ")", ")", "\n", "x", ",", "err", "=", "env", ".", "parser", ".", "ParseTokens", "(", ")", "\n", "//P(\"\\n after ResetAddNewInput, err = %v. x = '%s'\\n\", err, SexpArray(x).SexpString())", "if", "len", "(", "x", ")", ">", "0", "{", "xs", "=", "append", "(", "xs", ",", "x", "...", ")", "\n", "}", "\n\n", "for", "err", "==", "ErrMoreInputNeeded", "||", "err", "==", "UnexpectedEnd", "||", "err", "==", "ResetRequested", "{", "if", "noLiner", "{", "fmt", ".", "Printf", "(", "continuationPrompt", ")", "\n", "nextline", ",", "err", "=", "getLine", "(", "reader", ")", "\n", "}", "else", "{", "nextline", ",", "err", "=", "pr", ".", "Getline", "(", "&", "continuationPrompt", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "err", "\n", "}", "\n", "env", ".", "parser", ".", "NewInput", "(", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "nextline", "+", "\"", "\\n", "\"", ")", ")", ")", "\n", "x", ",", "err", "=", "env", ".", "parser", ".", "ParseTokens", "(", ")", "\n", "if", "len", "(", "x", ")", ">", "0", "{", "for", "i", ":=", "range", "x", "{", "if", "x", "[", "i", "]", "==", "SexpEnd", "{", "P", "(", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n", "xs", "=", "append", "(", "xs", ",", "x", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "switch", "err", "{", "case", "nil", ":", "line", "+=", "\"", "\\n", "\"", "+", "nextline", "\n", "Q", "(", "\"", "\\n", "\"", ",", "line", ",", "(", "&", "SexpArray", "{", "Val", ":", "x", ",", "Env", ":", "env", "}", ")", ".", "SexpString", "(", "nil", ")", ")", "\n", "return", "line", ",", "xs", ",", "nil", "\n", "case", "ResetRequested", ":", "continue", "\n", "case", "ErrMoreInputNeeded", ":", "continue", "\n", "default", ":", "return", "\"", "\"", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "env", ".", "parser", ".", "lexer", ".", "Linenum", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "line", ",", "xs", ",", "nil", "\n", "}" ]
// liner reads Stdin only. If noLiner, then we read from reader.
[ "liner", "reads", "Stdin", "only", ".", "If", "noLiner", "then", "we", "read", "from", "reader", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/repl.go#L83-L144
8,994
glycerine/zygomys
zygo/time.go
AsTmFunction
func AsTmFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 1 { return SexpNull, WrongNargs } var str *SexpStr switch t := args[0].(type) { case *SexpStr: str = t default: return SexpNull, errors.New("argument of astm should be a string RFC3999Nano timestamp that we want to convert to time.Time") } tm, err := time.ParseInLocation(time.RFC3339Nano, str.S, NYC) if err != nil { return SexpNull, err } return &SexpTime{Tm: tm.In(NYC)}, nil }
go
func AsTmFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 1 { return SexpNull, WrongNargs } var str *SexpStr switch t := args[0].(type) { case *SexpStr: str = t default: return SexpNull, errors.New("argument of astm should be a string RFC3999Nano timestamp that we want to convert to time.Time") } tm, err := time.ParseInLocation(time.RFC3339Nano, str.S, NYC) if err != nil { return SexpNull, err } return &SexpTime{Tm: tm.In(NYC)}, nil }
[ "func", "AsTmFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "var", "str", "*", "SexpStr", "\n", "switch", "t", ":=", "args", "[", "0", "]", ".", "(", "type", ")", "{", "case", "*", "SexpStr", ":", "str", "=", "t", "\n", "default", ":", "return", "SexpNull", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "tm", ",", "err", ":=", "time", ".", "ParseInLocation", "(", "time", ".", "RFC3339Nano", ",", "str", ".", "S", ",", "NYC", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n", "return", "&", "SexpTime", "{", "Tm", ":", "tm", ".", "In", "(", "NYC", ")", "}", ",", "nil", "\n", "}" ]
// string -> time.Time
[ "string", "-", ">", "time", ".", "Time" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/time.go#L38-L59
8,995
glycerine/zygomys
zygo/source.go
SimpleSourceFunction
func SimpleSourceFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 1 { return SexpNull, WrongNargs } src, isStr := args[0].(*SexpStr) if !isStr { return SexpNull, fmt.Errorf("-> error: first argument must be a string") } file := src.S if !FileExists(file) { return SexpNull, fmt.Errorf("path '%s' does not exist", file) } env2 := env.Duplicate() f, err := os.Open(file) if err != nil { return SexpNull, err } defer f.Close() err = env2.LoadFile(f) if err != nil { return SexpNull, err } _, err = env2.Run() return SexpNull, err }
go
func SimpleSourceFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) { if len(args) != 1 { return SexpNull, WrongNargs } src, isStr := args[0].(*SexpStr) if !isStr { return SexpNull, fmt.Errorf("-> error: first argument must be a string") } file := src.S if !FileExists(file) { return SexpNull, fmt.Errorf("path '%s' does not exist", file) } env2 := env.Duplicate() f, err := os.Open(file) if err != nil { return SexpNull, err } defer f.Close() err = env2.LoadFile(f) if err != nil { return SexpNull, err } _, err = env2.Run() return SexpNull, err }
[ "func", "SimpleSourceFunction", "(", "env", "*", "Zlisp", ",", "name", "string", ",", "args", "[", "]", "Sexp", ")", "(", "Sexp", ",", "error", ")", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "return", "SexpNull", ",", "WrongNargs", "\n", "}", "\n\n", "src", ",", "isStr", ":=", "args", "[", "0", "]", ".", "(", "*", "SexpStr", ")", "\n", "if", "!", "isStr", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "file", ":=", "src", ".", "S", "\n", "if", "!", "FileExists", "(", "file", ")", "{", "return", "SexpNull", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "file", ")", "\n", "}", "\n\n", "env2", ":=", "env", ".", "Duplicate", "(", ")", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "err", "=", "env2", ".", "LoadFile", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SexpNull", ",", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "env2", ".", "Run", "(", ")", "\n\n", "return", "SexpNull", ",", "err", "\n", "}" ]
// alternative. simpler, currently panics.
[ "alternative", ".", "simpler", "currently", "panics", "." ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/source.go#L12-L43
8,996
glycerine/zygomys
zygo/source.go
SourceExpressions
func (env *Zlisp) SourceExpressions(expressions []Sexp) error { gen := NewGenerator(env) err := gen.GenerateBegin(expressions) if err != nil { return err } //P("debug: in SourceExpressions, FROM expressions='%s'", (&SexpArray{Val: expressions, Env: env}).SexpString(0)) //P("debug: in SourceExpressions, gen=") //DumpFunction(ZlispFunction(gen.instructions), -1) curfunc := env.curfunc curpc := env.pc env.curfunc = env.MakeFunction("__source", 0, false, gen.instructions, nil) env.pc = 0 result, err := env.Run() if err != nil { return err } //P("end of SourceExpressions, result going onto datastack is: '%s'", result.SexpString(0)) env.datastack.PushExpr(result) //P("debug done with Run in source, now stack is:") //env.datastack.PrintStack() env.pc = curpc env.curfunc = curfunc return nil }
go
func (env *Zlisp) SourceExpressions(expressions []Sexp) error { gen := NewGenerator(env) err := gen.GenerateBegin(expressions) if err != nil { return err } //P("debug: in SourceExpressions, FROM expressions='%s'", (&SexpArray{Val: expressions, Env: env}).SexpString(0)) //P("debug: in SourceExpressions, gen=") //DumpFunction(ZlispFunction(gen.instructions), -1) curfunc := env.curfunc curpc := env.pc env.curfunc = env.MakeFunction("__source", 0, false, gen.instructions, nil) env.pc = 0 result, err := env.Run() if err != nil { return err } //P("end of SourceExpressions, result going onto datastack is: '%s'", result.SexpString(0)) env.datastack.PushExpr(result) //P("debug done with Run in source, now stack is:") //env.datastack.PrintStack() env.pc = curpc env.curfunc = curfunc return nil }
[ "func", "(", "env", "*", "Zlisp", ")", "SourceExpressions", "(", "expressions", "[", "]", "Sexp", ")", "error", "{", "gen", ":=", "NewGenerator", "(", "env", ")", "\n\n", "err", ":=", "gen", ".", "GenerateBegin", "(", "expressions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "//P(\"debug: in SourceExpressions, FROM expressions='%s'\", (&SexpArray{Val: expressions, Env: env}).SexpString(0))", "//P(\"debug: in SourceExpressions, gen=\")", "//DumpFunction(ZlispFunction(gen.instructions), -1)", "curfunc", ":=", "env", ".", "curfunc", "\n", "curpc", ":=", "env", ".", "pc", "\n\n", "env", ".", "curfunc", "=", "env", ".", "MakeFunction", "(", "\"", "\"", ",", "0", ",", "false", ",", "gen", ".", "instructions", ",", "nil", ")", "\n", "env", ".", "pc", "=", "0", "\n\n", "result", ",", "err", ":=", "env", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "//P(\"end of SourceExpressions, result going onto datastack is: '%s'\", result.SexpString(0))", "env", ".", "datastack", ".", "PushExpr", "(", "result", ")", "\n\n", "//P(\"debug done with Run in source, now stack is:\")", "//env.datastack.PrintStack()", "env", ".", "pc", "=", "curpc", "\n", "env", ".", "curfunc", "=", "curfunc", "\n\n", "return", "nil", "\n", "}" ]
// existing // SourceExpressions, this should be called from a user func context
[ "existing", "SourceExpressions", "this", "should", "be", "called", "from", "a", "user", "func", "context" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/source.go#L48-L80
8,997
glycerine/zygomys
zygo/source.go
sourceItem
func (env *Zlisp) sourceItem(item Sexp) error { switch t := item.(type) { case *SexpArray: for _, v := range t.Val { if err := env.sourceItem(v); err != nil { return err } } case *SexpPair: expr := item for expr != SexpNull { list := expr.(*SexpPair) if err := env.sourceItem(list.Head); err != nil { return err } expr = list.Tail } case *SexpStr: var f *os.File var err error if f, err = os.Open(t.S); err != nil { return err } defer f.Close() if err = env.SourceFile(f); err != nil { return err } default: return fmt.Errorf("source: Expected `string`, `list`, `array`. Instead found type %T val %v", item, item) } return nil }
go
func (env *Zlisp) sourceItem(item Sexp) error { switch t := item.(type) { case *SexpArray: for _, v := range t.Val { if err := env.sourceItem(v); err != nil { return err } } case *SexpPair: expr := item for expr != SexpNull { list := expr.(*SexpPair) if err := env.sourceItem(list.Head); err != nil { return err } expr = list.Tail } case *SexpStr: var f *os.File var err error if f, err = os.Open(t.S); err != nil { return err } defer f.Close() if err = env.SourceFile(f); err != nil { return err } default: return fmt.Errorf("source: Expected `string`, `list`, `array`. Instead found type %T val %v", item, item) } return nil }
[ "func", "(", "env", "*", "Zlisp", ")", "sourceItem", "(", "item", "Sexp", ")", "error", "{", "switch", "t", ":=", "item", ".", "(", "type", ")", "{", "case", "*", "SexpArray", ":", "for", "_", ",", "v", ":=", "range", "t", ".", "Val", "{", "if", "err", ":=", "env", ".", "sourceItem", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "case", "*", "SexpPair", ":", "expr", ":=", "item", "\n", "for", "expr", "!=", "SexpNull", "{", "list", ":=", "expr", ".", "(", "*", "SexpPair", ")", "\n", "if", "err", ":=", "env", ".", "sourceItem", "(", "list", ".", "Head", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "expr", "=", "list", ".", "Tail", "\n", "}", "\n", "case", "*", "SexpStr", ":", "var", "f", "*", "os", ".", "File", "\n", "var", "err", "error", "\n\n", "if", "f", ",", "err", "=", "os", ".", "Open", "(", "t", ".", "S", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "if", "err", "=", "env", ".", "SourceFile", "(", "f", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "item", ",", "item", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// helper for SourceFileFunction recursion
[ "helper", "for", "SourceFileFunction", "recursion" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/source.go#L116-L150
8,998
glycerine/zygomys
zygo/builders.go
SexpString
func (p *RecordDefn) SexpString(ps *PrintState) string { Q("RecordDefn::SexpString() called!") if len(p.Fields) == 0 { return fmt.Sprintf("(struct %s)", p.Name) } s := fmt.Sprintf("(struct %s [\n", p.Name) w := make([][]int, len(p.Fields)) maxnfield := 0 for i, f := range p.Fields { w[i] = f.FieldWidths() Q("w[i=%v] = %v", i, w[i]) maxnfield = maxi(maxnfield, len(w[i])) } biggestCol := make([]int, maxnfield) Q("\n") for j := 0; j < maxnfield; j++ { for i := range p.Fields { Q("i= %v, j=%v, len(w[i])=%v check=%v", i, j, len(w[i]), len(w[i]) < j) if j < len(w[i]) { biggestCol[j] = maxi(biggestCol[j], w[i][j]+1) } } } Q("RecordDefn::SexpString(): maxnfield = %v, out of %v", maxnfield, len(p.Fields)) Q("RecordDefn::SexpString(): biggestCol = %#v", biggestCol) // computing padding // x // xx xx // xxxxxxx x // xxx x x x // // becomes // // x // xx xx // xxxxxxx // xxx x x x Q("pad = %#v", biggestCol) for _, f := range p.Fields { s += " " + f.AlignString(biggestCol) + "\n" } s += " ])\n" return s }
go
func (p *RecordDefn) SexpString(ps *PrintState) string { Q("RecordDefn::SexpString() called!") if len(p.Fields) == 0 { return fmt.Sprintf("(struct %s)", p.Name) } s := fmt.Sprintf("(struct %s [\n", p.Name) w := make([][]int, len(p.Fields)) maxnfield := 0 for i, f := range p.Fields { w[i] = f.FieldWidths() Q("w[i=%v] = %v", i, w[i]) maxnfield = maxi(maxnfield, len(w[i])) } biggestCol := make([]int, maxnfield) Q("\n") for j := 0; j < maxnfield; j++ { for i := range p.Fields { Q("i= %v, j=%v, len(w[i])=%v check=%v", i, j, len(w[i]), len(w[i]) < j) if j < len(w[i]) { biggestCol[j] = maxi(biggestCol[j], w[i][j]+1) } } } Q("RecordDefn::SexpString(): maxnfield = %v, out of %v", maxnfield, len(p.Fields)) Q("RecordDefn::SexpString(): biggestCol = %#v", biggestCol) // computing padding // x // xx xx // xxxxxxx x // xxx x x x // // becomes // // x // xx xx // xxxxxxx // xxx x x x Q("pad = %#v", biggestCol) for _, f := range p.Fields { s += " " + f.AlignString(biggestCol) + "\n" } s += " ])\n" return s }
[ "func", "(", "p", "*", "RecordDefn", ")", "SexpString", "(", "ps", "*", "PrintState", ")", "string", "{", "Q", "(", "\"", "\"", ")", "\n", "if", "len", "(", "p", ".", "Fields", ")", "==", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "Name", ")", "\n", "}", "\n", "s", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "p", ".", "Name", ")", "\n\n", "w", ":=", "make", "(", "[", "]", "[", "]", "int", ",", "len", "(", "p", ".", "Fields", ")", ")", "\n", "maxnfield", ":=", "0", "\n", "for", "i", ",", "f", ":=", "range", "p", ".", "Fields", "{", "w", "[", "i", "]", "=", "f", ".", "FieldWidths", "(", ")", "\n", "Q", "(", "\"", "\"", ",", "i", ",", "w", "[", "i", "]", ")", "\n", "maxnfield", "=", "maxi", "(", "maxnfield", ",", "len", "(", "w", "[", "i", "]", ")", ")", "\n", "}", "\n\n", "biggestCol", ":=", "make", "(", "[", "]", "int", ",", "maxnfield", ")", "\n", "Q", "(", "\"", "\\n", "\"", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "maxnfield", ";", "j", "++", "{", "for", "i", ":=", "range", "p", ".", "Fields", "{", "Q", "(", "\"", "\"", ",", "i", ",", "j", ",", "len", "(", "w", "[", "i", "]", ")", ",", "len", "(", "w", "[", "i", "]", ")", "<", "j", ")", "\n", "if", "j", "<", "len", "(", "w", "[", "i", "]", ")", "{", "biggestCol", "[", "j", "]", "=", "maxi", "(", "biggestCol", "[", "j", "]", ",", "w", "[", "i", "]", "[", "j", "]", "+", "1", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "Q", "(", "\"", "\"", ",", "maxnfield", ",", "len", "(", "p", ".", "Fields", ")", ")", "\n", "Q", "(", "\"", "\"", ",", "biggestCol", ")", "\n\n", "// computing padding", "// x", "// xx xx", "// xxxxxxx x", "// xxx x x x", "//", "// becomes", "//", "// x", "// xx xx", "// xxxxxxx", "// xxx x x x", "Q", "(", "\"", "\"", ",", "biggestCol", ")", "\n", "for", "_", ",", "f", ":=", "range", "p", ".", "Fields", "{", "s", "+=", "\"", "\"", "+", "f", ".", "AlignString", "(", "biggestCol", ")", "+", "\"", "\\n", "\"", "\n", "}", "\n", "s", "+=", "\"", "\\n", "\"", "\n", "return", "s", "\n", "}" ]
// pretty print a struct
[ "pretty", "print", "a", "struct" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/builders.go#L90-L136
8,999
glycerine/zygomys
zygo/builders.go
FieldWidths
func (f *SexpField) FieldWidths() []int { hash := (*SexpHash)(f) wide := []int{} for _, key := range hash.KeyOrder { val, err := hash.HashGet(nil, key) str := "" if err == nil { switch s := key.(type) { case *SexpStr: str += s.S + ":" case *SexpSymbol: str += s.name + ":" default: str += key.SexpString(nil) + ":" } wide = append(wide, len(str)) wide = append(wide, len(val.SexpString(nil))+1) } else { panic(err) } } return wide }
go
func (f *SexpField) FieldWidths() []int { hash := (*SexpHash)(f) wide := []int{} for _, key := range hash.KeyOrder { val, err := hash.HashGet(nil, key) str := "" if err == nil { switch s := key.(type) { case *SexpStr: str += s.S + ":" case *SexpSymbol: str += s.name + ":" default: str += key.SexpString(nil) + ":" } wide = append(wide, len(str)) wide = append(wide, len(val.SexpString(nil))+1) } else { panic(err) } } return wide }
[ "func", "(", "f", "*", "SexpField", ")", "FieldWidths", "(", ")", "[", "]", "int", "{", "hash", ":=", "(", "*", "SexpHash", ")", "(", "f", ")", "\n", "wide", ":=", "[", "]", "int", "{", "}", "\n", "for", "_", ",", "key", ":=", "range", "hash", ".", "KeyOrder", "{", "val", ",", "err", ":=", "hash", ".", "HashGet", "(", "nil", ",", "key", ")", "\n", "str", ":=", "\"", "\"", "\n", "if", "err", "==", "nil", "{", "switch", "s", ":=", "key", ".", "(", "type", ")", "{", "case", "*", "SexpStr", ":", "str", "+=", "s", ".", "S", "+", "\"", "\"", "\n", "case", "*", "SexpSymbol", ":", "str", "+=", "s", ".", "name", "+", "\"", "\"", "\n", "default", ":", "str", "+=", "key", ".", "SexpString", "(", "nil", ")", "+", "\"", "\"", "\n", "}", "\n", "wide", "=", "append", "(", "wide", ",", "len", "(", "str", ")", ")", "\n", "wide", "=", "append", "(", "wide", ",", "len", "(", "val", ".", "SexpString", "(", "nil", ")", ")", "+", "1", ")", "\n", "}", "else", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "wide", "\n", "}" ]
// compute key and value widths to assist alignment
[ "compute", "key", "and", "value", "widths", "to", "assist", "alignment" ]
36f1c7120ff2d831cebbb6f059ddc948273a8b56
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/builders.go#L152-L174