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
7,500
aporeto-inc/trireme-lib
policy/policy.go
SetIPAddresses
func (p *PUPolicy) SetIPAddresses(l ExtendedMap) { p.Lock() defer p.Unlock() p.ips = l }
go
func (p *PUPolicy) SetIPAddresses(l ExtendedMap) { p.Lock() defer p.Unlock() p.ips = l }
[ "func", "(", "p", "*", "PUPolicy", ")", "SetIPAddresses", "(", "l", "ExtendedMap", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "p", ".", "ips", "=", "l", "\n", "}" ]
// SetIPAddresses sets the IP addresses for the processing unit
[ "SetIPAddresses", "sets", "the", "IP", "addresses", "for", "the", "processing", "unit" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L283-L288
7,501
aporeto-inc/trireme-lib
policy/policy.go
ExposedServices
func (p *PUPolicy) ExposedServices() ApplicationServicesList { p.Lock() defer p.Unlock() return p.exposedServices }
go
func (p *PUPolicy) ExposedServices() ApplicationServicesList { p.Lock() defer p.Unlock() return p.exposedServices }
[ "func", "(", "p", "*", "PUPolicy", ")", "ExposedServices", "(", ")", "ApplicationServicesList", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "return", "p", ".", "exposedServices", "\n", "}" ]
// ExposedServices returns the exposed services
[ "ExposedServices", "returns", "the", "exposed", "services" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L291-L296
7,502
aporeto-inc/trireme-lib
policy/policy.go
DependentServices
func (p *PUPolicy) DependentServices() ApplicationServicesList { p.Lock() defer p.Unlock() return p.dependentServices }
go
func (p *PUPolicy) DependentServices() ApplicationServicesList { p.Lock() defer p.Unlock() return p.dependentServices }
[ "func", "(", "p", "*", "PUPolicy", ")", "DependentServices", "(", ")", "ApplicationServicesList", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "return", "p", ".", "dependentServices", "\n", "}" ]
// DependentServices returns the external services.
[ "DependentServices", "returns", "the", "external", "services", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L299-L304
7,503
aporeto-inc/trireme-lib
policy/policy.go
ServicesListeningPort
func (p *PUPolicy) ServicesListeningPort() string { p.Lock() defer p.Unlock() return strconv.Itoa(p.servicesListeningPort) }
go
func (p *PUPolicy) ServicesListeningPort() string { p.Lock() defer p.Unlock() return strconv.Itoa(p.servicesListeningPort) }
[ "func", "(", "p", "*", "PUPolicy", ")", "ServicesListeningPort", "(", ")", "string", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "return", "strconv", ".", "Itoa", "(", "p", ".", "servicesListeningPort", ")", "\n", "}" ]
// ServicesListeningPort returns the port that should be used by the proxies.
[ "ServicesListeningPort", "returns", "the", "port", "that", "should", "be", "used", "by", "the", "proxies", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L307-L312
7,504
aporeto-inc/trireme-lib
policy/policy.go
UpdateDNSNetworks
func (p *PUPolicy) UpdateDNSNetworks(networks DNSRuleList) { p.Lock() defer p.Unlock() p.DNSACLs = make(DNSRuleList, len(networks)) copy(p.DNSACLs, networks) }
go
func (p *PUPolicy) UpdateDNSNetworks(networks DNSRuleList) { p.Lock() defer p.Unlock() p.DNSACLs = make(DNSRuleList, len(networks)) copy(p.DNSACLs, networks) }
[ "func", "(", "p", "*", "PUPolicy", ")", "UpdateDNSNetworks", "(", "networks", "DNSRuleList", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "p", ".", "DNSACLs", "=", "make", "(", "DNSRuleList", ",", "len", "(", "networks", ")", ")", "\n\n", "copy", "(", "p", ".", "DNSACLs", ",", "networks", ")", "\n", "}" ]
// UpdateDNSNetworks updates the set of FQDN names allowed by the policy
[ "UpdateDNSNetworks", "updates", "the", "set", "of", "FQDN", "names", "allowed", "by", "the", "policy" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L315-L322
7,505
aporeto-inc/trireme-lib
policy/policy.go
UpdateServiceCertificates
func (p *PUPolicy) UpdateServiceCertificates(cert, key string) { p.Lock() defer p.Unlock() p.servicesCertificate = cert p.servicesPrivateKey = key }
go
func (p *PUPolicy) UpdateServiceCertificates(cert, key string) { p.Lock() defer p.Unlock() p.servicesCertificate = cert p.servicesPrivateKey = key }
[ "func", "(", "p", "*", "PUPolicy", ")", "UpdateServiceCertificates", "(", "cert", ",", "key", "string", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "p", ".", "servicesCertificate", "=", "cert", "\n", "p", ".", "servicesPrivateKey", "=", "key", "\n", "}" ]
// UpdateServiceCertificates updates the certificate and private key of the policy
[ "UpdateServiceCertificates", "updates", "the", "certificate", "and", "private", "key", "of", "the", "policy" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L325-L331
7,506
aporeto-inc/trireme-lib
policy/policy.go
ServiceCertificates
func (p *PUPolicy) ServiceCertificates() (string, string, string) { p.Lock() defer p.Unlock() return p.servicesCertificate, p.servicesPrivateKey, p.servicesCA }
go
func (p *PUPolicy) ServiceCertificates() (string, string, string) { p.Lock() defer p.Unlock() return p.servicesCertificate, p.servicesPrivateKey, p.servicesCA }
[ "func", "(", "p", "*", "PUPolicy", ")", "ServiceCertificates", "(", ")", "(", "string", ",", "string", ",", "string", ")", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "return", "p", ".", "servicesCertificate", ",", "p", ".", "servicesPrivateKey", ",", "p", ".", "servicesCA", "\n", "}" ]
// ServiceCertificates returns the service certificate.
[ "ServiceCertificates", "returns", "the", "service", "certificate", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L334-L339
7,507
aporeto-inc/trireme-lib
policy/policy.go
Scopes
func (p *PUPolicy) Scopes() []string { p.Lock() defer p.Unlock() return p.scopes }
go
func (p *PUPolicy) Scopes() []string { p.Lock() defer p.Unlock() return p.scopes }
[ "func", "(", "p", "*", "PUPolicy", ")", "Scopes", "(", ")", "[", "]", "string", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "return", "p", ".", "scopes", "\n", "}" ]
// Scopes returns the scopes of the policy.
[ "Scopes", "returns", "the", "scopes", "of", "the", "policy", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L342-L347
7,508
aporeto-inc/trireme-lib
policy/policy.go
ToPublicPolicy
func (p *PUPolicy) ToPublicPolicy() *PUPolicyPublic { p.Lock() defer p.Unlock() return &PUPolicyPublic{ ManagementID: p.managementID, TriremeAction: p.triremeAction, ApplicationACLs: p.applicationACLs.Copy(), NetworkACLs: p.networkACLs.Copy(), DNSACLs: p.DNSACLs.Copy(), TransmitterRules: p.transmitterRules.Copy(), ReceiverRules: p.receiverRules.Copy(), Annotations: p.annotations.Copy(), Identity: p.identity.Copy(), IPs: p.ips.Copy(), ServicesListeningPort: p.servicesListeningPort, ExposedServices: p.exposedServices, DependentServices: p.dependentServices, Scopes: p.scopes, ServicesCA: p.servicesCA, ServicesCertificate: p.servicesCertificate, ServicesPrivateKey: p.servicesPrivateKey, } }
go
func (p *PUPolicy) ToPublicPolicy() *PUPolicyPublic { p.Lock() defer p.Unlock() return &PUPolicyPublic{ ManagementID: p.managementID, TriremeAction: p.triremeAction, ApplicationACLs: p.applicationACLs.Copy(), NetworkACLs: p.networkACLs.Copy(), DNSACLs: p.DNSACLs.Copy(), TransmitterRules: p.transmitterRules.Copy(), ReceiverRules: p.receiverRules.Copy(), Annotations: p.annotations.Copy(), Identity: p.identity.Copy(), IPs: p.ips.Copy(), ServicesListeningPort: p.servicesListeningPort, ExposedServices: p.exposedServices, DependentServices: p.dependentServices, Scopes: p.scopes, ServicesCA: p.servicesCA, ServicesCertificate: p.servicesCertificate, ServicesPrivateKey: p.servicesPrivateKey, } }
[ "func", "(", "p", "*", "PUPolicy", ")", "ToPublicPolicy", "(", ")", "*", "PUPolicyPublic", "{", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n\n", "return", "&", "PUPolicyPublic", "{", "ManagementID", ":", "p", ".", "managementID", ",", "TriremeAction", ":", "p", ".", "triremeAction", ",", "ApplicationACLs", ":", "p", ".", "applicationACLs", ".", "Copy", "(", ")", ",", "NetworkACLs", ":", "p", ".", "networkACLs", ".", "Copy", "(", ")", ",", "DNSACLs", ":", "p", ".", "DNSACLs", ".", "Copy", "(", ")", ",", "TransmitterRules", ":", "p", ".", "transmitterRules", ".", "Copy", "(", ")", ",", "ReceiverRules", ":", "p", ".", "receiverRules", ".", "Copy", "(", ")", ",", "Annotations", ":", "p", ".", "annotations", ".", "Copy", "(", ")", ",", "Identity", ":", "p", ".", "identity", ".", "Copy", "(", ")", ",", "IPs", ":", "p", ".", "ips", ".", "Copy", "(", ")", ",", "ServicesListeningPort", ":", "p", ".", "servicesListeningPort", ",", "ExposedServices", ":", "p", ".", "exposedServices", ",", "DependentServices", ":", "p", ".", "dependentServices", ",", "Scopes", ":", "p", ".", "scopes", ",", "ServicesCA", ":", "p", ".", "servicesCA", ",", "ServicesCertificate", ":", "p", ".", "servicesCertificate", ",", "ServicesPrivateKey", ":", "p", ".", "servicesPrivateKey", ",", "}", "\n", "}" ]
// ToPublicPolicy converts the object to a marshallable object.
[ "ToPublicPolicy", "converts", "the", "object", "to", "a", "marshallable", "object", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L350-L373
7,509
aporeto-inc/trireme-lib
policy/policy.go
ToPrivatePolicy
func (p *PUPolicyPublic) ToPrivatePolicy(convert bool) (*PUPolicy, error) { var err error exposedServices := ApplicationServicesList{} for _, e := range p.ExposedServices { if convert { e.UserAuthorizationHandler, err = usertokens.NewVerifier(e.UserAuthorizationHandler) if err != nil { return nil, fmt.Errorf("unable to initialize user authorization handler for service: %s - error %s", e.ID, err) } } exposedServices = append(exposedServices, e) } return &PUPolicy{ managementID: p.ManagementID, triremeAction: p.TriremeAction, applicationACLs: p.ApplicationACLs, networkACLs: p.NetworkACLs.Copy(), DNSACLs: p.DNSACLs.Copy(), transmitterRules: p.TransmitterRules.Copy(), receiverRules: p.ReceiverRules.Copy(), annotations: p.Annotations.Copy(), identity: p.Identity.Copy(), ips: p.IPs.Copy(), servicesListeningPort: p.ServicesListeningPort, exposedServices: exposedServices, dependentServices: p.DependentServices, scopes: p.Scopes, servicesCA: p.ServicesCA, servicesCertificate: p.ServicesCertificate, servicesPrivateKey: p.ServicesPrivateKey, }, nil }
go
func (p *PUPolicyPublic) ToPrivatePolicy(convert bool) (*PUPolicy, error) { var err error exposedServices := ApplicationServicesList{} for _, e := range p.ExposedServices { if convert { e.UserAuthorizationHandler, err = usertokens.NewVerifier(e.UserAuthorizationHandler) if err != nil { return nil, fmt.Errorf("unable to initialize user authorization handler for service: %s - error %s", e.ID, err) } } exposedServices = append(exposedServices, e) } return &PUPolicy{ managementID: p.ManagementID, triremeAction: p.TriremeAction, applicationACLs: p.ApplicationACLs, networkACLs: p.NetworkACLs.Copy(), DNSACLs: p.DNSACLs.Copy(), transmitterRules: p.TransmitterRules.Copy(), receiverRules: p.ReceiverRules.Copy(), annotations: p.Annotations.Copy(), identity: p.Identity.Copy(), ips: p.IPs.Copy(), servicesListeningPort: p.ServicesListeningPort, exposedServices: exposedServices, dependentServices: p.DependentServices, scopes: p.Scopes, servicesCA: p.ServicesCA, servicesCertificate: p.ServicesCertificate, servicesPrivateKey: p.ServicesPrivateKey, }, nil }
[ "func", "(", "p", "*", "PUPolicyPublic", ")", "ToPrivatePolicy", "(", "convert", "bool", ")", "(", "*", "PUPolicy", ",", "error", ")", "{", "var", "err", "error", "\n\n", "exposedServices", ":=", "ApplicationServicesList", "{", "}", "\n", "for", "_", ",", "e", ":=", "range", "p", ".", "ExposedServices", "{", "if", "convert", "{", "e", ".", "UserAuthorizationHandler", ",", "err", "=", "usertokens", ".", "NewVerifier", "(", "e", ".", "UserAuthorizationHandler", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "e", ".", "ID", ",", "err", ")", "\n", "}", "\n", "}", "\n", "exposedServices", "=", "append", "(", "exposedServices", ",", "e", ")", "\n", "}", "\n\n", "return", "&", "PUPolicy", "{", "managementID", ":", "p", ".", "ManagementID", ",", "triremeAction", ":", "p", ".", "TriremeAction", ",", "applicationACLs", ":", "p", ".", "ApplicationACLs", ",", "networkACLs", ":", "p", ".", "NetworkACLs", ".", "Copy", "(", ")", ",", "DNSACLs", ":", "p", ".", "DNSACLs", ".", "Copy", "(", ")", ",", "transmitterRules", ":", "p", ".", "TransmitterRules", ".", "Copy", "(", ")", ",", "receiverRules", ":", "p", ".", "ReceiverRules", ".", "Copy", "(", ")", ",", "annotations", ":", "p", ".", "Annotations", ".", "Copy", "(", ")", ",", "identity", ":", "p", ".", "Identity", ".", "Copy", "(", ")", ",", "ips", ":", "p", ".", "IPs", ".", "Copy", "(", ")", ",", "servicesListeningPort", ":", "p", ".", "ServicesListeningPort", ",", "exposedServices", ":", "exposedServices", ",", "dependentServices", ":", "p", ".", "DependentServices", ",", "scopes", ":", "p", ".", "Scopes", ",", "servicesCA", ":", "p", ".", "ServicesCA", ",", "servicesCertificate", ":", "p", ".", "ServicesCertificate", ",", "servicesPrivateKey", ":", "p", ".", "ServicesPrivateKey", ",", "}", ",", "nil", "\n", "}" ]
// ToPrivatePolicy converts the object to a private object.
[ "ToPrivatePolicy", "converts", "the", "object", "to", "a", "private", "object", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/policy/policy.go#L398-L431
7,510
aporeto-inc/trireme-lib
controller/internal/enforcer/secretsproxy/transformer.go
NewGenericSecretsDriver
func NewGenericSecretsDriver(ca []byte, token string, network *common.Service) (SecretsDriver, error) { caPool := x509.NewCertPool() if !caPool.AppendCertsFromPEM(ca) { return nil, fmt.Errorf("No valid CA provided") } targetAddress := "" if len(network.FQDNs) > 0 { targetAddress = network.FQDNs[0] } else if len(network.Addresses) > 0 { targetAddress = network.Addresses[0].IP.String() } else { return nil, fmt.Errorf("No valid target") } if network.Ports.Min == 0 { return nil, fmt.Errorf("Invalid port specification") } targetURL, err := url.Parse("https://" + targetAddress + ":" + strconv.Itoa(int(network.Ports.Min))) if err != nil { return nil, fmt.Errorf("Invalid URL for secrets service") } return &GenericSecretsDriver{ transport: &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: caPool, }, }, token: token, targetURL: targetURL, }, nil }
go
func NewGenericSecretsDriver(ca []byte, token string, network *common.Service) (SecretsDriver, error) { caPool := x509.NewCertPool() if !caPool.AppendCertsFromPEM(ca) { return nil, fmt.Errorf("No valid CA provided") } targetAddress := "" if len(network.FQDNs) > 0 { targetAddress = network.FQDNs[0] } else if len(network.Addresses) > 0 { targetAddress = network.Addresses[0].IP.String() } else { return nil, fmt.Errorf("No valid target") } if network.Ports.Min == 0 { return nil, fmt.Errorf("Invalid port specification") } targetURL, err := url.Parse("https://" + targetAddress + ":" + strconv.Itoa(int(network.Ports.Min))) if err != nil { return nil, fmt.Errorf("Invalid URL for secrets service") } return &GenericSecretsDriver{ transport: &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: caPool, }, }, token: token, targetURL: targetURL, }, nil }
[ "func", "NewGenericSecretsDriver", "(", "ca", "[", "]", "byte", ",", "token", "string", ",", "network", "*", "common", ".", "Service", ")", "(", "SecretsDriver", ",", "error", ")", "{", "caPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "if", "!", "caPool", ".", "AppendCertsFromPEM", "(", "ca", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "targetAddress", ":=", "\"", "\"", "\n", "if", "len", "(", "network", ".", "FQDNs", ")", ">", "0", "{", "targetAddress", "=", "network", ".", "FQDNs", "[", "0", "]", "\n", "}", "else", "if", "len", "(", "network", ".", "Addresses", ")", ">", "0", "{", "targetAddress", "=", "network", ".", "Addresses", "[", "0", "]", ".", "IP", ".", "String", "(", ")", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "network", ".", "Ports", ".", "Min", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "targetURL", ",", "err", ":=", "url", ".", "Parse", "(", "\"", "\"", "+", "targetAddress", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "int", "(", "network", ".", "Ports", ".", "Min", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "GenericSecretsDriver", "{", "transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "RootCAs", ":", "caPool", ",", "}", ",", "}", ",", "token", ":", "token", ",", "targetURL", ":", "targetURL", ",", "}", ",", "nil", "\n", "}" ]
// NewGenericSecretsDriver creates a new Kubernetes Secrets Driver. It // always uses the incluster config to automatically derive all the // necessary values.
[ "NewGenericSecretsDriver", "creates", "a", "new", "Kubernetes", "Secrets", "Driver", ".", "It", "always", "uses", "the", "incluster", "config", "to", "automatically", "derive", "all", "the", "necessary", "values", "." ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/controller/internal/enforcer/secretsproxy/transformer.go#L31-L65
7,511
aporeto-inc/trireme-lib
controller/internal/enforcer/secretsproxy/transformer.go
Transform
func (k *GenericSecretsDriver) Transform(r *http.Request) error { r.Host = k.targetURL.Host r.URL = k.targetURL r.Header.Add("Authorization", "Bearer "+k.token) return nil }
go
func (k *GenericSecretsDriver) Transform(r *http.Request) error { r.Host = k.targetURL.Host r.URL = k.targetURL r.Header.Add("Authorization", "Bearer "+k.token) return nil }
[ "func", "(", "k", "*", "GenericSecretsDriver", ")", "Transform", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "r", ".", "Host", "=", "k", ".", "targetURL", ".", "Host", "\n", "r", ".", "URL", "=", "k", ".", "targetURL", "\n", "r", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", "+", "k", ".", "token", ")", "\n\n", "return", "nil", "\n", "}" ]
// Transform transforms the request of the SecretsDriver
[ "Transform", "transforms", "the", "request", "of", "the", "SecretsDriver" ]
009258cf9b4f3f70f71994d9fadebe564f7e0437
https://github.com/aporeto-inc/trireme-lib/blob/009258cf9b4f3f70f71994d9fadebe564f7e0437/controller/internal/enforcer/secretsproxy/transformer.go#L73-L80
7,512
mattn/anko
internal/corelib/corelib.go
ValueEqual
func ValueEqual(v1 interface{}, v2 interface{}) bool { v1RV := reflect.ValueOf(v1) switch v1RV.Kind() { case reflect.Func: // This is best effort to check if functions match, but it could be wrong v2RV := reflect.ValueOf(v2) if !v1RV.IsValid() || !v2RV.IsValid() { if v1RV.IsValid() != !v2RV.IsValid() { return false } return true } else if v1RV.Kind() != v2RV.Kind() { return false } else if v1RV.Type() != v2RV.Type() { return false } else if v1RV.Pointer() != v2RV.Pointer() { // From reflect: If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. return false } return true } switch value1 := v1.(type) { case error: switch value2 := v2.(type) { case error: return value1.Error() == value2.Error() } } return reflect.DeepEqual(v1, v2) }
go
func ValueEqual(v1 interface{}, v2 interface{}) bool { v1RV := reflect.ValueOf(v1) switch v1RV.Kind() { case reflect.Func: // This is best effort to check if functions match, but it could be wrong v2RV := reflect.ValueOf(v2) if !v1RV.IsValid() || !v2RV.IsValid() { if v1RV.IsValid() != !v2RV.IsValid() { return false } return true } else if v1RV.Kind() != v2RV.Kind() { return false } else if v1RV.Type() != v2RV.Type() { return false } else if v1RV.Pointer() != v2RV.Pointer() { // From reflect: If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. return false } return true } switch value1 := v1.(type) { case error: switch value2 := v2.(type) { case error: return value1.Error() == value2.Error() } } return reflect.DeepEqual(v1, v2) }
[ "func", "ValueEqual", "(", "v1", "interface", "{", "}", ",", "v2", "interface", "{", "}", ")", "bool", "{", "v1RV", ":=", "reflect", ".", "ValueOf", "(", "v1", ")", "\n", "switch", "v1RV", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Func", ":", "// This is best effort to check if functions match, but it could be wrong", "v2RV", ":=", "reflect", ".", "ValueOf", "(", "v2", ")", "\n", "if", "!", "v1RV", ".", "IsValid", "(", ")", "||", "!", "v2RV", ".", "IsValid", "(", ")", "{", "if", "v1RV", ".", "IsValid", "(", ")", "!=", "!", "v2RV", ".", "IsValid", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", "else", "if", "v1RV", ".", "Kind", "(", ")", "!=", "v2RV", ".", "Kind", "(", ")", "{", "return", "false", "\n", "}", "else", "if", "v1RV", ".", "Type", "(", ")", "!=", "v2RV", ".", "Type", "(", ")", "{", "return", "false", "\n", "}", "else", "if", "v1RV", ".", "Pointer", "(", ")", "!=", "v2RV", ".", "Pointer", "(", ")", "{", "// From reflect: If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely.", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "switch", "value1", ":=", "v1", ".", "(", "type", ")", "{", "case", "error", ":", "switch", "value2", ":=", "v2", ".", "(", "type", ")", "{", "case", "error", ":", "return", "value1", ".", "Error", "(", ")", "==", "value2", ".", "Error", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "reflect", ".", "DeepEqual", "(", "v1", ",", "v2", ")", "\n", "}" ]
// ValueEqual return true if v1 and v2 is same value. If passed function, does // extra checks otherwise just doing reflect.DeepEqual
[ "ValueEqual", "return", "true", "if", "v1", "and", "v2", "is", "same", "value", ".", "If", "passed", "function", "does", "extra", "checks", "otherwise", "just", "doing", "reflect", ".", "DeepEqual" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/internal/corelib/corelib.go#L22-L52
7,513
mattn/anko
vm/vmStmt.go
Run
func Run(stmt ast.Stmt, env *Env) (interface{}, error) { return RunContext(context.Background(), stmt, env) }
go
func Run(stmt ast.Stmt, env *Env) (interface{}, error) { return RunContext(context.Background(), stmt, env) }
[ "func", "Run", "(", "stmt", "ast", ".", "Stmt", ",", "env", "*", "Env", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "RunContext", "(", "context", ".", "Background", "(", ")", ",", "stmt", ",", "env", ")", "\n", "}" ]
// Run executes statement in the specified environment.
[ "Run", "executes", "statement", "in", "the", "specified", "environment", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmStmt.go#L12-L14
7,514
mattn/anko
vm/vmStmt.go
RunContext
func RunContext(ctx context.Context, stmt ast.Stmt, env *Env) (interface{}, error) { runInfo := runInfoStruct{ctx: ctx, env: env, stmt: stmt, rv: nilValue} runInfo.runSingleStmt() if runInfo.err == ErrReturn { runInfo.err = nil } return runInfo.rv.Interface(), runInfo.err }
go
func RunContext(ctx context.Context, stmt ast.Stmt, env *Env) (interface{}, error) { runInfo := runInfoStruct{ctx: ctx, env: env, stmt: stmt, rv: nilValue} runInfo.runSingleStmt() if runInfo.err == ErrReturn { runInfo.err = nil } return runInfo.rv.Interface(), runInfo.err }
[ "func", "RunContext", "(", "ctx", "context", ".", "Context", ",", "stmt", "ast", ".", "Stmt", ",", "env", "*", "Env", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "runInfo", ":=", "runInfoStruct", "{", "ctx", ":", "ctx", ",", "env", ":", "env", ",", "stmt", ":", "stmt", ",", "rv", ":", "nilValue", "}", "\n", "runInfo", ".", "runSingleStmt", "(", ")", "\n", "if", "runInfo", ".", "err", "==", "ErrReturn", "{", "runInfo", ".", "err", "=", "nil", "\n", "}", "\n", "return", "runInfo", ".", "rv", ".", "Interface", "(", ")", ",", "runInfo", ".", "err", "\n", "}" ]
// RunContext executes statement in the specified environment with context.
[ "RunContext", "executes", "statement", "in", "the", "specified", "environment", "with", "context", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmStmt.go#L17-L24
7,515
mattn/anko
vm/vm.go
newError
func newError(pos ast.Pos, err error) error { if err == nil { return nil } if pos == nil { return &Error{Message: err.Error(), Pos: ast.Position{Line: 1, Column: 1}} } return &Error{Message: err.Error(), Pos: pos.Position()} }
go
func newError(pos ast.Pos, err error) error { if err == nil { return nil } if pos == nil { return &Error{Message: err.Error(), Pos: ast.Position{Line: 1, Column: 1}} } return &Error{Message: err.Error(), Pos: pos.Position()} }
[ "func", "newError", "(", "pos", "ast", ".", "Pos", ",", "err", "error", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "pos", "==", "nil", "{", "return", "&", "Error", "{", "Message", ":", "err", ".", "Error", "(", ")", ",", "Pos", ":", "ast", ".", "Position", "{", "Line", ":", "1", ",", "Column", ":", "1", "}", "}", "\n", "}", "\n", "return", "&", "Error", "{", "Message", ":", "err", ".", "Error", "(", ")", ",", "Pos", ":", "pos", ".", "Position", "(", ")", "}", "\n", "}" ]
// newError makes VM error from error
[ "newError", "makes", "VM", "error", "from", "error" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vm.go#L69-L77
7,516
mattn/anko
vm/vm.go
newStringError
func newStringError(pos ast.Pos, err string) error { if err == "" { return nil } if pos == nil { return &Error{Message: err, Pos: ast.Position{Line: 1, Column: 1}} } return &Error{Message: err, Pos: pos.Position()} }
go
func newStringError(pos ast.Pos, err string) error { if err == "" { return nil } if pos == nil { return &Error{Message: err, Pos: ast.Position{Line: 1, Column: 1}} } return &Error{Message: err, Pos: pos.Position()} }
[ "func", "newStringError", "(", "pos", "ast", ".", "Pos", ",", "err", "string", ")", "error", "{", "if", "err", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "if", "pos", "==", "nil", "{", "return", "&", "Error", "{", "Message", ":", "err", ",", "Pos", ":", "ast", ".", "Position", "{", "Line", ":", "1", ",", "Column", ":", "1", "}", "}", "\n", "}", "\n", "return", "&", "Error", "{", "Message", ":", "err", ",", "Pos", ":", "pos", ".", "Position", "(", ")", "}", "\n", "}" ]
// newStringError makes VM error from string
[ "newStringError", "makes", "VM", "error", "from", "string" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vm.go#L80-L88
7,517
mattn/anko
vm/vm.go
equal
func equal(lhsV, rhsV reflect.Value) bool { lhsIsNil, rhsIsNil := isNil(lhsV), isNil(rhsV) if lhsIsNil && rhsIsNil { return true } if (!lhsIsNil && rhsIsNil) || (lhsIsNil && !rhsIsNil) { return false } if lhsV.Kind() == reflect.Interface || lhsV.Kind() == reflect.Ptr { lhsV = lhsV.Elem() } if rhsV.Kind() == reflect.Interface || rhsV.Kind() == reflect.Ptr { rhsV = rhsV.Elem() } // Compare a string and a number. // This will attempt to convert the string to a number, // while leaving the other side alone. Code further // down takes care of converting ints and floats as needed. if isNum(lhsV) && rhsV.Kind() == reflect.String { rhsF, err := tryToFloat64(rhsV) if err != nil { // Couldn't convert RHS to a float, they can't be compared. return false } rhsV = reflect.ValueOf(rhsF) } else if lhsV.Kind() == reflect.String && isNum(rhsV) { // If the LHS is a string formatted as an int, try that before trying float lhsI, err := tryToInt64(lhsV) if err != nil { // if LHS is a float, e.g. "1.2", we need to set lhsV to a float64 lhsF, err := tryToFloat64(lhsV) if err != nil { return false } lhsV = reflect.ValueOf(lhsF) } else { lhsV = reflect.ValueOf(lhsI) } } if isNum(lhsV) && isNum(rhsV) { return fmt.Sprintf("%v", lhsV) == fmt.Sprintf("%v", rhsV) } // Try to compare bools to strings and numbers if lhsV.Kind() == reflect.Bool || rhsV.Kind() == reflect.Bool { lhsB, err := tryToBool(lhsV) if err != nil { return false } rhsB, err := tryToBool(rhsV) if err != nil { return false } return lhsB == rhsB } return reflect.DeepEqual(lhsV.Interface(), rhsV.Interface()) }
go
func equal(lhsV, rhsV reflect.Value) bool { lhsIsNil, rhsIsNil := isNil(lhsV), isNil(rhsV) if lhsIsNil && rhsIsNil { return true } if (!lhsIsNil && rhsIsNil) || (lhsIsNil && !rhsIsNil) { return false } if lhsV.Kind() == reflect.Interface || lhsV.Kind() == reflect.Ptr { lhsV = lhsV.Elem() } if rhsV.Kind() == reflect.Interface || rhsV.Kind() == reflect.Ptr { rhsV = rhsV.Elem() } // Compare a string and a number. // This will attempt to convert the string to a number, // while leaving the other side alone. Code further // down takes care of converting ints and floats as needed. if isNum(lhsV) && rhsV.Kind() == reflect.String { rhsF, err := tryToFloat64(rhsV) if err != nil { // Couldn't convert RHS to a float, they can't be compared. return false } rhsV = reflect.ValueOf(rhsF) } else if lhsV.Kind() == reflect.String && isNum(rhsV) { // If the LHS is a string formatted as an int, try that before trying float lhsI, err := tryToInt64(lhsV) if err != nil { // if LHS is a float, e.g. "1.2", we need to set lhsV to a float64 lhsF, err := tryToFloat64(lhsV) if err != nil { return false } lhsV = reflect.ValueOf(lhsF) } else { lhsV = reflect.ValueOf(lhsI) } } if isNum(lhsV) && isNum(rhsV) { return fmt.Sprintf("%v", lhsV) == fmt.Sprintf("%v", rhsV) } // Try to compare bools to strings and numbers if lhsV.Kind() == reflect.Bool || rhsV.Kind() == reflect.Bool { lhsB, err := tryToBool(lhsV) if err != nil { return false } rhsB, err := tryToBool(rhsV) if err != nil { return false } return lhsB == rhsB } return reflect.DeepEqual(lhsV.Interface(), rhsV.Interface()) }
[ "func", "equal", "(", "lhsV", ",", "rhsV", "reflect", ".", "Value", ")", "bool", "{", "lhsIsNil", ",", "rhsIsNil", ":=", "isNil", "(", "lhsV", ")", ",", "isNil", "(", "rhsV", ")", "\n", "if", "lhsIsNil", "&&", "rhsIsNil", "{", "return", "true", "\n", "}", "\n", "if", "(", "!", "lhsIsNil", "&&", "rhsIsNil", ")", "||", "(", "lhsIsNil", "&&", "!", "rhsIsNil", ")", "{", "return", "false", "\n", "}", "\n", "if", "lhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "||", "lhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "lhsV", "=", "lhsV", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "rhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "||", "rhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "rhsV", "=", "rhsV", ".", "Elem", "(", ")", "\n", "}", "\n\n", "// Compare a string and a number.", "// This will attempt to convert the string to a number,", "// while leaving the other side alone. Code further", "// down takes care of converting ints and floats as needed.", "if", "isNum", "(", "lhsV", ")", "&&", "rhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "String", "{", "rhsF", ",", "err", ":=", "tryToFloat64", "(", "rhsV", ")", "\n", "if", "err", "!=", "nil", "{", "// Couldn't convert RHS to a float, they can't be compared.", "return", "false", "\n", "}", "\n", "rhsV", "=", "reflect", ".", "ValueOf", "(", "rhsF", ")", "\n", "}", "else", "if", "lhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "String", "&&", "isNum", "(", "rhsV", ")", "{", "// If the LHS is a string formatted as an int, try that before trying float", "lhsI", ",", "err", ":=", "tryToInt64", "(", "lhsV", ")", "\n", "if", "err", "!=", "nil", "{", "// if LHS is a float, e.g. \"1.2\", we need to set lhsV to a float64", "lhsF", ",", "err", ":=", "tryToFloat64", "(", "lhsV", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "lhsV", "=", "reflect", ".", "ValueOf", "(", "lhsF", ")", "\n", "}", "else", "{", "lhsV", "=", "reflect", ".", "ValueOf", "(", "lhsI", ")", "\n", "}", "\n", "}", "\n\n", "if", "isNum", "(", "lhsV", ")", "&&", "isNum", "(", "rhsV", ")", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lhsV", ")", "==", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rhsV", ")", "\n", "}", "\n\n", "// Try to compare bools to strings and numbers", "if", "lhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "Bool", "||", "rhsV", ".", "Kind", "(", ")", "==", "reflect", ".", "Bool", "{", "lhsB", ",", "err", ":=", "tryToBool", "(", "lhsV", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "rhsB", ",", "err", ":=", "tryToBool", "(", "rhsV", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "lhsB", "==", "rhsB", "\n", "}", "\n\n", "return", "reflect", ".", "DeepEqual", "(", "lhsV", ".", "Interface", "(", ")", ",", "rhsV", ".", "Interface", "(", ")", ")", "\n", "}" ]
// equal returns true when lhsV and rhsV is same value.
[ "equal", "returns", "true", "when", "lhsV", "and", "rhsV", "is", "same", "value", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vm.go#L114-L173
7,518
mattn/anko
vm/vm.go
appendSlice
func appendSlice(expr ast.Expr, lhsV reflect.Value, rhsV reflect.Value) (reflect.Value, error) { lhsT := lhsV.Type().Elem() rhsT := rhsV.Type().Elem() if lhsT == rhsT { return reflect.AppendSlice(lhsV, rhsV), nil } if rhsT.ConvertibleTo(lhsT) { for i := 0; i < rhsV.Len(); i++ { lhsV = reflect.Append(lhsV, rhsV.Index(i).Convert(lhsT)) } return lhsV, nil } leftHasSubArray := lhsT.Kind() == reflect.Slice || lhsT.Kind() == reflect.Array rightHasSubArray := rhsT.Kind() == reflect.Slice || rhsT.Kind() == reflect.Array if leftHasSubArray != rightHasSubArray && lhsT != interfaceType && rhsT != interfaceType { return nilValue, newStringError(expr, "invalid type conversion") } if !leftHasSubArray && !rightHasSubArray { for i := 0; i < rhsV.Len(); i++ { value := rhsV.Index(i) if rhsT == interfaceType { value = value.Elem() } if lhsT == value.Type() { lhsV = reflect.Append(lhsV, value) } else if value.Type().ConvertibleTo(lhsT) { lhsV = reflect.Append(lhsV, value.Convert(lhsT)) } else { return nilValue, newStringError(expr, "invalid type conversion") } } return lhsV, nil } if (leftHasSubArray || lhsT == interfaceType) && (rightHasSubArray || rhsT == interfaceType) { for i := 0; i < rhsV.Len(); i++ { value := rhsV.Index(i) if rhsT == interfaceType { value = value.Elem() if value.Kind() != reflect.Slice && value.Kind() != reflect.Array { return nilValue, newStringError(expr, "invalid type conversion") } } newSlice, err := appendSlice(expr, reflect.MakeSlice(lhsT, 0, value.Len()), value) if err != nil { return nilValue, err } lhsV = reflect.Append(lhsV, newSlice) } return lhsV, nil } return nilValue, newStringError(expr, "invalid type conversion") }
go
func appendSlice(expr ast.Expr, lhsV reflect.Value, rhsV reflect.Value) (reflect.Value, error) { lhsT := lhsV.Type().Elem() rhsT := rhsV.Type().Elem() if lhsT == rhsT { return reflect.AppendSlice(lhsV, rhsV), nil } if rhsT.ConvertibleTo(lhsT) { for i := 0; i < rhsV.Len(); i++ { lhsV = reflect.Append(lhsV, rhsV.Index(i).Convert(lhsT)) } return lhsV, nil } leftHasSubArray := lhsT.Kind() == reflect.Slice || lhsT.Kind() == reflect.Array rightHasSubArray := rhsT.Kind() == reflect.Slice || rhsT.Kind() == reflect.Array if leftHasSubArray != rightHasSubArray && lhsT != interfaceType && rhsT != interfaceType { return nilValue, newStringError(expr, "invalid type conversion") } if !leftHasSubArray && !rightHasSubArray { for i := 0; i < rhsV.Len(); i++ { value := rhsV.Index(i) if rhsT == interfaceType { value = value.Elem() } if lhsT == value.Type() { lhsV = reflect.Append(lhsV, value) } else if value.Type().ConvertibleTo(lhsT) { lhsV = reflect.Append(lhsV, value.Convert(lhsT)) } else { return nilValue, newStringError(expr, "invalid type conversion") } } return lhsV, nil } if (leftHasSubArray || lhsT == interfaceType) && (rightHasSubArray || rhsT == interfaceType) { for i := 0; i < rhsV.Len(); i++ { value := rhsV.Index(i) if rhsT == interfaceType { value = value.Elem() if value.Kind() != reflect.Slice && value.Kind() != reflect.Array { return nilValue, newStringError(expr, "invalid type conversion") } } newSlice, err := appendSlice(expr, reflect.MakeSlice(lhsT, 0, value.Len()), value) if err != nil { return nilValue, err } lhsV = reflect.Append(lhsV, newSlice) } return lhsV, nil } return nilValue, newStringError(expr, "invalid type conversion") }
[ "func", "appendSlice", "(", "expr", "ast", ".", "Expr", ",", "lhsV", "reflect", ".", "Value", ",", "rhsV", "reflect", ".", "Value", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "lhsT", ":=", "lhsV", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n", "rhsT", ":=", "rhsV", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n\n", "if", "lhsT", "==", "rhsT", "{", "return", "reflect", ".", "AppendSlice", "(", "lhsV", ",", "rhsV", ")", ",", "nil", "\n", "}", "\n\n", "if", "rhsT", ".", "ConvertibleTo", "(", "lhsT", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "rhsV", ".", "Len", "(", ")", ";", "i", "++", "{", "lhsV", "=", "reflect", ".", "Append", "(", "lhsV", ",", "rhsV", ".", "Index", "(", "i", ")", ".", "Convert", "(", "lhsT", ")", ")", "\n", "}", "\n", "return", "lhsV", ",", "nil", "\n", "}", "\n\n", "leftHasSubArray", ":=", "lhsT", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "||", "lhsT", ".", "Kind", "(", ")", "==", "reflect", ".", "Array", "\n", "rightHasSubArray", ":=", "rhsT", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "||", "rhsT", ".", "Kind", "(", ")", "==", "reflect", ".", "Array", "\n\n", "if", "leftHasSubArray", "!=", "rightHasSubArray", "&&", "lhsT", "!=", "interfaceType", "&&", "rhsT", "!=", "interfaceType", "{", "return", "nilValue", ",", "newStringError", "(", "expr", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "leftHasSubArray", "&&", "!", "rightHasSubArray", "{", "for", "i", ":=", "0", ";", "i", "<", "rhsV", ".", "Len", "(", ")", ";", "i", "++", "{", "value", ":=", "rhsV", ".", "Index", "(", "i", ")", "\n", "if", "rhsT", "==", "interfaceType", "{", "value", "=", "value", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "lhsT", "==", "value", ".", "Type", "(", ")", "{", "lhsV", "=", "reflect", ".", "Append", "(", "lhsV", ",", "value", ")", "\n", "}", "else", "if", "value", ".", "Type", "(", ")", ".", "ConvertibleTo", "(", "lhsT", ")", "{", "lhsV", "=", "reflect", ".", "Append", "(", "lhsV", ",", "value", ".", "Convert", "(", "lhsT", ")", ")", "\n", "}", "else", "{", "return", "nilValue", ",", "newStringError", "(", "expr", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "lhsV", ",", "nil", "\n", "}", "\n\n", "if", "(", "leftHasSubArray", "||", "lhsT", "==", "interfaceType", ")", "&&", "(", "rightHasSubArray", "||", "rhsT", "==", "interfaceType", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "rhsV", ".", "Len", "(", ")", ";", "i", "++", "{", "value", ":=", "rhsV", ".", "Index", "(", "i", ")", "\n", "if", "rhsT", "==", "interfaceType", "{", "value", "=", "value", ".", "Elem", "(", ")", "\n", "if", "value", ".", "Kind", "(", ")", "!=", "reflect", ".", "Slice", "&&", "value", ".", "Kind", "(", ")", "!=", "reflect", ".", "Array", "{", "return", "nilValue", ",", "newStringError", "(", "expr", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "newSlice", ",", "err", ":=", "appendSlice", "(", "expr", ",", "reflect", ".", "MakeSlice", "(", "lhsT", ",", "0", ",", "value", ".", "Len", "(", ")", ")", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nilValue", ",", "err", "\n", "}", "\n", "lhsV", "=", "reflect", ".", "Append", "(", "lhsV", ",", "newSlice", ")", "\n", "}", "\n", "return", "lhsV", ",", "nil", "\n", "}", "\n\n", "return", "nilValue", ",", "newStringError", "(", "expr", ",", "\"", "\"", ")", "\n", "}" ]
// appendSlice appends rhs to lhs // function assumes lhsV and rhsV are slice or array
[ "appendSlice", "appends", "rhs", "to", "lhs", "function", "assumes", "lhsV", "and", "rhsV", "are", "slice", "or", "array" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vm.go#L202-L260
7,519
mattn/anko
vm/vm.go
precedenceOfKinds
func precedenceOfKinds(kind1 reflect.Kind, kind2 reflect.Kind) reflect.Kind { if kind1 == kind2 { return kind1 } switch kind1 { case reflect.String: return kind1 case reflect.Float64, reflect.Float32: switch kind2 { case reflect.String: return kind2 } return kind1 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: switch kind2 { case reflect.String, reflect.Float64, reflect.Float32: return kind2 } } return kind1 }
go
func precedenceOfKinds(kind1 reflect.Kind, kind2 reflect.Kind) reflect.Kind { if kind1 == kind2 { return kind1 } switch kind1 { case reflect.String: return kind1 case reflect.Float64, reflect.Float32: switch kind2 { case reflect.String: return kind2 } return kind1 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: switch kind2 { case reflect.String, reflect.Float64, reflect.Float32: return kind2 } } return kind1 }
[ "func", "precedenceOfKinds", "(", "kind1", "reflect", ".", "Kind", ",", "kind2", "reflect", ".", "Kind", ")", "reflect", ".", "Kind", "{", "if", "kind1", "==", "kind2", "{", "return", "kind1", "\n", "}", "\n", "switch", "kind1", "{", "case", "reflect", ".", "String", ":", "return", "kind1", "\n", "case", "reflect", ".", "Float64", ",", "reflect", ".", "Float32", ":", "switch", "kind2", "{", "case", "reflect", ".", "String", ":", "return", "kind2", "\n", "}", "\n", "return", "kind1", "\n", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "switch", "kind2", "{", "case", "reflect", ".", "String", ",", "reflect", ".", "Float64", ",", "reflect", ".", "Float32", ":", "return", "kind2", "\n", "}", "\n", "}", "\n", "return", "kind1", "\n", "}" ]
// precedenceOfKinds returns the greater of two kinds // string > float > int
[ "precedenceOfKinds", "returns", "the", "greater", "of", "two", "kinds", "string", ">", "float", ">", "int" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vm.go#L426-L446
7,520
mattn/anko
vm/vmToX.go
toString
func toString(v reflect.Value) string { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() == reflect.String { return v.String() } return fmt.Sprint(v.Interface()) }
go
func toString(v reflect.Value) string { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() == reflect.String { return v.String() } return fmt.Sprint(v.Interface()) }
[ "func", "toString", "(", "v", "reflect", ".", "Value", ")", "string", "{", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "&&", "!", "v", ".", "IsNil", "(", ")", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "v", "=", "v", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "v", ".", "Kind", "(", ")", "==", "reflect", ".", "String", "{", "return", "v", ".", "String", "(", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprint", "(", "v", ".", "Interface", "(", ")", ")", "\n", "}" ]
// toString converts all reflect.Value-s into string.
[ "toString", "converts", "all", "reflect", ".", "Value", "-", "s", "into", "string", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmToX.go#L12-L23
7,521
mattn/anko
vm/vmToX.go
toBool
func toBool(v reflect.Value) bool { b, _ := tryToBool(v) return b }
go
func toBool(v reflect.Value) bool { b, _ := tryToBool(v) return b }
[ "func", "toBool", "(", "v", "reflect", ".", "Value", ")", "bool", "{", "b", ",", "_", ":=", "tryToBool", "(", "v", ")", "\n", "return", "b", "\n", "}" ]
// toBool converts all reflect.Value-s into bool.
[ "toBool", "converts", "all", "reflect", ".", "Value", "-", "s", "into", "bool", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmToX.go#L26-L29
7,522
mattn/anko
vm/vmToX.go
toFloat64
func toFloat64(v reflect.Value) float64 { f, _ := tryToFloat64(v) return f }
go
func toFloat64(v reflect.Value) float64 { f, _ := tryToFloat64(v) return f }
[ "func", "toFloat64", "(", "v", "reflect", ".", "Value", ")", "float64", "{", "f", ",", "_", ":=", "tryToFloat64", "(", "v", ")", "\n", "return", "f", "\n", "}" ]
// toFloat64 converts all reflect.Value-s into float64.
[ "toFloat64", "converts", "all", "reflect", ".", "Value", "-", "s", "into", "float64", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmToX.go#L71-L74
7,523
mattn/anko
vm/vmToX.go
toInt64
func toInt64(v reflect.Value) int64 { i, _ := tryToInt64(v) return i }
go
func toInt64(v reflect.Value) int64 { i, _ := tryToInt64(v) return i }
[ "func", "toInt64", "(", "v", "reflect", ".", "Value", ")", "int64", "{", "i", ",", "_", ":=", "tryToInt64", "(", "v", ")", "\n", "return", "i", "\n", "}" ]
// toInt64 converts all reflect.Value-s into int64.
[ "toInt64", "converts", "all", "reflect", ".", "Value", "-", "s", "into", "int64", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmToX.go#L103-L106
7,524
mattn/anko
vm/vmToX.go
toInt
func toInt(v reflect.Value) int { i, _ := tryToInt(v) return i }
go
func toInt(v reflect.Value) int { i, _ := tryToInt(v) return i }
[ "func", "toInt", "(", "v", "reflect", ".", "Value", ")", "int", "{", "i", ",", "_", ":=", "tryToInt", "(", "v", ")", "\n", "return", "i", "\n", "}" ]
// toInt converts all reflect.Value-s into int.
[ "toInt", "converts", "all", "reflect", ".", "Value", "-", "s", "into", "int", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmToX.go#L142-L145
7,525
mattn/anko
parser/lexer.go
isHex
func isHex(ch rune) bool { return ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') }
go
func isHex(ch rune) bool { return ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F') }
[ "func", "isHex", "(", "ch", "rune", ")", "bool", "{", "return", "(", "'0'", "<=", "ch", "&&", "ch", "<=", "'9'", ")", "||", "(", "'a'", "<=", "ch", "&&", "ch", "<=", "'f'", ")", "||", "(", "'A'", "<=", "ch", "&&", "ch", "<=", "'F'", ")", "\n", "}" ]
// isHex returns true if the rune is a hex digits.
[ "isHex", "returns", "true", "if", "the", "rune", "is", "a", "hex", "digits", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L338-L340
7,526
mattn/anko
parser/lexer.go
peek
func (s *Scanner) peek() rune { if s.reachEOF() { return EOF } return s.src[s.offset] }
go
func (s *Scanner) peek() rune { if s.reachEOF() { return EOF } return s.src[s.offset] }
[ "func", "(", "s", "*", "Scanner", ")", "peek", "(", ")", "rune", "{", "if", "s", ".", "reachEOF", "(", ")", "{", "return", "EOF", "\n", "}", "\n", "return", "s", ".", "src", "[", "s", ".", "offset", "]", "\n", "}" ]
// peek returns current rune in the code.
[ "peek", "returns", "current", "rune", "in", "the", "code", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L353-L358
7,527
mattn/anko
parser/lexer.go
next
func (s *Scanner) next() { if !s.reachEOF() { if s.peek() == '\n' { s.lineHead = s.offset + 1 s.line++ } s.offset++ } }
go
func (s *Scanner) next() { if !s.reachEOF() { if s.peek() == '\n' { s.lineHead = s.offset + 1 s.line++ } s.offset++ } }
[ "func", "(", "s", "*", "Scanner", ")", "next", "(", ")", "{", "if", "!", "s", ".", "reachEOF", "(", ")", "{", "if", "s", ".", "peek", "(", ")", "==", "'\\n'", "{", "s", ".", "lineHead", "=", "s", ".", "offset", "+", "1", "\n", "s", ".", "line", "++", "\n", "}", "\n", "s", ".", "offset", "++", "\n", "}", "\n", "}" ]
// next moves offset to next.
[ "next", "moves", "offset", "to", "next", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L361-L369
7,528
mattn/anko
parser/lexer.go
pos
func (s *Scanner) pos() ast.Position { return ast.Position{Line: s.line + 1, Column: s.offset - s.lineHead + 1} }
go
func (s *Scanner) pos() ast.Position { return ast.Position{Line: s.line + 1, Column: s.offset - s.lineHead + 1} }
[ "func", "(", "s", "*", "Scanner", ")", "pos", "(", ")", "ast", ".", "Position", "{", "return", "ast", ".", "Position", "{", "Line", ":", "s", ".", "line", "+", "1", ",", "Column", ":", "s", ".", "offset", "-", "s", ".", "lineHead", "+", "1", "}", "\n", "}" ]
// pos returns the position of current.
[ "pos", "returns", "the", "position", "of", "current", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L392-L394
7,529
mattn/anko
parser/lexer.go
scanIdentifier
func (s *Scanner) scanIdentifier() (string, error) { var ret []rune for { if !isLetter(s.peek()) && !isDigit(s.peek()) { break } ret = append(ret, s.peek()) s.next() } return string(ret), nil }
go
func (s *Scanner) scanIdentifier() (string, error) { var ret []rune for { if !isLetter(s.peek()) && !isDigit(s.peek()) { break } ret = append(ret, s.peek()) s.next() } return string(ret), nil }
[ "func", "(", "s", "*", "Scanner", ")", "scanIdentifier", "(", ")", "(", "string", ",", "error", ")", "{", "var", "ret", "[", "]", "rune", "\n", "for", "{", "if", "!", "isLetter", "(", "s", ".", "peek", "(", ")", ")", "&&", "!", "isDigit", "(", "s", ".", "peek", "(", ")", ")", "{", "break", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "s", ".", "peek", "(", ")", ")", "\n", "s", ".", "next", "(", ")", "\n", "}", "\n", "return", "string", "(", "ret", ")", ",", "nil", "\n", "}" ]
// scanIdentifier returns identifier beginning at current position.
[ "scanIdentifier", "returns", "identifier", "beginning", "at", "current", "position", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L404-L414
7,530
mattn/anko
parser/lexer.go
scanNumber
func (s *Scanner) scanNumber() (string, error) { result := []rune{s.peek()} s.next() if result[0] == '0' && (s.peek() == 'x' || s.peek() == 'X') { // hex result = append(result, 'x') s.next() for isHex(s.peek()) { result = append(result, s.peek()) s.next() } } else { // non-hex found := false for { if isDigit(s.peek()) { // is digit result = append(result, s.peek()) s.next() continue } if s.peek() == '.' { // is . result = append(result, '.') s.next() continue } if s.peek() == 'e' || s.peek() == 'E' { // is e if found { return "", errors.New("unexpected " + string(s.peek())) } found = true s.next() // check if + or - if s.peek() == '+' || s.peek() == '-' { // add e with + or - result = append(result, 'e') result = append(result, s.peek()) s.next() } else { // add e, but next char not + or - result = append(result, 'e') } continue } // not digit, e, nor . break } } if isLetter(s.peek()) { return "", errors.New("identifier starts immediately after numeric literal") } return string(result), nil }
go
func (s *Scanner) scanNumber() (string, error) { result := []rune{s.peek()} s.next() if result[0] == '0' && (s.peek() == 'x' || s.peek() == 'X') { // hex result = append(result, 'x') s.next() for isHex(s.peek()) { result = append(result, s.peek()) s.next() } } else { // non-hex found := false for { if isDigit(s.peek()) { // is digit result = append(result, s.peek()) s.next() continue } if s.peek() == '.' { // is . result = append(result, '.') s.next() continue } if s.peek() == 'e' || s.peek() == 'E' { // is e if found { return "", errors.New("unexpected " + string(s.peek())) } found = true s.next() // check if + or - if s.peek() == '+' || s.peek() == '-' { // add e with + or - result = append(result, 'e') result = append(result, s.peek()) s.next() } else { // add e, but next char not + or - result = append(result, 'e') } continue } // not digit, e, nor . break } } if isLetter(s.peek()) { return "", errors.New("identifier starts immediately after numeric literal") } return string(result), nil }
[ "func", "(", "s", "*", "Scanner", ")", "scanNumber", "(", ")", "(", "string", ",", "error", ")", "{", "result", ":=", "[", "]", "rune", "{", "s", ".", "peek", "(", ")", "}", "\n", "s", ".", "next", "(", ")", "\n\n", "if", "result", "[", "0", "]", "==", "'0'", "&&", "(", "s", ".", "peek", "(", ")", "==", "'x'", "||", "s", ".", "peek", "(", ")", "==", "'X'", ")", "{", "// hex", "result", "=", "append", "(", "result", ",", "'x'", ")", "\n", "s", ".", "next", "(", ")", "\n", "for", "isHex", "(", "s", ".", "peek", "(", ")", ")", "{", "result", "=", "append", "(", "result", ",", "s", ".", "peek", "(", ")", ")", "\n", "s", ".", "next", "(", ")", "\n", "}", "\n", "}", "else", "{", "// non-hex", "found", ":=", "false", "\n", "for", "{", "if", "isDigit", "(", "s", ".", "peek", "(", ")", ")", "{", "// is digit", "result", "=", "append", "(", "result", ",", "s", ".", "peek", "(", ")", ")", "\n", "s", ".", "next", "(", ")", "\n", "continue", "\n", "}", "\n\n", "if", "s", ".", "peek", "(", ")", "==", "'.'", "{", "// is .", "result", "=", "append", "(", "result", ",", "'.'", ")", "\n", "s", ".", "next", "(", ")", "\n", "continue", "\n", "}", "\n\n", "if", "s", ".", "peek", "(", ")", "==", "'e'", "||", "s", ".", "peek", "(", ")", "==", "'E'", "{", "// is e", "if", "found", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", "+", "string", "(", "s", ".", "peek", "(", ")", ")", ")", "\n", "}", "\n", "found", "=", "true", "\n", "s", ".", "next", "(", ")", "\n\n", "// check if + or -", "if", "s", ".", "peek", "(", ")", "==", "'+'", "||", "s", ".", "peek", "(", ")", "==", "'-'", "{", "// add e with + or -", "result", "=", "append", "(", "result", ",", "'e'", ")", "\n", "result", "=", "append", "(", "result", ",", "s", ".", "peek", "(", ")", ")", "\n", "s", ".", "next", "(", ")", "\n", "}", "else", "{", "// add e, but next char not + or -", "result", "=", "append", "(", "result", ",", "'e'", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// not digit, e, nor .", "break", "\n", "}", "\n", "}", "\n\n", "if", "isLetter", "(", "s", ".", "peek", "(", ")", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "string", "(", "result", ")", ",", "nil", "\n", "}" ]
// scanNumber returns number beginning at current position.
[ "scanNumber", "returns", "number", "beginning", "at", "current", "position", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L417-L478
7,531
mattn/anko
parser/lexer.go
scanRawString
func (s *Scanner) scanRawString(l rune) (string, error) { var ret []rune for { s.next() if s.peek() == EOF { return "", errors.New("unexpected EOF") } if s.peek() == l { s.next() break } ret = append(ret, s.peek()) } return string(ret), nil }
go
func (s *Scanner) scanRawString(l rune) (string, error) { var ret []rune for { s.next() if s.peek() == EOF { return "", errors.New("unexpected EOF") } if s.peek() == l { s.next() break } ret = append(ret, s.peek()) } return string(ret), nil }
[ "func", "(", "s", "*", "Scanner", ")", "scanRawString", "(", "l", "rune", ")", "(", "string", ",", "error", ")", "{", "var", "ret", "[", "]", "rune", "\n", "for", "{", "s", ".", "next", "(", ")", "\n", "if", "s", ".", "peek", "(", ")", "==", "EOF", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "peek", "(", ")", "==", "l", "{", "s", ".", "next", "(", ")", "\n", "break", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "s", ".", "peek", "(", ")", ")", "\n", "}", "\n", "return", "string", "(", "ret", ")", ",", "nil", "\n", "}" ]
// scanRawString returns raw-string starting at current position.
[ "scanRawString", "returns", "raw", "-", "string", "starting", "at", "current", "position", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L481-L495
7,532
mattn/anko
parser/lexer.go
scanString
func (s *Scanner) scanString(l rune) (string, error) { var ret []rune eos: for { s.next() switch s.peek() { case EOL: return "", errors.New("unexpected EOL") case EOF: return "", errors.New("unexpected EOF") case l: s.next() break eos case '\\': s.next() switch s.peek() { case 'b': ret = append(ret, '\b') continue case 'f': ret = append(ret, '\f') continue case 'r': ret = append(ret, '\r') continue case 'n': ret = append(ret, '\n') continue case 't': ret = append(ret, '\t') continue } ret = append(ret, s.peek()) continue default: ret = append(ret, s.peek()) } } return string(ret), nil }
go
func (s *Scanner) scanString(l rune) (string, error) { var ret []rune eos: for { s.next() switch s.peek() { case EOL: return "", errors.New("unexpected EOL") case EOF: return "", errors.New("unexpected EOF") case l: s.next() break eos case '\\': s.next() switch s.peek() { case 'b': ret = append(ret, '\b') continue case 'f': ret = append(ret, '\f') continue case 'r': ret = append(ret, '\r') continue case 'n': ret = append(ret, '\n') continue case 't': ret = append(ret, '\t') continue } ret = append(ret, s.peek()) continue default: ret = append(ret, s.peek()) } } return string(ret), nil }
[ "func", "(", "s", "*", "Scanner", ")", "scanString", "(", "l", "rune", ")", "(", "string", ",", "error", ")", "{", "var", "ret", "[", "]", "rune", "\n", "eos", ":", "for", "{", "s", ".", "next", "(", ")", "\n", "switch", "s", ".", "peek", "(", ")", "{", "case", "EOL", ":", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "EOF", ":", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "l", ":", "s", ".", "next", "(", ")", "\n", "break", "eos", "\n", "case", "'\\\\'", ":", "s", ".", "next", "(", ")", "\n", "switch", "s", ".", "peek", "(", ")", "{", "case", "'b'", ":", "ret", "=", "append", "(", "ret", ",", "'\\b'", ")", "\n", "continue", "\n", "case", "'f'", ":", "ret", "=", "append", "(", "ret", ",", "'\\f'", ")", "\n", "continue", "\n", "case", "'r'", ":", "ret", "=", "append", "(", "ret", ",", "'\\r'", ")", "\n", "continue", "\n", "case", "'n'", ":", "ret", "=", "append", "(", "ret", ",", "'\\n'", ")", "\n", "continue", "\n", "case", "'t'", ":", "ret", "=", "append", "(", "ret", ",", "'\\t'", ")", "\n", "continue", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "s", ".", "peek", "(", ")", ")", "\n", "continue", "\n", "default", ":", "ret", "=", "append", "(", "ret", ",", "s", ".", "peek", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "string", "(", "ret", ")", ",", "nil", "\n", "}" ]
// scanString returns string starting at current position. // This handles backslash escaping.
[ "scanString", "returns", "string", "starting", "at", "current", "position", ".", "This", "handles", "backslash", "escaping", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L499-L538
7,533
mattn/anko
parser/lexer.go
Lex
func (l *Lexer) Lex(lval *yySymType) int { tok, lit, pos, err := l.s.Scan() if err != nil { l.e = &Error{Message: err.Error(), Pos: pos, Fatal: true} } lval.tok = ast.Token{Tok: tok, Lit: lit} lval.tok.SetPosition(pos) l.lit = lit l.pos = pos return tok }
go
func (l *Lexer) Lex(lval *yySymType) int { tok, lit, pos, err := l.s.Scan() if err != nil { l.e = &Error{Message: err.Error(), Pos: pos, Fatal: true} } lval.tok = ast.Token{Tok: tok, Lit: lit} lval.tok.SetPosition(pos) l.lit = lit l.pos = pos return tok }
[ "func", "(", "l", "*", "Lexer", ")", "Lex", "(", "lval", "*", "yySymType", ")", "int", "{", "tok", ",", "lit", ",", "pos", ",", "err", ":=", "l", ".", "s", ".", "Scan", "(", ")", "\n", "if", "err", "!=", "nil", "{", "l", ".", "e", "=", "&", "Error", "{", "Message", ":", "err", ".", "Error", "(", ")", ",", "Pos", ":", "pos", ",", "Fatal", ":", "true", "}", "\n", "}", "\n", "lval", ".", "tok", "=", "ast", ".", "Token", "{", "Tok", ":", "tok", ",", "Lit", ":", "lit", "}", "\n", "lval", ".", "tok", ".", "SetPosition", "(", "pos", ")", "\n", "l", ".", "lit", "=", "lit", "\n", "l", ".", "pos", "=", "pos", "\n", "return", "tok", "\n", "}" ]
// Lex scans the token and literals.
[ "Lex", "scans", "the", "token", "and", "literals", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L550-L560
7,534
mattn/anko
parser/lexer.go
Error
func (l *Lexer) Error(msg string) { l.e = &Error{Message: msg, Pos: l.pos, Fatal: false} }
go
func (l *Lexer) Error(msg string) { l.e = &Error{Message: msg, Pos: l.pos, Fatal: false} }
[ "func", "(", "l", "*", "Lexer", ")", "Error", "(", "msg", "string", ")", "{", "l", ".", "e", "=", "&", "Error", "{", "Message", ":", "msg", ",", "Pos", ":", "l", ".", "pos", ",", "Fatal", ":", "false", "}", "\n", "}" ]
// Error sets parse error.
[ "Error", "sets", "parse", "error", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L563-L565
7,535
mattn/anko
parser/lexer.go
Parse
func Parse(s *Scanner) (ast.Stmt, error) { l := Lexer{s: s} if yyParse(&l) != 0 { return nil, l.e } return l.stmt, l.e }
go
func Parse(s *Scanner) (ast.Stmt, error) { l := Lexer{s: s} if yyParse(&l) != 0 { return nil, l.e } return l.stmt, l.e }
[ "func", "Parse", "(", "s", "*", "Scanner", ")", "(", "ast", ".", "Stmt", ",", "error", ")", "{", "l", ":=", "Lexer", "{", "s", ":", "s", "}", "\n", "if", "yyParse", "(", "&", "l", ")", "!=", "0", "{", "return", "nil", ",", "l", ".", "e", "\n", "}", "\n", "return", "l", ".", "stmt", ",", "l", ".", "e", "\n", "}" ]
// Parse provides way to parse the code using Scanner.
[ "Parse", "provides", "way", "to", "parse", "the", "code", "using", "Scanner", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L568-L574
7,536
mattn/anko
parser/lexer.go
ParseSrc
func ParseSrc(src string) (ast.Stmt, error) { scanner := &Scanner{ src: []rune(src), } return Parse(scanner) }
go
func ParseSrc(src string) (ast.Stmt, error) { scanner := &Scanner{ src: []rune(src), } return Parse(scanner) }
[ "func", "ParseSrc", "(", "src", "string", ")", "(", "ast", ".", "Stmt", ",", "error", ")", "{", "scanner", ":=", "&", "Scanner", "{", "src", ":", "[", "]", "rune", "(", "src", ")", ",", "}", "\n", "return", "Parse", "(", "scanner", ")", "\n", "}" ]
// ParseSrc provides way to parse the code from source.
[ "ParseSrc", "provides", "way", "to", "parse", "the", "code", "from", "source", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/parser/lexer.go#L582-L587
7,537
mattn/anko
packages/packages.go
DefineImport
func DefineImport(e *vm.Env) { e.Define("import", func(source string) *vm.Env { methods, ok := Packages[source] if !ok { panic(fmt.Sprintf("package '%s' not found", source)) } var err error pack := e.NewPackage(source) for methodName, methodValue := range methods { err = pack.Define(methodName, methodValue) if err != nil { panic(fmt.Sprintf("import Define error: %v", err)) } } types, ok := PackageTypes[source] if ok { for typeName, typeValue := range types { err = pack.DefineType(typeName, typeValue) if err != nil { panic(fmt.Sprintf("import DefineType error: %v", err)) } } } return pack }) }
go
func DefineImport(e *vm.Env) { e.Define("import", func(source string) *vm.Env { methods, ok := Packages[source] if !ok { panic(fmt.Sprintf("package '%s' not found", source)) } var err error pack := e.NewPackage(source) for methodName, methodValue := range methods { err = pack.Define(methodName, methodValue) if err != nil { panic(fmt.Sprintf("import Define error: %v", err)) } } types, ok := PackageTypes[source] if ok { for typeName, typeValue := range types { err = pack.DefineType(typeName, typeValue) if err != nil { panic(fmt.Sprintf("import DefineType error: %v", err)) } } } return pack }) }
[ "func", "DefineImport", "(", "e", "*", "vm", ".", "Env", ")", "{", "e", ".", "Define", "(", "\"", "\"", ",", "func", "(", "source", "string", ")", "*", "vm", ".", "Env", "{", "methods", ",", "ok", ":=", "Packages", "[", "source", "]", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "source", ")", ")", "\n", "}", "\n", "var", "err", "error", "\n", "pack", ":=", "e", ".", "NewPackage", "(", "source", ")", "\n", "for", "methodName", ",", "methodValue", ":=", "range", "methods", "{", "err", "=", "pack", ".", "Define", "(", "methodName", ",", "methodValue", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}", "\n", "types", ",", "ok", ":=", "PackageTypes", "[", "source", "]", "\n", "if", "ok", "{", "for", "typeName", ",", "typeValue", ":=", "range", "types", "{", "err", "=", "pack", ".", "DefineType", "(", "typeName", ",", "typeValue", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "pack", "\n", "}", ")", "\n", "}" ]
// DefineImport defines the vm import command that will import packages and package types when wanted
[ "DefineImport", "defines", "the", "vm", "import", "command", "that", "will", "import", "packages", "and", "package", "types", "when", "wanted" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/packages/packages.go#L17-L42
7,538
mattn/anko
vm/vmConvertToX.go
reflectValueSlicetoInterfaceSlice
func reflectValueSlicetoInterfaceSlice(valueSlice []reflect.Value) reflect.Value { interfaceSlice := make([]interface{}, 0, len(valueSlice)) for _, value := range valueSlice { if value.Kind() == reflect.Interface && !value.IsNil() { value = value.Elem() } if value.CanInterface() { interfaceSlice = append(interfaceSlice, value.Interface()) } else { interfaceSlice = append(interfaceSlice, nil) } } return reflect.ValueOf(interfaceSlice) }
go
func reflectValueSlicetoInterfaceSlice(valueSlice []reflect.Value) reflect.Value { interfaceSlice := make([]interface{}, 0, len(valueSlice)) for _, value := range valueSlice { if value.Kind() == reflect.Interface && !value.IsNil() { value = value.Elem() } if value.CanInterface() { interfaceSlice = append(interfaceSlice, value.Interface()) } else { interfaceSlice = append(interfaceSlice, nil) } } return reflect.ValueOf(interfaceSlice) }
[ "func", "reflectValueSlicetoInterfaceSlice", "(", "valueSlice", "[", "]", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "interfaceSlice", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "len", "(", "valueSlice", ")", ")", "\n", "for", "_", ",", "value", ":=", "range", "valueSlice", "{", "if", "value", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "&&", "!", "value", ".", "IsNil", "(", ")", "{", "value", "=", "value", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "value", ".", "CanInterface", "(", ")", "{", "interfaceSlice", "=", "append", "(", "interfaceSlice", ",", "value", ".", "Interface", "(", ")", ")", "\n", "}", "else", "{", "interfaceSlice", "=", "append", "(", "interfaceSlice", ",", "nil", ")", "\n", "}", "\n", "}", "\n", "return", "reflect", ".", "ValueOf", "(", "interfaceSlice", ")", "\n", "}" ]
// reflectValueSlicetoInterfaceSlice convert from a slice of reflect.Value to a interface slice // returned in normal reflect.Value form
[ "reflectValueSlicetoInterfaceSlice", "convert", "from", "a", "slice", "of", "reflect", ".", "Value", "to", "a", "interface", "slice", "returned", "in", "normal", "reflect", ".", "Value", "form" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmConvertToX.go#L11-L24
7,539
mattn/anko
vm/vmConvertToX.go
convertReflectValueToType
func convertReflectValueToType(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { if rt == interfaceType || rv.Type() == rt { // if reflect.Type is interface or the types match, return the provided reflect.Value return rv, nil } if rv.Type().ConvertibleTo(rt) { // if reflect can covert, do that conversion and return return rv.Convert(rt), nil } if (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array) && (rt.Kind() == reflect.Slice || rt.Kind() == reflect.Array) { // covert slice or array return convertSliceOrArray(rv, rt) } if rv.Kind() == rt.Kind() { // kind matches switch rv.Kind() { case reflect.Map: // convert map return convertMap(rv, rt) case reflect.Func: // for runVMFunction conversions, call convertVMFunctionToType return convertVMFunctionToType(rv, rt) case reflect.Ptr: // both rv and rt are pointers, convert what they are pointing to value, err := convertReflectValueToType(rv.Elem(), rt.Elem()) if err != nil { return rv, err } // need to make a new value to be able to set it ptrV, err := makeValue(rt) if err != nil { return rv, err } // set value and return new pointer ptrV.Elem().Set(value) return ptrV, nil } } if rv.Type() == interfaceType { if rv.IsNil() { // return nil of correct type return reflect.Zero(rt), nil } // try to convert the element return convertReflectValueToType(rv.Elem(), rt) } // TODO: need to handle the case where either rv or rt are a pointer but not both return rv, fmt.Errorf("invalid type conversion") }
go
func convertReflectValueToType(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { if rt == interfaceType || rv.Type() == rt { // if reflect.Type is interface or the types match, return the provided reflect.Value return rv, nil } if rv.Type().ConvertibleTo(rt) { // if reflect can covert, do that conversion and return return rv.Convert(rt), nil } if (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array) && (rt.Kind() == reflect.Slice || rt.Kind() == reflect.Array) { // covert slice or array return convertSliceOrArray(rv, rt) } if rv.Kind() == rt.Kind() { // kind matches switch rv.Kind() { case reflect.Map: // convert map return convertMap(rv, rt) case reflect.Func: // for runVMFunction conversions, call convertVMFunctionToType return convertVMFunctionToType(rv, rt) case reflect.Ptr: // both rv and rt are pointers, convert what they are pointing to value, err := convertReflectValueToType(rv.Elem(), rt.Elem()) if err != nil { return rv, err } // need to make a new value to be able to set it ptrV, err := makeValue(rt) if err != nil { return rv, err } // set value and return new pointer ptrV.Elem().Set(value) return ptrV, nil } } if rv.Type() == interfaceType { if rv.IsNil() { // return nil of correct type return reflect.Zero(rt), nil } // try to convert the element return convertReflectValueToType(rv.Elem(), rt) } // TODO: need to handle the case where either rv or rt are a pointer but not both return rv, fmt.Errorf("invalid type conversion") }
[ "func", "convertReflectValueToType", "(", "rv", "reflect", ".", "Value", ",", "rt", "reflect", ".", "Type", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "if", "rt", "==", "interfaceType", "||", "rv", ".", "Type", "(", ")", "==", "rt", "{", "// if reflect.Type is interface or the types match, return the provided reflect.Value", "return", "rv", ",", "nil", "\n", "}", "\n", "if", "rv", ".", "Type", "(", ")", ".", "ConvertibleTo", "(", "rt", ")", "{", "// if reflect can covert, do that conversion and return", "return", "rv", ".", "Convert", "(", "rt", ")", ",", "nil", "\n", "}", "\n", "if", "(", "rv", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "||", "rv", ".", "Kind", "(", ")", "==", "reflect", ".", "Array", ")", "&&", "(", "rt", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "||", "rt", ".", "Kind", "(", ")", "==", "reflect", ".", "Array", ")", "{", "// covert slice or array", "return", "convertSliceOrArray", "(", "rv", ",", "rt", ")", "\n", "}", "\n", "if", "rv", ".", "Kind", "(", ")", "==", "rt", ".", "Kind", "(", ")", "{", "// kind matches", "switch", "rv", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Map", ":", "// convert map", "return", "convertMap", "(", "rv", ",", "rt", ")", "\n", "case", "reflect", ".", "Func", ":", "// for runVMFunction conversions, call convertVMFunctionToType", "return", "convertVMFunctionToType", "(", "rv", ",", "rt", ")", "\n", "case", "reflect", ".", "Ptr", ":", "// both rv and rt are pointers, convert what they are pointing to", "value", ",", "err", ":=", "convertReflectValueToType", "(", "rv", ".", "Elem", "(", ")", ",", "rt", ".", "Elem", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "// need to make a new value to be able to set it", "ptrV", ",", "err", ":=", "makeValue", "(", "rt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "// set value and return new pointer", "ptrV", ".", "Elem", "(", ")", ".", "Set", "(", "value", ")", "\n", "return", "ptrV", ",", "nil", "\n", "}", "\n", "}", "\n", "if", "rv", ".", "Type", "(", ")", "==", "interfaceType", "{", "if", "rv", ".", "IsNil", "(", ")", "{", "// return nil of correct type", "return", "reflect", ".", "Zero", "(", "rt", ")", ",", "nil", "\n", "}", "\n", "// try to convert the element", "return", "convertReflectValueToType", "(", "rv", ".", "Elem", "(", ")", ",", "rt", ")", "\n", "}", "\n\n", "// TODO: need to handle the case where either rv or rt are a pointer but not both", "return", "rv", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// convertReflectValueToType trys to covert the reflect.Value to the reflect.Type // if it can not, it returns the original rv and an error
[ "convertReflectValueToType", "trys", "to", "covert", "the", "reflect", ".", "Value", "to", "the", "reflect", ".", "Type", "if", "it", "can", "not", "it", "returns", "the", "original", "rv", "and", "an", "error" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmConvertToX.go#L28-L79
7,540
mattn/anko
vm/vmConvertToX.go
convertSliceOrArray
func convertSliceOrArray(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { rtElemType := rt.Elem() // try to covert elements to new slice/array var value reflect.Value if rt.Kind() == reflect.Slice { // make slice value = reflect.MakeSlice(rt, rv.Len(), rv.Len()) } else { // make array value = reflect.New(rt).Elem() } var err error var v reflect.Value for i := 0; i < rv.Len(); i++ { v, err = convertReflectValueToType(rv.Index(i), rtElemType) if err != nil { return rv, err } value.Index(i).Set(v) } // return new converted slice or array return value, nil }
go
func convertSliceOrArray(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { rtElemType := rt.Elem() // try to covert elements to new slice/array var value reflect.Value if rt.Kind() == reflect.Slice { // make slice value = reflect.MakeSlice(rt, rv.Len(), rv.Len()) } else { // make array value = reflect.New(rt).Elem() } var err error var v reflect.Value for i := 0; i < rv.Len(); i++ { v, err = convertReflectValueToType(rv.Index(i), rtElemType) if err != nil { return rv, err } value.Index(i).Set(v) } // return new converted slice or array return value, nil }
[ "func", "convertSliceOrArray", "(", "rv", "reflect", ".", "Value", ",", "rt", "reflect", ".", "Type", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "rtElemType", ":=", "rt", ".", "Elem", "(", ")", "\n\n", "// try to covert elements to new slice/array", "var", "value", "reflect", ".", "Value", "\n", "if", "rt", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", "{", "// make slice", "value", "=", "reflect", ".", "MakeSlice", "(", "rt", ",", "rv", ".", "Len", "(", ")", ",", "rv", ".", "Len", "(", ")", ")", "\n", "}", "else", "{", "// make array", "value", "=", "reflect", ".", "New", "(", "rt", ")", ".", "Elem", "(", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "var", "v", "reflect", ".", "Value", "\n", "for", "i", ":=", "0", ";", "i", "<", "rv", ".", "Len", "(", ")", ";", "i", "++", "{", "v", ",", "err", "=", "convertReflectValueToType", "(", "rv", ".", "Index", "(", "i", ")", ",", "rtElemType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "value", ".", "Index", "(", "i", ")", ".", "Set", "(", "v", ")", "\n", "}", "\n\n", "// return new converted slice or array", "return", "value", ",", "nil", "\n", "}" ]
// convertSliceOrArray trys to covert the reflect.Value slice or array to the slice or array reflect.Type
[ "convertSliceOrArray", "trys", "to", "covert", "the", "reflect", ".", "Value", "slice", "or", "array", "to", "the", "slice", "or", "array", "reflect", ".", "Type" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmConvertToX.go#L82-L107
7,541
mattn/anko
vm/vmConvertToX.go
convertMap
func convertMap(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { rtKey := rt.Key() rtElem := rt.Elem() // create new map // note creating slice as work around to create map // just doing MakeMap can give incorrect type for defined types newMap := reflect.MakeSlice(reflect.SliceOf(rt), 0, 1) newMap = reflect.Append(newMap, reflect.MakeMap(reflect.MapOf(rtKey, rtElem))).Index(0) // copy keys to new map // The only way to do this right now is to get all the keys. // At some point there will be a MapRange that could be used. // https://github.com/golang/go/issues/11104 // In the mean time using MapKeys, which will costly for large maps. mapKeys := rv.MapKeys() for i := 0; i < len(mapKeys); i++ { newKey, err := convertReflectValueToType(mapKeys[i], rtKey) if err != nil { return rv, err } value := rv.MapIndex(mapKeys[i]) value, err = convertReflectValueToType(value, rtElem) if err != nil { return rv, err } newMap.SetMapIndex(newKey, value) } return newMap, nil }
go
func convertMap(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { rtKey := rt.Key() rtElem := rt.Elem() // create new map // note creating slice as work around to create map // just doing MakeMap can give incorrect type for defined types newMap := reflect.MakeSlice(reflect.SliceOf(rt), 0, 1) newMap = reflect.Append(newMap, reflect.MakeMap(reflect.MapOf(rtKey, rtElem))).Index(0) // copy keys to new map // The only way to do this right now is to get all the keys. // At some point there will be a MapRange that could be used. // https://github.com/golang/go/issues/11104 // In the mean time using MapKeys, which will costly for large maps. mapKeys := rv.MapKeys() for i := 0; i < len(mapKeys); i++ { newKey, err := convertReflectValueToType(mapKeys[i], rtKey) if err != nil { return rv, err } value := rv.MapIndex(mapKeys[i]) value, err = convertReflectValueToType(value, rtElem) if err != nil { return rv, err } newMap.SetMapIndex(newKey, value) } return newMap, nil }
[ "func", "convertMap", "(", "rv", "reflect", ".", "Value", ",", "rt", "reflect", ".", "Type", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "rtKey", ":=", "rt", ".", "Key", "(", ")", "\n", "rtElem", ":=", "rt", ".", "Elem", "(", ")", "\n\n", "// create new map", "// note creating slice as work around to create map", "// just doing MakeMap can give incorrect type for defined types", "newMap", ":=", "reflect", ".", "MakeSlice", "(", "reflect", ".", "SliceOf", "(", "rt", ")", ",", "0", ",", "1", ")", "\n", "newMap", "=", "reflect", ".", "Append", "(", "newMap", ",", "reflect", ".", "MakeMap", "(", "reflect", ".", "MapOf", "(", "rtKey", ",", "rtElem", ")", ")", ")", ".", "Index", "(", "0", ")", "\n\n", "// copy keys to new map", "// The only way to do this right now is to get all the keys.", "// At some point there will be a MapRange that could be used.", "// https://github.com/golang/go/issues/11104", "// In the mean time using MapKeys, which will costly for large maps.", "mapKeys", ":=", "rv", ".", "MapKeys", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "mapKeys", ")", ";", "i", "++", "{", "newKey", ",", "err", ":=", "convertReflectValueToType", "(", "mapKeys", "[", "i", "]", ",", "rtKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "value", ":=", "rv", ".", "MapIndex", "(", "mapKeys", "[", "i", "]", ")", "\n", "value", ",", "err", "=", "convertReflectValueToType", "(", "value", ",", "rtElem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "rv", ",", "err", "\n", "}", "\n", "newMap", ".", "SetMapIndex", "(", "newKey", ",", "value", ")", "\n", "}", "\n\n", "return", "newMap", ",", "nil", "\n", "}" ]
// convertMap trys to covert the reflect.Value map to the map reflect.Type
[ "convertMap", "trys", "to", "covert", "the", "reflect", ".", "Value", "map", "to", "the", "map", "reflect", ".", "Type" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmConvertToX.go#L110-L140
7,542
mattn/anko
vm/vmConvertToX.go
convertVMFunctionToType
func convertVMFunctionToType(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { // only translates runVMFunction type if !checkIfRunVMFunction(rv.Type()) { return rv, fmt.Errorf("invalid type conversion") } // create runVMConvertFunction to match reflect.Type // this function is being called by the Go function runVMConvertFunction := func(in []reflect.Value) []reflect.Value { // note: this function is being called by another reflect Call // only way to pass along any errors is by panic // make the reflect.Value slice of each of the VM reflect.Value args := make([]reflect.Value, 0, rt.NumIn()+1) // for runVMFunction first arg is always context // TOFIX: use normal context args = append(args, reflect.ValueOf(context.Background())) for i := 0; i < rt.NumIn(); i++ { // have to do the double reflect.ValueOf that runVMFunction expects args = append(args, reflect.ValueOf(in[i])) } // Call runVMFunction rvs := rv.Call(args) // call processCallReturnValues to process runVMFunction return values // returns normal VM reflect.Value form rv, err := processCallReturnValues(rvs, true, false) if err != nil { panic("function run error: " + err.Error()) } if rt.NumOut() < 1 { // Go function does not want any return values, so give it none return []reflect.Value{} } if rt.NumOut() < 2 { // Go function wants one return value // will try to covert to reflect.Value correct type and return rv, err = convertReflectValueToType(rv, rt.Out(0)) if err != nil { panic("function wants return type " + rt.Out(0).String() + " but received type " + rv.Type().String()) } return []reflect.Value{rv} } // Go function wants more than one return value // make sure we have a slice/array with enought values if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array { panic(fmt.Sprintf("function wants %v return values but received %v", rt.NumOut(), rv.Kind().String())) } if rv.Len() < rt.NumOut() { panic(fmt.Sprintf("function wants %v return values but received %v values", rt.NumOut(), rv.Len())) } // try to covert each value in slice to wanted type and put into a reflect.Value slice rvs = make([]reflect.Value, rt.NumOut()) for i := 0; i < rv.Len(); i++ { rvs[i], err = convertReflectValueToType(rv.Index(i), rt.Out(i)) if err != nil { panic("function wants return type " + rt.Out(i).String() + " but received type " + rvs[i].Type().String()) } } // return created reflect.Value slice return rvs } // make the reflect.Value function that calls runVMConvertFunction return reflect.MakeFunc(rt, runVMConvertFunction), nil }
go
func convertVMFunctionToType(rv reflect.Value, rt reflect.Type) (reflect.Value, error) { // only translates runVMFunction type if !checkIfRunVMFunction(rv.Type()) { return rv, fmt.Errorf("invalid type conversion") } // create runVMConvertFunction to match reflect.Type // this function is being called by the Go function runVMConvertFunction := func(in []reflect.Value) []reflect.Value { // note: this function is being called by another reflect Call // only way to pass along any errors is by panic // make the reflect.Value slice of each of the VM reflect.Value args := make([]reflect.Value, 0, rt.NumIn()+1) // for runVMFunction first arg is always context // TOFIX: use normal context args = append(args, reflect.ValueOf(context.Background())) for i := 0; i < rt.NumIn(); i++ { // have to do the double reflect.ValueOf that runVMFunction expects args = append(args, reflect.ValueOf(in[i])) } // Call runVMFunction rvs := rv.Call(args) // call processCallReturnValues to process runVMFunction return values // returns normal VM reflect.Value form rv, err := processCallReturnValues(rvs, true, false) if err != nil { panic("function run error: " + err.Error()) } if rt.NumOut() < 1 { // Go function does not want any return values, so give it none return []reflect.Value{} } if rt.NumOut() < 2 { // Go function wants one return value // will try to covert to reflect.Value correct type and return rv, err = convertReflectValueToType(rv, rt.Out(0)) if err != nil { panic("function wants return type " + rt.Out(0).String() + " but received type " + rv.Type().String()) } return []reflect.Value{rv} } // Go function wants more than one return value // make sure we have a slice/array with enought values if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array { panic(fmt.Sprintf("function wants %v return values but received %v", rt.NumOut(), rv.Kind().String())) } if rv.Len() < rt.NumOut() { panic(fmt.Sprintf("function wants %v return values but received %v values", rt.NumOut(), rv.Len())) } // try to covert each value in slice to wanted type and put into a reflect.Value slice rvs = make([]reflect.Value, rt.NumOut()) for i := 0; i < rv.Len(); i++ { rvs[i], err = convertReflectValueToType(rv.Index(i), rt.Out(i)) if err != nil { panic("function wants return type " + rt.Out(i).String() + " but received type " + rvs[i].Type().String()) } } // return created reflect.Value slice return rvs } // make the reflect.Value function that calls runVMConvertFunction return reflect.MakeFunc(rt, runVMConvertFunction), nil }
[ "func", "convertVMFunctionToType", "(", "rv", "reflect", ".", "Value", ",", "rt", "reflect", ".", "Type", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "// only translates runVMFunction type", "if", "!", "checkIfRunVMFunction", "(", "rv", ".", "Type", "(", ")", ")", "{", "return", "rv", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// create runVMConvertFunction to match reflect.Type", "// this function is being called by the Go function", "runVMConvertFunction", ":=", "func", "(", "in", "[", "]", "reflect", ".", "Value", ")", "[", "]", "reflect", ".", "Value", "{", "// note: this function is being called by another reflect Call", "// only way to pass along any errors is by panic", "// make the reflect.Value slice of each of the VM reflect.Value", "args", ":=", "make", "(", "[", "]", "reflect", ".", "Value", ",", "0", ",", "rt", ".", "NumIn", "(", ")", "+", "1", ")", "\n", "// for runVMFunction first arg is always context", "// TOFIX: use normal context", "args", "=", "append", "(", "args", ",", "reflect", ".", "ValueOf", "(", "context", ".", "Background", "(", ")", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "rt", ".", "NumIn", "(", ")", ";", "i", "++", "{", "// have to do the double reflect.ValueOf that runVMFunction expects", "args", "=", "append", "(", "args", ",", "reflect", ".", "ValueOf", "(", "in", "[", "i", "]", ")", ")", "\n", "}", "\n\n", "// Call runVMFunction", "rvs", ":=", "rv", ".", "Call", "(", "args", ")", "\n\n", "// call processCallReturnValues to process runVMFunction return values", "// returns normal VM reflect.Value form", "rv", ",", "err", ":=", "processCallReturnValues", "(", "rvs", ",", "true", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "if", "rt", ".", "NumOut", "(", ")", "<", "1", "{", "// Go function does not want any return values, so give it none", "return", "[", "]", "reflect", ".", "Value", "{", "}", "\n", "}", "\n", "if", "rt", ".", "NumOut", "(", ")", "<", "2", "{", "// Go function wants one return value", "// will try to covert to reflect.Value correct type and return", "rv", ",", "err", "=", "convertReflectValueToType", "(", "rv", ",", "rt", ".", "Out", "(", "0", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", "+", "rt", ".", "Out", "(", "0", ")", ".", "String", "(", ")", "+", "\"", "\"", "+", "rv", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "[", "]", "reflect", ".", "Value", "{", "rv", "}", "\n", "}", "\n\n", "// Go function wants more than one return value", "// make sure we have a slice/array with enought values", "if", "rv", ".", "Kind", "(", ")", "!=", "reflect", ".", "Slice", "&&", "rv", ".", "Kind", "(", ")", "!=", "reflect", ".", "Array", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rt", ".", "NumOut", "(", ")", ",", "rv", ".", "Kind", "(", ")", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "if", "rv", ".", "Len", "(", ")", "<", "rt", ".", "NumOut", "(", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rt", ".", "NumOut", "(", ")", ",", "rv", ".", "Len", "(", ")", ")", ")", "\n", "}", "\n\n", "// try to covert each value in slice to wanted type and put into a reflect.Value slice", "rvs", "=", "make", "(", "[", "]", "reflect", ".", "Value", ",", "rt", ".", "NumOut", "(", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "rv", ".", "Len", "(", ")", ";", "i", "++", "{", "rvs", "[", "i", "]", ",", "err", "=", "convertReflectValueToType", "(", "rv", ".", "Index", "(", "i", ")", ",", "rt", ".", "Out", "(", "i", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", "+", "rt", ".", "Out", "(", "i", ")", ".", "String", "(", ")", "+", "\"", "\"", "+", "rvs", "[", "i", "]", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "// return created reflect.Value slice", "return", "rvs", "\n", "}", "\n\n", "// make the reflect.Value function that calls runVMConvertFunction", "return", "reflect", ".", "MakeFunc", "(", "rt", ",", "runVMConvertFunction", ")", ",", "nil", "\n", "}" ]
// convertVMFunctionToType is for translating a runVMFunction into the correct type // so it can be passed to a Go function argument with the correct static types // it creates a translate function runVMConvertFunction
[ "convertVMFunctionToType", "is", "for", "translating", "a", "runVMFunction", "into", "the", "correct", "type", "so", "it", "can", "be", "passed", "to", "a", "Go", "function", "argument", "with", "the", "correct", "static", "types", "it", "creates", "a", "translate", "function", "runVMConvertFunction" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmConvertToX.go#L145-L216
7,543
mattn/anko
core/toX.go
toSlice
func toSlice(from []interface{}, ptr interface{}) { // Value of the pointer to the target obj := reflect.Indirect(reflect.ValueOf(ptr)) // We can't just convert from interface{} to whatever the target is (diff memory layout), // so we need to create a New slice of the proper type and copy the values individually t := reflect.TypeOf(ptr).Elem() tt := t.Elem() slice := reflect.MakeSlice(t, len(from), len(from)) // Copying the data, val is an addressable Pointer of the actual target type val := reflect.Indirect(reflect.New(tt)) for i := 0; i < len(from); i++ { v := reflect.ValueOf(from[i]) if v.IsValid() && v.Type().ConvertibleTo(tt) { val.Set(v.Convert(tt)) } else { val.Set(reflect.Zero(tt)) } slice.Index(i).Set(val) } // Ok now assign our slice to the target pointer obj.Set(slice) }
go
func toSlice(from []interface{}, ptr interface{}) { // Value of the pointer to the target obj := reflect.Indirect(reflect.ValueOf(ptr)) // We can't just convert from interface{} to whatever the target is (diff memory layout), // so we need to create a New slice of the proper type and copy the values individually t := reflect.TypeOf(ptr).Elem() tt := t.Elem() slice := reflect.MakeSlice(t, len(from), len(from)) // Copying the data, val is an addressable Pointer of the actual target type val := reflect.Indirect(reflect.New(tt)) for i := 0; i < len(from); i++ { v := reflect.ValueOf(from[i]) if v.IsValid() && v.Type().ConvertibleTo(tt) { val.Set(v.Convert(tt)) } else { val.Set(reflect.Zero(tt)) } slice.Index(i).Set(val) } // Ok now assign our slice to the target pointer obj.Set(slice) }
[ "func", "toSlice", "(", "from", "[", "]", "interface", "{", "}", ",", "ptr", "interface", "{", "}", ")", "{", "// Value of the pointer to the target", "obj", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "ptr", ")", ")", "\n", "// We can't just convert from interface{} to whatever the target is (diff memory layout),", "// so we need to create a New slice of the proper type and copy the values individually", "t", ":=", "reflect", ".", "TypeOf", "(", "ptr", ")", ".", "Elem", "(", ")", "\n", "tt", ":=", "t", ".", "Elem", "(", ")", "\n", "slice", ":=", "reflect", ".", "MakeSlice", "(", "t", ",", "len", "(", "from", ")", ",", "len", "(", "from", ")", ")", "\n", "// Copying the data, val is an addressable Pointer of the actual target type", "val", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "New", "(", "tt", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "from", ")", ";", "i", "++", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "from", "[", "i", "]", ")", "\n", "if", "v", ".", "IsValid", "(", ")", "&&", "v", ".", "Type", "(", ")", ".", "ConvertibleTo", "(", "tt", ")", "{", "val", ".", "Set", "(", "v", ".", "Convert", "(", "tt", ")", ")", "\n", "}", "else", "{", "val", ".", "Set", "(", "reflect", ".", "Zero", "(", "tt", ")", ")", "\n", "}", "\n", "slice", ".", "Index", "(", "i", ")", ".", "Set", "(", "val", ")", "\n", "}", "\n", "// Ok now assign our slice to the target pointer", "obj", ".", "Set", "(", "slice", ")", "\n", "}" ]
// toSlice takes in a "generic" slice and converts and copies // it's elements into the typed slice pointed at by ptr. // Note that this is a costly operation.
[ "toSlice", "takes", "in", "a", "generic", "slice", "and", "converts", "and", "copies", "it", "s", "elements", "into", "the", "typed", "slice", "pointed", "at", "by", "ptr", ".", "Note", "that", "this", "is", "a", "costly", "operation", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/core/toX.go#L150-L171
7,544
mattn/anko
vm/vmExprFunction.go
funcExpr
func (runInfo *runInfoStruct) funcExpr() { funcExpr := runInfo.expr.(*ast.FuncExpr) // create the inTypes needed by reflect.FuncOf inTypes := make([]reflect.Type, len(funcExpr.Params)+1) // for runVMFunction first arg is always context inTypes[0] = contextType for i := 1; i < len(inTypes); i++ { inTypes[i] = reflectValueType } if funcExpr.VarArg { inTypes[len(inTypes)-1] = interfaceSliceType } // create funcType, output is always slice of reflect.Type with two values funcType := reflect.FuncOf(inTypes, []reflect.Type{reflectValueType, reflectValueType}, funcExpr.VarArg) // for adding env into saved function envFunc := runInfo.env // create a function that can be used by reflect.MakeFunc // this function is a translator that converts a function call into a vm run // returns slice of reflect.Type with two values: // return value of the function and error value of the run runVMFunction := func(in []reflect.Value) []reflect.Value { runInfo := runInfoStruct{ctx: in[0].Interface().(context.Context), env: envFunc.NewEnv(), stmt: funcExpr.Stmt, rv: nilValue} // add Params to newEnv, except last Params for i := 0; i < len(funcExpr.Params)-1; i++ { runInfo.rv = in[i+1].Interface().(reflect.Value) runInfo.env.defineValue(funcExpr.Params[i], runInfo.rv) } // add last Params to newEnv if len(funcExpr.Params) > 0 { if funcExpr.VarArg { // function is variadic, add last Params to newEnv without convert to Interface and then reflect.Value runInfo.rv = in[len(funcExpr.Params)] runInfo.env.defineValue(funcExpr.Params[len(funcExpr.Params)-1], runInfo.rv) } else { // function is not variadic, add last Params to newEnv runInfo.rv = in[len(funcExpr.Params)].Interface().(reflect.Value) runInfo.env.defineValue(funcExpr.Params[len(funcExpr.Params)-1], runInfo.rv) } } // run function statements runInfo.runSingleStmt() if runInfo.err != nil && runInfo.err != ErrReturn { runInfo.err = newError(funcExpr, runInfo.err) // return nil value and error // need to do single reflect.ValueOf because nilValue is already reflect.Value of nil // need to do double reflect.ValueOf of newError in order to match return []reflect.Value{reflectValueNilValue, reflect.ValueOf(reflect.ValueOf(newError(funcExpr, runInfo.err)))} } // the reflect.ValueOf of rv is needed to work in the reflect.Value slice // reflectValueErrorNilValue is already a double reflect.ValueOf return []reflect.Value{reflect.ValueOf(runInfo.rv), reflectValueErrorNilValue} } // make the reflect.Value function that calls runVMFunction runInfo.rv = reflect.MakeFunc(funcType, runVMFunction) // if function name is not empty, define it in the env if funcExpr.Name != "" { runInfo.env.defineValue(funcExpr.Name, runInfo.rv) } }
go
func (runInfo *runInfoStruct) funcExpr() { funcExpr := runInfo.expr.(*ast.FuncExpr) // create the inTypes needed by reflect.FuncOf inTypes := make([]reflect.Type, len(funcExpr.Params)+1) // for runVMFunction first arg is always context inTypes[0] = contextType for i := 1; i < len(inTypes); i++ { inTypes[i] = reflectValueType } if funcExpr.VarArg { inTypes[len(inTypes)-1] = interfaceSliceType } // create funcType, output is always slice of reflect.Type with two values funcType := reflect.FuncOf(inTypes, []reflect.Type{reflectValueType, reflectValueType}, funcExpr.VarArg) // for adding env into saved function envFunc := runInfo.env // create a function that can be used by reflect.MakeFunc // this function is a translator that converts a function call into a vm run // returns slice of reflect.Type with two values: // return value of the function and error value of the run runVMFunction := func(in []reflect.Value) []reflect.Value { runInfo := runInfoStruct{ctx: in[0].Interface().(context.Context), env: envFunc.NewEnv(), stmt: funcExpr.Stmt, rv: nilValue} // add Params to newEnv, except last Params for i := 0; i < len(funcExpr.Params)-1; i++ { runInfo.rv = in[i+1].Interface().(reflect.Value) runInfo.env.defineValue(funcExpr.Params[i], runInfo.rv) } // add last Params to newEnv if len(funcExpr.Params) > 0 { if funcExpr.VarArg { // function is variadic, add last Params to newEnv without convert to Interface and then reflect.Value runInfo.rv = in[len(funcExpr.Params)] runInfo.env.defineValue(funcExpr.Params[len(funcExpr.Params)-1], runInfo.rv) } else { // function is not variadic, add last Params to newEnv runInfo.rv = in[len(funcExpr.Params)].Interface().(reflect.Value) runInfo.env.defineValue(funcExpr.Params[len(funcExpr.Params)-1], runInfo.rv) } } // run function statements runInfo.runSingleStmt() if runInfo.err != nil && runInfo.err != ErrReturn { runInfo.err = newError(funcExpr, runInfo.err) // return nil value and error // need to do single reflect.ValueOf because nilValue is already reflect.Value of nil // need to do double reflect.ValueOf of newError in order to match return []reflect.Value{reflectValueNilValue, reflect.ValueOf(reflect.ValueOf(newError(funcExpr, runInfo.err)))} } // the reflect.ValueOf of rv is needed to work in the reflect.Value slice // reflectValueErrorNilValue is already a double reflect.ValueOf return []reflect.Value{reflect.ValueOf(runInfo.rv), reflectValueErrorNilValue} } // make the reflect.Value function that calls runVMFunction runInfo.rv = reflect.MakeFunc(funcType, runVMFunction) // if function name is not empty, define it in the env if funcExpr.Name != "" { runInfo.env.defineValue(funcExpr.Name, runInfo.rv) } }
[ "func", "(", "runInfo", "*", "runInfoStruct", ")", "funcExpr", "(", ")", "{", "funcExpr", ":=", "runInfo", ".", "expr", ".", "(", "*", "ast", ".", "FuncExpr", ")", "\n\n", "// create the inTypes needed by reflect.FuncOf", "inTypes", ":=", "make", "(", "[", "]", "reflect", ".", "Type", ",", "len", "(", "funcExpr", ".", "Params", ")", "+", "1", ")", "\n", "// for runVMFunction first arg is always context", "inTypes", "[", "0", "]", "=", "contextType", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "inTypes", ")", ";", "i", "++", "{", "inTypes", "[", "i", "]", "=", "reflectValueType", "\n", "}", "\n", "if", "funcExpr", ".", "VarArg", "{", "inTypes", "[", "len", "(", "inTypes", ")", "-", "1", "]", "=", "interfaceSliceType", "\n", "}", "\n", "// create funcType, output is always slice of reflect.Type with two values", "funcType", ":=", "reflect", ".", "FuncOf", "(", "inTypes", ",", "[", "]", "reflect", ".", "Type", "{", "reflectValueType", ",", "reflectValueType", "}", ",", "funcExpr", ".", "VarArg", ")", "\n\n", "// for adding env into saved function", "envFunc", ":=", "runInfo", ".", "env", "\n\n", "// create a function that can be used by reflect.MakeFunc", "// this function is a translator that converts a function call into a vm run", "// returns slice of reflect.Type with two values:", "// return value of the function and error value of the run", "runVMFunction", ":=", "func", "(", "in", "[", "]", "reflect", ".", "Value", ")", "[", "]", "reflect", ".", "Value", "{", "runInfo", ":=", "runInfoStruct", "{", "ctx", ":", "in", "[", "0", "]", ".", "Interface", "(", ")", ".", "(", "context", ".", "Context", ")", ",", "env", ":", "envFunc", ".", "NewEnv", "(", ")", ",", "stmt", ":", "funcExpr", ".", "Stmt", ",", "rv", ":", "nilValue", "}", "\n\n", "// add Params to newEnv, except last Params", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "funcExpr", ".", "Params", ")", "-", "1", ";", "i", "++", "{", "runInfo", ".", "rv", "=", "in", "[", "i", "+", "1", "]", ".", "Interface", "(", ")", ".", "(", "reflect", ".", "Value", ")", "\n", "runInfo", ".", "env", ".", "defineValue", "(", "funcExpr", ".", "Params", "[", "i", "]", ",", "runInfo", ".", "rv", ")", "\n", "}", "\n", "// add last Params to newEnv", "if", "len", "(", "funcExpr", ".", "Params", ")", ">", "0", "{", "if", "funcExpr", ".", "VarArg", "{", "// function is variadic, add last Params to newEnv without convert to Interface and then reflect.Value", "runInfo", ".", "rv", "=", "in", "[", "len", "(", "funcExpr", ".", "Params", ")", "]", "\n", "runInfo", ".", "env", ".", "defineValue", "(", "funcExpr", ".", "Params", "[", "len", "(", "funcExpr", ".", "Params", ")", "-", "1", "]", ",", "runInfo", ".", "rv", ")", "\n", "}", "else", "{", "// function is not variadic, add last Params to newEnv", "runInfo", ".", "rv", "=", "in", "[", "len", "(", "funcExpr", ".", "Params", ")", "]", ".", "Interface", "(", ")", ".", "(", "reflect", ".", "Value", ")", "\n", "runInfo", ".", "env", ".", "defineValue", "(", "funcExpr", ".", "Params", "[", "len", "(", "funcExpr", ".", "Params", ")", "-", "1", "]", ",", "runInfo", ".", "rv", ")", "\n", "}", "\n", "}", "\n\n", "// run function statements", "runInfo", ".", "runSingleStmt", "(", ")", "\n", "if", "runInfo", ".", "err", "!=", "nil", "&&", "runInfo", ".", "err", "!=", "ErrReturn", "{", "runInfo", ".", "err", "=", "newError", "(", "funcExpr", ",", "runInfo", ".", "err", ")", "\n", "// return nil value and error", "// need to do single reflect.ValueOf because nilValue is already reflect.Value of nil", "// need to do double reflect.ValueOf of newError in order to match", "return", "[", "]", "reflect", ".", "Value", "{", "reflectValueNilValue", ",", "reflect", ".", "ValueOf", "(", "reflect", ".", "ValueOf", "(", "newError", "(", "funcExpr", ",", "runInfo", ".", "err", ")", ")", ")", "}", "\n", "}", "\n\n", "// the reflect.ValueOf of rv is needed to work in the reflect.Value slice", "// reflectValueErrorNilValue is already a double reflect.ValueOf", "return", "[", "]", "reflect", ".", "Value", "{", "reflect", ".", "ValueOf", "(", "runInfo", ".", "rv", ")", ",", "reflectValueErrorNilValue", "}", "\n", "}", "\n\n", "// make the reflect.Value function that calls runVMFunction", "runInfo", ".", "rv", "=", "reflect", ".", "MakeFunc", "(", "funcType", ",", "runVMFunction", ")", "\n\n", "// if function name is not empty, define it in the env", "if", "funcExpr", ".", "Name", "!=", "\"", "\"", "{", "runInfo", ".", "env", ".", "defineValue", "(", "funcExpr", ".", "Name", ",", "runInfo", ".", "rv", ")", "\n", "}", "\n", "}" ]
// funcExpr creates a function that reflect Call can use. // When called, it will run runVMFunction, to run the function statements
[ "funcExpr", "creates", "a", "function", "that", "reflect", "Call", "can", "use", ".", "When", "called", "it", "will", "run", "runVMFunction", "to", "run", "the", "function", "statements" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmExprFunction.go#L14-L80
7,545
mattn/anko
vm/vmExprFunction.go
anonCallExpr
func (runInfo *runInfoStruct) anonCallExpr() { anonCallExpr := runInfo.expr.(*ast.AnonCallExpr) runInfo.expr = anonCallExpr.Expr runInfo.invokeExpr() if runInfo.err != nil { return } if runInfo.rv.Kind() == reflect.Interface && !runInfo.rv.IsNil() { runInfo.rv = runInfo.rv.Elem() } if runInfo.rv.Kind() != reflect.Func { runInfo.err = newStringError(anonCallExpr, "cannot call type "+runInfo.rv.Kind().String()) runInfo.rv = nilValue return } runInfo.expr = &ast.CallExpr{Func: runInfo.rv, SubExprs: anonCallExpr.SubExprs, VarArg: anonCallExpr.VarArg, Go: anonCallExpr.Go} runInfo.invokeExpr() }
go
func (runInfo *runInfoStruct) anonCallExpr() { anonCallExpr := runInfo.expr.(*ast.AnonCallExpr) runInfo.expr = anonCallExpr.Expr runInfo.invokeExpr() if runInfo.err != nil { return } if runInfo.rv.Kind() == reflect.Interface && !runInfo.rv.IsNil() { runInfo.rv = runInfo.rv.Elem() } if runInfo.rv.Kind() != reflect.Func { runInfo.err = newStringError(anonCallExpr, "cannot call type "+runInfo.rv.Kind().String()) runInfo.rv = nilValue return } runInfo.expr = &ast.CallExpr{Func: runInfo.rv, SubExprs: anonCallExpr.SubExprs, VarArg: anonCallExpr.VarArg, Go: anonCallExpr.Go} runInfo.invokeExpr() }
[ "func", "(", "runInfo", "*", "runInfoStruct", ")", "anonCallExpr", "(", ")", "{", "anonCallExpr", ":=", "runInfo", ".", "expr", ".", "(", "*", "ast", ".", "AnonCallExpr", ")", "\n\n", "runInfo", ".", "expr", "=", "anonCallExpr", ".", "Expr", "\n", "runInfo", ".", "invokeExpr", "(", ")", "\n", "if", "runInfo", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "runInfo", ".", "rv", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "&&", "!", "runInfo", ".", "rv", ".", "IsNil", "(", ")", "{", "runInfo", ".", "rv", "=", "runInfo", ".", "rv", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "runInfo", ".", "rv", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "runInfo", ".", "err", "=", "newStringError", "(", "anonCallExpr", ",", "\"", "\"", "+", "runInfo", ".", "rv", ".", "Kind", "(", ")", ".", "String", "(", ")", ")", "\n", "runInfo", ".", "rv", "=", "nilValue", "\n", "return", "\n", "}", "\n\n", "runInfo", ".", "expr", "=", "&", "ast", ".", "CallExpr", "{", "Func", ":", "runInfo", ".", "rv", ",", "SubExprs", ":", "anonCallExpr", ".", "SubExprs", ",", "VarArg", ":", "anonCallExpr", ".", "VarArg", ",", "Go", ":", "anonCallExpr", ".", "Go", "}", "\n", "runInfo", ".", "invokeExpr", "(", ")", "\n", "}" ]
// anonCallExpr handles ast.AnonCallExpr which calls a function anonymously
[ "anonCallExpr", "handles", "ast", ".", "AnonCallExpr", "which", "calls", "a", "function", "anonymously" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmExprFunction.go#L83-L103
7,546
mattn/anko
vm/vmExprFunction.go
checkIfRunVMFunction
func checkIfRunVMFunction(rt reflect.Type) bool { if rt.NumIn() < 1 || rt.NumOut() != 2 || rt.In(0) != contextType || rt.Out(0) != reflectValueType || rt.Out(1) != reflectValueType { return false } if rt.NumIn() > 1 { if rt.IsVariadic() { if rt.In(rt.NumIn()-1) != interfaceSliceType { return false } } else { if rt.In(rt.NumIn()-1) != reflectValueType { return false } } for i := 1; i < rt.NumIn()-1; i++ { if rt.In(i) != reflectValueType { return false } } } return true }
go
func checkIfRunVMFunction(rt reflect.Type) bool { if rt.NumIn() < 1 || rt.NumOut() != 2 || rt.In(0) != contextType || rt.Out(0) != reflectValueType || rt.Out(1) != reflectValueType { return false } if rt.NumIn() > 1 { if rt.IsVariadic() { if rt.In(rt.NumIn()-1) != interfaceSliceType { return false } } else { if rt.In(rt.NumIn()-1) != reflectValueType { return false } } for i := 1; i < rt.NumIn()-1; i++ { if rt.In(i) != reflectValueType { return false } } } return true }
[ "func", "checkIfRunVMFunction", "(", "rt", "reflect", ".", "Type", ")", "bool", "{", "if", "rt", ".", "NumIn", "(", ")", "<", "1", "||", "rt", ".", "NumOut", "(", ")", "!=", "2", "||", "rt", ".", "In", "(", "0", ")", "!=", "contextType", "||", "rt", ".", "Out", "(", "0", ")", "!=", "reflectValueType", "||", "rt", ".", "Out", "(", "1", ")", "!=", "reflectValueType", "{", "return", "false", "\n", "}", "\n", "if", "rt", ".", "NumIn", "(", ")", ">", "1", "{", "if", "rt", ".", "IsVariadic", "(", ")", "{", "if", "rt", ".", "In", "(", "rt", ".", "NumIn", "(", ")", "-", "1", ")", "!=", "interfaceSliceType", "{", "return", "false", "\n", "}", "\n", "}", "else", "{", "if", "rt", ".", "In", "(", "rt", ".", "NumIn", "(", ")", "-", "1", ")", "!=", "reflectValueType", "{", "return", "false", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "rt", ".", "NumIn", "(", ")", "-", "1", ";", "i", "++", "{", "if", "rt", ".", "In", "(", "i", ")", "!=", "reflectValueType", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// checkIfRunVMFunction checking the number and types of the reflect.Type. // If it matches the types for a runVMFunction this will return true, otherwise false
[ "checkIfRunVMFunction", "checking", "the", "number", "and", "types", "of", "the", "reflect", ".", "Type", ".", "If", "it", "matches", "the", "types", "for", "a", "runVMFunction", "this", "will", "return", "true", "otherwise", "false" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/vmExprFunction.go#L189-L210
7,547
mattn/anko
vm/env.go
NewEnv
func NewEnv() *Env { return &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: nil, } }
go
func NewEnv() *Env { return &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: nil, } }
[ "func", "NewEnv", "(", ")", "*", "Env", "{", "return", "&", "Env", "{", "env", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", ",", "typ", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", ",", "parent", ":", "nil", ",", "}", "\n", "}" ]
// NewEnv creates new global scope.
[ "NewEnv", "creates", "new", "global", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L48-L54
7,548
mattn/anko
vm/env.go
NewEnv
func (e *Env) NewEnv() *Env { return &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: e, name: e.name, } }
go
func (e *Env) NewEnv() *Env { return &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: e, name: e.name, } }
[ "func", "(", "e", "*", "Env", ")", "NewEnv", "(", ")", "*", "Env", "{", "return", "&", "Env", "{", "env", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", ",", "typ", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", ",", "parent", ":", "e", ",", "name", ":", "e", ".", "name", ",", "}", "\n", "}" ]
// NewEnv creates new child scope.
[ "NewEnv", "creates", "new", "child", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L57-L64
7,549
mattn/anko
vm/env.go
NewPackage
func NewPackage(n string) *Env { return &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: nil, name: n, } }
go
func NewPackage(n string) *Env { return &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: nil, name: n, } }
[ "func", "NewPackage", "(", "n", "string", ")", "*", "Env", "{", "return", "&", "Env", "{", "env", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", ",", "typ", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", ",", "parent", ":", "nil", ",", "name", ":", "n", ",", "}", "\n", "}" ]
// NewPackage creates a new env with a name
[ "NewPackage", "creates", "a", "new", "env", "with", "a", "name" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L67-L74
7,550
mattn/anko
vm/env.go
AddPackage
func (e *Env) AddPackage(name string, methods map[string]interface{}, types map[string]interface{}) (*Env, error) { if strings.Contains(name, ".") { return nil, fmt.Errorf("unknown symbol '%s'", name) } var err error pack := e.NewPackage(name) for methodName, methodValue := range methods { err = pack.Define(methodName, methodValue) if err != nil { return pack, err } } for typeName, typeValue := range types { err = pack.DefineType(typeName, typeValue) if err != nil { return pack, err } } // can ignore error from Define because of check at the start of the function e.Define(name, pack) return pack, nil }
go
func (e *Env) AddPackage(name string, methods map[string]interface{}, types map[string]interface{}) (*Env, error) { if strings.Contains(name, ".") { return nil, fmt.Errorf("unknown symbol '%s'", name) } var err error pack := e.NewPackage(name) for methodName, methodValue := range methods { err = pack.Define(methodName, methodValue) if err != nil { return pack, err } } for typeName, typeValue := range types { err = pack.DefineType(typeName, typeValue) if err != nil { return pack, err } } // can ignore error from Define because of check at the start of the function e.Define(name, pack) return pack, nil }
[ "func", "(", "e", "*", "Env", ")", "AddPackage", "(", "name", "string", ",", "methods", "map", "[", "string", "]", "interface", "{", "}", ",", "types", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "*", "Env", ",", "error", ")", "{", "if", "strings", ".", "Contains", "(", "name", ",", "\"", "\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "var", "err", "error", "\n", "pack", ":=", "e", ".", "NewPackage", "(", "name", ")", "\n\n", "for", "methodName", ",", "methodValue", ":=", "range", "methods", "{", "err", "=", "pack", ".", "Define", "(", "methodName", ",", "methodValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "pack", ",", "err", "\n", "}", "\n", "}", "\n", "for", "typeName", ",", "typeValue", ":=", "range", "types", "{", "err", "=", "pack", ".", "DefineType", "(", "typeName", ",", "typeValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "pack", ",", "err", "\n", "}", "\n", "}", "\n\n", "// can ignore error from Define because of check at the start of the function", "e", ".", "Define", "(", "name", ",", "pack", ")", "\n", "return", "pack", ",", "nil", "\n", "}" ]
// AddPackage creates a new env with a name that has methods and types in it. Created under the parent env
[ "AddPackage", "creates", "a", "new", "env", "with", "a", "name", "that", "has", "methods", "and", "types", "in", "it", ".", "Created", "under", "the", "parent", "env" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L87-L110
7,551
mattn/anko
vm/env.go
NewModule
func (e *Env) NewModule(n string) *Env { m := &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: e, name: n, } e.Define(n, m) return m }
go
func (e *Env) NewModule(n string) *Env { m := &Env{ env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: e, name: n, } e.Define(n, m) return m }
[ "func", "(", "e", "*", "Env", ")", "NewModule", "(", "n", "string", ")", "*", "Env", "{", "m", ":=", "&", "Env", "{", "env", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", ",", "typ", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", ",", "parent", ":", "e", ",", "name", ":", "n", ",", "}", "\n", "e", ".", "Define", "(", "n", ",", "m", ")", "\n", "return", "m", "\n", "}" ]
// NewModule creates new module.
[ "NewModule", "creates", "new", "module", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L118-L127
7,552
mattn/anko
vm/env.go
SetName
func (e *Env) SetName(n string) { e.Lock() e.name = n e.Unlock() }
go
func (e *Env) SetName(n string) { e.Lock() e.name = n e.Unlock() }
[ "func", "(", "e", "*", "Env", ")", "SetName", "(", "n", "string", ")", "{", "e", ".", "Lock", "(", ")", "\n", "e", ".", "name", "=", "n", "\n", "e", ".", "Unlock", "(", ")", "\n", "}" ]
// SetName sets a name of the scope. This means that the scope is module.
[ "SetName", "sets", "a", "name", "of", "the", "scope", ".", "This", "means", "that", "the", "scope", "is", "module", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L130-L134
7,553
mattn/anko
vm/env.go
GetName
func (e *Env) GetName() string { e.RLock() defer e.RUnlock() return e.name }
go
func (e *Env) GetName() string { e.RLock() defer e.RUnlock() return e.name }
[ "func", "(", "e", "*", "Env", ")", "GetName", "(", ")", "string", "{", "e", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "RUnlock", "(", ")", "\n\n", "return", "e", ".", "name", "\n", "}" ]
// GetName returns module name.
[ "GetName", "returns", "module", "name", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L137-L142
7,554
mattn/anko
vm/env.go
Addr
func (e *Env) Addr(k string) (reflect.Value, error) { e.RLock() defer e.RUnlock() if v, ok := e.env[k]; ok { if v.CanAddr() { return v.Addr(), nil } return nilValue, fmt.Errorf("unaddressable") } if e.external != nil { v, err := e.external.Get(k) if err == nil { if v.CanAddr() { return v.Addr(), nil } return nilValue, fmt.Errorf("unaddressable") } } if e.parent == nil { return nilValue, fmt.Errorf("undefined symbol '%s'", k) } return e.parent.Addr(k) }
go
func (e *Env) Addr(k string) (reflect.Value, error) { e.RLock() defer e.RUnlock() if v, ok := e.env[k]; ok { if v.CanAddr() { return v.Addr(), nil } return nilValue, fmt.Errorf("unaddressable") } if e.external != nil { v, err := e.external.Get(k) if err == nil { if v.CanAddr() { return v.Addr(), nil } return nilValue, fmt.Errorf("unaddressable") } } if e.parent == nil { return nilValue, fmt.Errorf("undefined symbol '%s'", k) } return e.parent.Addr(k) }
[ "func", "(", "e", "*", "Env", ")", "Addr", "(", "k", "string", ")", "(", "reflect", ".", "Value", ",", "error", ")", "{", "e", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "RUnlock", "(", ")", "\n\n", "if", "v", ",", "ok", ":=", "e", ".", "env", "[", "k", "]", ";", "ok", "{", "if", "v", ".", "CanAddr", "(", ")", "{", "return", "v", ".", "Addr", "(", ")", ",", "nil", "\n", "}", "\n", "return", "nilValue", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "e", ".", "external", "!=", "nil", "{", "v", ",", "err", ":=", "e", ".", "external", ".", "Get", "(", "k", ")", "\n", "if", "err", "==", "nil", "{", "if", "v", ".", "CanAddr", "(", ")", "{", "return", "v", ".", "Addr", "(", ")", ",", "nil", "\n", "}", "\n", "return", "nilValue", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "e", ".", "parent", "==", "nil", "{", "return", "nilValue", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "return", "e", ".", "parent", ".", "Addr", "(", "k", ")", "\n", "}" ]
// Addr returns pointer value which specified symbol. It goes to upper scope until // found or returns error.
[ "Addr", "returns", "pointer", "value", "which", "specified", "symbol", ".", "It", "goes", "to", "upper", "scope", "until", "found", "or", "returns", "error", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L146-L169
7,555
mattn/anko
vm/env.go
Type
func (e *Env) Type(k string) (reflect.Type, error) { e.RLock() defer e.RUnlock() if v, ok := e.typ[k]; ok { return v, nil } if e.external != nil { v, err := e.external.Type(k) if err == nil { return v, nil } } if e.parent == nil { if v, ok := basicTypes[k]; ok { return v, nil } return nilType, fmt.Errorf("undefined type '%s'", k) } return e.parent.Type(k) }
go
func (e *Env) Type(k string) (reflect.Type, error) { e.RLock() defer e.RUnlock() if v, ok := e.typ[k]; ok { return v, nil } if e.external != nil { v, err := e.external.Type(k) if err == nil { return v, nil } } if e.parent == nil { if v, ok := basicTypes[k]; ok { return v, nil } return nilType, fmt.Errorf("undefined type '%s'", k) } return e.parent.Type(k) }
[ "func", "(", "e", "*", "Env", ")", "Type", "(", "k", "string", ")", "(", "reflect", ".", "Type", ",", "error", ")", "{", "e", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "RUnlock", "(", ")", "\n\n", "if", "v", ",", "ok", ":=", "e", ".", "typ", "[", "k", "]", ";", "ok", "{", "return", "v", ",", "nil", "\n", "}", "\n", "if", "e", ".", "external", "!=", "nil", "{", "v", ",", "err", ":=", "e", ".", "external", ".", "Type", "(", "k", ")", "\n", "if", "err", "==", "nil", "{", "return", "v", ",", "nil", "\n", "}", "\n", "}", "\n", "if", "e", ".", "parent", "==", "nil", "{", "if", "v", ",", "ok", ":=", "basicTypes", "[", "k", "]", ";", "ok", "{", "return", "v", ",", "nil", "\n", "}", "\n", "return", "nilType", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "return", "e", ".", "parent", ".", "Type", "(", "k", ")", "\n", "}" ]
// Type returns type which specified symbol. It goes to upper scope until // found or returns error.
[ "Type", "returns", "type", "which", "specified", "symbol", ".", "It", "goes", "to", "upper", "scope", "until", "found", "or", "returns", "error", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L173-L193
7,556
mattn/anko
vm/env.go
Get
func (e *Env) Get(k string) (interface{}, error) { rv, err := e.get(k) return rv.Interface(), err }
go
func (e *Env) Get(k string) (interface{}, error) { rv, err := e.get(k) return rv.Interface(), err }
[ "func", "(", "e", "*", "Env", ")", "Get", "(", "k", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "rv", ",", "err", ":=", "e", ".", "get", "(", "k", ")", "\n", "return", "rv", ".", "Interface", "(", ")", ",", "err", "\n", "}" ]
// Get returns value which specified symbol. It goes to upper scope until // found or returns error.
[ "Get", "returns", "value", "which", "specified", "symbol", ".", "It", "goes", "to", "upper", "scope", "until", "found", "or", "returns", "error", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L197-L200
7,557
mattn/anko
vm/env.go
Set
func (e *Env) Set(k string, v interface{}) error { if v == nil { return e.setValue(k, nilValue) } return e.setValue(k, reflect.ValueOf(v)) }
go
func (e *Env) Set(k string, v interface{}) error { if v == nil { return e.setValue(k, nilValue) } return e.setValue(k, reflect.ValueOf(v)) }
[ "func", "(", "e", "*", "Env", ")", "Set", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "e", ".", "setValue", "(", "k", ",", "nilValue", ")", "\n", "}", "\n", "return", "e", ".", "setValue", "(", "k", ",", "reflect", ".", "ValueOf", "(", "v", ")", ")", "\n", "}" ]
// Set modifies value which specified as symbol. It goes to upper scope until // found or returns error.
[ "Set", "modifies", "value", "which", "specified", "as", "symbol", ".", "It", "goes", "to", "upper", "scope", "until", "found", "or", "returns", "error", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L223-L228
7,558
mattn/anko
vm/env.go
DefineGlobal
func (e *Env) DefineGlobal(k string, v interface{}) error { for e.parent != nil { e = e.parent } return e.Define(k, v) }
go
func (e *Env) DefineGlobal(k string, v interface{}) error { for e.parent != nil { e = e.parent } return e.Define(k, v) }
[ "func", "(", "e", "*", "Env", ")", "DefineGlobal", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "for", "e", ".", "parent", "!=", "nil", "{", "e", "=", "e", ".", "parent", "\n", "}", "\n", "return", "e", ".", "Define", "(", "k", ",", "v", ")", "\n", "}" ]
// DefineGlobal defines symbol in global scope.
[ "DefineGlobal", "defines", "symbol", "in", "global", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L247-L252
7,559
mattn/anko
vm/env.go
defineGlobalValue
func (e *Env) defineGlobalValue(k string, v reflect.Value) error { for e.parent != nil { e = e.parent } return e.defineValue(k, v) }
go
func (e *Env) defineGlobalValue(k string, v reflect.Value) error { for e.parent != nil { e = e.parent } return e.defineValue(k, v) }
[ "func", "(", "e", "*", "Env", ")", "defineGlobalValue", "(", "k", "string", ",", "v", "reflect", ".", "Value", ")", "error", "{", "for", "e", ".", "parent", "!=", "nil", "{", "e", "=", "e", ".", "parent", "\n", "}", "\n", "return", "e", ".", "defineValue", "(", "k", ",", "v", ")", "\n", "}" ]
// defineGlobalValue defines symbol in global scope.
[ "defineGlobalValue", "defines", "symbol", "in", "global", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L255-L260
7,560
mattn/anko
vm/env.go
Define
func (e *Env) Define(k string, v interface{}) error { if v == nil { return e.defineValue(k, nilValue) } return e.defineValue(k, reflect.ValueOf(v)) }
go
func (e *Env) Define(k string, v interface{}) error { if v == nil { return e.defineValue(k, nilValue) } return e.defineValue(k, reflect.ValueOf(v)) }
[ "func", "(", "e", "*", "Env", ")", "Define", "(", "k", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "if", "v", "==", "nil", "{", "return", "e", ".", "defineValue", "(", "k", ",", "nilValue", ")", "\n", "}", "\n", "return", "e", ".", "defineValue", "(", "k", ",", "reflect", ".", "ValueOf", "(", "v", ")", ")", "\n", "}" ]
// Define defines symbol in current scope.
[ "Define", "defines", "symbol", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L263-L268
7,561
mattn/anko
vm/env.go
defineValue
func (e *Env) defineValue(k string, v reflect.Value) error { if strings.Contains(k, ".") { return fmt.Errorf("unknown symbol '%s'", k) } e.Lock() e.env[k] = v e.Unlock() return nil }
go
func (e *Env) defineValue(k string, v reflect.Value) error { if strings.Contains(k, ".") { return fmt.Errorf("unknown symbol '%s'", k) } e.Lock() e.env[k] = v e.Unlock() return nil }
[ "func", "(", "e", "*", "Env", ")", "defineValue", "(", "k", "string", ",", "v", "reflect", ".", "Value", ")", "error", "{", "if", "strings", ".", "Contains", "(", "k", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n\n", "e", ".", "Lock", "(", ")", "\n", "e", ".", "env", "[", "k", "]", "=", "v", "\n", "e", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// defineValue defines symbol in current scope.
[ "defineValue", "defines", "symbol", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L271-L281
7,562
mattn/anko
vm/env.go
Delete
func (e *Env) Delete(k string) error { if strings.Contains(k, ".") { return fmt.Errorf("Unknown symbol '%s'", k) } e.Lock() delete(e.env, k) e.Unlock() return nil }
go
func (e *Env) Delete(k string) error { if strings.Contains(k, ".") { return fmt.Errorf("Unknown symbol '%s'", k) } e.Lock() delete(e.env, k) e.Unlock() return nil }
[ "func", "(", "e", "*", "Env", ")", "Delete", "(", "k", "string", ")", "error", "{", "if", "strings", ".", "Contains", "(", "k", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n\n", "e", ".", "Lock", "(", ")", "\n", "delete", "(", "e", ".", "env", ",", "k", ")", "\n", "e", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Delete deletes symbol in current scope.
[ "Delete", "deletes", "symbol", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L284-L294
7,563
mattn/anko
vm/env.go
DeleteGlobal
func (e *Env) DeleteGlobal(k string) error { if e.parent == nil { return e.Delete(k) } e.RLock() _, ok := e.env[k] e.RUnlock() if ok { return e.Delete(k) } return e.parent.DeleteGlobal(k) }
go
func (e *Env) DeleteGlobal(k string) error { if e.parent == nil { return e.Delete(k) } e.RLock() _, ok := e.env[k] e.RUnlock() if ok { return e.Delete(k) } return e.parent.DeleteGlobal(k) }
[ "func", "(", "e", "*", "Env", ")", "DeleteGlobal", "(", "k", "string", ")", "error", "{", "if", "e", ".", "parent", "==", "nil", "{", "return", "e", ".", "Delete", "(", "k", ")", "\n", "}", "\n\n", "e", ".", "RLock", "(", ")", "\n", "_", ",", "ok", ":=", "e", ".", "env", "[", "k", "]", "\n", "e", ".", "RUnlock", "(", ")", "\n\n", "if", "ok", "{", "return", "e", ".", "Delete", "(", "k", ")", "\n", "}", "\n\n", "return", "e", ".", "parent", ".", "DeleteGlobal", "(", "k", ")", "\n", "}" ]
// DeleteGlobal deletes the first matching symbol found in current or parent scope.
[ "DeleteGlobal", "deletes", "the", "first", "matching", "symbol", "found", "in", "current", "or", "parent", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L297-L311
7,564
mattn/anko
vm/env.go
DefineGlobalType
func (e *Env) DefineGlobalType(k string, t interface{}) error { for e.parent != nil { e = e.parent } return e.DefineType(k, t) }
go
func (e *Env) DefineGlobalType(k string, t interface{}) error { for e.parent != nil { e = e.parent } return e.DefineType(k, t) }
[ "func", "(", "e", "*", "Env", ")", "DefineGlobalType", "(", "k", "string", ",", "t", "interface", "{", "}", ")", "error", "{", "for", "e", ".", "parent", "!=", "nil", "{", "e", "=", "e", ".", "parent", "\n", "}", "\n", "return", "e", ".", "DefineType", "(", "k", ",", "t", ")", "\n", "}" ]
// DefineGlobalType defines type in global scope.
[ "DefineGlobalType", "defines", "type", "in", "global", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L314-L319
7,565
mattn/anko
vm/env.go
DefineGlobalReflectType
func (e *Env) DefineGlobalReflectType(k string, t reflect.Type) error { for e.parent != nil { e = e.parent } return e.DefineReflectType(k, t) }
go
func (e *Env) DefineGlobalReflectType(k string, t reflect.Type) error { for e.parent != nil { e = e.parent } return e.DefineReflectType(k, t) }
[ "func", "(", "e", "*", "Env", ")", "DefineGlobalReflectType", "(", "k", "string", ",", "t", "reflect", ".", "Type", ")", "error", "{", "for", "e", ".", "parent", "!=", "nil", "{", "e", "=", "e", ".", "parent", "\n", "}", "\n", "return", "e", ".", "DefineReflectType", "(", "k", ",", "t", ")", "\n", "}" ]
// DefineGlobalReflectType defines type in global scope.
[ "DefineGlobalReflectType", "defines", "type", "in", "global", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L322-L327
7,566
mattn/anko
vm/env.go
DefineType
func (e *Env) DefineType(k string, t interface{}) error { var typ reflect.Type if t == nil { typ = nilType } else { var ok bool typ, ok = t.(reflect.Type) if !ok { typ = reflect.TypeOf(t) } } return e.DefineReflectType(k, typ) }
go
func (e *Env) DefineType(k string, t interface{}) error { var typ reflect.Type if t == nil { typ = nilType } else { var ok bool typ, ok = t.(reflect.Type) if !ok { typ = reflect.TypeOf(t) } } return e.DefineReflectType(k, typ) }
[ "func", "(", "e", "*", "Env", ")", "DefineType", "(", "k", "string", ",", "t", "interface", "{", "}", ")", "error", "{", "var", "typ", "reflect", ".", "Type", "\n", "if", "t", "==", "nil", "{", "typ", "=", "nilType", "\n", "}", "else", "{", "var", "ok", "bool", "\n", "typ", ",", "ok", "=", "t", ".", "(", "reflect", ".", "Type", ")", "\n", "if", "!", "ok", "{", "typ", "=", "reflect", ".", "TypeOf", "(", "t", ")", "\n", "}", "\n", "}", "\n\n", "return", "e", ".", "DefineReflectType", "(", "k", ",", "typ", ")", "\n", "}" ]
// DefineType defines type in current scope.
[ "DefineType", "defines", "type", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L330-L343
7,567
mattn/anko
vm/env.go
DefineReflectType
func (e *Env) DefineReflectType(k string, t reflect.Type) error { if strings.Contains(k, ".") { return fmt.Errorf("unknown symbol '%s'", k) } e.Lock() e.typ[k] = t e.Unlock() return nil }
go
func (e *Env) DefineReflectType(k string, t reflect.Type) error { if strings.Contains(k, ".") { return fmt.Errorf("unknown symbol '%s'", k) } e.Lock() e.typ[k] = t e.Unlock() return nil }
[ "func", "(", "e", "*", "Env", ")", "DefineReflectType", "(", "k", "string", ",", "t", "reflect", ".", "Type", ")", "error", "{", "if", "strings", ".", "Contains", "(", "k", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n\n", "e", ".", "Lock", "(", ")", "\n", "e", ".", "typ", "[", "k", "]", "=", "t", "\n", "e", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// DefineReflectType defines type in current scope.
[ "DefineReflectType", "defines", "type", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L346-L356
7,568
mattn/anko
vm/env.go
String
func (e *Env) String() string { e.RLock() defer e.RUnlock() return e.name }
go
func (e *Env) String() string { e.RLock() defer e.RUnlock() return e.name }
[ "func", "(", "e", "*", "Env", ")", "String", "(", ")", "string", "{", "e", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "RUnlock", "(", ")", "\n\n", "return", "e", ".", "name", "\n", "}" ]
// String return the name of current scope.
[ "String", "return", "the", "name", "of", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L359-L364
7,569
mattn/anko
vm/env.go
Dump
func (e *Env) Dump() { e.RLock() fmt.Printf("Name: %v\n", e.name) fmt.Printf("Has parent: %v\n", e.parent != nil) for k, v := range e.env { fmt.Printf("%v = %#v\n", k, v) } e.RUnlock() }
go
func (e *Env) Dump() { e.RLock() fmt.Printf("Name: %v\n", e.name) fmt.Printf("Has parent: %v\n", e.parent != nil) for k, v := range e.env { fmt.Printf("%v = %#v\n", k, v) } e.RUnlock() }
[ "func", "(", "e", "*", "Env", ")", "Dump", "(", ")", "{", "e", ".", "RLock", "(", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "e", ".", "name", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "e", ".", "parent", "!=", "nil", ")", "\n", "for", "k", ",", "v", ":=", "range", "e", ".", "env", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "e", ".", "RUnlock", "(", ")", "\n", "}" ]
// Dump show symbol values in the scope.
[ "Dump", "show", "symbol", "values", "in", "the", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L367-L375
7,570
mattn/anko
vm/env.go
Execute
func (e *Env) Execute(src string) (interface{}, error) { return e.ExecuteContext(context.Background(), src) }
go
func (e *Env) Execute(src string) (interface{}, error) { return e.ExecuteContext(context.Background(), src) }
[ "func", "(", "e", "*", "Env", ")", "Execute", "(", "src", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "e", ".", "ExecuteContext", "(", "context", ".", "Background", "(", ")", ",", "src", ")", "\n", "}" ]
// Execute parses and runs source in current scope.
[ "Execute", "parses", "and", "runs", "source", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L378-L380
7,571
mattn/anko
vm/env.go
ExecuteContext
func (e *Env) ExecuteContext(ctx context.Context, src string) (interface{}, error) { stmt, err := parser.ParseSrc(src) if err != nil { return nilValue, err } return RunContext(ctx, stmt, e) }
go
func (e *Env) ExecuteContext(ctx context.Context, src string) (interface{}, error) { stmt, err := parser.ParseSrc(src) if err != nil { return nilValue, err } return RunContext(ctx, stmt, e) }
[ "func", "(", "e", "*", "Env", ")", "ExecuteContext", "(", "ctx", "context", ".", "Context", ",", "src", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "stmt", ",", "err", ":=", "parser", ".", "ParseSrc", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nilValue", ",", "err", "\n", "}", "\n", "return", "RunContext", "(", "ctx", ",", "stmt", ",", "e", ")", "\n", "}" ]
// ExecuteContext parses and runs source in current scope.
[ "ExecuteContext", "parses", "and", "runs", "source", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L383-L389
7,572
mattn/anko
vm/env.go
RunContext
func (e *Env) RunContext(ctx context.Context, stmt ast.Stmt) (interface{}, error) { return RunContext(ctx, stmt, e) }
go
func (e *Env) RunContext(ctx context.Context, stmt ast.Stmt) (interface{}, error) { return RunContext(ctx, stmt, e) }
[ "func", "(", "e", "*", "Env", ")", "RunContext", "(", "ctx", "context", ".", "Context", ",", "stmt", "ast", ".", "Stmt", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "RunContext", "(", "ctx", ",", "stmt", ",", "e", ")", "\n", "}" ]
// RunContext runs statement in current scope.
[ "RunContext", "runs", "statement", "in", "current", "scope", "." ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L397-L399
7,573
mattn/anko
vm/env.go
Copy
func (e *Env) Copy() *Env { e.Lock() defer e.Unlock() copy := Env{ name: e.name, env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: e.parent, external: e.external, } for name, value := range e.env { copy.env[name] = value } for name, typ := range e.typ { copy.typ[name] = typ } return &copy }
go
func (e *Env) Copy() *Env { e.Lock() defer e.Unlock() copy := Env{ name: e.name, env: make(map[string]reflect.Value), typ: make(map[string]reflect.Type), parent: e.parent, external: e.external, } for name, value := range e.env { copy.env[name] = value } for name, typ := range e.typ { copy.typ[name] = typ } return &copy }
[ "func", "(", "e", "*", "Env", ")", "Copy", "(", ")", "*", "Env", "{", "e", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "Unlock", "(", ")", "\n", "copy", ":=", "Env", "{", "name", ":", "e", ".", "name", ",", "env", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Value", ")", ",", "typ", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", ",", "parent", ":", "e", ".", "parent", ",", "external", ":", "e", ".", "external", ",", "}", "\n", "for", "name", ",", "value", ":=", "range", "e", ".", "env", "{", "copy", ".", "env", "[", "name", "]", "=", "value", "\n", "}", "\n", "for", "name", ",", "typ", ":=", "range", "e", ".", "typ", "{", "copy", ".", "typ", "[", "name", "]", "=", "typ", "\n", "}", "\n", "return", "&", "copy", "\n", "}" ]
// Copy the state of the virtual machine environment
[ "Copy", "the", "state", "of", "the", "virtual", "machine", "environment" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L402-L419
7,574
mattn/anko
vm/env.go
DeepCopy
func (e *Env) DeepCopy() *Env { copy := e.Copy() if copy.parent != nil { copy.parent = copy.parent.DeepCopy() } return copy }
go
func (e *Env) DeepCopy() *Env { copy := e.Copy() if copy.parent != nil { copy.parent = copy.parent.DeepCopy() } return copy }
[ "func", "(", "e", "*", "Env", ")", "DeepCopy", "(", ")", "*", "Env", "{", "copy", ":=", "e", ".", "Copy", "(", ")", "\n", "if", "copy", ".", "parent", "!=", "nil", "{", "copy", ".", "parent", "=", "copy", ".", "parent", ".", "DeepCopy", "(", ")", "\n", "}", "\n", "return", "copy", "\n", "}" ]
// DeepCopy copy recursively the state of the virtual machine environment
[ "DeepCopy", "copy", "recursively", "the", "state", "of", "the", "virtual", "machine", "environment" ]
98bb0482ab4cd4fe854a932bbb0d818acc0e3338
https://github.com/mattn/anko/blob/98bb0482ab4cd4fe854a932bbb0d818acc0e3338/vm/env.go#L422-L428
7,575
gin-contrib/cors
cors.go
AddAllowMethods
func (c *Config) AddAllowMethods(methods ...string) { c.AllowMethods = append(c.AllowMethods, methods...) }
go
func (c *Config) AddAllowMethods(methods ...string) { c.AllowMethods = append(c.AllowMethods, methods...) }
[ "func", "(", "c", "*", "Config", ")", "AddAllowMethods", "(", "methods", "...", "string", ")", "{", "c", ".", "AllowMethods", "=", "append", "(", "c", ".", "AllowMethods", ",", "methods", "...", ")", "\n", "}" ]
// AddAllowMethods is allowed to add custom methods
[ "AddAllowMethods", "is", "allowed", "to", "add", "custom", "methods" ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L59-L61
7,576
gin-contrib/cors
cors.go
AddAllowHeaders
func (c *Config) AddAllowHeaders(headers ...string) { c.AllowHeaders = append(c.AllowHeaders, headers...) }
go
func (c *Config) AddAllowHeaders(headers ...string) { c.AllowHeaders = append(c.AllowHeaders, headers...) }
[ "func", "(", "c", "*", "Config", ")", "AddAllowHeaders", "(", "headers", "...", "string", ")", "{", "c", ".", "AllowHeaders", "=", "append", "(", "c", ".", "AllowHeaders", ",", "headers", "...", ")", "\n", "}" ]
// AddAllowHeaders is allowed to add custom headers
[ "AddAllowHeaders", "is", "allowed", "to", "add", "custom", "headers" ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L64-L66
7,577
gin-contrib/cors
cors.go
AddExposeHeaders
func (c *Config) AddExposeHeaders(headers ...string) { c.ExposeHeaders = append(c.ExposeHeaders, headers...) }
go
func (c *Config) AddExposeHeaders(headers ...string) { c.ExposeHeaders = append(c.ExposeHeaders, headers...) }
[ "func", "(", "c", "*", "Config", ")", "AddExposeHeaders", "(", "headers", "...", "string", ")", "{", "c", ".", "ExposeHeaders", "=", "append", "(", "c", ".", "ExposeHeaders", ",", "headers", "...", ")", "\n", "}" ]
// AddExposeHeaders is allowed to add custom expose headers
[ "AddExposeHeaders", "is", "allowed", "to", "add", "custom", "expose", "headers" ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L69-L71
7,578
gin-contrib/cors
cors.go
Validate
func (c *Config) Validate() error { if c.AllowAllOrigins && (c.AllowOriginFunc != nil || len(c.AllowOrigins) > 0) { return errors.New("conflict settings: all origins are allowed. AllowOriginFunc or AllowOrigins is not needed") } if !c.AllowAllOrigins && c.AllowOriginFunc == nil && len(c.AllowOrigins) == 0 { return errors.New("conflict settings: all origins disabled") } for _, origin := range c.AllowOrigins { if origin == "*" { c.AllowAllOrigins = true return nil } else if !strings.Contains(origin, "*") && !c.validateAllowedSchemas(origin) { return errors.New("bad origin: origins must contain '*' or include " + strings.Join(c.getAllowedSchemas(), ",")) } } return nil }
go
func (c *Config) Validate() error { if c.AllowAllOrigins && (c.AllowOriginFunc != nil || len(c.AllowOrigins) > 0) { return errors.New("conflict settings: all origins are allowed. AllowOriginFunc or AllowOrigins is not needed") } if !c.AllowAllOrigins && c.AllowOriginFunc == nil && len(c.AllowOrigins) == 0 { return errors.New("conflict settings: all origins disabled") } for _, origin := range c.AllowOrigins { if origin == "*" { c.AllowAllOrigins = true return nil } else if !strings.Contains(origin, "*") && !c.validateAllowedSchemas(origin) { return errors.New("bad origin: origins must contain '*' or include " + strings.Join(c.getAllowedSchemas(), ",")) } } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "AllowAllOrigins", "&&", "(", "c", ".", "AllowOriginFunc", "!=", "nil", "||", "len", "(", "c", ".", "AllowOrigins", ")", ">", "0", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "c", ".", "AllowAllOrigins", "&&", "c", ".", "AllowOriginFunc", "==", "nil", "&&", "len", "(", "c", ".", "AllowOrigins", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "origin", ":=", "range", "c", ".", "AllowOrigins", "{", "if", "origin", "==", "\"", "\"", "{", "c", ".", "AllowAllOrigins", "=", "true", "\n", "return", "nil", "\n", "}", "else", "if", "!", "strings", ".", "Contains", "(", "origin", ",", "\"", "\"", ")", "&&", "!", "c", ".", "validateAllowedSchemas", "(", "origin", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "strings", ".", "Join", "(", "c", ".", "getAllowedSchemas", "(", ")", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate is check configuration of user defined.
[ "Validate", "is", "check", "configuration", "of", "user", "defined", "." ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L98-L114
7,579
gin-contrib/cors
cors.go
DefaultConfig
func DefaultConfig() Config { return Config{ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"}, AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"}, AllowCredentials: false, MaxAge: 12 * time.Hour, } }
go
func DefaultConfig() Config { return Config{ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"}, AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"}, AllowCredentials: false, MaxAge: 12 * time.Hour, } }
[ "func", "DefaultConfig", "(", ")", "Config", "{", "return", "Config", "{", "AllowMethods", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "AllowHeaders", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "AllowCredentials", ":", "false", ",", "MaxAge", ":", "12", "*", "time", ".", "Hour", ",", "}", "\n", "}" ]
// DefaultConfig returns a generic default configuration mapped to localhost.
[ "DefaultConfig", "returns", "a", "generic", "default", "configuration", "mapped", "to", "localhost", "." ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L149-L156
7,580
gin-contrib/cors
cors.go
Default
func Default() gin.HandlerFunc { config := DefaultConfig() config.AllowAllOrigins = true return New(config) }
go
func Default() gin.HandlerFunc { config := DefaultConfig() config.AllowAllOrigins = true return New(config) }
[ "func", "Default", "(", ")", "gin", ".", "HandlerFunc", "{", "config", ":=", "DefaultConfig", "(", ")", "\n", "config", ".", "AllowAllOrigins", "=", "true", "\n", "return", "New", "(", "config", ")", "\n", "}" ]
// Default returns the location middleware with default configuration.
[ "Default", "returns", "the", "location", "middleware", "with", "default", "configuration", "." ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L159-L163
7,581
gin-contrib/cors
cors.go
New
func New(config Config) gin.HandlerFunc { cors := newCors(config) return func(c *gin.Context) { cors.applyCors(c) } }
go
func New(config Config) gin.HandlerFunc { cors := newCors(config) return func(c *gin.Context) { cors.applyCors(c) } }
[ "func", "New", "(", "config", "Config", ")", "gin", ".", "HandlerFunc", "{", "cors", ":=", "newCors", "(", "config", ")", "\n", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "cors", ".", "applyCors", "(", "c", ")", "\n", "}", "\n", "}" ]
// New returns the location middleware with user-defined custom configuration.
[ "New", "returns", "the", "location", "middleware", "with", "user", "-", "defined", "custom", "configuration", "." ]
bd1331c62cae84c40036ce4e7d95b15d62157d4e
https://github.com/gin-contrib/cors/blob/bd1331c62cae84c40036ce4e7d95b15d62157d4e/cors.go#L166-L171
7,582
pkg/profile
profile.go
MemProfileRate
func MemProfileRate(rate int) func(*Profile) { return func(p *Profile) { p.memProfileRate = rate p.mode = memMode } }
go
func MemProfileRate(rate int) func(*Profile) { return func(p *Profile) { p.memProfileRate = rate p.mode = memMode } }
[ "func", "MemProfileRate", "(", "rate", "int", ")", "func", "(", "*", "Profile", ")", "{", "return", "func", "(", "p", "*", "Profile", ")", "{", "p", ".", "memProfileRate", "=", "rate", "\n", "p", ".", "mode", "=", "memMode", "\n", "}", "\n", "}" ]
// MemProfileRate enables memory profiling at the preferred rate. // It disables any previous profiling settings.
[ "MemProfileRate", "enables", "memory", "profiling", "at", "the", "preferred", "rate", ".", "It", "disables", "any", "previous", "profiling", "settings", "." ]
f6fe06335df110bcf1ed6d4e852b760bfc15beee
https://github.com/pkg/profile/blob/f6fe06335df110bcf1ed6d4e852b760bfc15beee/profile.go#L78-L83
7,583
pkg/profile
profile.go
Stop
func (p *Profile) Stop() { if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) { // someone has already called close return } p.closer() atomic.StoreUint32(&started, 0) }
go
func (p *Profile) Stop() { if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) { // someone has already called close return } p.closer() atomic.StoreUint32(&started, 0) }
[ "func", "(", "p", "*", "Profile", ")", "Stop", "(", ")", "{", "if", "!", "atomic", ".", "CompareAndSwapUint32", "(", "&", "p", ".", "stopped", ",", "0", ",", "1", ")", "{", "// someone has already called close", "return", "\n", "}", "\n", "p", ".", "closer", "(", ")", "\n", "atomic", ".", "StoreUint32", "(", "&", "started", ",", "0", ")", "\n", "}" ]
// Stop stops the profile and flushes any unwritten data.
[ "Stop", "stops", "the", "profile", "and", "flushes", "any", "unwritten", "data", "." ]
f6fe06335df110bcf1ed6d4e852b760bfc15beee
https://github.com/pkg/profile/blob/f6fe06335df110bcf1ed6d4e852b760bfc15beee/profile.go#L111-L118
7,584
uber-go/ratelimit
ratelimit.go
New
func New(rate int, opts ...Option) Limiter { l := &limiter{ perRequest: time.Second / time.Duration(rate), maxSlack: -10 * time.Second / time.Duration(rate), } for _, opt := range opts { opt(l) } if l.clock == nil { l.clock = clock.New() } return l }
go
func New(rate int, opts ...Option) Limiter { l := &limiter{ perRequest: time.Second / time.Duration(rate), maxSlack: -10 * time.Second / time.Duration(rate), } for _, opt := range opts { opt(l) } if l.clock == nil { l.clock = clock.New() } return l }
[ "func", "New", "(", "rate", "int", ",", "opts", "...", "Option", ")", "Limiter", "{", "l", ":=", "&", "limiter", "{", "perRequest", ":", "time", ".", "Second", "/", "time", ".", "Duration", "(", "rate", ")", ",", "maxSlack", ":", "-", "10", "*", "time", ".", "Second", "/", "time", ".", "Duration", "(", "rate", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "l", ")", "\n", "}", "\n", "if", "l", ".", "clock", "==", "nil", "{", "l", ".", "clock", "=", "clock", ".", "New", "(", ")", "\n", "}", "\n", "return", "l", "\n", "}" ]
// New returns a Limiter that will limit to the given RPS.
[ "New", "returns", "a", "Limiter", "that", "will", "limit", "to", "the", "given", "RPS", "." ]
c15da02342779cb6dc027fc95ee2277787698f36
https://github.com/uber-go/ratelimit/blob/c15da02342779cb6dc027fc95ee2277787698f36/ratelimit.go#L62-L74
7,585
gorilla/schema
cache.go
newCache
func newCache() *cache { c := cache{ m: make(map[reflect.Type]*structInfo), regconv: make(map[reflect.Type]Converter), tag: "schema", } return &c }
go
func newCache() *cache { c := cache{ m: make(map[reflect.Type]*structInfo), regconv: make(map[reflect.Type]Converter), tag: "schema", } return &c }
[ "func", "newCache", "(", ")", "*", "cache", "{", "c", ":=", "cache", "{", "m", ":", "make", "(", "map", "[", "reflect", ".", "Type", "]", "*", "structInfo", ")", ",", "regconv", ":", "make", "(", "map", "[", "reflect", ".", "Type", "]", "Converter", ")", ",", "tag", ":", "\"", "\"", ",", "}", "\n", "return", "&", "c", "\n", "}" ]
// newCache returns a new cache.
[ "newCache", "returns", "a", "new", "cache", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L18-L25
7,586
gorilla/schema
cache.go
registerConverter
func (c *cache) registerConverter(value interface{}, converterFunc Converter) { c.regconv[reflect.TypeOf(value)] = converterFunc }
go
func (c *cache) registerConverter(value interface{}, converterFunc Converter) { c.regconv[reflect.TypeOf(value)] = converterFunc }
[ "func", "(", "c", "*", "cache", ")", "registerConverter", "(", "value", "interface", "{", "}", ",", "converterFunc", "Converter", ")", "{", "c", ".", "regconv", "[", "reflect", ".", "TypeOf", "(", "value", ")", "]", "=", "converterFunc", "\n", "}" ]
// registerConverter registers a converter function for a custom type.
[ "registerConverter", "registers", "a", "converter", "function", "for", "a", "custom", "type", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L36-L38
7,587
gorilla/schema
cache.go
get
func (c *cache) get(t reflect.Type) *structInfo { c.l.RLock() info := c.m[t] c.l.RUnlock() if info == nil { info = c.create(t, "") c.l.Lock() c.m[t] = info c.l.Unlock() } return info }
go
func (c *cache) get(t reflect.Type) *structInfo { c.l.RLock() info := c.m[t] c.l.RUnlock() if info == nil { info = c.create(t, "") c.l.Lock() c.m[t] = info c.l.Unlock() } return info }
[ "func", "(", "c", "*", "cache", ")", "get", "(", "t", "reflect", ".", "Type", ")", "*", "structInfo", "{", "c", ".", "l", ".", "RLock", "(", ")", "\n", "info", ":=", "c", ".", "m", "[", "t", "]", "\n", "c", ".", "l", ".", "RUnlock", "(", ")", "\n", "if", "info", "==", "nil", "{", "info", "=", "c", ".", "create", "(", "t", ",", "\"", "\"", ")", "\n", "c", ".", "l", ".", "Lock", "(", ")", "\n", "c", ".", "m", "[", "t", "]", "=", "info", "\n", "c", ".", "l", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "info", "\n", "}" ]
// get returns a cached structInfo, creating it if necessary.
[ "get", "returns", "a", "cached", "structInfo", "creating", "it", "if", "necessary", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L115-L126
7,588
gorilla/schema
cache.go
create
func (c *cache) create(t reflect.Type, parentAlias string) *structInfo { info := &structInfo{} var anonymousInfos []*structInfo for i := 0; i < t.NumField(); i++ { if f := c.createField(t.Field(i), parentAlias); f != nil { info.fields = append(info.fields, f) if ft := indirectType(f.typ); ft.Kind() == reflect.Struct && f.isAnonymous { anonymousInfos = append(anonymousInfos, c.create(ft, f.canonicalAlias)) } } } for i, a := range anonymousInfos { others := []*structInfo{info} others = append(others, anonymousInfos[:i]...) others = append(others, anonymousInfos[i+1:]...) for _, f := range a.fields { if !containsAlias(others, f.alias) { info.fields = append(info.fields, f) } } } return info }
go
func (c *cache) create(t reflect.Type, parentAlias string) *structInfo { info := &structInfo{} var anonymousInfos []*structInfo for i := 0; i < t.NumField(); i++ { if f := c.createField(t.Field(i), parentAlias); f != nil { info.fields = append(info.fields, f) if ft := indirectType(f.typ); ft.Kind() == reflect.Struct && f.isAnonymous { anonymousInfos = append(anonymousInfos, c.create(ft, f.canonicalAlias)) } } } for i, a := range anonymousInfos { others := []*structInfo{info} others = append(others, anonymousInfos[:i]...) others = append(others, anonymousInfos[i+1:]...) for _, f := range a.fields { if !containsAlias(others, f.alias) { info.fields = append(info.fields, f) } } } return info }
[ "func", "(", "c", "*", "cache", ")", "create", "(", "t", "reflect", ".", "Type", ",", "parentAlias", "string", ")", "*", "structInfo", "{", "info", ":=", "&", "structInfo", "{", "}", "\n", "var", "anonymousInfos", "[", "]", "*", "structInfo", "\n", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumField", "(", ")", ";", "i", "++", "{", "if", "f", ":=", "c", ".", "createField", "(", "t", ".", "Field", "(", "i", ")", ",", "parentAlias", ")", ";", "f", "!=", "nil", "{", "info", ".", "fields", "=", "append", "(", "info", ".", "fields", ",", "f", ")", "\n", "if", "ft", ":=", "indirectType", "(", "f", ".", "typ", ")", ";", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "&&", "f", ".", "isAnonymous", "{", "anonymousInfos", "=", "append", "(", "anonymousInfos", ",", "c", ".", "create", "(", "ft", ",", "f", ".", "canonicalAlias", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "i", ",", "a", ":=", "range", "anonymousInfos", "{", "others", ":=", "[", "]", "*", "structInfo", "{", "info", "}", "\n", "others", "=", "append", "(", "others", ",", "anonymousInfos", "[", ":", "i", "]", "...", ")", "\n", "others", "=", "append", "(", "others", ",", "anonymousInfos", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "for", "_", ",", "f", ":=", "range", "a", ".", "fields", "{", "if", "!", "containsAlias", "(", "others", ",", "f", ".", "alias", ")", "{", "info", ".", "fields", "=", "append", "(", "info", ".", "fields", ",", "f", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "info", "\n", "}" ]
// create creates a structInfo with meta-data about a struct.
[ "create", "creates", "a", "structInfo", "with", "meta", "-", "data", "about", "a", "struct", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L129-L151
7,589
gorilla/schema
cache.go
createField
func (c *cache) createField(field reflect.StructField, parentAlias string) *fieldInfo { alias, options := fieldAlias(field, c.tag) if alias == "-" { // Ignore this field. return nil } canonicalAlias := alias if parentAlias != "" { canonicalAlias = parentAlias + "." + alias } // Check if the type is supported and don't cache it if not. // First let's get the basic type. isSlice, isStruct := false, false ft := field.Type m := isTextUnmarshaler(reflect.Zero(ft)) if ft.Kind() == reflect.Ptr { ft = ft.Elem() } if isSlice = ft.Kind() == reflect.Slice; isSlice { ft = ft.Elem() if ft.Kind() == reflect.Ptr { ft = ft.Elem() } } if ft.Kind() == reflect.Array { ft = ft.Elem() if ft.Kind() == reflect.Ptr { ft = ft.Elem() } } if isStruct = ft.Kind() == reflect.Struct; !isStruct { if c.converter(ft) == nil && builtinConverters[ft.Kind()] == nil { // Type is not supported. return nil } } return &fieldInfo{ typ: field.Type, name: field.Name, alias: alias, canonicalAlias: canonicalAlias, unmarshalerInfo: m, isSliceOfStructs: isSlice && isStruct, isAnonymous: field.Anonymous, isRequired: options.Contains("required"), } }
go
func (c *cache) createField(field reflect.StructField, parentAlias string) *fieldInfo { alias, options := fieldAlias(field, c.tag) if alias == "-" { // Ignore this field. return nil } canonicalAlias := alias if parentAlias != "" { canonicalAlias = parentAlias + "." + alias } // Check if the type is supported and don't cache it if not. // First let's get the basic type. isSlice, isStruct := false, false ft := field.Type m := isTextUnmarshaler(reflect.Zero(ft)) if ft.Kind() == reflect.Ptr { ft = ft.Elem() } if isSlice = ft.Kind() == reflect.Slice; isSlice { ft = ft.Elem() if ft.Kind() == reflect.Ptr { ft = ft.Elem() } } if ft.Kind() == reflect.Array { ft = ft.Elem() if ft.Kind() == reflect.Ptr { ft = ft.Elem() } } if isStruct = ft.Kind() == reflect.Struct; !isStruct { if c.converter(ft) == nil && builtinConverters[ft.Kind()] == nil { // Type is not supported. return nil } } return &fieldInfo{ typ: field.Type, name: field.Name, alias: alias, canonicalAlias: canonicalAlias, unmarshalerInfo: m, isSliceOfStructs: isSlice && isStruct, isAnonymous: field.Anonymous, isRequired: options.Contains("required"), } }
[ "func", "(", "c", "*", "cache", ")", "createField", "(", "field", "reflect", ".", "StructField", ",", "parentAlias", "string", ")", "*", "fieldInfo", "{", "alias", ",", "options", ":=", "fieldAlias", "(", "field", ",", "c", ".", "tag", ")", "\n", "if", "alias", "==", "\"", "\"", "{", "// Ignore this field.", "return", "nil", "\n", "}", "\n", "canonicalAlias", ":=", "alias", "\n", "if", "parentAlias", "!=", "\"", "\"", "{", "canonicalAlias", "=", "parentAlias", "+", "\"", "\"", "+", "alias", "\n", "}", "\n", "// Check if the type is supported and don't cache it if not.", "// First let's get the basic type.", "isSlice", ",", "isStruct", ":=", "false", ",", "false", "\n", "ft", ":=", "field", ".", "Type", "\n", "m", ":=", "isTextUnmarshaler", "(", "reflect", ".", "Zero", "(", "ft", ")", ")", "\n", "if", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "ft", "=", "ft", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "isSlice", "=", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Slice", ";", "isSlice", "{", "ft", "=", "ft", ".", "Elem", "(", ")", "\n", "if", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "ft", "=", "ft", ".", "Elem", "(", ")", "\n", "}", "\n", "}", "\n", "if", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Array", "{", "ft", "=", "ft", ".", "Elem", "(", ")", "\n", "if", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "ft", "=", "ft", ".", "Elem", "(", ")", "\n", "}", "\n", "}", "\n", "if", "isStruct", "=", "ft", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", ";", "!", "isStruct", "{", "if", "c", ".", "converter", "(", "ft", ")", "==", "nil", "&&", "builtinConverters", "[", "ft", ".", "Kind", "(", ")", "]", "==", "nil", "{", "// Type is not supported.", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "&", "fieldInfo", "{", "typ", ":", "field", ".", "Type", ",", "name", ":", "field", ".", "Name", ",", "alias", ":", "alias", ",", "canonicalAlias", ":", "canonicalAlias", ",", "unmarshalerInfo", ":", "m", ",", "isSliceOfStructs", ":", "isSlice", "&&", "isStruct", ",", "isAnonymous", ":", "field", ".", "Anonymous", ",", "isRequired", ":", "options", ".", "Contains", "(", "\"", "\"", ")", ",", "}", "\n", "}" ]
// createField creates a fieldInfo for the given field.
[ "createField", "creates", "a", "fieldInfo", "for", "the", "given", "field", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L154-L201
7,590
gorilla/schema
cache.go
converter
func (c *cache) converter(t reflect.Type) Converter { return c.regconv[t] }
go
func (c *cache) converter(t reflect.Type) Converter { return c.regconv[t] }
[ "func", "(", "c", "*", "cache", ")", "converter", "(", "t", "reflect", ".", "Type", ")", "Converter", "{", "return", "c", ".", "regconv", "[", "t", "]", "\n", "}" ]
// converter returns the converter for a type.
[ "converter", "returns", "the", "converter", "for", "a", "type", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L204-L206
7,591
gorilla/schema
cache.go
fieldAlias
func fieldAlias(field reflect.StructField, tagName string) (alias string, options tagOptions) { if tag := field.Tag.Get(tagName); tag != "" { alias, options = parseTag(tag) } if alias == "" { alias = field.Name } return alias, options }
go
func fieldAlias(field reflect.StructField, tagName string) (alias string, options tagOptions) { if tag := field.Tag.Get(tagName); tag != "" { alias, options = parseTag(tag) } if alias == "" { alias = field.Name } return alias, options }
[ "func", "fieldAlias", "(", "field", "reflect", ".", "StructField", ",", "tagName", "string", ")", "(", "alias", "string", ",", "options", "tagOptions", ")", "{", "if", "tag", ":=", "field", ".", "Tag", ".", "Get", "(", "tagName", ")", ";", "tag", "!=", "\"", "\"", "{", "alias", ",", "options", "=", "parseTag", "(", "tag", ")", "\n", "}", "\n", "if", "alias", "==", "\"", "\"", "{", "alias", "=", "field", ".", "Name", "\n", "}", "\n", "return", "alias", ",", "options", "\n", "}" ]
// fieldAlias parses a field tag to get a field alias.
[ "fieldAlias", "parses", "a", "field", "tag", "to", "get", "a", "field", "alias", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L276-L284
7,592
gorilla/schema
cache.go
parseTag
func parseTag(tag string) (string, tagOptions) { s := strings.Split(tag, ",") return s[0], s[1:] }
go
func parseTag(tag string) (string, tagOptions) { s := strings.Split(tag, ",") return s[0], s[1:] }
[ "func", "parseTag", "(", "tag", "string", ")", "(", "string", ",", "tagOptions", ")", "{", "s", ":=", "strings", ".", "Split", "(", "tag", ",", "\"", "\"", ")", "\n", "return", "s", "[", "0", "]", ",", "s", "[", "1", ":", "]", "\n", "}" ]
// parseTag splits a struct field's url tag into its name and comma-separated // options.
[ "parseTag", "splits", "a", "struct", "field", "s", "url", "tag", "into", "its", "name", "and", "comma", "-", "separated", "options", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L292-L295
7,593
gorilla/schema
cache.go
Contains
func (o tagOptions) Contains(option string) bool { for _, s := range o { if s == option { return true } } return false }
go
func (o tagOptions) Contains(option string) bool { for _, s := range o { if s == option { return true } } return false }
[ "func", "(", "o", "tagOptions", ")", "Contains", "(", "option", "string", ")", "bool", "{", "for", "_", ",", "s", ":=", "range", "o", "{", "if", "s", "==", "option", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Contains checks whether the tagOptions contains the specified option.
[ "Contains", "checks", "whether", "the", "tagOptions", "contains", "the", "specified", "option", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/cache.go#L298-L305
7,594
gorilla/schema
decoder.go
RegisterConverter
func (d *Decoder) RegisterConverter(value interface{}, converterFunc Converter) { d.cache.registerConverter(value, converterFunc) }
go
func (d *Decoder) RegisterConverter(value interface{}, converterFunc Converter) { d.cache.registerConverter(value, converterFunc) }
[ "func", "(", "d", "*", "Decoder", ")", "RegisterConverter", "(", "value", "interface", "{", "}", ",", "converterFunc", "Converter", ")", "{", "d", ".", "cache", ".", "registerConverter", "(", "value", ",", "converterFunc", ")", "\n", "}" ]
// RegisterConverter registers a converter function for a custom type.
[ "RegisterConverter", "registers", "a", "converter", "function", "for", "a", "custom", "type", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/decoder.go#L58-L60
7,595
gorilla/schema
decoder.go
checkRequired
func (d *Decoder) checkRequired(t reflect.Type, src map[string][]string) MultiError { m, errs := d.findRequiredFields(t, "", "") for key, fields := range m { if isEmptyFields(fields, src) { errs[key] = EmptyFieldError{Key: key} } } return errs }
go
func (d *Decoder) checkRequired(t reflect.Type, src map[string][]string) MultiError { m, errs := d.findRequiredFields(t, "", "") for key, fields := range m { if isEmptyFields(fields, src) { errs[key] = EmptyFieldError{Key: key} } } return errs }
[ "func", "(", "d", "*", "Decoder", ")", "checkRequired", "(", "t", "reflect", ".", "Type", ",", "src", "map", "[", "string", "]", "[", "]", "string", ")", "MultiError", "{", "m", ",", "errs", ":=", "d", ".", "findRequiredFields", "(", "t", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "for", "key", ",", "fields", ":=", "range", "m", "{", "if", "isEmptyFields", "(", "fields", ",", "src", ")", "{", "errs", "[", "key", "]", "=", "EmptyFieldError", "{", "Key", ":", "key", "}", "\n", "}", "\n", "}", "\n", "return", "errs", "\n", "}" ]
// checkRequired checks whether required fields are empty // // check type t recursively if t has struct fields. // // src is the source map for decoding, we use it here to see if those required fields are included in src
[ "checkRequired", "checks", "whether", "required", "fields", "are", "empty", "check", "type", "t", "recursively", "if", "t", "has", "struct", "fields", ".", "src", "is", "the", "source", "map", "for", "decoding", "we", "use", "it", "here", "to", "see", "if", "those", "required", "fields", "are", "included", "in", "src" ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/decoder.go#L99-L107
7,596
gorilla/schema
decoder.go
findRequiredFields
func (d *Decoder) findRequiredFields(t reflect.Type, canonicalPrefix, searchPrefix string) (map[string][]fieldWithPrefix, MultiError) { struc := d.cache.get(t) if struc == nil { // unexpect, cache.get never return nil return nil, MultiError{canonicalPrefix + "*": errors.New("cache fail")} } m := map[string][]fieldWithPrefix{} errs := MultiError{} for _, f := range struc.fields { if f.typ.Kind() == reflect.Struct { fcprefix := canonicalPrefix + f.canonicalAlias + "." for _, fspath := range f.paths(searchPrefix) { fm, ferrs := d.findRequiredFields(f.typ, fcprefix, fspath+".") for key, fields := range fm { m[key] = append(m[key], fields...) } errs.merge(ferrs) } } if f.isRequired { key := canonicalPrefix + f.canonicalAlias m[key] = append(m[key], fieldWithPrefix{ fieldInfo: f, prefix: searchPrefix, }) } } return m, errs }
go
func (d *Decoder) findRequiredFields(t reflect.Type, canonicalPrefix, searchPrefix string) (map[string][]fieldWithPrefix, MultiError) { struc := d.cache.get(t) if struc == nil { // unexpect, cache.get never return nil return nil, MultiError{canonicalPrefix + "*": errors.New("cache fail")} } m := map[string][]fieldWithPrefix{} errs := MultiError{} for _, f := range struc.fields { if f.typ.Kind() == reflect.Struct { fcprefix := canonicalPrefix + f.canonicalAlias + "." for _, fspath := range f.paths(searchPrefix) { fm, ferrs := d.findRequiredFields(f.typ, fcprefix, fspath+".") for key, fields := range fm { m[key] = append(m[key], fields...) } errs.merge(ferrs) } } if f.isRequired { key := canonicalPrefix + f.canonicalAlias m[key] = append(m[key], fieldWithPrefix{ fieldInfo: f, prefix: searchPrefix, }) } } return m, errs }
[ "func", "(", "d", "*", "Decoder", ")", "findRequiredFields", "(", "t", "reflect", ".", "Type", ",", "canonicalPrefix", ",", "searchPrefix", "string", ")", "(", "map", "[", "string", "]", "[", "]", "fieldWithPrefix", ",", "MultiError", ")", "{", "struc", ":=", "d", ".", "cache", ".", "get", "(", "t", ")", "\n", "if", "struc", "==", "nil", "{", "// unexpect, cache.get never return nil", "return", "nil", ",", "MultiError", "{", "canonicalPrefix", "+", "\"", "\"", ":", "errors", ".", "New", "(", "\"", "\"", ")", "}", "\n", "}", "\n\n", "m", ":=", "map", "[", "string", "]", "[", "]", "fieldWithPrefix", "{", "}", "\n", "errs", ":=", "MultiError", "{", "}", "\n", "for", "_", ",", "f", ":=", "range", "struc", ".", "fields", "{", "if", "f", ".", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "{", "fcprefix", ":=", "canonicalPrefix", "+", "f", ".", "canonicalAlias", "+", "\"", "\"", "\n", "for", "_", ",", "fspath", ":=", "range", "f", ".", "paths", "(", "searchPrefix", ")", "{", "fm", ",", "ferrs", ":=", "d", ".", "findRequiredFields", "(", "f", ".", "typ", ",", "fcprefix", ",", "fspath", "+", "\"", "\"", ")", "\n", "for", "key", ",", "fields", ":=", "range", "fm", "{", "m", "[", "key", "]", "=", "append", "(", "m", "[", "key", "]", ",", "fields", "...", ")", "\n", "}", "\n", "errs", ".", "merge", "(", "ferrs", ")", "\n", "}", "\n", "}", "\n", "if", "f", ".", "isRequired", "{", "key", ":=", "canonicalPrefix", "+", "f", ".", "canonicalAlias", "\n", "m", "[", "key", "]", "=", "append", "(", "m", "[", "key", "]", ",", "fieldWithPrefix", "{", "fieldInfo", ":", "f", ",", "prefix", ":", "searchPrefix", ",", "}", ")", "\n", "}", "\n", "}", "\n", "return", "m", ",", "errs", "\n", "}" ]
// findRequiredFields recursively searches the struct type t for required fields. // // canonicalPrefix and searchPrefix are used to resolve full paths in dotted notation // for nested struct fields. canonicalPrefix is a complete path which never omits // any embedded struct fields. searchPrefix is a user-friendly path which may omit // some embedded struct fields to point promoted fields.
[ "findRequiredFields", "recursively", "searches", "the", "struct", "type", "t", "for", "required", "fields", ".", "canonicalPrefix", "and", "searchPrefix", "are", "used", "to", "resolve", "full", "paths", "in", "dotted", "notation", "for", "nested", "struct", "fields", ".", "canonicalPrefix", "is", "a", "complete", "path", "which", "never", "omits", "any", "embedded", "struct", "fields", ".", "searchPrefix", "is", "a", "user", "-", "friendly", "path", "which", "may", "omit", "some", "embedded", "struct", "fields", "to", "point", "promoted", "fields", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/decoder.go#L115-L144
7,597
gorilla/schema
decoder.go
isEmptyFields
func isEmptyFields(fields []fieldWithPrefix, src map[string][]string) bool { for _, f := range fields { for _, path := range f.paths(f.prefix) { if !isEmpty(f.typ, src[path]) { return false } } } return true }
go
func isEmptyFields(fields []fieldWithPrefix, src map[string][]string) bool { for _, f := range fields { for _, path := range f.paths(f.prefix) { if !isEmpty(f.typ, src[path]) { return false } } } return true }
[ "func", "isEmptyFields", "(", "fields", "[", "]", "fieldWithPrefix", ",", "src", "map", "[", "string", "]", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "f", ":=", "range", "fields", "{", "for", "_", ",", "path", ":=", "range", "f", ".", "paths", "(", "f", ".", "prefix", ")", "{", "if", "!", "isEmpty", "(", "f", ".", "typ", ",", "src", "[", "path", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isEmptyFields returns true if all of specified fields are empty.
[ "isEmptyFields", "returns", "true", "if", "all", "of", "specified", "fields", "are", "empty", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/decoder.go#L152-L161
7,598
gorilla/schema
decoder.go
isEmpty
func isEmpty(t reflect.Type, value []string) bool { if len(value) == 0 { return true } switch t.Kind() { case boolType, float32Type, float64Type, intType, int8Type, int32Type, int64Type, stringType, uint8Type, uint16Type, uint32Type, uint64Type: return len(value[0]) == 0 } return false }
go
func isEmpty(t reflect.Type, value []string) bool { if len(value) == 0 { return true } switch t.Kind() { case boolType, float32Type, float64Type, intType, int8Type, int32Type, int64Type, stringType, uint8Type, uint16Type, uint32Type, uint64Type: return len(value[0]) == 0 } return false }
[ "func", "isEmpty", "(", "t", "reflect", ".", "Type", ",", "value", "[", "]", "string", ")", "bool", "{", "if", "len", "(", "value", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "switch", "t", ".", "Kind", "(", ")", "{", "case", "boolType", ",", "float32Type", ",", "float64Type", ",", "intType", ",", "int8Type", ",", "int32Type", ",", "int64Type", ",", "stringType", ",", "uint8Type", ",", "uint16Type", ",", "uint32Type", ",", "uint64Type", ":", "return", "len", "(", "value", "[", "0", "]", ")", "==", "0", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isEmpty returns true if value is empty for specific type
[ "isEmpty", "returns", "true", "if", "value", "is", "empty", "for", "specific", "type" ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/decoder.go#L164-L173
7,599
gorilla/schema
encoder.go
NewEncoder
func NewEncoder() *Encoder { return &Encoder{cache: newCache(), regenc: make(map[reflect.Type]encoderFunc)} }
go
func NewEncoder() *Encoder { return &Encoder{cache: newCache(), regenc: make(map[reflect.Type]encoderFunc)} }
[ "func", "NewEncoder", "(", ")", "*", "Encoder", "{", "return", "&", "Encoder", "{", "cache", ":", "newCache", "(", ")", ",", "regenc", ":", "make", "(", "map", "[", "reflect", ".", "Type", "]", "encoderFunc", ")", "}", "\n", "}" ]
// NewEncoder returns a new Encoder with defaults.
[ "NewEncoder", "returns", "a", "new", "Encoder", "with", "defaults", "." ]
d768c7020973d24fadced0db99bfdc261241d85f
https://github.com/gorilla/schema/blob/d768c7020973d24fadced0db99bfdc261241d85f/encoder.go#L19-L21