repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
hyperledger/burrow | storage/kvstore.go | CompareKeys | func CompareKeys(k1, k2 []byte) int {
ko1 := KeyOrder(k1)
ko2 := KeyOrder(k2)
if ko1 < ko2 {
return -1
}
if ko1 > ko2 {
return 1
}
return bytes.Compare(k1, k2)
} | go | func CompareKeys(k1, k2 []byte) int {
ko1 := KeyOrder(k1)
ko2 := KeyOrder(k2)
if ko1 < ko2 {
return -1
}
if ko1 > ko2 {
return 1
}
return bytes.Compare(k1, k2)
} | [
"func",
"CompareKeys",
"(",
"k1",
",",
"k2",
"[",
"]",
"byte",
")",
"int",
"{",
"ko1",
":=",
"KeyOrder",
"(",
"k1",
")",
"\n",
"ko2",
":=",
"KeyOrder",
"(",
"k2",
")",
"\n",
"if",
"ko1",
"<",
"ko2",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"if",
"ko1",
">",
"ko2",
"{",
"return",
"1",
"\n",
"}",
"\n",
"return",
"bytes",
".",
"Compare",
"(",
"k1",
",",
"k2",
")",
"\n",
"}"
] | // Sorts the keys as if they were compared lexicographically with their KeyOrder prepended | [
"Sorts",
"the",
"keys",
"as",
"if",
"they",
"were",
"compared",
"lexicographically",
"with",
"their",
"KeyOrder",
"prepended"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/kvstore.go#L106-L116 | train |
hyperledger/burrow | execution/evm/vm.go | delegateCall | func (vm *VM) delegateCall(callState Interface, eventSink EventSink, caller, callee crypto.Address,
code, input []byte, value uint64, gas *uint64,
callType exec.CallType) (output []byte, err errors.CodedError) {
// fire the post call event (including exception if applicable) and make sure we return the accumulated call error
defer func() {
vm.fireCallEvent(eventSink, callType, callState, &output, caller, callee, input, value, gas, callState)
err = callState.Error()
}()
// DelegateCall does not transfer the value to the callee.
callState.PushError(vm.ensureStackDepth())
// Early exit
if callState.Error() != nil {
return
}
if len(code) > 0 {
vm.stackDepth += 1
output = vm.execute(callState, eventSink, caller, callee, code, input, value, gas)
vm.stackDepth -= 1
}
return
} | go | func (vm *VM) delegateCall(callState Interface, eventSink EventSink, caller, callee crypto.Address,
code, input []byte, value uint64, gas *uint64,
callType exec.CallType) (output []byte, err errors.CodedError) {
// fire the post call event (including exception if applicable) and make sure we return the accumulated call error
defer func() {
vm.fireCallEvent(eventSink, callType, callState, &output, caller, callee, input, value, gas, callState)
err = callState.Error()
}()
// DelegateCall does not transfer the value to the callee.
callState.PushError(vm.ensureStackDepth())
// Early exit
if callState.Error() != nil {
return
}
if len(code) > 0 {
vm.stackDepth += 1
output = vm.execute(callState, eventSink, caller, callee, code, input, value, gas)
vm.stackDepth -= 1
}
return
} | [
"func",
"(",
"vm",
"*",
"VM",
")",
"delegateCall",
"(",
"callState",
"Interface",
",",
"eventSink",
"EventSink",
",",
"caller",
",",
"callee",
"crypto",
".",
"Address",
",",
"code",
",",
"input",
"[",
"]",
"byte",
",",
"value",
"uint64",
",",
"gas",
"*",
"uint64",
",",
"callType",
"exec",
".",
"CallType",
")",
"(",
"output",
"[",
"]",
"byte",
",",
"err",
"errors",
".",
"CodedError",
")",
"{",
"// fire the post call event (including exception if applicable) and make sure we return the accumulated call error",
"defer",
"func",
"(",
")",
"{",
"vm",
".",
"fireCallEvent",
"(",
"eventSink",
",",
"callType",
",",
"callState",
",",
"&",
"output",
",",
"caller",
",",
"callee",
",",
"input",
",",
"value",
",",
"gas",
",",
"callState",
")",
"\n",
"err",
"=",
"callState",
".",
"Error",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// DelegateCall does not transfer the value to the callee.",
"callState",
".",
"PushError",
"(",
"vm",
".",
"ensureStackDepth",
"(",
")",
")",
"\n\n",
"// Early exit",
"if",
"callState",
".",
"Error",
"(",
")",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"code",
")",
">",
"0",
"{",
"vm",
".",
"stackDepth",
"+=",
"1",
"\n",
"output",
"=",
"vm",
".",
"execute",
"(",
"callState",
",",
"eventSink",
",",
"caller",
",",
"callee",
",",
"code",
",",
"input",
",",
"value",
",",
"gas",
")",
"\n",
"vm",
".",
"stackDepth",
"-=",
"1",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // DelegateCall is executed by the DELEGATECALL opcode, introduced as off Ethereum Homestead.
// The intent of delegate call is to run the code of the callee in the storage context of the caller;
// while preserving the original caller to the previous callee.
// Different to the normal CALL or CALLCODE, the value does not need to be transferred to the callee. | [
"DelegateCall",
"is",
"executed",
"by",
"the",
"DELEGATECALL",
"opcode",
"introduced",
"as",
"off",
"Ethereum",
"Homestead",
".",
"The",
"intent",
"of",
"delegate",
"call",
"is",
"to",
"run",
"the",
"code",
"of",
"the",
"callee",
"in",
"the",
"storage",
"context",
"of",
"the",
"caller",
";",
"while",
"preserving",
"the",
"original",
"caller",
"to",
"the",
"previous",
"callee",
".",
"Different",
"to",
"the",
"normal",
"CALL",
"or",
"CALLCODE",
"the",
"value",
"does",
"not",
"need",
"to",
"be",
"transferred",
"to",
"the",
"callee",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/vm.go#L188-L213 | train |
hyperledger/burrow | execution/evm/vm.go | useGasNegative | func useGasNegative(gasLeft *uint64, gasToUse uint64, err errors.Sink) {
if *gasLeft >= gasToUse {
*gasLeft -= gasToUse
} else {
err.PushError(errors.ErrorCodeInsufficientGas)
}
} | go | func useGasNegative(gasLeft *uint64, gasToUse uint64, err errors.Sink) {
if *gasLeft >= gasToUse {
*gasLeft -= gasToUse
} else {
err.PushError(errors.ErrorCodeInsufficientGas)
}
} | [
"func",
"useGasNegative",
"(",
"gasLeft",
"*",
"uint64",
",",
"gasToUse",
"uint64",
",",
"err",
"errors",
".",
"Sink",
")",
"{",
"if",
"*",
"gasLeft",
">=",
"gasToUse",
"{",
"*",
"gasLeft",
"-=",
"gasToUse",
"\n",
"}",
"else",
"{",
"err",
".",
"PushError",
"(",
"errors",
".",
"ErrorCodeInsufficientGas",
")",
"\n",
"}",
"\n",
"}"
] | // Try to deduct gasToUse from gasLeft. If ok return false, otherwise
// set err and return true. | [
"Try",
"to",
"deduct",
"gasToUse",
"from",
"gasLeft",
".",
"If",
"ok",
"return",
"false",
"otherwise",
"set",
"err",
"and",
"return",
"true",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/vm.go#L217-L223 | train |
hyperledger/burrow | execution/evm/vm.go | dumpTokens | func dumpTokens(nonce []byte, caller, callee crypto.Address, code []byte) {
var tokensString string
tokens, err := acm.Bytecode(code).Tokens()
if err != nil {
tokensString = fmt.Sprintf("error generating tokens from bytecode: %v", err)
} else {
tokensString = strings.Join(tokens, "\n")
}
txHashString := "nil-nonce"
if len(nonce) >= 4 {
txHashString = fmt.Sprintf("nonce-%X", nonce[:4])
}
callerString := "caller-none"
if caller != crypto.ZeroAddress {
callerString = fmt.Sprintf("caller-%v", caller)
}
calleeString := "callee-none"
if callee != crypto.ZeroAddress {
calleeString = fmt.Sprintf("callee-%v", caller)
}
ioutil.WriteFile(fmt.Sprintf("tokens_%s_%s_%s.asm", txHashString, callerString, calleeString),
[]byte(tokensString), 0777)
} | go | func dumpTokens(nonce []byte, caller, callee crypto.Address, code []byte) {
var tokensString string
tokens, err := acm.Bytecode(code).Tokens()
if err != nil {
tokensString = fmt.Sprintf("error generating tokens from bytecode: %v", err)
} else {
tokensString = strings.Join(tokens, "\n")
}
txHashString := "nil-nonce"
if len(nonce) >= 4 {
txHashString = fmt.Sprintf("nonce-%X", nonce[:4])
}
callerString := "caller-none"
if caller != crypto.ZeroAddress {
callerString = fmt.Sprintf("caller-%v", caller)
}
calleeString := "callee-none"
if callee != crypto.ZeroAddress {
calleeString = fmt.Sprintf("callee-%v", caller)
}
ioutil.WriteFile(fmt.Sprintf("tokens_%s_%s_%s.asm", txHashString, callerString, calleeString),
[]byte(tokensString), 0777)
} | [
"func",
"dumpTokens",
"(",
"nonce",
"[",
"]",
"byte",
",",
"caller",
",",
"callee",
"crypto",
".",
"Address",
",",
"code",
"[",
"]",
"byte",
")",
"{",
"var",
"tokensString",
"string",
"\n",
"tokens",
",",
"err",
":=",
"acm",
".",
"Bytecode",
"(",
"code",
")",
".",
"Tokens",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"tokensString",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"tokensString",
"=",
"strings",
".",
"Join",
"(",
"tokens",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"txHashString",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"nonce",
")",
">=",
"4",
"{",
"txHashString",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"nonce",
"[",
":",
"4",
"]",
")",
"\n",
"}",
"\n",
"callerString",
":=",
"\"",
"\"",
"\n",
"if",
"caller",
"!=",
"crypto",
".",
"ZeroAddress",
"{",
"callerString",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"caller",
")",
"\n",
"}",
"\n",
"calleeString",
":=",
"\"",
"\"",
"\n",
"if",
"callee",
"!=",
"crypto",
".",
"ZeroAddress",
"{",
"calleeString",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"caller",
")",
"\n",
"}",
"\n",
"ioutil",
".",
"WriteFile",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"txHashString",
",",
"callerString",
",",
"calleeString",
")",
",",
"[",
"]",
"byte",
"(",
"tokensString",
")",
",",
"0777",
")",
"\n",
"}"
] | // Dump the bytecode being sent to the EVM in the current working directory | [
"Dump",
"the",
"bytecode",
"being",
"sent",
"to",
"the",
"EVM",
"in",
"the",
"current",
"working",
"directory"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/vm.go#L1064-L1086 | train |
hyperledger/burrow | integration/integration.go | MakePrivateAccounts | func MakePrivateAccounts(n int) []*acm.PrivateAccount {
accounts := make([]*acm.PrivateAccount, n)
for i := 0; i < n; i++ {
accounts[i] = acm.GeneratePrivateAccountFromSecret("mysecret" + strconv.Itoa(i))
}
return accounts
} | go | func MakePrivateAccounts(n int) []*acm.PrivateAccount {
accounts := make([]*acm.PrivateAccount, n)
for i := 0; i < n; i++ {
accounts[i] = acm.GeneratePrivateAccountFromSecret("mysecret" + strconv.Itoa(i))
}
return accounts
} | [
"func",
"MakePrivateAccounts",
"(",
"n",
"int",
")",
"[",
"]",
"*",
"acm",
".",
"PrivateAccount",
"{",
"accounts",
":=",
"make",
"(",
"[",
"]",
"*",
"acm",
".",
"PrivateAccount",
",",
"n",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"accounts",
"[",
"i",
"]",
"=",
"acm",
".",
"GeneratePrivateAccountFromSecret",
"(",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"i",
")",
")",
"\n",
"}",
"\n",
"return",
"accounts",
"\n",
"}"
] | // Deterministic account generation helper. Pass number of accounts to make | [
"Deterministic",
"account",
"generation",
"helper",
".",
"Pass",
"number",
"of",
"accounts",
"to",
"make"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/integration/integration.go#L190-L196 | train |
hyperledger/burrow | vent/sqldb/adapters/postgres_adapter.go | NewPostgresAdapter | func NewPostgresAdapter(schema string, log *logger.Logger) *PostgresAdapter {
return &PostgresAdapter{
Log: log,
Schema: schema,
}
} | go | func NewPostgresAdapter(schema string, log *logger.Logger) *PostgresAdapter {
return &PostgresAdapter{
Log: log,
Schema: schema,
}
} | [
"func",
"NewPostgresAdapter",
"(",
"schema",
"string",
",",
"log",
"*",
"logger",
".",
"Logger",
")",
"*",
"PostgresAdapter",
"{",
"return",
"&",
"PostgresAdapter",
"{",
"Log",
":",
"log",
",",
"Schema",
":",
"schema",
",",
"}",
"\n",
"}"
] | // NewPostgresAdapter constructs a new db adapter | [
"NewPostgresAdapter",
"constructs",
"a",
"new",
"db",
"adapter"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L33-L38 | train |
hyperledger/burrow | vent/sqldb/adapters/postgres_adapter.go | Open | func (adapter *PostgresAdapter) Open(dbURL string) (*sql.DB, error) {
db, err := sql.Open("postgres", dbURL)
if err != nil {
adapter.Log.Info("msg", "Error creating database connection", "err", err)
return nil, err
}
// if there is a supplied Schema
if adapter.Schema != "" {
if err = db.Ping(); err != nil {
adapter.Log.Info("msg", "Error opening database connection", "err", err)
return nil, err
}
var found bool
query := Cleanf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`, adapter.Schema)
adapter.Log.Info("msg", "FIND SCHEMA", "query", query)
if err := db.QueryRow(query).Scan(&found); err == nil {
if !found {
adapter.Log.Warn("msg", "Schema not found")
}
adapter.Log.Info("msg", "Creating schema")
query = Cleanf("CREATE SCHEMA %s;", adapter.Schema)
adapter.Log.Info("msg", "CREATE SCHEMA", "query", query)
if _, err = db.Exec(query); err != nil {
if adapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedSchema) {
adapter.Log.Warn("msg", "Duplicated schema")
return db, nil
}
}
} else {
adapter.Log.Info("msg", "Error searching schema", "err", err)
return nil, err
}
} else {
return nil, fmt.Errorf("no schema supplied")
}
return db, err
} | go | func (adapter *PostgresAdapter) Open(dbURL string) (*sql.DB, error) {
db, err := sql.Open("postgres", dbURL)
if err != nil {
adapter.Log.Info("msg", "Error creating database connection", "err", err)
return nil, err
}
// if there is a supplied Schema
if adapter.Schema != "" {
if err = db.Ping(); err != nil {
adapter.Log.Info("msg", "Error opening database connection", "err", err)
return nil, err
}
var found bool
query := Cleanf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`, adapter.Schema)
adapter.Log.Info("msg", "FIND SCHEMA", "query", query)
if err := db.QueryRow(query).Scan(&found); err == nil {
if !found {
adapter.Log.Warn("msg", "Schema not found")
}
adapter.Log.Info("msg", "Creating schema")
query = Cleanf("CREATE SCHEMA %s;", adapter.Schema)
adapter.Log.Info("msg", "CREATE SCHEMA", "query", query)
if _, err = db.Exec(query); err != nil {
if adapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedSchema) {
adapter.Log.Warn("msg", "Duplicated schema")
return db, nil
}
}
} else {
adapter.Log.Info("msg", "Error searching schema", "err", err)
return nil, err
}
} else {
return nil, fmt.Errorf("no schema supplied")
}
return db, err
} | [
"func",
"(",
"adapter",
"*",
"PostgresAdapter",
")",
"Open",
"(",
"dbURL",
"string",
")",
"(",
"*",
"sql",
".",
"DB",
",",
"error",
")",
"{",
"db",
",",
"err",
":=",
"sql",
".",
"Open",
"(",
"\"",
"\"",
",",
"dbURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// if there is a supplied Schema",
"if",
"adapter",
".",
"Schema",
"!=",
"\"",
"\"",
"{",
"if",
"err",
"=",
"db",
".",
"Ping",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"found",
"bool",
"\n\n",
"query",
":=",
"Cleanf",
"(",
"`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`",
",",
"adapter",
".",
"Schema",
")",
"\n",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"query",
")",
"\n\n",
"if",
"err",
":=",
"db",
".",
"QueryRow",
"(",
"query",
")",
".",
"Scan",
"(",
"&",
"found",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"!",
"found",
"{",
"adapter",
".",
"Log",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"query",
"=",
"Cleanf",
"(",
"\"",
"\"",
",",
"adapter",
".",
"Schema",
")",
"\n",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"query",
")",
"\n\n",
"if",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"query",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"adapter",
".",
"ErrorEquals",
"(",
"err",
",",
"types",
".",
"SQLErrorTypeDuplicatedSchema",
")",
"{",
"adapter",
".",
"Log",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"db",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"db",
",",
"err",
"\n",
"}"
] | // Open connects to a PostgreSQL database, opens it & create default schema if provided | [
"Open",
"connects",
"to",
"a",
"PostgreSQL",
"database",
"opens",
"it",
"&",
"create",
"default",
"schema",
"if",
"provided"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L41-L84 | train |
hyperledger/burrow | vent/sqldb/adapters/postgres_adapter.go | CreateTableQuery | func (adapter *PostgresAdapter) CreateTableQuery(tableName string, columns []*types.SQLTableColumn) (string, string) {
// build query
columnsDef := ""
primaryKey := ""
dictionaryValues := ""
for i, column := range columns {
secureColumn := adapter.SecureName(column.Name)
sqlType, _ := adapter.TypeMapping(column.Type)
pKey := 0
if columnsDef != "" {
columnsDef += ", "
dictionaryValues += ", "
}
columnsDef += Cleanf("%s %s", secureColumn, sqlType)
if column.Length > 0 {
columnsDef += Cleanf("(%v)", column.Length)
}
if column.Primary {
pKey = 1
columnsDef += " NOT NULL"
if primaryKey != "" {
primaryKey += ", "
}
primaryKey += secureColumn
}
dictionaryValues += Cleanf("('%s','%s',%d,%d,%d,%d)",
tableName,
column.Name,
column.Type,
column.Length,
pKey,
i)
}
query := Cleanf("CREATE TABLE %s.%s (%s", adapter.Schema, adapter.SecureName(tableName), columnsDef)
if primaryKey != "" {
query += "," + Cleanf("CONSTRAINT %s_pkey PRIMARY KEY (%s)", tableName, primaryKey)
}
query += ");"
dictionaryQuery := Cleanf("INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s) VALUES %s;",
adapter.Schema, types.SQLDictionaryTableName,
types.SQLColumnLabelTableName, types.SQLColumnLabelColumnName,
types.SQLColumnLabelColumnType, types.SQLColumnLabelColumnLength,
types.SQLColumnLabelPrimaryKey, types.SQLColumnLabelColumnOrder,
dictionaryValues)
return query, dictionaryQuery
} | go | func (adapter *PostgresAdapter) CreateTableQuery(tableName string, columns []*types.SQLTableColumn) (string, string) {
// build query
columnsDef := ""
primaryKey := ""
dictionaryValues := ""
for i, column := range columns {
secureColumn := adapter.SecureName(column.Name)
sqlType, _ := adapter.TypeMapping(column.Type)
pKey := 0
if columnsDef != "" {
columnsDef += ", "
dictionaryValues += ", "
}
columnsDef += Cleanf("%s %s", secureColumn, sqlType)
if column.Length > 0 {
columnsDef += Cleanf("(%v)", column.Length)
}
if column.Primary {
pKey = 1
columnsDef += " NOT NULL"
if primaryKey != "" {
primaryKey += ", "
}
primaryKey += secureColumn
}
dictionaryValues += Cleanf("('%s','%s',%d,%d,%d,%d)",
tableName,
column.Name,
column.Type,
column.Length,
pKey,
i)
}
query := Cleanf("CREATE TABLE %s.%s (%s", adapter.Schema, adapter.SecureName(tableName), columnsDef)
if primaryKey != "" {
query += "," + Cleanf("CONSTRAINT %s_pkey PRIMARY KEY (%s)", tableName, primaryKey)
}
query += ");"
dictionaryQuery := Cleanf("INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s) VALUES %s;",
adapter.Schema, types.SQLDictionaryTableName,
types.SQLColumnLabelTableName, types.SQLColumnLabelColumnName,
types.SQLColumnLabelColumnType, types.SQLColumnLabelColumnLength,
types.SQLColumnLabelPrimaryKey, types.SQLColumnLabelColumnOrder,
dictionaryValues)
return query, dictionaryQuery
} | [
"func",
"(",
"adapter",
"*",
"PostgresAdapter",
")",
"CreateTableQuery",
"(",
"tableName",
"string",
",",
"columns",
"[",
"]",
"*",
"types",
".",
"SQLTableColumn",
")",
"(",
"string",
",",
"string",
")",
"{",
"// build query",
"columnsDef",
":=",
"\"",
"\"",
"\n",
"primaryKey",
":=",
"\"",
"\"",
"\n",
"dictionaryValues",
":=",
"\"",
"\"",
"\n\n",
"for",
"i",
",",
"column",
":=",
"range",
"columns",
"{",
"secureColumn",
":=",
"adapter",
".",
"SecureName",
"(",
"column",
".",
"Name",
")",
"\n",
"sqlType",
",",
"_",
":=",
"adapter",
".",
"TypeMapping",
"(",
"column",
".",
"Type",
")",
"\n",
"pKey",
":=",
"0",
"\n\n",
"if",
"columnsDef",
"!=",
"\"",
"\"",
"{",
"columnsDef",
"+=",
"\"",
"\"",
"\n",
"dictionaryValues",
"+=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"columnsDef",
"+=",
"Cleanf",
"(",
"\"",
"\"",
",",
"secureColumn",
",",
"sqlType",
")",
"\n\n",
"if",
"column",
".",
"Length",
">",
"0",
"{",
"columnsDef",
"+=",
"Cleanf",
"(",
"\"",
"\"",
",",
"column",
".",
"Length",
")",
"\n",
"}",
"\n\n",
"if",
"column",
".",
"Primary",
"{",
"pKey",
"=",
"1",
"\n",
"columnsDef",
"+=",
"\"",
"\"",
"\n",
"if",
"primaryKey",
"!=",
"\"",
"\"",
"{",
"primaryKey",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"primaryKey",
"+=",
"secureColumn",
"\n",
"}",
"\n\n",
"dictionaryValues",
"+=",
"Cleanf",
"(",
"\"",
"\"",
",",
"tableName",
",",
"column",
".",
"Name",
",",
"column",
".",
"Type",
",",
"column",
".",
"Length",
",",
"pKey",
",",
"i",
")",
"\n",
"}",
"\n\n",
"query",
":=",
"Cleanf",
"(",
"\"",
"\"",
",",
"adapter",
".",
"Schema",
",",
"adapter",
".",
"SecureName",
"(",
"tableName",
")",
",",
"columnsDef",
")",
"\n",
"if",
"primaryKey",
"!=",
"\"",
"\"",
"{",
"query",
"+=",
"\"",
"\"",
"+",
"Cleanf",
"(",
"\"",
"\"",
",",
"tableName",
",",
"primaryKey",
")",
"\n",
"}",
"\n",
"query",
"+=",
"\"",
"\"",
"\n\n",
"dictionaryQuery",
":=",
"Cleanf",
"(",
"\"",
"\"",
",",
"adapter",
".",
"Schema",
",",
"types",
".",
"SQLDictionaryTableName",
",",
"types",
".",
"SQLColumnLabelTableName",
",",
"types",
".",
"SQLColumnLabelColumnName",
",",
"types",
".",
"SQLColumnLabelColumnType",
",",
"types",
".",
"SQLColumnLabelColumnLength",
",",
"types",
".",
"SQLColumnLabelPrimaryKey",
",",
"types",
".",
"SQLColumnLabelColumnOrder",
",",
"dictionaryValues",
")",
"\n\n",
"return",
"query",
",",
"dictionaryQuery",
"\n",
"}"
] | // CreateTableQuery builds query for creating a new table | [
"CreateTableQuery",
"builds",
"query",
"for",
"creating",
"a",
"new",
"table"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L101-L155 | train |
hyperledger/burrow | vent/sqldb/adapters/postgres_adapter.go | TableDefinitionQuery | func (adapter *PostgresAdapter) TableDefinitionQuery() string {
query := `
SELECT
%s,%s,%s,%s
FROM
%s.%s
WHERE
%s = $1
ORDER BY
%s;`
return Cleanf(query,
types.SQLColumnLabelColumnName, types.SQLColumnLabelColumnType, // select
types.SQLColumnLabelColumnLength, types.SQLColumnLabelPrimaryKey, // select
adapter.Schema, types.SQLDictionaryTableName, // from
types.SQLColumnLabelTableName, // where
types.SQLColumnLabelColumnOrder) // order by
} | go | func (adapter *PostgresAdapter) TableDefinitionQuery() string {
query := `
SELECT
%s,%s,%s,%s
FROM
%s.%s
WHERE
%s = $1
ORDER BY
%s;`
return Cleanf(query,
types.SQLColumnLabelColumnName, types.SQLColumnLabelColumnType, // select
types.SQLColumnLabelColumnLength, types.SQLColumnLabelPrimaryKey, // select
adapter.Schema, types.SQLDictionaryTableName, // from
types.SQLColumnLabelTableName, // where
types.SQLColumnLabelColumnOrder) // order by
} | [
"func",
"(",
"adapter",
"*",
"PostgresAdapter",
")",
"TableDefinitionQuery",
"(",
")",
"string",
"{",
"query",
":=",
"`\n\t\tSELECT\n\t\t\t%s,%s,%s,%s\n\t\tFROM\n\t\t\t%s.%s\n\t\tWHERE\n\t\t\t%s = $1\n\t\tORDER BY\n\t\t\t%s;`",
"\n\n",
"return",
"Cleanf",
"(",
"query",
",",
"types",
".",
"SQLColumnLabelColumnName",
",",
"types",
".",
"SQLColumnLabelColumnType",
",",
"// select",
"types",
".",
"SQLColumnLabelColumnLength",
",",
"types",
".",
"SQLColumnLabelPrimaryKey",
",",
"// select",
"adapter",
".",
"Schema",
",",
"types",
".",
"SQLDictionaryTableName",
",",
"// from",
"types",
".",
"SQLColumnLabelTableName",
",",
"// where",
"types",
".",
"SQLColumnLabelColumnOrder",
")",
"// order by",
"\n\n",
"}"
] | // TableDefinitionQuery returns a query with table structure | [
"TableDefinitionQuery",
"returns",
"a",
"query",
"with",
"table",
"structure"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L187-L205 | train |
hyperledger/burrow | vent/sqldb/adapters/postgres_adapter.go | InsertLogQuery | func (adapter *PostgresAdapter) InsertLogQuery() string {
query := `
INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
VALUES (CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6 ,$7, $8, $9);`
return Cleanf(query,
adapter.Schema, types.SQLLogTableName, // insert
//fields
types.SQLColumnLabelTimeStamp, types.SQLColumnLabelTableName, types.SQLColumnLabelEventName, types.SQLColumnLabelEventFilter,
types.SQLColumnLabelHeight, types.SQLColumnLabelTxHash, types.SQLColumnLabelAction, types.SQLColumnLabelDataRow,
types.SQLColumnLabelSqlStmt, types.SQLColumnLabelSqlValues)
} | go | func (adapter *PostgresAdapter) InsertLogQuery() string {
query := `
INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
VALUES (CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6 ,$7, $8, $9);`
return Cleanf(query,
adapter.Schema, types.SQLLogTableName, // insert
//fields
types.SQLColumnLabelTimeStamp, types.SQLColumnLabelTableName, types.SQLColumnLabelEventName, types.SQLColumnLabelEventFilter,
types.SQLColumnLabelHeight, types.SQLColumnLabelTxHash, types.SQLColumnLabelAction, types.SQLColumnLabelDataRow,
types.SQLColumnLabelSqlStmt, types.SQLColumnLabelSqlValues)
} | [
"func",
"(",
"adapter",
"*",
"PostgresAdapter",
")",
"InsertLogQuery",
"(",
")",
"string",
"{",
"query",
":=",
"`\n\t\tINSERT INTO %s.%s (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\n\t\tVALUES (CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6 ,$7, $8, $9);`",
"\n\n",
"return",
"Cleanf",
"(",
"query",
",",
"adapter",
".",
"Schema",
",",
"types",
".",
"SQLLogTableName",
",",
"// insert",
"//fields",
"types",
".",
"SQLColumnLabelTimeStamp",
",",
"types",
".",
"SQLColumnLabelTableName",
",",
"types",
".",
"SQLColumnLabelEventName",
",",
"types",
".",
"SQLColumnLabelEventFilter",
",",
"types",
".",
"SQLColumnLabelHeight",
",",
"types",
".",
"SQLColumnLabelTxHash",
",",
"types",
".",
"SQLColumnLabelAction",
",",
"types",
".",
"SQLColumnLabelDataRow",
",",
"types",
".",
"SQLColumnLabelSqlStmt",
",",
"types",
".",
"SQLColumnLabelSqlValues",
")",
"\n",
"}"
] | // InsertLogQuery returns a query to insert a row in log table | [
"InsertLogQuery",
"returns",
"a",
"query",
"to",
"insert",
"a",
"row",
"in",
"log",
"table"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L256-L267 | train |
hyperledger/burrow | consensus/abci/process.go | NewProcess | func NewProcess(committer execution.BatchCommitter, blockchain *bcm.Blockchain, txDecoder txs.Decoder,
commitInterval time.Duration, panicFunc func(error)) *Process {
p := &Process{
committer: committer,
blockchain: blockchain,
done: make(chan struct{}),
txDecoder: txDecoder,
panic: panicFunc,
}
if commitInterval != 0 {
p.ticker = time.NewTicker(commitInterval)
go p.triggerCommits()
}
return p
} | go | func NewProcess(committer execution.BatchCommitter, blockchain *bcm.Blockchain, txDecoder txs.Decoder,
commitInterval time.Duration, panicFunc func(error)) *Process {
p := &Process{
committer: committer,
blockchain: blockchain,
done: make(chan struct{}),
txDecoder: txDecoder,
panic: panicFunc,
}
if commitInterval != 0 {
p.ticker = time.NewTicker(commitInterval)
go p.triggerCommits()
}
return p
} | [
"func",
"NewProcess",
"(",
"committer",
"execution",
".",
"BatchCommitter",
",",
"blockchain",
"*",
"bcm",
".",
"Blockchain",
",",
"txDecoder",
"txs",
".",
"Decoder",
",",
"commitInterval",
"time",
".",
"Duration",
",",
"panicFunc",
"func",
"(",
"error",
")",
")",
"*",
"Process",
"{",
"p",
":=",
"&",
"Process",
"{",
"committer",
":",
"committer",
",",
"blockchain",
":",
"blockchain",
",",
"done",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"txDecoder",
":",
"txDecoder",
",",
"panic",
":",
"panicFunc",
",",
"}",
"\n\n",
"if",
"commitInterval",
"!=",
"0",
"{",
"p",
".",
"ticker",
"=",
"time",
".",
"NewTicker",
"(",
"commitInterval",
")",
"\n",
"go",
"p",
".",
"triggerCommits",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] | // NewProcess returns a no-consensus ABCI process suitable for running a single node without Tendermint.
// The CheckTx function can be used to submit transactions which are processed according | [
"NewProcess",
"returns",
"a",
"no",
"-",
"consensus",
"ABCI",
"process",
"suitable",
"for",
"running",
"a",
"single",
"node",
"without",
"Tendermint",
".",
"The",
"CheckTx",
"function",
"can",
"be",
"used",
"to",
"submit",
"transactions",
"which",
"are",
"processed",
"according"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/consensus/abci/process.go#L31-L48 | train |
hyperledger/burrow | txs/tx.go | Sign | func (tx *Tx) Sign(signingAccounts ...acm.AddressableSigner) (*Envelope, error) {
env := tx.Enclose()
err := env.Sign(signingAccounts...)
if err != nil {
return nil, err
}
tx.Rehash()
return env, nil
} | go | func (tx *Tx) Sign(signingAccounts ...acm.AddressableSigner) (*Envelope, error) {
env := tx.Enclose()
err := env.Sign(signingAccounts...)
if err != nil {
return nil, err
}
tx.Rehash()
return env, nil
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"Sign",
"(",
"signingAccounts",
"...",
"acm",
".",
"AddressableSigner",
")",
"(",
"*",
"Envelope",
",",
"error",
")",
"{",
"env",
":=",
"tx",
".",
"Enclose",
"(",
")",
"\n",
"err",
":=",
"env",
".",
"Sign",
"(",
"signingAccounts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tx",
".",
"Rehash",
"(",
")",
"\n",
"return",
"env",
",",
"nil",
"\n",
"}"
] | // Encloses in Envelope and signs envelope | [
"Encloses",
"in",
"Envelope",
"and",
"signs",
"envelope"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/tx.go#L56-L64 | train |
hyperledger/burrow | txs/tx.go | MustSignBytes | func (tx *Tx) MustSignBytes() []byte {
bs, err := tx.SignBytes()
if err != nil {
panic(err)
}
return bs
} | go | func (tx *Tx) MustSignBytes() []byte {
bs, err := tx.SignBytes()
if err != nil {
panic(err)
}
return bs
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"MustSignBytes",
"(",
")",
"[",
"]",
"byte",
"{",
"bs",
",",
"err",
":=",
"tx",
".",
"SignBytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"bs",
"\n",
"}"
] | // Generate SignBytes, panicking on any failure | [
"Generate",
"SignBytes",
"panicking",
"on",
"any",
"failure"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/tx.go#L67-L73 | train |
hyperledger/burrow | txs/tx.go | GenerateReceipt | func (tx *Tx) GenerateReceipt() *Receipt {
receipt := &Receipt{
TxType: tx.Type(),
TxHash: tx.Hash(),
}
if callTx, ok := tx.Payload.(*payload.CallTx); ok {
receipt.CreatesContract = callTx.Address == nil
if receipt.CreatesContract {
receipt.ContractAddress = crypto.NewContractAddress(callTx.Input.Address, tx.Hash())
} else {
receipt.ContractAddress = *callTx.Address
}
}
return receipt
} | go | func (tx *Tx) GenerateReceipt() *Receipt {
receipt := &Receipt{
TxType: tx.Type(),
TxHash: tx.Hash(),
}
if callTx, ok := tx.Payload.(*payload.CallTx); ok {
receipt.CreatesContract = callTx.Address == nil
if receipt.CreatesContract {
receipt.ContractAddress = crypto.NewContractAddress(callTx.Input.Address, tx.Hash())
} else {
receipt.ContractAddress = *callTx.Address
}
}
return receipt
} | [
"func",
"(",
"tx",
"*",
"Tx",
")",
"GenerateReceipt",
"(",
")",
"*",
"Receipt",
"{",
"receipt",
":=",
"&",
"Receipt",
"{",
"TxType",
":",
"tx",
".",
"Type",
"(",
")",
",",
"TxHash",
":",
"tx",
".",
"Hash",
"(",
")",
",",
"}",
"\n",
"if",
"callTx",
",",
"ok",
":=",
"tx",
".",
"Payload",
".",
"(",
"*",
"payload",
".",
"CallTx",
")",
";",
"ok",
"{",
"receipt",
".",
"CreatesContract",
"=",
"callTx",
".",
"Address",
"==",
"nil",
"\n",
"if",
"receipt",
".",
"CreatesContract",
"{",
"receipt",
".",
"ContractAddress",
"=",
"crypto",
".",
"NewContractAddress",
"(",
"callTx",
".",
"Input",
".",
"Address",
",",
"tx",
".",
"Hash",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"receipt",
".",
"ContractAddress",
"=",
"*",
"callTx",
".",
"Address",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"receipt",
"\n",
"}"
] | // Generate a transaction Receipt containing the Tx hash and other information if the Tx is call.
// Returned by ABCI methods. | [
"Generate",
"a",
"transaction",
"Receipt",
"containing",
"the",
"Tx",
"hash",
"and",
"other",
"information",
"if",
"the",
"Tx",
"is",
"call",
".",
"Returned",
"by",
"ABCI",
"methods",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/tx.go#L184-L198 | train |
hyperledger/burrow | logging/loggers/filter_logger.go | FilterLogger | func FilterLogger(outputLogger log.Logger, predicate func(keyvals []interface{}) bool) log.Logger {
return log.LoggerFunc(func(keyvals ...interface{}) error {
// Always forward signals
if structure.Signal(keyvals) != "" || !predicate(keyvals) {
return outputLogger.Log(keyvals...)
}
return nil
})
} | go | func FilterLogger(outputLogger log.Logger, predicate func(keyvals []interface{}) bool) log.Logger {
return log.LoggerFunc(func(keyvals ...interface{}) error {
// Always forward signals
if structure.Signal(keyvals) != "" || !predicate(keyvals) {
return outputLogger.Log(keyvals...)
}
return nil
})
} | [
"func",
"FilterLogger",
"(",
"outputLogger",
"log",
".",
"Logger",
",",
"predicate",
"func",
"(",
"keyvals",
"[",
"]",
"interface",
"{",
"}",
")",
"bool",
")",
"log",
".",
"Logger",
"{",
"return",
"log",
".",
"LoggerFunc",
"(",
"func",
"(",
"keyvals",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"// Always forward signals",
"if",
"structure",
".",
"Signal",
"(",
"keyvals",
")",
"!=",
"\"",
"\"",
"||",
"!",
"predicate",
"(",
"keyvals",
")",
"{",
"return",
"outputLogger",
".",
"Log",
"(",
"keyvals",
"...",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // Filter logger allows us to filter lines logged to it before passing on to underlying
// output logger
// Creates a logger that removes lines from output when the predicate evaluates true | [
"Filter",
"logger",
"allows",
"us",
"to",
"filter",
"lines",
"logged",
"to",
"it",
"before",
"passing",
"on",
"to",
"underlying",
"output",
"logger",
"Creates",
"a",
"logger",
"that",
"removes",
"lines",
"from",
"output",
"when",
"the",
"predicate",
"evaluates",
"true"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/loggers/filter_logger.go#L11-L19 | train |
hyperledger/burrow | deploy/def/client.go | dial | func (c *Client) dial(logger *logging.Logger) error {
if c.transactClient == nil {
conn, err := grpc.Dial(c.ChainAddress, grpc.WithInsecure())
if err != nil {
return err
}
c.transactClient = rpctransact.NewTransactClient(conn)
c.queryClient = rpcquery.NewQueryClient(conn)
c.executionEventsClient = rpcevents.NewExecutionEventsClient(conn)
if c.KeysClientAddress == "" {
logger.InfoMsg("Using mempool signing since no keyClient set, pass --keys to sign locally or elsewhere")
c.MempoolSigning = true
c.keyClient, err = keys.NewRemoteKeyClient(c.ChainAddress, logger)
} else {
logger.InfoMsg("Using keys server", "server", c.KeysClientAddress)
c.keyClient, err = keys.NewRemoteKeyClient(c.KeysClientAddress, logger)
}
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
stat, err := c.queryClient.Status(ctx, &rpcquery.StatusParam{})
if err != nil {
return err
}
c.chainID = stat.ChainID
}
return nil
} | go | func (c *Client) dial(logger *logging.Logger) error {
if c.transactClient == nil {
conn, err := grpc.Dial(c.ChainAddress, grpc.WithInsecure())
if err != nil {
return err
}
c.transactClient = rpctransact.NewTransactClient(conn)
c.queryClient = rpcquery.NewQueryClient(conn)
c.executionEventsClient = rpcevents.NewExecutionEventsClient(conn)
if c.KeysClientAddress == "" {
logger.InfoMsg("Using mempool signing since no keyClient set, pass --keys to sign locally or elsewhere")
c.MempoolSigning = true
c.keyClient, err = keys.NewRemoteKeyClient(c.ChainAddress, logger)
} else {
logger.InfoMsg("Using keys server", "server", c.KeysClientAddress)
c.keyClient, err = keys.NewRemoteKeyClient(c.KeysClientAddress, logger)
}
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
stat, err := c.queryClient.Status(ctx, &rpcquery.StatusParam{})
if err != nil {
return err
}
c.chainID = stat.ChainID
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"dial",
"(",
"logger",
"*",
"logging",
".",
"Logger",
")",
"error",
"{",
"if",
"c",
".",
"transactClient",
"==",
"nil",
"{",
"conn",
",",
"err",
":=",
"grpc",
".",
"Dial",
"(",
"c",
".",
"ChainAddress",
",",
"grpc",
".",
"WithInsecure",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"transactClient",
"=",
"rpctransact",
".",
"NewTransactClient",
"(",
"conn",
")",
"\n",
"c",
".",
"queryClient",
"=",
"rpcquery",
".",
"NewQueryClient",
"(",
"conn",
")",
"\n",
"c",
".",
"executionEventsClient",
"=",
"rpcevents",
".",
"NewExecutionEventsClient",
"(",
"conn",
")",
"\n",
"if",
"c",
".",
"KeysClientAddress",
"==",
"\"",
"\"",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"MempoolSigning",
"=",
"true",
"\n",
"c",
".",
"keyClient",
",",
"err",
"=",
"keys",
".",
"NewRemoteKeyClient",
"(",
"c",
".",
"ChainAddress",
",",
"logger",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"c",
".",
"KeysClientAddress",
")",
"\n",
"c",
".",
"keyClient",
",",
"err",
"=",
"keys",
".",
"NewRemoteKeyClient",
"(",
"c",
".",
"KeysClientAddress",
",",
"logger",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"c",
".",
"timeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"stat",
",",
"err",
":=",
"c",
".",
"queryClient",
".",
"Status",
"(",
"ctx",
",",
"&",
"rpcquery",
".",
"StatusParam",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"chainID",
"=",
"stat",
".",
"ChainID",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Connect GRPC clients using ChainURL | [
"Connect",
"GRPC",
"clients",
"using",
"ChainURL"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L58-L89 | train |
hyperledger/burrow | deploy/def/client.go | CreateKey | func (c *Client) CreateKey(keyName, curveTypeString string, logger *logging.Logger) (crypto.PublicKey, error) {
err := c.dial(logger)
if err != nil {
return crypto.PublicKey{}, err
}
if c.keyClient == nil {
return crypto.PublicKey{}, fmt.Errorf("could not create key pair since no keys service is attached, " +
"pass --keys flag")
}
curveType := crypto.CurveTypeEd25519
if curveTypeString != "" {
curveType, err = crypto.CurveTypeFromString(curveTypeString)
if err != nil {
return crypto.PublicKey{}, err
}
}
address, err := c.keyClient.Generate(keyName, curveType)
if err != nil {
return crypto.PublicKey{}, err
}
return c.keyClient.PublicKey(address)
} | go | func (c *Client) CreateKey(keyName, curveTypeString string, logger *logging.Logger) (crypto.PublicKey, error) {
err := c.dial(logger)
if err != nil {
return crypto.PublicKey{}, err
}
if c.keyClient == nil {
return crypto.PublicKey{}, fmt.Errorf("could not create key pair since no keys service is attached, " +
"pass --keys flag")
}
curveType := crypto.CurveTypeEd25519
if curveTypeString != "" {
curveType, err = crypto.CurveTypeFromString(curveTypeString)
if err != nil {
return crypto.PublicKey{}, err
}
}
address, err := c.keyClient.Generate(keyName, curveType)
if err != nil {
return crypto.PublicKey{}, err
}
return c.keyClient.PublicKey(address)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CreateKey",
"(",
"keyName",
",",
"curveTypeString",
"string",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"crypto",
".",
"PublicKey",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"dial",
"(",
"logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"crypto",
".",
"PublicKey",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"c",
".",
"keyClient",
"==",
"nil",
"{",
"return",
"crypto",
".",
"PublicKey",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"curveType",
":=",
"crypto",
".",
"CurveTypeEd25519",
"\n",
"if",
"curveTypeString",
"!=",
"\"",
"\"",
"{",
"curveType",
",",
"err",
"=",
"crypto",
".",
"CurveTypeFromString",
"(",
"curveTypeString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"crypto",
".",
"PublicKey",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"address",
",",
"err",
":=",
"c",
".",
"keyClient",
".",
"Generate",
"(",
"keyName",
",",
"curveType",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"crypto",
".",
"PublicKey",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"keyClient",
".",
"PublicKey",
"(",
"address",
")",
"\n",
"}"
] | // Creates a keypair using attached keys service | [
"Creates",
"a",
"keypair",
"using",
"attached",
"keys",
"service"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L238-L259 | train |
hyperledger/burrow | deploy/def/client.go | Broadcast | func (c *Client) Broadcast(tx payload.Payload, logger *logging.Logger) (*exec.TxExecution, error) {
err := c.dial(logger)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Payload: tx.Any()})
} | go | func (c *Client) Broadcast(tx payload.Payload, logger *logging.Logger) (*exec.TxExecution, error) {
err := c.dial(logger)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Payload: tx.Any()})
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Broadcast",
"(",
"tx",
"payload",
".",
"Payload",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"*",
"exec",
".",
"TxExecution",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"dial",
"(",
"logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"c",
".",
"timeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"return",
"c",
".",
"transactClient",
".",
"BroadcastTxSync",
"(",
"ctx",
",",
"&",
"rpctransact",
".",
"TxEnvelopeParam",
"{",
"Payload",
":",
"tx",
".",
"Any",
"(",
")",
"}",
")",
"\n",
"}"
] | // Broadcast payload for remote signing | [
"Broadcast",
"payload",
"for",
"remote",
"signing"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L262-L270 | train |
hyperledger/burrow | deploy/def/client.go | BroadcastEnvelope | func (c *Client) BroadcastEnvelope(txEnv *txs.Envelope, logger *logging.Logger) (*exec.TxExecution, error) {
err := c.dial(logger)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Envelope: txEnv})
} | go | func (c *Client) BroadcastEnvelope(txEnv *txs.Envelope, logger *logging.Logger) (*exec.TxExecution, error) {
err := c.dial(logger)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Envelope: txEnv})
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"BroadcastEnvelope",
"(",
"txEnv",
"*",
"txs",
".",
"Envelope",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"*",
"exec",
".",
"TxExecution",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"dial",
"(",
"logger",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"c",
".",
"timeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"return",
"c",
".",
"transactClient",
".",
"BroadcastTxSync",
"(",
"ctx",
",",
"&",
"rpctransact",
".",
"TxEnvelopeParam",
"{",
"Envelope",
":",
"txEnv",
"}",
")",
"\n",
"}"
] | // Broadcast envelope - can be locally signed or remote signing will be attempted | [
"Broadcast",
"envelope",
"-",
"can",
"be",
"locally",
"signed",
"or",
"remote",
"signing",
"will",
"be",
"attempted"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L273-L282 | train |
hyperledger/burrow | core/processes.go | NoConsensusLauncher | func NoConsensusLauncher(kern *Kernel) process.Launcher {
return process.Launcher{
Name: NoConsensusProcessName,
Enabled: kern.Node == nil,
Launch: func() (process.Process, error) {
accountState := kern.State
nameRegState := kern.State
kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, kern.State, nil, kern.Logger)
// TimeoutFactor scales in units of seconds
blockDuration := time.Duration(kern.timeoutFactor * float64(time.Second))
//proc := abci.NewProcess(kern.checker, kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)
proc := abci.NewProcess(kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)
// Provide execution accounts against backend state since we will commit immediately
accounts := execution.NewAccounts(kern.committer, kern.keyClient, AccountsRingMutexCount)
// Elide consensus and use a CheckTx function that immediately commits any valid transaction
kern.Transactor = execution.NewTransactor(kern.Blockchain, kern.Emitter, accounts, proc.CheckTx, kern.txCodec,
kern.Logger)
return proc, nil
},
}
} | go | func NoConsensusLauncher(kern *Kernel) process.Launcher {
return process.Launcher{
Name: NoConsensusProcessName,
Enabled: kern.Node == nil,
Launch: func() (process.Process, error) {
accountState := kern.State
nameRegState := kern.State
kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, kern.State, nil, kern.Logger)
// TimeoutFactor scales in units of seconds
blockDuration := time.Duration(kern.timeoutFactor * float64(time.Second))
//proc := abci.NewProcess(kern.checker, kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)
proc := abci.NewProcess(kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)
// Provide execution accounts against backend state since we will commit immediately
accounts := execution.NewAccounts(kern.committer, kern.keyClient, AccountsRingMutexCount)
// Elide consensus and use a CheckTx function that immediately commits any valid transaction
kern.Transactor = execution.NewTransactor(kern.Blockchain, kern.Emitter, accounts, proc.CheckTx, kern.txCodec,
kern.Logger)
return proc, nil
},
}
} | [
"func",
"NoConsensusLauncher",
"(",
"kern",
"*",
"Kernel",
")",
"process",
".",
"Launcher",
"{",
"return",
"process",
".",
"Launcher",
"{",
"Name",
":",
"NoConsensusProcessName",
",",
"Enabled",
":",
"kern",
".",
"Node",
"==",
"nil",
",",
"Launch",
":",
"func",
"(",
")",
"(",
"process",
".",
"Process",
",",
"error",
")",
"{",
"accountState",
":=",
"kern",
".",
"State",
"\n",
"nameRegState",
":=",
"kern",
".",
"State",
"\n",
"kern",
".",
"Service",
"=",
"rpc",
".",
"NewService",
"(",
"accountState",
",",
"nameRegState",
",",
"kern",
".",
"Blockchain",
",",
"kern",
".",
"State",
",",
"nil",
",",
"kern",
".",
"Logger",
")",
"\n",
"// TimeoutFactor scales in units of seconds",
"blockDuration",
":=",
"time",
".",
"Duration",
"(",
"kern",
".",
"timeoutFactor",
"*",
"float64",
"(",
"time",
".",
"Second",
")",
")",
"\n",
"//proc := abci.NewProcess(kern.checker, kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)",
"proc",
":=",
"abci",
".",
"NewProcess",
"(",
"kern",
".",
"committer",
",",
"kern",
".",
"Blockchain",
",",
"kern",
".",
"txCodec",
",",
"blockDuration",
",",
"kern",
".",
"Panic",
")",
"\n",
"// Provide execution accounts against backend state since we will commit immediately",
"accounts",
":=",
"execution",
".",
"NewAccounts",
"(",
"kern",
".",
"committer",
",",
"kern",
".",
"keyClient",
",",
"AccountsRingMutexCount",
")",
"\n",
"// Elide consensus and use a CheckTx function that immediately commits any valid transaction",
"kern",
".",
"Transactor",
"=",
"execution",
".",
"NewTransactor",
"(",
"kern",
".",
"Blockchain",
",",
"kern",
".",
"Emitter",
",",
"accounts",
",",
"proc",
".",
"CheckTx",
",",
"kern",
".",
"txCodec",
",",
"kern",
".",
"Logger",
")",
"\n",
"return",
"proc",
",",
"nil",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // Run a single uncoordinated local state | [
"Run",
"a",
"single",
"uncoordinated",
"local",
"state"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/core/processes.go#L87-L107 | train |
hyperledger/burrow | acm/private_account.go | SigningAccounts | func SigningAccounts(concretePrivateAccounts []*PrivateAccount) []AddressableSigner {
signingAccounts := make([]AddressableSigner, len(concretePrivateAccounts))
for i, cpa := range concretePrivateAccounts {
signingAccounts[i] = cpa
}
return signingAccounts
} | go | func SigningAccounts(concretePrivateAccounts []*PrivateAccount) []AddressableSigner {
signingAccounts := make([]AddressableSigner, len(concretePrivateAccounts))
for i, cpa := range concretePrivateAccounts {
signingAccounts[i] = cpa
}
return signingAccounts
} | [
"func",
"SigningAccounts",
"(",
"concretePrivateAccounts",
"[",
"]",
"*",
"PrivateAccount",
")",
"[",
"]",
"AddressableSigner",
"{",
"signingAccounts",
":=",
"make",
"(",
"[",
"]",
"AddressableSigner",
",",
"len",
"(",
"concretePrivateAccounts",
")",
")",
"\n",
"for",
"i",
",",
"cpa",
":=",
"range",
"concretePrivateAccounts",
"{",
"signingAccounts",
"[",
"i",
"]",
"=",
"cpa",
"\n",
"}",
"\n",
"return",
"signingAccounts",
"\n",
"}"
] | // Convert slice of ConcretePrivateAccounts to slice of SigningAccounts | [
"Convert",
"slice",
"of",
"ConcretePrivateAccounts",
"to",
"slice",
"of",
"SigningAccounts"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/private_account.go#L99-L105 | train |
hyperledger/burrow | acm/private_account.go | GeneratePrivateAccount | func GeneratePrivateAccount() (*PrivateAccount, error) {
privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519)
if err != nil {
return nil, err
}
publicKey := privateKey.GetPublicKey()
return ConcretePrivateAccount{
Address: publicKey.GetAddress(),
PublicKey: publicKey,
PrivateKey: privateKey,
}.PrivateAccount(), nil
} | go | func GeneratePrivateAccount() (*PrivateAccount, error) {
privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519)
if err != nil {
return nil, err
}
publicKey := privateKey.GetPublicKey()
return ConcretePrivateAccount{
Address: publicKey.GetAddress(),
PublicKey: publicKey,
PrivateKey: privateKey,
}.PrivateAccount(), nil
} | [
"func",
"GeneratePrivateAccount",
"(",
")",
"(",
"*",
"PrivateAccount",
",",
"error",
")",
"{",
"privateKey",
",",
"err",
":=",
"crypto",
".",
"GeneratePrivateKey",
"(",
"nil",
",",
"crypto",
".",
"CurveTypeEd25519",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"publicKey",
":=",
"privateKey",
".",
"GetPublicKey",
"(",
")",
"\n",
"return",
"ConcretePrivateAccount",
"{",
"Address",
":",
"publicKey",
".",
"GetAddress",
"(",
")",
",",
"PublicKey",
":",
"publicKey",
",",
"PrivateKey",
":",
"privateKey",
",",
"}",
".",
"PrivateAccount",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Generates a new account with private key. | [
"Generates",
"a",
"new",
"account",
"with",
"private",
"key",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/private_account.go#L108-L119 | train |
hyperledger/burrow | acm/private_account.go | GeneratePrivateAccountFromSecret | func GeneratePrivateAccountFromSecret(secret string) *PrivateAccount {
privateKey := crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519)
publicKey := privateKey.GetPublicKey()
return ConcretePrivateAccount{
Address: publicKey.GetAddress(),
PublicKey: publicKey,
PrivateKey: privateKey,
}.PrivateAccount()
} | go | func GeneratePrivateAccountFromSecret(secret string) *PrivateAccount {
privateKey := crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519)
publicKey := privateKey.GetPublicKey()
return ConcretePrivateAccount{
Address: publicKey.GetAddress(),
PublicKey: publicKey,
PrivateKey: privateKey,
}.PrivateAccount()
} | [
"func",
"GeneratePrivateAccountFromSecret",
"(",
"secret",
"string",
")",
"*",
"PrivateAccount",
"{",
"privateKey",
":=",
"crypto",
".",
"PrivateKeyFromSecret",
"(",
"secret",
",",
"crypto",
".",
"CurveTypeEd25519",
")",
"\n",
"publicKey",
":=",
"privateKey",
".",
"GetPublicKey",
"(",
")",
"\n",
"return",
"ConcretePrivateAccount",
"{",
"Address",
":",
"publicKey",
".",
"GetAddress",
"(",
")",
",",
"PublicKey",
":",
"publicKey",
",",
"PrivateKey",
":",
"privateKey",
",",
"}",
".",
"PrivateAccount",
"(",
")",
"\n",
"}"
] | // Generates a new account with private key from SHA256 hash of a secret | [
"Generates",
"a",
"new",
"account",
"with",
"private",
"key",
"from",
"SHA256",
"hash",
"of",
"a",
"secret"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/private_account.go#L122-L130 | train |
hyperledger/burrow | cmd/burrow/commands/snatives.go | Snatives | func Snatives(output Output) func(cmd *cli.Cmd) {
return func(cmd *cli.Cmd) {
contractsOpt := cmd.StringsOpt("c contracts", nil, "Contracts to generate")
cmd.Action = func() {
contracts := evm.SNativeContracts()
// Index of next contract
i := 1
for _, contract := range contracts {
if len(*contractsOpt) > 0 {
found := false
for _, c := range *contractsOpt {
if c == contract.Name {
found = true
break
}
}
if !found {
continue
}
}
solidity, err := templates.NewSolidityContract(contract).Solidity()
if err != nil {
fmt.Printf("Error generating solidity for contract %s: %s\n",
contract.Name, err)
}
fmt.Println(solidity)
if i < len(contracts) {
// Two new lines between contracts as per Solidity style guide
// (the template gives us 1 trailing new line)
fmt.Println()
}
i++
}
}
}
} | go | func Snatives(output Output) func(cmd *cli.Cmd) {
return func(cmd *cli.Cmd) {
contractsOpt := cmd.StringsOpt("c contracts", nil, "Contracts to generate")
cmd.Action = func() {
contracts := evm.SNativeContracts()
// Index of next contract
i := 1
for _, contract := range contracts {
if len(*contractsOpt) > 0 {
found := false
for _, c := range *contractsOpt {
if c == contract.Name {
found = true
break
}
}
if !found {
continue
}
}
solidity, err := templates.NewSolidityContract(contract).Solidity()
if err != nil {
fmt.Printf("Error generating solidity for contract %s: %s\n",
contract.Name, err)
}
fmt.Println(solidity)
if i < len(contracts) {
// Two new lines between contracts as per Solidity style guide
// (the template gives us 1 trailing new line)
fmt.Println()
}
i++
}
}
}
} | [
"func",
"Snatives",
"(",
"output",
"Output",
")",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"return",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"contractsOpt",
":=",
"cmd",
".",
"StringsOpt",
"(",
"\"",
"\"",
",",
"nil",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Action",
"=",
"func",
"(",
")",
"{",
"contracts",
":=",
"evm",
".",
"SNativeContracts",
"(",
")",
"\n",
"// Index of next contract",
"i",
":=",
"1",
"\n",
"for",
"_",
",",
"contract",
":=",
"range",
"contracts",
"{",
"if",
"len",
"(",
"*",
"contractsOpt",
")",
">",
"0",
"{",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"*",
"contractsOpt",
"{",
"if",
"c",
"==",
"contract",
".",
"Name",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"solidity",
",",
"err",
":=",
"templates",
".",
"NewSolidityContract",
"(",
"contract",
")",
".",
"Solidity",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"contract",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"solidity",
")",
"\n",
"if",
"i",
"<",
"len",
"(",
"contracts",
")",
"{",
"// Two new lines between contracts as per Solidity style guide",
"// (the template gives us 1 trailing new line)",
"fmt",
".",
"Println",
"(",
")",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Dump SNative contracts | [
"Dump",
"SNative",
"contracts"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/cmd/burrow/commands/snatives.go#L27-L62 | train |
hyperledger/burrow | storage/rwtree.go | Save | func (rwt *RWTree) Save() ([]byte, int64, error) {
// save state at a new version may still be orphaned before we save the version against the hash
hash, version, err := rwt.tree.SaveVersion()
if err != nil {
return nil, 0, fmt.Errorf("could not save RWTree: %v", err)
}
// Take an immutable reference to the tree we just saved for querying
rwt.ImmutableTree, err = rwt.tree.GetImmutable(version)
if err != nil {
return nil, 0, fmt.Errorf("RWTree.Save() could not obtain ImmutableTree read tree: %v", err)
}
rwt.updated = false
return hash, version, nil
} | go | func (rwt *RWTree) Save() ([]byte, int64, error) {
// save state at a new version may still be orphaned before we save the version against the hash
hash, version, err := rwt.tree.SaveVersion()
if err != nil {
return nil, 0, fmt.Errorf("could not save RWTree: %v", err)
}
// Take an immutable reference to the tree we just saved for querying
rwt.ImmutableTree, err = rwt.tree.GetImmutable(version)
if err != nil {
return nil, 0, fmt.Errorf("RWTree.Save() could not obtain ImmutableTree read tree: %v", err)
}
rwt.updated = false
return hash, version, nil
} | [
"func",
"(",
"rwt",
"*",
"RWTree",
")",
"Save",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"int64",
",",
"error",
")",
"{",
"// save state at a new version may still be orphaned before we save the version against the hash",
"hash",
",",
"version",
",",
"err",
":=",
"rwt",
".",
"tree",
".",
"SaveVersion",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// Take an immutable reference to the tree we just saved for querying",
"rwt",
".",
"ImmutableTree",
",",
"err",
"=",
"rwt",
".",
"tree",
".",
"GetImmutable",
"(",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"rwt",
".",
"updated",
"=",
"false",
"\n",
"return",
"hash",
",",
"version",
",",
"nil",
"\n",
"}"
] | // Save the current write tree making writes accessible from read tree. | [
"Save",
"the",
"current",
"write",
"tree",
"making",
"writes",
"accessible",
"from",
"read",
"tree",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/rwtree.go#L50-L63 | train |
hyperledger/burrow | execution/evm/stack.go | PushBytes | func (st *Stack) PushBytes(bz []byte) {
if len(bz) != 32 {
panic("Invalid bytes size: expected 32")
}
st.Push(LeftPadWord256(bz))
} | go | func (st *Stack) PushBytes(bz []byte) {
if len(bz) != 32 {
panic("Invalid bytes size: expected 32")
}
st.Push(LeftPadWord256(bz))
} | [
"func",
"(",
"st",
"*",
"Stack",
")",
"PushBytes",
"(",
"bz",
"[",
"]",
"byte",
")",
"{",
"if",
"len",
"(",
"bz",
")",
"!=",
"32",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"st",
".",
"Push",
"(",
"LeftPadWord256",
"(",
"bz",
")",
")",
"\n",
"}"
] | // currently only called after sha3.Sha3 | [
"currently",
"only",
"called",
"after",
"sha3",
".",
"Sha3"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/stack.go#L74-L79 | train |
hyperledger/burrow | execution/evm/stack.go | PushBigInt | func (st *Stack) PushBigInt(bigInt *big.Int) Word256 {
word := LeftPadWord256(U256(bigInt).Bytes())
st.Push(word)
return word
} | go | func (st *Stack) PushBigInt(bigInt *big.Int) Word256 {
word := LeftPadWord256(U256(bigInt).Bytes())
st.Push(word)
return word
} | [
"func",
"(",
"st",
"*",
"Stack",
")",
"PushBigInt",
"(",
"bigInt",
"*",
"big",
".",
"Int",
")",
"Word256",
"{",
"word",
":=",
"LeftPadWord256",
"(",
"U256",
"(",
"bigInt",
")",
".",
"Bytes",
"(",
")",
")",
"\n",
"st",
".",
"Push",
"(",
"word",
")",
"\n",
"return",
"word",
"\n",
"}"
] | // Pushes the bigInt as a Word256 encoding negative values in 32-byte twos complement and returns the encoded result | [
"Pushes",
"the",
"bigInt",
"as",
"a",
"Word256",
"encoding",
"negative",
"values",
"in",
"32",
"-",
"byte",
"twos",
"complement",
"and",
"returns",
"the",
"encoded",
"result"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/stack.go#L94-L98 | train |
hyperledger/burrow | execution/evm/stack.go | Peek | func (st *Stack) Peek() Word256 {
if st.ptr == 0 {
st.pushErr(errors.ErrorCodeDataStackUnderflow)
return Zero256
}
return st.slice[st.ptr-1]
} | go | func (st *Stack) Peek() Word256 {
if st.ptr == 0 {
st.pushErr(errors.ErrorCodeDataStackUnderflow)
return Zero256
}
return st.slice[st.ptr-1]
} | [
"func",
"(",
"st",
"*",
"Stack",
")",
"Peek",
"(",
")",
"Word256",
"{",
"if",
"st",
".",
"ptr",
"==",
"0",
"{",
"st",
".",
"pushErr",
"(",
"errors",
".",
"ErrorCodeDataStackUnderflow",
")",
"\n",
"return",
"Zero256",
"\n",
"}",
"\n",
"return",
"st",
".",
"slice",
"[",
"st",
".",
"ptr",
"-",
"1",
"]",
"\n",
"}"
] | // Not an opcode, costs no gas. | [
"Not",
"an",
"opcode",
"costs",
"no",
"gas",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/stack.go#L170-L176 | train |
hyperledger/burrow | acm/acmstate/state_cache.go | NewCache | func NewCache(backend Reader, options ...CacheOption) *Cache {
cache := &Cache{
backend: backend,
accounts: make(map[crypto.Address]*accountInfo),
}
for _, option := range options {
option(cache)
}
return cache
} | go | func NewCache(backend Reader, options ...CacheOption) *Cache {
cache := &Cache{
backend: backend,
accounts: make(map[crypto.Address]*accountInfo),
}
for _, option := range options {
option(cache)
}
return cache
} | [
"func",
"NewCache",
"(",
"backend",
"Reader",
",",
"options",
"...",
"CacheOption",
")",
"*",
"Cache",
"{",
"cache",
":=",
"&",
"Cache",
"{",
"backend",
":",
"backend",
",",
"accounts",
":",
"make",
"(",
"map",
"[",
"crypto",
".",
"Address",
"]",
"*",
"accountInfo",
")",
",",
"}",
"\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"cache",
")",
"\n",
"}",
"\n",
"return",
"cache",
"\n",
"}"
] | // Returns a Cache that wraps an underlying Reader to use on a cache miss, can write to an output Writer
// via Sync. Goroutine safe for concurrent access. | [
"Returns",
"a",
"Cache",
"that",
"wraps",
"an",
"underlying",
"Reader",
"to",
"use",
"on",
"a",
"cache",
"miss",
"can",
"write",
"to",
"an",
"output",
"Writer",
"via",
"Sync",
".",
"Goroutine",
"safe",
"for",
"concurrent",
"access",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L49-L58 | train |
hyperledger/burrow | acm/acmstate/state_cache.go | IterateCachedAccount | func (cache *Cache) IterateCachedAccount(consumer func(*acm.Account) (stop bool)) (stopped bool, err error) {
// Try cache first for early exit
cache.RLock()
for _, info := range cache.accounts {
if consumer(info.account) {
cache.RUnlock()
return true, nil
}
}
cache.RUnlock()
return false, nil
} | go | func (cache *Cache) IterateCachedAccount(consumer func(*acm.Account) (stop bool)) (stopped bool, err error) {
// Try cache first for early exit
cache.RLock()
for _, info := range cache.accounts {
if consumer(info.account) {
cache.RUnlock()
return true, nil
}
}
cache.RUnlock()
return false, nil
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"IterateCachedAccount",
"(",
"consumer",
"func",
"(",
"*",
"acm",
".",
"Account",
")",
"(",
"stop",
"bool",
")",
")",
"(",
"stopped",
"bool",
",",
"err",
"error",
")",
"{",
"// Try cache first for early exit",
"cache",
".",
"RLock",
"(",
")",
"\n",
"for",
"_",
",",
"info",
":=",
"range",
"cache",
".",
"accounts",
"{",
"if",
"consumer",
"(",
"info",
".",
"account",
")",
"{",
"cache",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"cache",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // Iterates over all cached accounts first in cache and then in backend until consumer returns true for 'stop' | [
"Iterates",
"over",
"all",
"cached",
"accounts",
"first",
"in",
"cache",
"and",
"then",
"in",
"backend",
"until",
"consumer",
"returns",
"true",
"for",
"stop"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L125-L136 | train |
hyperledger/burrow | acm/acmstate/state_cache.go | IterateCachedStorage | func (cache *Cache) IterateCachedStorage(address crypto.Address,
consumer func(key, value binary.Word256) error) error {
accInfo, err := cache.get(address)
if err != nil {
return err
}
accInfo.RLock()
// Try cache first for early exit
for key, value := range accInfo.storage {
if err := consumer(key, value); err != nil {
accInfo.RUnlock()
return err
}
}
accInfo.RUnlock()
return err
} | go | func (cache *Cache) IterateCachedStorage(address crypto.Address,
consumer func(key, value binary.Word256) error) error {
accInfo, err := cache.get(address)
if err != nil {
return err
}
accInfo.RLock()
// Try cache first for early exit
for key, value := range accInfo.storage {
if err := consumer(key, value); err != nil {
accInfo.RUnlock()
return err
}
}
accInfo.RUnlock()
return err
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"IterateCachedStorage",
"(",
"address",
"crypto",
".",
"Address",
",",
"consumer",
"func",
"(",
"key",
",",
"value",
"binary",
".",
"Word256",
")",
"error",
")",
"error",
"{",
"accInfo",
",",
"err",
":=",
"cache",
".",
"get",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"accInfo",
".",
"RLock",
"(",
")",
"\n",
"// Try cache first for early exit",
"for",
"key",
",",
"value",
":=",
"range",
"accInfo",
".",
"storage",
"{",
"if",
"err",
":=",
"consumer",
"(",
"key",
",",
"value",
")",
";",
"err",
"!=",
"nil",
"{",
"accInfo",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"accInfo",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Iterates over all cached storage items first in cache and then in backend until consumer returns true for 'stop' | [
"Iterates",
"over",
"all",
"cached",
"storage",
"items",
"first",
"in",
"cache",
"and",
"then",
"in",
"backend",
"until",
"consumer",
"returns",
"true",
"for",
"stop"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L188-L204 | train |
hyperledger/burrow | acm/acmstate/state_cache.go | Sync | func (cache *Cache) Sync(st Writer) error {
if cache.readonly {
// Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods
return nil
}
cache.Lock()
defer cache.Unlock()
var addresses crypto.Addresses
for address := range cache.accounts {
addresses = append(addresses, address)
}
sort.Sort(addresses)
for _, address := range addresses {
accInfo := cache.accounts[address]
accInfo.RLock()
if accInfo.removed {
err := st.RemoveAccount(address)
if err != nil {
return err
}
} else if accInfo.updated {
// First update account in case it needs to be created
err := st.UpdateAccount(accInfo.account)
if err != nil {
return err
}
// Sort keys
var keys binary.Words256
for key := range accInfo.storage {
keys = append(keys, key)
}
sort.Sort(keys)
// Update account's storage
for _, key := range keys {
value := accInfo.storage[key]
err := st.SetStorage(address, key, value)
if err != nil {
return err
}
}
}
accInfo.RUnlock()
}
return nil
} | go | func (cache *Cache) Sync(st Writer) error {
if cache.readonly {
// Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods
return nil
}
cache.Lock()
defer cache.Unlock()
var addresses crypto.Addresses
for address := range cache.accounts {
addresses = append(addresses, address)
}
sort.Sort(addresses)
for _, address := range addresses {
accInfo := cache.accounts[address]
accInfo.RLock()
if accInfo.removed {
err := st.RemoveAccount(address)
if err != nil {
return err
}
} else if accInfo.updated {
// First update account in case it needs to be created
err := st.UpdateAccount(accInfo.account)
if err != nil {
return err
}
// Sort keys
var keys binary.Words256
for key := range accInfo.storage {
keys = append(keys, key)
}
sort.Sort(keys)
// Update account's storage
for _, key := range keys {
value := accInfo.storage[key]
err := st.SetStorage(address, key, value)
if err != nil {
return err
}
}
}
accInfo.RUnlock()
}
return nil
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"Sync",
"(",
"st",
"Writer",
")",
"error",
"{",
"if",
"cache",
".",
"readonly",
"{",
"// Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods",
"return",
"nil",
"\n",
"}",
"\n",
"cache",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cache",
".",
"Unlock",
"(",
")",
"\n",
"var",
"addresses",
"crypto",
".",
"Addresses",
"\n",
"for",
"address",
":=",
"range",
"cache",
".",
"accounts",
"{",
"addresses",
"=",
"append",
"(",
"addresses",
",",
"address",
")",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"addresses",
")",
"\n",
"for",
"_",
",",
"address",
":=",
"range",
"addresses",
"{",
"accInfo",
":=",
"cache",
".",
"accounts",
"[",
"address",
"]",
"\n",
"accInfo",
".",
"RLock",
"(",
")",
"\n",
"if",
"accInfo",
".",
"removed",
"{",
"err",
":=",
"st",
".",
"RemoveAccount",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"accInfo",
".",
"updated",
"{",
"// First update account in case it needs to be created",
"err",
":=",
"st",
".",
"UpdateAccount",
"(",
"accInfo",
".",
"account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Sort keys",
"var",
"keys",
"binary",
".",
"Words256",
"\n",
"for",
"key",
":=",
"range",
"accInfo",
".",
"storage",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"keys",
")",
"\n",
"// Update account's storage",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"value",
":=",
"accInfo",
".",
"storage",
"[",
"key",
"]",
"\n",
"err",
":=",
"st",
".",
"SetStorage",
"(",
"address",
",",
"key",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"\n",
"accInfo",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Syncs changes to the backend in deterministic order. Sends storage updates before updating
// the account they belong so that storage values can be taken account of in the update. | [
"Syncs",
"changes",
"to",
"the",
"backend",
"in",
"deterministic",
"order",
".",
"Sends",
"storage",
"updates",
"before",
"updating",
"the",
"account",
"they",
"belong",
"so",
"that",
"storage",
"values",
"can",
"be",
"taken",
"account",
"of",
"in",
"the",
"update",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L208-L254 | train |
hyperledger/burrow | logging/logconfig/filter.go | matchLogLine | func matchLogLine(keyvals []interface{}, keyRegexes, valueRegexes []*regexp.Regexp, matchAll bool) bool {
all := matchAll
// We should be passed an aligned list of keyRegexes and valueRegexes, but since we can't error here we'll guard
// against a failure of the caller to pass valid arguments
length := len(keyRegexes)
if len(valueRegexes) < length {
length = len(valueRegexes)
}
for i := 0; i < length; i++ {
matched := findMatchInLogLine(keyvals, keyRegexes[i], valueRegexes[i])
if matchAll {
all = all && matched
} else if matched {
return true
}
}
return all
} | go | func matchLogLine(keyvals []interface{}, keyRegexes, valueRegexes []*regexp.Regexp, matchAll bool) bool {
all := matchAll
// We should be passed an aligned list of keyRegexes and valueRegexes, but since we can't error here we'll guard
// against a failure of the caller to pass valid arguments
length := len(keyRegexes)
if len(valueRegexes) < length {
length = len(valueRegexes)
}
for i := 0; i < length; i++ {
matched := findMatchInLogLine(keyvals, keyRegexes[i], valueRegexes[i])
if matchAll {
all = all && matched
} else if matched {
return true
}
}
return all
} | [
"func",
"matchLogLine",
"(",
"keyvals",
"[",
"]",
"interface",
"{",
"}",
",",
"keyRegexes",
",",
"valueRegexes",
"[",
"]",
"*",
"regexp",
".",
"Regexp",
",",
"matchAll",
"bool",
")",
"bool",
"{",
"all",
":=",
"matchAll",
"\n",
"// We should be passed an aligned list of keyRegexes and valueRegexes, but since we can't error here we'll guard",
"// against a failure of the caller to pass valid arguments",
"length",
":=",
"len",
"(",
"keyRegexes",
")",
"\n",
"if",
"len",
"(",
"valueRegexes",
")",
"<",
"length",
"{",
"length",
"=",
"len",
"(",
"valueRegexes",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
"{",
"matched",
":=",
"findMatchInLogLine",
"(",
"keyvals",
",",
"keyRegexes",
"[",
"i",
"]",
",",
"valueRegexes",
"[",
"i",
"]",
")",
"\n",
"if",
"matchAll",
"{",
"all",
"=",
"all",
"&&",
"matched",
"\n",
"}",
"else",
"if",
"matched",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"all",
"\n",
"}"
] | // matchLogLine tries to match a log line by trying to match each key value pair with each pair of key value regexes
// if matchAll is true then matchLogLine returns true iff every key value regexes finds a match or the line or regexes
// are empty | [
"matchLogLine",
"tries",
"to",
"match",
"a",
"log",
"line",
"by",
"trying",
"to",
"match",
"each",
"key",
"value",
"pair",
"with",
"each",
"pair",
"of",
"key",
"value",
"regexes",
"if",
"matchAll",
"is",
"true",
"then",
"matchLogLine",
"returns",
"true",
"iff",
"every",
"key",
"value",
"regexes",
"finds",
"a",
"match",
"or",
"the",
"line",
"or",
"regexes",
"are",
"empty"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/logconfig/filter.go#L54-L71 | train |
hyperledger/burrow | genesis/genesis.go | JSONBytes | func (genesisDoc *GenesisDoc) JSONBytes() ([]byte, error) {
// Just in case
genesisDoc.GenesisTime = genesisDoc.GenesisTime.UTC()
return json.MarshalIndent(genesisDoc, "", "\t")
} | go | func (genesisDoc *GenesisDoc) JSONBytes() ([]byte, error) {
// Just in case
genesisDoc.GenesisTime = genesisDoc.GenesisTime.UTC()
return json.MarshalIndent(genesisDoc, "", "\t")
} | [
"func",
"(",
"genesisDoc",
"*",
"GenesisDoc",
")",
"JSONBytes",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Just in case",
"genesisDoc",
".",
"GenesisTime",
"=",
"genesisDoc",
".",
"GenesisTime",
".",
"UTC",
"(",
")",
"\n",
"return",
"json",
".",
"MarshalIndent",
"(",
"genesisDoc",
",",
"\"",
"\"",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"}"
] | // JSONBytes returns the JSON canonical bytes for a given GenesisDoc or an error. | [
"JSONBytes",
"returns",
"the",
"JSON",
"canonical",
"bytes",
"for",
"a",
"given",
"GenesisDoc",
"or",
"an",
"error",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L91-L95 | train |
hyperledger/burrow | genesis/genesis.go | Clone | func (genesisAccount *Account) Clone() Account {
// clone the account permissions
return Account{
BasicAccount: BasicAccount{
Address: genesisAccount.Address,
Amount: genesisAccount.Amount,
},
Name: genesisAccount.Name,
Permissions: genesisAccount.Permissions.Clone(),
}
} | go | func (genesisAccount *Account) Clone() Account {
// clone the account permissions
return Account{
BasicAccount: BasicAccount{
Address: genesisAccount.Address,
Amount: genesisAccount.Amount,
},
Name: genesisAccount.Name,
Permissions: genesisAccount.Permissions.Clone(),
}
} | [
"func",
"(",
"genesisAccount",
"*",
"Account",
")",
"Clone",
"(",
")",
"Account",
"{",
"// clone the account permissions",
"return",
"Account",
"{",
"BasicAccount",
":",
"BasicAccount",
"{",
"Address",
":",
"genesisAccount",
".",
"Address",
",",
"Amount",
":",
"genesisAccount",
".",
"Amount",
",",
"}",
",",
"Name",
":",
"genesisAccount",
".",
"Name",
",",
"Permissions",
":",
"genesisAccount",
".",
"Permissions",
".",
"Clone",
"(",
")",
",",
"}",
"\n",
"}"
] | // Clone clones the genesis account | [
"Clone",
"clones",
"the",
"genesis",
"account"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L151-L161 | train |
hyperledger/burrow | genesis/genesis.go | Clone | func (gv *Validator) Clone() Validator {
// clone the addresses to unbond to
unbondToClone := make([]BasicAccount, len(gv.UnbondTo))
for i, basicAccount := range gv.UnbondTo {
unbondToClone[i] = basicAccount.Clone()
}
return Validator{
BasicAccount: BasicAccount{
PublicKey: gv.PublicKey,
Amount: gv.Amount,
},
Name: gv.Name,
UnbondTo: unbondToClone,
NodeAddress: gv.NodeAddress,
}
} | go | func (gv *Validator) Clone() Validator {
// clone the addresses to unbond to
unbondToClone := make([]BasicAccount, len(gv.UnbondTo))
for i, basicAccount := range gv.UnbondTo {
unbondToClone[i] = basicAccount.Clone()
}
return Validator{
BasicAccount: BasicAccount{
PublicKey: gv.PublicKey,
Amount: gv.Amount,
},
Name: gv.Name,
UnbondTo: unbondToClone,
NodeAddress: gv.NodeAddress,
}
} | [
"func",
"(",
"gv",
"*",
"Validator",
")",
"Clone",
"(",
")",
"Validator",
"{",
"// clone the addresses to unbond to",
"unbondToClone",
":=",
"make",
"(",
"[",
"]",
"BasicAccount",
",",
"len",
"(",
"gv",
".",
"UnbondTo",
")",
")",
"\n",
"for",
"i",
",",
"basicAccount",
":=",
"range",
"gv",
".",
"UnbondTo",
"{",
"unbondToClone",
"[",
"i",
"]",
"=",
"basicAccount",
".",
"Clone",
"(",
")",
"\n",
"}",
"\n",
"return",
"Validator",
"{",
"BasicAccount",
":",
"BasicAccount",
"{",
"PublicKey",
":",
"gv",
".",
"PublicKey",
",",
"Amount",
":",
"gv",
".",
"Amount",
",",
"}",
",",
"Name",
":",
"gv",
".",
"Name",
",",
"UnbondTo",
":",
"unbondToClone",
",",
"NodeAddress",
":",
"gv",
".",
"NodeAddress",
",",
"}",
"\n",
"}"
] | // Clone clones the genesis validator | [
"Clone",
"clones",
"the",
"genesis",
"validator"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L185-L200 | train |
hyperledger/burrow | genesis/genesis.go | MakeGenesisDocFromAccounts | func MakeGenesisDocFromAccounts(chainName string, salt []byte, genesisTime time.Time, accounts map[string]*acm.Account,
validators map[string]*validator.Validator) *GenesisDoc {
// Establish deterministic order of accounts by name so we obtain identical GenesisDoc
// from identical input
names := make([]string, 0, len(accounts))
for name := range accounts {
names = append(names, name)
}
sort.Strings(names)
// copy slice of pointers to accounts into slice of accounts
genesisAccounts := make([]Account, 0, len(accounts))
for _, name := range names {
genesisAccounts = append(genesisAccounts, GenesisAccountFromAccount(name, accounts[name]))
}
// Sigh...
names = names[:0]
for name := range validators {
names = append(names, name)
}
sort.Strings(names)
// copy slice of pointers to validators into slice of validators
genesisValidators := make([]Validator, 0, len(validators))
for _, name := range names {
val := validators[name]
genesisValidators = append(genesisValidators, Validator{
Name: name,
BasicAccount: BasicAccount{
Address: *val.Address,
PublicKey: val.PublicKey,
Amount: val.Power,
},
// Simpler to just do this by convention
UnbondTo: []BasicAccount{
{
Amount: val.Power,
Address: *val.Address,
},
},
})
}
return &GenesisDoc{
ChainName: chainName,
Salt: salt,
GenesisTime: genesisTime,
GlobalPermissions: permission.DefaultAccountPermissions.Clone(),
Accounts: genesisAccounts,
Validators: genesisValidators,
}
} | go | func MakeGenesisDocFromAccounts(chainName string, salt []byte, genesisTime time.Time, accounts map[string]*acm.Account,
validators map[string]*validator.Validator) *GenesisDoc {
// Establish deterministic order of accounts by name so we obtain identical GenesisDoc
// from identical input
names := make([]string, 0, len(accounts))
for name := range accounts {
names = append(names, name)
}
sort.Strings(names)
// copy slice of pointers to accounts into slice of accounts
genesisAccounts := make([]Account, 0, len(accounts))
for _, name := range names {
genesisAccounts = append(genesisAccounts, GenesisAccountFromAccount(name, accounts[name]))
}
// Sigh...
names = names[:0]
for name := range validators {
names = append(names, name)
}
sort.Strings(names)
// copy slice of pointers to validators into slice of validators
genesisValidators := make([]Validator, 0, len(validators))
for _, name := range names {
val := validators[name]
genesisValidators = append(genesisValidators, Validator{
Name: name,
BasicAccount: BasicAccount{
Address: *val.Address,
PublicKey: val.PublicKey,
Amount: val.Power,
},
// Simpler to just do this by convention
UnbondTo: []BasicAccount{
{
Amount: val.Power,
Address: *val.Address,
},
},
})
}
return &GenesisDoc{
ChainName: chainName,
Salt: salt,
GenesisTime: genesisTime,
GlobalPermissions: permission.DefaultAccountPermissions.Clone(),
Accounts: genesisAccounts,
Validators: genesisValidators,
}
} | [
"func",
"MakeGenesisDocFromAccounts",
"(",
"chainName",
"string",
",",
"salt",
"[",
"]",
"byte",
",",
"genesisTime",
"time",
".",
"Time",
",",
"accounts",
"map",
"[",
"string",
"]",
"*",
"acm",
".",
"Account",
",",
"validators",
"map",
"[",
"string",
"]",
"*",
"validator",
".",
"Validator",
")",
"*",
"GenesisDoc",
"{",
"// Establish deterministic order of accounts by name so we obtain identical GenesisDoc",
"// from identical input",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"accounts",
")",
")",
"\n",
"for",
"name",
":=",
"range",
"accounts",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"name",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n",
"// copy slice of pointers to accounts into slice of accounts",
"genesisAccounts",
":=",
"make",
"(",
"[",
"]",
"Account",
",",
"0",
",",
"len",
"(",
"accounts",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"genesisAccounts",
"=",
"append",
"(",
"genesisAccounts",
",",
"GenesisAccountFromAccount",
"(",
"name",
",",
"accounts",
"[",
"name",
"]",
")",
")",
"\n",
"}",
"\n",
"// Sigh...",
"names",
"=",
"names",
"[",
":",
"0",
"]",
"\n",
"for",
"name",
":=",
"range",
"validators",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"name",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n",
"// copy slice of pointers to validators into slice of validators",
"genesisValidators",
":=",
"make",
"(",
"[",
"]",
"Validator",
",",
"0",
",",
"len",
"(",
"validators",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"val",
":=",
"validators",
"[",
"name",
"]",
"\n",
"genesisValidators",
"=",
"append",
"(",
"genesisValidators",
",",
"Validator",
"{",
"Name",
":",
"name",
",",
"BasicAccount",
":",
"BasicAccount",
"{",
"Address",
":",
"*",
"val",
".",
"Address",
",",
"PublicKey",
":",
"val",
".",
"PublicKey",
",",
"Amount",
":",
"val",
".",
"Power",
",",
"}",
",",
"// Simpler to just do this by convention",
"UnbondTo",
":",
"[",
"]",
"BasicAccount",
"{",
"{",
"Amount",
":",
"val",
".",
"Power",
",",
"Address",
":",
"*",
"val",
".",
"Address",
",",
"}",
",",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"&",
"GenesisDoc",
"{",
"ChainName",
":",
"chainName",
",",
"Salt",
":",
"salt",
",",
"GenesisTime",
":",
"genesisTime",
",",
"GlobalPermissions",
":",
"permission",
".",
"DefaultAccountPermissions",
".",
"Clone",
"(",
")",
",",
"Accounts",
":",
"genesisAccounts",
",",
"Validators",
":",
"genesisValidators",
",",
"}",
"\n",
"}"
] | // MakeGenesisDocFromAccounts takes a chainName and a slice of pointers to Account,
// and a slice of pointers to Validator to construct a GenesisDoc, or returns an error on
// failure. In particular MakeGenesisDocFromAccount uses the local time as a
// timestamp for the GenesisDoc. | [
"MakeGenesisDocFromAccounts",
"takes",
"a",
"chainName",
"and",
"a",
"slice",
"of",
"pointers",
"to",
"Account",
"and",
"a",
"slice",
"of",
"pointers",
"to",
"Validator",
"to",
"construct",
"a",
"GenesisDoc",
"or",
"returns",
"an",
"error",
"on",
"failure",
".",
"In",
"particular",
"MakeGenesisDocFromAccount",
"uses",
"the",
"local",
"time",
"as",
"a",
"timestamp",
"for",
"the",
"GenesisDoc",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L217-L266 | train |
hyperledger/burrow | acm/bytecode.go | Tokens | func (bc Bytecode) Tokens() ([]string, error) {
// Overestimate of capacity in the presence of pushes
tokens := make([]string, 0, len(bc))
for i := 0; i < len(bc); i++ {
op, ok := asm.GetOpCode(bc[i])
if !ok {
return tokens, fmt.Errorf("did not recognise byte %#x at position %v as an OpCode:\n %s",
bc[i], i, lexingPositionString(bc, i, tokens))
}
pushes := op.Pushes()
tokens = append(tokens, op.Name())
if pushes > 0 {
// This is a PUSH<N> OpCode so consume N bytes from the input, render them as hex, and skip to next OpCode
if i+pushes >= len(bc) {
return tokens, fmt.Errorf("token %v of input is %s but not enough input remains to push %v: %s",
i, op.Name(), pushes, lexingPositionString(bc, i, tokens))
}
pushedBytes := bc[i+1 : i+pushes+1]
tokens = append(tokens, fmt.Sprintf("0x%s", pushedBytes))
i += pushes
}
}
return tokens, nil
} | go | func (bc Bytecode) Tokens() ([]string, error) {
// Overestimate of capacity in the presence of pushes
tokens := make([]string, 0, len(bc))
for i := 0; i < len(bc); i++ {
op, ok := asm.GetOpCode(bc[i])
if !ok {
return tokens, fmt.Errorf("did not recognise byte %#x at position %v as an OpCode:\n %s",
bc[i], i, lexingPositionString(bc, i, tokens))
}
pushes := op.Pushes()
tokens = append(tokens, op.Name())
if pushes > 0 {
// This is a PUSH<N> OpCode so consume N bytes from the input, render them as hex, and skip to next OpCode
if i+pushes >= len(bc) {
return tokens, fmt.Errorf("token %v of input is %s but not enough input remains to push %v: %s",
i, op.Name(), pushes, lexingPositionString(bc, i, tokens))
}
pushedBytes := bc[i+1 : i+pushes+1]
tokens = append(tokens, fmt.Sprintf("0x%s", pushedBytes))
i += pushes
}
}
return tokens, nil
} | [
"func",
"(",
"bc",
"Bytecode",
")",
"Tokens",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"// Overestimate of capacity in the presence of pushes",
"tokens",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"bc",
")",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"bc",
")",
";",
"i",
"++",
"{",
"op",
",",
"ok",
":=",
"asm",
".",
"GetOpCode",
"(",
"bc",
"[",
"i",
"]",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"tokens",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"bc",
"[",
"i",
"]",
",",
"i",
",",
"lexingPositionString",
"(",
"bc",
",",
"i",
",",
"tokens",
")",
")",
"\n",
"}",
"\n",
"pushes",
":=",
"op",
".",
"Pushes",
"(",
")",
"\n",
"tokens",
"=",
"append",
"(",
"tokens",
",",
"op",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"pushes",
">",
"0",
"{",
"// This is a PUSH<N> OpCode so consume N bytes from the input, render them as hex, and skip to next OpCode",
"if",
"i",
"+",
"pushes",
">=",
"len",
"(",
"bc",
")",
"{",
"return",
"tokens",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"i",
",",
"op",
".",
"Name",
"(",
")",
",",
"pushes",
",",
"lexingPositionString",
"(",
"bc",
",",
"i",
",",
"tokens",
")",
")",
"\n",
"}",
"\n",
"pushedBytes",
":=",
"bc",
"[",
"i",
"+",
"1",
":",
"i",
"+",
"pushes",
"+",
"1",
"]",
"\n",
"tokens",
"=",
"append",
"(",
"tokens",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pushedBytes",
")",
")",
"\n",
"i",
"+=",
"pushes",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"tokens",
",",
"nil",
"\n",
"}"
] | // Tokenises the bytecode into opcodes and values | [
"Tokenises",
"the",
"bytecode",
"into",
"opcodes",
"and",
"values"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/bytecode.go#L94-L118 | train |
hyperledger/burrow | event/query/builder.go | NewBuilder | func NewBuilder(queries ...string) *Builder {
qb := new(Builder)
qb.queryString = qb.and(stringIterator(queries...))
return qb
} | go | func NewBuilder(queries ...string) *Builder {
qb := new(Builder)
qb.queryString = qb.and(stringIterator(queries...))
return qb
} | [
"func",
"NewBuilder",
"(",
"queries",
"...",
"string",
")",
"*",
"Builder",
"{",
"qb",
":=",
"new",
"(",
"Builder",
")",
"\n",
"qb",
".",
"queryString",
"=",
"qb",
".",
"and",
"(",
"stringIterator",
"(",
"queries",
"...",
")",
")",
"\n",
"return",
"qb",
"\n",
"}"
] | // Creates a new query builder with a base query that is the conjunction of all queries passed | [
"Creates",
"a",
"new",
"query",
"builder",
"with",
"a",
"base",
"query",
"that",
"is",
"the",
"conjunction",
"of",
"all",
"queries",
"passed"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L95-L99 | train |
hyperledger/burrow | event/query/builder.go | And | func (qb *Builder) And(queryBuilders ...*Builder) *Builder {
return NewBuilder(qb.and(queryBuilderIterator(queryBuilders...)))
} | go | func (qb *Builder) And(queryBuilders ...*Builder) *Builder {
return NewBuilder(qb.and(queryBuilderIterator(queryBuilders...)))
} | [
"func",
"(",
"qb",
"*",
"Builder",
")",
"And",
"(",
"queryBuilders",
"...",
"*",
"Builder",
")",
"*",
"Builder",
"{",
"return",
"NewBuilder",
"(",
"qb",
".",
"and",
"(",
"queryBuilderIterator",
"(",
"queryBuilders",
"...",
")",
")",
")",
"\n",
"}"
] | // Creates the conjunction of Builder and rightQuery | [
"Creates",
"the",
"conjunction",
"of",
"Builder",
"and",
"rightQuery"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L120-L122 | train |
hyperledger/burrow | event/query/builder.go | AndEquals | func (qb *Builder) AndEquals(tag string, operand interface{}) *Builder {
qb.condition.Tag = tag
qb.condition.Op = equalString
qb.condition.Operand = operandString(operand)
return NewBuilder(qb.and(stringIterator(qb.conditionString())))
} | go | func (qb *Builder) AndEquals(tag string, operand interface{}) *Builder {
qb.condition.Tag = tag
qb.condition.Op = equalString
qb.condition.Operand = operandString(operand)
return NewBuilder(qb.and(stringIterator(qb.conditionString())))
} | [
"func",
"(",
"qb",
"*",
"Builder",
")",
"AndEquals",
"(",
"tag",
"string",
",",
"operand",
"interface",
"{",
"}",
")",
"*",
"Builder",
"{",
"qb",
".",
"condition",
".",
"Tag",
"=",
"tag",
"\n",
"qb",
".",
"condition",
".",
"Op",
"=",
"equalString",
"\n",
"qb",
".",
"condition",
".",
"Operand",
"=",
"operandString",
"(",
"operand",
")",
"\n",
"return",
"NewBuilder",
"(",
"qb",
".",
"and",
"(",
"stringIterator",
"(",
"qb",
".",
"conditionString",
"(",
")",
")",
")",
")",
"\n",
"}"
] | // Creates the conjunction of Builder and tag = operand | [
"Creates",
"the",
"conjunction",
"of",
"Builder",
"and",
"tag",
"=",
"operand"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L125-L130 | train |
hyperledger/burrow | event/query/builder.go | stringIterator | func stringIterator(strs ...string) func(func(string)) {
return func(callback func(string)) {
for _, s := range strs {
callback(s)
}
}
} | go | func stringIterator(strs ...string) func(func(string)) {
return func(callback func(string)) {
for _, s := range strs {
callback(s)
}
}
} | [
"func",
"stringIterator",
"(",
"strs",
"...",
"string",
")",
"func",
"(",
"func",
"(",
"string",
")",
")",
"{",
"return",
"func",
"(",
"callback",
"func",
"(",
"string",
")",
")",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"strs",
"{",
"callback",
"(",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Iterators over some strings | [
"Iterators",
"over",
"some",
"strings"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L260-L266 | train |
mvdan/sh | syntax/parser.go | NewParser | func NewParser(options ...func(*Parser)) *Parser {
p := &Parser{helperBuf: new(bytes.Buffer)}
for _, opt := range options {
opt(p)
}
return p
} | go | func NewParser(options ...func(*Parser)) *Parser {
p := &Parser{helperBuf: new(bytes.Buffer)}
for _, opt := range options {
opt(p)
}
return p
} | [
"func",
"NewParser",
"(",
"options",
"...",
"func",
"(",
"*",
"Parser",
")",
")",
"*",
"Parser",
"{",
"p",
":=",
"&",
"Parser",
"{",
"helperBuf",
":",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"options",
"{",
"opt",
"(",
"p",
")",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // NewParser allocates a new Parser and applies any number of options. | [
"NewParser",
"allocates",
"a",
"new",
"Parser",
"and",
"applies",
"any",
"number",
"of",
"options",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L69-L75 | train |
mvdan/sh | syntax/parser.go | Parse | func (p *Parser) Parse(r io.Reader, name string) (*File, error) {
p.reset()
p.f = &File{Name: name}
p.src = r
p.rune()
p.next()
p.f.Stmts, p.f.Last = p.stmtList()
if p.err == nil {
// EOF immediately after heredoc word so no newline to
// trigger it
p.doHeredocs()
}
return p.f, p.err
} | go | func (p *Parser) Parse(r io.Reader, name string) (*File, error) {
p.reset()
p.f = &File{Name: name}
p.src = r
p.rune()
p.next()
p.f.Stmts, p.f.Last = p.stmtList()
if p.err == nil {
// EOF immediately after heredoc word so no newline to
// trigger it
p.doHeredocs()
}
return p.f, p.err
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Parse",
"(",
"r",
"io",
".",
"Reader",
",",
"name",
"string",
")",
"(",
"*",
"File",
",",
"error",
")",
"{",
"p",
".",
"reset",
"(",
")",
"\n",
"p",
".",
"f",
"=",
"&",
"File",
"{",
"Name",
":",
"name",
"}",
"\n",
"p",
".",
"src",
"=",
"r",
"\n",
"p",
".",
"rune",
"(",
")",
"\n",
"p",
".",
"next",
"(",
")",
"\n",
"p",
".",
"f",
".",
"Stmts",
",",
"p",
".",
"f",
".",
"Last",
"=",
"p",
".",
"stmtList",
"(",
")",
"\n",
"if",
"p",
".",
"err",
"==",
"nil",
"{",
"// EOF immediately after heredoc word so no newline to",
"// trigger it",
"p",
".",
"doHeredocs",
"(",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"f",
",",
"p",
".",
"err",
"\n",
"}"
] | // Parse reads and parses a shell program with an optional name. It
// returns the parsed program if no issues were encountered. Otherwise,
// an error is returned. Reads from r are buffered.
//
// Parse can be called more than once, but not concurrently. That is, a
// Parser can be reused once it is done working. | [
"Parse",
"reads",
"and",
"parses",
"a",
"shell",
"program",
"with",
"an",
"optional",
"name",
".",
"It",
"returns",
"the",
"parsed",
"program",
"if",
"no",
"issues",
"were",
"encountered",
".",
"Otherwise",
"an",
"error",
"is",
"returned",
".",
"Reads",
"from",
"r",
"are",
"buffered",
".",
"Parse",
"can",
"be",
"called",
"more",
"than",
"once",
"but",
"not",
"concurrently",
".",
"That",
"is",
"a",
"Parser",
"can",
"be",
"reused",
"once",
"it",
"is",
"done",
"working",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L83-L96 | train |
mvdan/sh | syntax/parser.go | Stmts | func (p *Parser) Stmts(r io.Reader, fn func(*Stmt) bool) error {
p.reset()
p.f = &File{}
p.src = r
p.rune()
p.next()
p.stmts(fn)
if p.err == nil {
// EOF immediately after heredoc word so no newline to
// trigger it
p.doHeredocs()
}
return p.err
} | go | func (p *Parser) Stmts(r io.Reader, fn func(*Stmt) bool) error {
p.reset()
p.f = &File{}
p.src = r
p.rune()
p.next()
p.stmts(fn)
if p.err == nil {
// EOF immediately after heredoc word so no newline to
// trigger it
p.doHeredocs()
}
return p.err
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Stmts",
"(",
"r",
"io",
".",
"Reader",
",",
"fn",
"func",
"(",
"*",
"Stmt",
")",
"bool",
")",
"error",
"{",
"p",
".",
"reset",
"(",
")",
"\n",
"p",
".",
"f",
"=",
"&",
"File",
"{",
"}",
"\n",
"p",
".",
"src",
"=",
"r",
"\n",
"p",
".",
"rune",
"(",
")",
"\n",
"p",
".",
"next",
"(",
")",
"\n",
"p",
".",
"stmts",
"(",
"fn",
")",
"\n",
"if",
"p",
".",
"err",
"==",
"nil",
"{",
"// EOF immediately after heredoc word so no newline to",
"// trigger it",
"p",
".",
"doHeredocs",
"(",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"err",
"\n",
"}"
] | // Stmts reads and parses statements one at a time, calling a function
// each time one is parsed. If the function returns false, parsing is
// stopped and the function is not called again. | [
"Stmts",
"reads",
"and",
"parses",
"statements",
"one",
"at",
"a",
"time",
"calling",
"a",
"function",
"each",
"time",
"one",
"is",
"parsed",
".",
"If",
"the",
"function",
"returns",
"false",
"parsing",
"is",
"stopped",
"and",
"the",
"function",
"is",
"not",
"called",
"again",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L101-L114 | train |
mvdan/sh | syntax/parser.go | Words | func (p *Parser) Words(r io.Reader, fn func(*Word) bool) error {
p.reset()
p.f = &File{}
p.src = r
p.rune()
p.next()
for {
p.got(_Newl)
w := p.getWord()
if w == nil {
if p.tok != _EOF {
p.curErr("%s is not a valid word", p.tok)
}
return p.err
}
if !fn(w) {
return nil
}
}
} | go | func (p *Parser) Words(r io.Reader, fn func(*Word) bool) error {
p.reset()
p.f = &File{}
p.src = r
p.rune()
p.next()
for {
p.got(_Newl)
w := p.getWord()
if w == nil {
if p.tok != _EOF {
p.curErr("%s is not a valid word", p.tok)
}
return p.err
}
if !fn(w) {
return nil
}
}
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Words",
"(",
"r",
"io",
".",
"Reader",
",",
"fn",
"func",
"(",
"*",
"Word",
")",
"bool",
")",
"error",
"{",
"p",
".",
"reset",
"(",
")",
"\n",
"p",
".",
"f",
"=",
"&",
"File",
"{",
"}",
"\n",
"p",
".",
"src",
"=",
"r",
"\n",
"p",
".",
"rune",
"(",
")",
"\n",
"p",
".",
"next",
"(",
")",
"\n",
"for",
"{",
"p",
".",
"got",
"(",
"_Newl",
")",
"\n",
"w",
":=",
"p",
".",
"getWord",
"(",
")",
"\n",
"if",
"w",
"==",
"nil",
"{",
"if",
"p",
".",
"tok",
"!=",
"_EOF",
"{",
"p",
".",
"curErr",
"(",
"\"",
"\"",
",",
"p",
".",
"tok",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"err",
"\n",
"}",
"\n",
"if",
"!",
"fn",
"(",
"w",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Words reads and parses words one at a time, calling a function each time one
// is parsed. If the function returns false, parsing is stopped and the function
// is not called again.
//
// Newlines are skipped, meaning that multi-line input will work fine. If the
// parser encounters a token that isn't a word, such as a semicolon, an error
// will be returned.
//
// Note that the lexer doesn't currently tokenize spaces, so it may need to read
// a non-space byte such as a newline or a letter before finishing the parsing
// of a word. This will be fixed in the future. | [
"Words",
"reads",
"and",
"parses",
"words",
"one",
"at",
"a",
"time",
"calling",
"a",
"function",
"each",
"time",
"one",
"is",
"parsed",
".",
"If",
"the",
"function",
"returns",
"false",
"parsing",
"is",
"stopped",
"and",
"the",
"function",
"is",
"not",
"called",
"again",
".",
"Newlines",
"are",
"skipped",
"meaning",
"that",
"multi",
"-",
"line",
"input",
"will",
"work",
"fine",
".",
"If",
"the",
"parser",
"encounters",
"a",
"token",
"that",
"isn",
"t",
"a",
"word",
"such",
"as",
"a",
"semicolon",
"an",
"error",
"will",
"be",
"returned",
".",
"Note",
"that",
"the",
"lexer",
"doesn",
"t",
"currently",
"tokenize",
"spaces",
"so",
"it",
"may",
"need",
"to",
"read",
"a",
"non",
"-",
"space",
"byte",
"such",
"as",
"a",
"newline",
"or",
"a",
"letter",
"before",
"finishing",
"the",
"parsing",
"of",
"a",
"word",
".",
"This",
"will",
"be",
"fixed",
"in",
"the",
"future",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L204-L223 | train |
mvdan/sh | syntax/parser.go | Document | func (p *Parser) Document(r io.Reader) (*Word, error) {
p.reset()
p.f = &File{}
p.src = r
p.rune()
p.quote = hdocBody
p.hdocStop = []byte("MVDAN_CC_SH_SYNTAX_EOF")
p.parsingDoc = true
p.next()
w := p.getWord()
return w, p.err
} | go | func (p *Parser) Document(r io.Reader) (*Word, error) {
p.reset()
p.f = &File{}
p.src = r
p.rune()
p.quote = hdocBody
p.hdocStop = []byte("MVDAN_CC_SH_SYNTAX_EOF")
p.parsingDoc = true
p.next()
w := p.getWord()
return w, p.err
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Document",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Word",
",",
"error",
")",
"{",
"p",
".",
"reset",
"(",
")",
"\n",
"p",
".",
"f",
"=",
"&",
"File",
"{",
"}",
"\n",
"p",
".",
"src",
"=",
"r",
"\n",
"p",
".",
"rune",
"(",
")",
"\n",
"p",
".",
"quote",
"=",
"hdocBody",
"\n",
"p",
".",
"hdocStop",
"=",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"parsingDoc",
"=",
"true",
"\n",
"p",
".",
"next",
"(",
")",
"\n",
"w",
":=",
"p",
".",
"getWord",
"(",
")",
"\n",
"return",
"w",
",",
"p",
".",
"err",
"\n",
"}"
] | // Document parses a single here-document word. That is, it parses the input as
// if they were lines following a <<EOF redirection.
//
// In practice, this is the same as parsing the input as if it were within
// double quotes, but without having to escape all double quote characters.
// Similarly, the here-document word parsed here cannot be ended by any
// delimiter other than reaching the end of the input. | [
"Document",
"parses",
"a",
"single",
"here",
"-",
"document",
"word",
".",
"That",
"is",
"it",
"parses",
"the",
"input",
"as",
"if",
"they",
"were",
"lines",
"following",
"a",
"<<EOF",
"redirection",
".",
"In",
"practice",
"this",
"is",
"the",
"same",
"as",
"parsing",
"the",
"input",
"as",
"if",
"it",
"were",
"within",
"double",
"quotes",
"but",
"without",
"having",
"to",
"escape",
"all",
"double",
"quote",
"characters",
".",
"Similarly",
"the",
"here",
"-",
"document",
"word",
"parsed",
"here",
"cannot",
"be",
"ended",
"by",
"any",
"delimiter",
"other",
"than",
"reaching",
"the",
"end",
"of",
"the",
"input",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L232-L243 | train |
mvdan/sh | syntax/parser.go | Incomplete | func (p *Parser) Incomplete() bool {
// If we're in a quote state other than noState, we're parsing a node
// such as a double-quoted string.
// If there are any open statements, we need to finish them.
// If we're constructing a literal, we need to finish it.
return p.quote != noState || p.openStmts > 0 || p.litBs != nil
} | go | func (p *Parser) Incomplete() bool {
// If we're in a quote state other than noState, we're parsing a node
// such as a double-quoted string.
// If there are any open statements, we need to finish them.
// If we're constructing a literal, we need to finish it.
return p.quote != noState || p.openStmts > 0 || p.litBs != nil
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"Incomplete",
"(",
")",
"bool",
"{",
"// If we're in a quote state other than noState, we're parsing a node",
"// such as a double-quoted string.",
"// If there are any open statements, we need to finish them.",
"// If we're constructing a literal, we need to finish it.",
"return",
"p",
".",
"quote",
"!=",
"noState",
"||",
"p",
".",
"openStmts",
">",
"0",
"||",
"p",
".",
"litBs",
"!=",
"nil",
"\n",
"}"
] | // Incomplete reports whether the parser is waiting to read more bytes because
// it needs to finish properly parsing a statement.
//
// It is only safe to call while the parser is blocked on a read. For an example
// use case, see the documentation for Parser.Interactive. | [
"Incomplete",
"reports",
"whether",
"the",
"parser",
"is",
"waiting",
"to",
"read",
"more",
"bytes",
"because",
"it",
"needs",
"to",
"finish",
"properly",
"parsing",
"a",
"statement",
".",
"It",
"is",
"only",
"safe",
"to",
"call",
"while",
"the",
"parser",
"is",
"blocked",
"on",
"a",
"read",
".",
"For",
"an",
"example",
"use",
"case",
"see",
"the",
"documentation",
"for",
"Parser",
".",
"Interactive",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L322-L328 | train |
mvdan/sh | syntax/parser.go | IsIncomplete | func IsIncomplete(err error) bool {
perr, ok := err.(ParseError)
return ok && perr.Incomplete
} | go | func IsIncomplete(err error) bool {
perr, ok := err.(ParseError)
return ok && perr.Incomplete
} | [
"func",
"IsIncomplete",
"(",
"err",
"error",
")",
"bool",
"{",
"perr",
",",
"ok",
":=",
"err",
".",
"(",
"ParseError",
")",
"\n",
"return",
"ok",
"&&",
"perr",
".",
"Incomplete",
"\n",
"}"
] | // IsIncomplete reports whether a Parser error could have been avoided with
// extra input bytes. For example, if an io.EOF was encountered while there was
// an unclosed quote or parenthesis. | [
"IsIncomplete",
"reports",
"whether",
"a",
"Parser",
"error",
"could",
"have",
"been",
"avoided",
"with",
"extra",
"input",
"bytes",
".",
"For",
"example",
"if",
"an",
"io",
".",
"EOF",
"was",
"encountered",
"while",
"there",
"was",
"an",
"unclosed",
"quote",
"or",
"parenthesis",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L653-L656 | train |
mvdan/sh | syntax/parser.go | ValidName | func ValidName(val string) bool {
if val == "" {
return false
}
for i, r := range val {
switch {
case 'a' <= r && r <= 'z':
case 'A' <= r && r <= 'Z':
case r == '_':
case i > 0 && '0' <= r && r <= '9':
default:
return false
}
}
return true
} | go | func ValidName(val string) bool {
if val == "" {
return false
}
for i, r := range val {
switch {
case 'a' <= r && r <= 'z':
case 'A' <= r && r <= 'Z':
case r == '_':
case i > 0 && '0' <= r && r <= '9':
default:
return false
}
}
return true
} | [
"func",
"ValidName",
"(",
"val",
"string",
")",
"bool",
"{",
"if",
"val",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"r",
":=",
"range",
"val",
"{",
"switch",
"{",
"case",
"'a'",
"<=",
"r",
"&&",
"r",
"<=",
"'z'",
":",
"case",
"'A'",
"<=",
"r",
"&&",
"r",
"<=",
"'Z'",
":",
"case",
"r",
"==",
"'_'",
":",
"case",
"i",
">",
"0",
"&&",
"'0'",
"<=",
"r",
"&&",
"r",
"<=",
"'9'",
":",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // ValidName returns whether val is a valid name as per the POSIX spec. | [
"ValidName",
"returns",
"whether",
"val",
"is",
"a",
"valid",
"name",
"as",
"per",
"the",
"POSIX",
"spec",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L1499-L1514 | train |
mvdan/sh | expand/environ.go | String | func (v Variable) String() string {
switch v.Kind {
case String:
return v.Str
case Indexed:
if len(v.List) > 0 {
return v.List[0]
}
case Associative:
// nothing to do
}
return ""
} | go | func (v Variable) String() string {
switch v.Kind {
case String:
return v.Str
case Indexed:
if len(v.List) > 0 {
return v.List[0]
}
case Associative:
// nothing to do
}
return ""
} | [
"func",
"(",
"v",
"Variable",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"v",
".",
"Kind",
"{",
"case",
"String",
":",
"return",
"v",
".",
"Str",
"\n",
"case",
"Indexed",
":",
"if",
"len",
"(",
"v",
".",
"List",
")",
">",
"0",
"{",
"return",
"v",
".",
"List",
"[",
"0",
"]",
"\n",
"}",
"\n",
"case",
"Associative",
":",
"// nothing to do",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // String returns the variable's value as a string. In general, this only makes
// sense if the variable has a string value or no value at all. | [
"String",
"returns",
"the",
"variable",
"s",
"value",
"as",
"a",
"string",
".",
"In",
"general",
"this",
"only",
"makes",
"sense",
"if",
"the",
"variable",
"has",
"a",
"string",
"value",
"or",
"no",
"value",
"at",
"all",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/environ.go#L88-L100 | train |
mvdan/sh | expand/environ.go | Resolve | func (v Variable) Resolve(env Environ) (string, Variable) {
name := ""
for i := 0; i < maxNameRefDepth; i++ {
if v.Kind != NameRef {
return name, v
}
name = v.Str // keep name for the next iteration
v = env.Get(name)
}
return name, Variable{}
} | go | func (v Variable) Resolve(env Environ) (string, Variable) {
name := ""
for i := 0; i < maxNameRefDepth; i++ {
if v.Kind != NameRef {
return name, v
}
name = v.Str // keep name for the next iteration
v = env.Get(name)
}
return name, Variable{}
} | [
"func",
"(",
"v",
"Variable",
")",
"Resolve",
"(",
"env",
"Environ",
")",
"(",
"string",
",",
"Variable",
")",
"{",
"name",
":=",
"\"",
"\"",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"maxNameRefDepth",
";",
"i",
"++",
"{",
"if",
"v",
".",
"Kind",
"!=",
"NameRef",
"{",
"return",
"name",
",",
"v",
"\n",
"}",
"\n",
"name",
"=",
"v",
".",
"Str",
"// keep name for the next iteration",
"\n",
"v",
"=",
"env",
".",
"Get",
"(",
"name",
")",
"\n",
"}",
"\n",
"return",
"name",
",",
"Variable",
"{",
"}",
"\n",
"}"
] | // Resolve follows a number of nameref variables, returning the last reference
// name that was followed and the variable that it points to. | [
"Resolve",
"follows",
"a",
"number",
"of",
"nameref",
"variables",
"returning",
"the",
"last",
"reference",
"name",
"that",
"was",
"followed",
"and",
"the",
"variable",
"that",
"it",
"points",
"to",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/environ.go#L109-L119 | train |
mvdan/sh | expand/environ.go | listEnvironWithUpper | func listEnvironWithUpper(upper bool, pairs ...string) Environ {
list := append([]string{}, pairs...)
if upper {
// Uppercase before sorting, so that we can remove duplicates
// without the need for linear search nor a map.
for i, s := range list {
if sep := strings.IndexByte(s, '='); sep > 0 {
list[i] = strings.ToUpper(s[:sep]) + s[sep:]
}
}
}
sort.Strings(list)
last := ""
for i := 0; i < len(list); {
s := list[i]
sep := strings.IndexByte(s, '=')
if sep <= 0 {
// invalid element; remove it
list = append(list[:i], list[i+1:]...)
continue
}
name := s[:sep]
if last == name {
// duplicate; the last one wins
list = append(list[:i-1], list[i:]...)
continue
}
last = name
i++
}
return listEnviron(list)
} | go | func listEnvironWithUpper(upper bool, pairs ...string) Environ {
list := append([]string{}, pairs...)
if upper {
// Uppercase before sorting, so that we can remove duplicates
// without the need for linear search nor a map.
for i, s := range list {
if sep := strings.IndexByte(s, '='); sep > 0 {
list[i] = strings.ToUpper(s[:sep]) + s[sep:]
}
}
}
sort.Strings(list)
last := ""
for i := 0; i < len(list); {
s := list[i]
sep := strings.IndexByte(s, '=')
if sep <= 0 {
// invalid element; remove it
list = append(list[:i], list[i+1:]...)
continue
}
name := s[:sep]
if last == name {
// duplicate; the last one wins
list = append(list[:i-1], list[i:]...)
continue
}
last = name
i++
}
return listEnviron(list)
} | [
"func",
"listEnvironWithUpper",
"(",
"upper",
"bool",
",",
"pairs",
"...",
"string",
")",
"Environ",
"{",
"list",
":=",
"append",
"(",
"[",
"]",
"string",
"{",
"}",
",",
"pairs",
"...",
")",
"\n",
"if",
"upper",
"{",
"// Uppercase before sorting, so that we can remove duplicates",
"// without the need for linear search nor a map.",
"for",
"i",
",",
"s",
":=",
"range",
"list",
"{",
"if",
"sep",
":=",
"strings",
".",
"IndexByte",
"(",
"s",
",",
"'='",
")",
";",
"sep",
">",
"0",
"{",
"list",
"[",
"i",
"]",
"=",
"strings",
".",
"ToUpper",
"(",
"s",
"[",
":",
"sep",
"]",
")",
"+",
"s",
"[",
"sep",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"list",
")",
"\n",
"last",
":=",
"\"",
"\"",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"list",
")",
";",
"{",
"s",
":=",
"list",
"[",
"i",
"]",
"\n",
"sep",
":=",
"strings",
".",
"IndexByte",
"(",
"s",
",",
"'='",
")",
"\n",
"if",
"sep",
"<=",
"0",
"{",
"// invalid element; remove it",
"list",
"=",
"append",
"(",
"list",
"[",
":",
"i",
"]",
",",
"list",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"name",
":=",
"s",
"[",
":",
"sep",
"]",
"\n",
"if",
"last",
"==",
"name",
"{",
"// duplicate; the last one wins",
"list",
"=",
"append",
"(",
"list",
"[",
":",
"i",
"-",
"1",
"]",
",",
"list",
"[",
"i",
":",
"]",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"last",
"=",
"name",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"listEnviron",
"(",
"list",
")",
"\n",
"}"
] | // listEnvironWithUpper implements ListEnviron, but letting the tests specify
// whether to uppercase all names or not. | [
"listEnvironWithUpper",
"implements",
"ListEnviron",
"but",
"letting",
"the",
"tests",
"specify",
"whether",
"to",
"uppercase",
"all",
"names",
"or",
"not",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/environ.go#L153-L184 | train |
mvdan/sh | interp/perm_unix.go | hasPermissionToDir | func hasPermissionToDir(info os.FileInfo) bool {
user, err := user.Current()
if err != nil {
return true
}
uid, _ := strconv.Atoi(user.Uid)
// super-user
if uid == 0 {
return true
}
st, _ := info.Sys().(*syscall.Stat_t)
if st == nil {
return true
}
perm := info.Mode().Perm()
// user (u)
if perm&0100 != 0 && st.Uid == uint32(uid) {
return true
}
gid, _ := strconv.Atoi(user.Gid)
// other users in group (g)
if perm&0010 != 0 && st.Uid != uint32(uid) && st.Gid == uint32(gid) {
return true
}
// remaining users (o)
if perm&0001 != 0 && st.Uid != uint32(uid) && st.Gid != uint32(gid) {
return true
}
return false
} | go | func hasPermissionToDir(info os.FileInfo) bool {
user, err := user.Current()
if err != nil {
return true
}
uid, _ := strconv.Atoi(user.Uid)
// super-user
if uid == 0 {
return true
}
st, _ := info.Sys().(*syscall.Stat_t)
if st == nil {
return true
}
perm := info.Mode().Perm()
// user (u)
if perm&0100 != 0 && st.Uid == uint32(uid) {
return true
}
gid, _ := strconv.Atoi(user.Gid)
// other users in group (g)
if perm&0010 != 0 && st.Uid != uint32(uid) && st.Gid == uint32(gid) {
return true
}
// remaining users (o)
if perm&0001 != 0 && st.Uid != uint32(uid) && st.Gid != uint32(gid) {
return true
}
return false
} | [
"func",
"hasPermissionToDir",
"(",
"info",
"os",
".",
"FileInfo",
")",
"bool",
"{",
"user",
",",
"err",
":=",
"user",
".",
"Current",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"uid",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"user",
".",
"Uid",
")",
"\n",
"// super-user",
"if",
"uid",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"st",
",",
"_",
":=",
"info",
".",
"Sys",
"(",
")",
".",
"(",
"*",
"syscall",
".",
"Stat_t",
")",
"\n",
"if",
"st",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"perm",
":=",
"info",
".",
"Mode",
"(",
")",
".",
"Perm",
"(",
")",
"\n",
"// user (u)",
"if",
"perm",
"&",
"0100",
"!=",
"0",
"&&",
"st",
".",
"Uid",
"==",
"uint32",
"(",
"uid",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"gid",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"user",
".",
"Gid",
")",
"\n",
"// other users in group (g)",
"if",
"perm",
"&",
"0010",
"!=",
"0",
"&&",
"st",
".",
"Uid",
"!=",
"uint32",
"(",
"uid",
")",
"&&",
"st",
".",
"Gid",
"==",
"uint32",
"(",
"gid",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// remaining users (o)",
"if",
"perm",
"&",
"0001",
"!=",
"0",
"&&",
"st",
".",
"Uid",
"!=",
"uint32",
"(",
"uid",
")",
"&&",
"st",
".",
"Gid",
"!=",
"uint32",
"(",
"gid",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // hasPermissionToDir returns if the OS current user has execute permission
// to the given directory | [
"hasPermissionToDir",
"returns",
"if",
"the",
"OS",
"current",
"user",
"has",
"execute",
"permission",
"to",
"the",
"given",
"directory"
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/perm_unix.go#L17-L49 | train |
mvdan/sh | shell/source.go | SourceFile | func SourceFile(ctx context.Context, path string) (map[string]expand.Variable, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("could not open: %v", err)
}
defer f.Close()
file, err := syntax.NewParser().Parse(f, path)
if err != nil {
return nil, fmt.Errorf("could not parse: %v", err)
}
return SourceNode(ctx, file)
} | go | func SourceFile(ctx context.Context, path string) (map[string]expand.Variable, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("could not open: %v", err)
}
defer f.Close()
file, err := syntax.NewParser().Parse(f, path)
if err != nil {
return nil, fmt.Errorf("could not parse: %v", err)
}
return SourceNode(ctx, file)
} | [
"func",
"SourceFile",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"expand",
".",
"Variable",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"file",
",",
"err",
":=",
"syntax",
".",
"NewParser",
"(",
")",
".",
"Parse",
"(",
"f",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"SourceNode",
"(",
"ctx",
",",
"file",
")",
"\n",
"}"
] | // SourceFile sources a shell file from disk and returns the variables
// declared in it. It is a convenience function that uses a default shell
// parser, parses a file from disk, and calls SourceNode.
//
// This function should be used with caution, as it can interpret arbitrary
// code. Untrusted shell programs shoudn't be sourced outside of a sandbox
// environment. | [
"SourceFile",
"sources",
"a",
"shell",
"file",
"from",
"disk",
"and",
"returns",
"the",
"variables",
"declared",
"in",
"it",
".",
"It",
"is",
"a",
"convenience",
"function",
"that",
"uses",
"a",
"default",
"shell",
"parser",
"parses",
"a",
"file",
"from",
"disk",
"and",
"calls",
"SourceNode",
".",
"This",
"function",
"should",
"be",
"used",
"with",
"caution",
"as",
"it",
"can",
"interpret",
"arbitrary",
"code",
".",
"Untrusted",
"shell",
"programs",
"shoudn",
"t",
"be",
"sourced",
"outside",
"of",
"a",
"sandbox",
"environment",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/shell/source.go#L23-L34 | train |
mvdan/sh | interp/interp.go | New | func New(opts ...func(*Runner) error) (*Runner, error) {
r := &Runner{usedNew: true}
r.dirStack = r.dirBootstrap[:0]
for _, opt := range opts {
if err := opt(r); err != nil {
return nil, err
}
}
// Set the default fallbacks, if necessary.
if r.Env == nil {
Env(nil)(r)
}
if r.Dir == "" {
if err := Dir("")(r); err != nil {
return nil, err
}
}
if r.Exec == nil {
Module(ModuleExec(nil))(r)
}
if r.Open == nil {
Module(ModuleOpen(nil))(r)
}
if r.Stdout == nil || r.Stderr == nil {
StdIO(r.Stdin, r.Stdout, r.Stderr)(r)
}
return r, nil
} | go | func New(opts ...func(*Runner) error) (*Runner, error) {
r := &Runner{usedNew: true}
r.dirStack = r.dirBootstrap[:0]
for _, opt := range opts {
if err := opt(r); err != nil {
return nil, err
}
}
// Set the default fallbacks, if necessary.
if r.Env == nil {
Env(nil)(r)
}
if r.Dir == "" {
if err := Dir("")(r); err != nil {
return nil, err
}
}
if r.Exec == nil {
Module(ModuleExec(nil))(r)
}
if r.Open == nil {
Module(ModuleOpen(nil))(r)
}
if r.Stdout == nil || r.Stderr == nil {
StdIO(r.Stdin, r.Stdout, r.Stderr)(r)
}
return r, nil
} | [
"func",
"New",
"(",
"opts",
"...",
"func",
"(",
"*",
"Runner",
")",
"error",
")",
"(",
"*",
"Runner",
",",
"error",
")",
"{",
"r",
":=",
"&",
"Runner",
"{",
"usedNew",
":",
"true",
"}",
"\n",
"r",
".",
"dirStack",
"=",
"r",
".",
"dirBootstrap",
"[",
":",
"0",
"]",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"if",
"err",
":=",
"opt",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// Set the default fallbacks, if necessary.",
"if",
"r",
".",
"Env",
"==",
"nil",
"{",
"Env",
"(",
"nil",
")",
"(",
"r",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Dir",
"==",
"\"",
"\"",
"{",
"if",
"err",
":=",
"Dir",
"(",
"\"",
"\"",
")",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"Exec",
"==",
"nil",
"{",
"Module",
"(",
"ModuleExec",
"(",
"nil",
")",
")",
"(",
"r",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Open",
"==",
"nil",
"{",
"Module",
"(",
"ModuleOpen",
"(",
"nil",
")",
")",
"(",
"r",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"Stdout",
"==",
"nil",
"||",
"r",
".",
"Stderr",
"==",
"nil",
"{",
"StdIO",
"(",
"r",
".",
"Stdin",
",",
"r",
".",
"Stdout",
",",
"r",
".",
"Stderr",
")",
"(",
"r",
")",
"\n",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // New creates a new Runner, applying a number of options. If applying any of
// the options results in an error, it is returned.
//
// Any unset options fall back to their defaults. For example, not supplying the
// environment falls back to the process's environment, and not supplying the
// standard output writer means that the output will be discarded. | [
"New",
"creates",
"a",
"new",
"Runner",
"applying",
"a",
"number",
"of",
"options",
".",
"If",
"applying",
"any",
"of",
"the",
"options",
"results",
"in",
"an",
"error",
"it",
"is",
"returned",
".",
"Any",
"unset",
"options",
"fall",
"back",
"to",
"their",
"defaults",
".",
"For",
"example",
"not",
"supplying",
"the",
"environment",
"falls",
"back",
"to",
"the",
"process",
"s",
"environment",
"and",
"not",
"supplying",
"the",
"standard",
"output",
"writer",
"means",
"that",
"the",
"output",
"will",
"be",
"discarded",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L34-L61 | train |
mvdan/sh | interp/interp.go | Env | func Env(env expand.Environ) func(*Runner) error {
return func(r *Runner) error {
if env == nil {
env = expand.ListEnviron(os.Environ()...)
}
r.Env = env
return nil
}
} | go | func Env(env expand.Environ) func(*Runner) error {
return func(r *Runner) error {
if env == nil {
env = expand.ListEnviron(os.Environ()...)
}
r.Env = env
return nil
}
} | [
"func",
"Env",
"(",
"env",
"expand",
".",
"Environ",
")",
"func",
"(",
"*",
"Runner",
")",
"error",
"{",
"return",
"func",
"(",
"r",
"*",
"Runner",
")",
"error",
"{",
"if",
"env",
"==",
"nil",
"{",
"env",
"=",
"expand",
".",
"ListEnviron",
"(",
"os",
".",
"Environ",
"(",
")",
"...",
")",
"\n",
"}",
"\n",
"r",
".",
"Env",
"=",
"env",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Env sets the interpreter's environment. If nil, a copy of the current
// process's environment is used. | [
"Env",
"sets",
"the",
"interpreter",
"s",
"environment",
".",
"If",
"nil",
"a",
"copy",
"of",
"the",
"current",
"process",
"s",
"environment",
"is",
"used",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L181-L189 | train |
mvdan/sh | interp/interp.go | Dir | func Dir(path string) func(*Runner) error {
return func(r *Runner) error {
if path == "" {
path, err := os.Getwd()
if err != nil {
return fmt.Errorf("could not get current dir: %v", err)
}
r.Dir = path
return nil
}
path, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("could not get absolute dir: %v", err)
}
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("could not stat: %v", err)
}
if !info.IsDir() {
return fmt.Errorf("%s is not a directory", path)
}
r.Dir = path
return nil
}
} | go | func Dir(path string) func(*Runner) error {
return func(r *Runner) error {
if path == "" {
path, err := os.Getwd()
if err != nil {
return fmt.Errorf("could not get current dir: %v", err)
}
r.Dir = path
return nil
}
path, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("could not get absolute dir: %v", err)
}
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("could not stat: %v", err)
}
if !info.IsDir() {
return fmt.Errorf("%s is not a directory", path)
}
r.Dir = path
return nil
}
} | [
"func",
"Dir",
"(",
"path",
"string",
")",
"func",
"(",
"*",
"Runner",
")",
"error",
"{",
"return",
"func",
"(",
"r",
"*",
"Runner",
")",
"error",
"{",
"if",
"path",
"==",
"\"",
"\"",
"{",
"path",
",",
"err",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"r",
".",
"Dir",
"=",
"path",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"path",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"info",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"r",
".",
"Dir",
"=",
"path",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Dir sets the interpreter's working directory. If empty, the process's current
// directory is used. | [
"Dir",
"sets",
"the",
"interpreter",
"s",
"working",
"directory",
".",
"If",
"empty",
"the",
"process",
"s",
"current",
"directory",
"is",
"used",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L193-L217 | train |
mvdan/sh | interp/interp.go | Module | func Module(mod ModuleFunc) func(*Runner) error {
return func(r *Runner) error {
switch mod := mod.(type) {
case ModuleExec:
if mod == nil {
mod = DefaultExec
}
r.Exec = mod
case ModuleOpen:
if mod == nil {
mod = DefaultOpen
}
r.Open = mod
default:
return fmt.Errorf("unknown module type: %T", mod)
}
return nil
}
} | go | func Module(mod ModuleFunc) func(*Runner) error {
return func(r *Runner) error {
switch mod := mod.(type) {
case ModuleExec:
if mod == nil {
mod = DefaultExec
}
r.Exec = mod
case ModuleOpen:
if mod == nil {
mod = DefaultOpen
}
r.Open = mod
default:
return fmt.Errorf("unknown module type: %T", mod)
}
return nil
}
} | [
"func",
"Module",
"(",
"mod",
"ModuleFunc",
")",
"func",
"(",
"*",
"Runner",
")",
"error",
"{",
"return",
"func",
"(",
"r",
"*",
"Runner",
")",
"error",
"{",
"switch",
"mod",
":=",
"mod",
".",
"(",
"type",
")",
"{",
"case",
"ModuleExec",
":",
"if",
"mod",
"==",
"nil",
"{",
"mod",
"=",
"DefaultExec",
"\n",
"}",
"\n",
"r",
".",
"Exec",
"=",
"mod",
"\n",
"case",
"ModuleOpen",
":",
"if",
"mod",
"==",
"nil",
"{",
"mod",
"=",
"DefaultOpen",
"\n",
"}",
"\n",
"r",
".",
"Open",
"=",
"mod",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"mod",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Module sets an interpreter module, which can be ModuleExec or ModuleOpen. If
// the value is nil, the default module implementation is used. | [
"Module",
"sets",
"an",
"interpreter",
"module",
"which",
"can",
"be",
"ModuleExec",
"or",
"ModuleOpen",
".",
"If",
"the",
"value",
"is",
"nil",
"the",
"default",
"module",
"implementation",
"is",
"used",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L283-L301 | train |
mvdan/sh | interp/interp.go | StdIO | func StdIO(in io.Reader, out, err io.Writer) func(*Runner) error {
return func(r *Runner) error {
r.Stdin = in
if out == nil {
out = ioutil.Discard
}
r.Stdout = out
if err == nil {
err = ioutil.Discard
}
r.Stderr = err
return nil
}
} | go | func StdIO(in io.Reader, out, err io.Writer) func(*Runner) error {
return func(r *Runner) error {
r.Stdin = in
if out == nil {
out = ioutil.Discard
}
r.Stdout = out
if err == nil {
err = ioutil.Discard
}
r.Stderr = err
return nil
}
} | [
"func",
"StdIO",
"(",
"in",
"io",
".",
"Reader",
",",
"out",
",",
"err",
"io",
".",
"Writer",
")",
"func",
"(",
"*",
"Runner",
")",
"error",
"{",
"return",
"func",
"(",
"r",
"*",
"Runner",
")",
"error",
"{",
"r",
".",
"Stdin",
"=",
"in",
"\n",
"if",
"out",
"==",
"nil",
"{",
"out",
"=",
"ioutil",
".",
"Discard",
"\n",
"}",
"\n",
"r",
".",
"Stdout",
"=",
"out",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"ioutil",
".",
"Discard",
"\n",
"}",
"\n",
"r",
".",
"Stderr",
"=",
"err",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // StdIO configures an interpreter's standard input, standard output, and
// standard error. If out or err are nil, they default to a writer that discards
// the output. | [
"StdIO",
"configures",
"an",
"interpreter",
"s",
"standard",
"input",
"standard",
"output",
"and",
"standard",
"error",
".",
"If",
"out",
"or",
"err",
"are",
"nil",
"they",
"default",
"to",
"a",
"writer",
"that",
"discards",
"the",
"output",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L306-L319 | train |
mvdan/sh | expand/expand.go | Literal | func Literal(cfg *Config, word *syntax.Word) (string, error) {
if word == nil {
return "", nil
}
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteNone)
if err != nil {
return "", err
}
return cfg.fieldJoin(field), nil
} | go | func Literal(cfg *Config, word *syntax.Word) (string, error) {
if word == nil {
return "", nil
}
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteNone)
if err != nil {
return "", err
}
return cfg.fieldJoin(field), nil
} | [
"func",
"Literal",
"(",
"cfg",
"*",
"Config",
",",
"word",
"*",
"syntax",
".",
"Word",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"word",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"cfg",
"=",
"prepareConfig",
"(",
"cfg",
")",
"\n",
"field",
",",
"err",
":=",
"cfg",
".",
"wordField",
"(",
"word",
".",
"Parts",
",",
"quoteNone",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"cfg",
".",
"fieldJoin",
"(",
"field",
")",
",",
"nil",
"\n",
"}"
] | // Literal expands a single shell word. It is similar to Fields, but the result
// is a single string. This is the behavior when a word is used as the value in
// a shell variable assignment, for example.
//
// The config specifies shell expansion options; nil behaves the same as an
// empty config. | [
"Literal",
"expands",
"a",
"single",
"shell",
"word",
".",
"It",
"is",
"similar",
"to",
"Fields",
"but",
"the",
"result",
"is",
"a",
"single",
"string",
".",
"This",
"is",
"the",
"behavior",
"when",
"a",
"word",
"is",
"used",
"as",
"the",
"value",
"in",
"a",
"shell",
"variable",
"assignment",
"for",
"example",
".",
"The",
"config",
"specifies",
"shell",
"expansion",
"options",
";",
"nil",
"behaves",
"the",
"same",
"as",
"an",
"empty",
"config",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L130-L140 | train |
mvdan/sh | expand/expand.go | Document | func Document(cfg *Config, word *syntax.Word) (string, error) {
if word == nil {
return "", nil
}
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteDouble)
if err != nil {
return "", err
}
return cfg.fieldJoin(field), nil
} | go | func Document(cfg *Config, word *syntax.Word) (string, error) {
if word == nil {
return "", nil
}
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteDouble)
if err != nil {
return "", err
}
return cfg.fieldJoin(field), nil
} | [
"func",
"Document",
"(",
"cfg",
"*",
"Config",
",",
"word",
"*",
"syntax",
".",
"Word",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"word",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"cfg",
"=",
"prepareConfig",
"(",
"cfg",
")",
"\n",
"field",
",",
"err",
":=",
"cfg",
".",
"wordField",
"(",
"word",
".",
"Parts",
",",
"quoteDouble",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"cfg",
".",
"fieldJoin",
"(",
"field",
")",
",",
"nil",
"\n",
"}"
] | // Document expands a single shell word as if it were within double quotes. It
// is simlar to Literal, but without brace expansion, tilde expansion, and
// globbing.
//
// The config specifies shell expansion options; nil behaves the same as an
// empty config. | [
"Document",
"expands",
"a",
"single",
"shell",
"word",
"as",
"if",
"it",
"were",
"within",
"double",
"quotes",
".",
"It",
"is",
"simlar",
"to",
"Literal",
"but",
"without",
"brace",
"expansion",
"tilde",
"expansion",
"and",
"globbing",
".",
"The",
"config",
"specifies",
"shell",
"expansion",
"options",
";",
"nil",
"behaves",
"the",
"same",
"as",
"an",
"empty",
"config",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L148-L158 | train |
mvdan/sh | expand/expand.go | Pattern | func Pattern(cfg *Config, word *syntax.Word) (string, error) {
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteNone)
if err != nil {
return "", err
}
buf := cfg.strBuilder()
for _, part := range field {
if part.quote > quoteNone {
buf.WriteString(syntax.QuotePattern(part.val))
} else {
buf.WriteString(part.val)
}
}
return buf.String(), nil
} | go | func Pattern(cfg *Config, word *syntax.Word) (string, error) {
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteNone)
if err != nil {
return "", err
}
buf := cfg.strBuilder()
for _, part := range field {
if part.quote > quoteNone {
buf.WriteString(syntax.QuotePattern(part.val))
} else {
buf.WriteString(part.val)
}
}
return buf.String(), nil
} | [
"func",
"Pattern",
"(",
"cfg",
"*",
"Config",
",",
"word",
"*",
"syntax",
".",
"Word",
")",
"(",
"string",
",",
"error",
")",
"{",
"cfg",
"=",
"prepareConfig",
"(",
"cfg",
")",
"\n",
"field",
",",
"err",
":=",
"cfg",
".",
"wordField",
"(",
"word",
".",
"Parts",
",",
"quoteNone",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"buf",
":=",
"cfg",
".",
"strBuilder",
"(",
")",
"\n",
"for",
"_",
",",
"part",
":=",
"range",
"field",
"{",
"if",
"part",
".",
"quote",
">",
"quoteNone",
"{",
"buf",
".",
"WriteString",
"(",
"syntax",
".",
"QuotePattern",
"(",
"part",
".",
"val",
")",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteString",
"(",
"part",
".",
"val",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Pattern expands a single shell word as a pattern, using syntax.QuotePattern
// on any non-quoted parts of the input word. The result can be used on
// syntax.TranslatePattern directly.
//
// The config specifies shell expansion options; nil behaves the same as an
// empty config. | [
"Pattern",
"expands",
"a",
"single",
"shell",
"word",
"as",
"a",
"pattern",
"using",
"syntax",
".",
"QuotePattern",
"on",
"any",
"non",
"-",
"quoted",
"parts",
"of",
"the",
"input",
"word",
".",
"The",
"result",
"can",
"be",
"used",
"on",
"syntax",
".",
"TranslatePattern",
"directly",
".",
"The",
"config",
"specifies",
"shell",
"expansion",
"options",
";",
"nil",
"behaves",
"the",
"same",
"as",
"an",
"empty",
"config",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L166-L181 | train |
mvdan/sh | expand/expand.go | Fields | func Fields(cfg *Config, words ...*syntax.Word) ([]string, error) {
cfg = prepareConfig(cfg)
fields := make([]string, 0, len(words))
dir := cfg.envGet("PWD")
for _, word := range words {
afterBraces := []*syntax.Word{word}
if w2 := syntax.SplitBraces(word); w2 != word {
afterBraces = Braces(w2)
}
for _, word2 := range afterBraces {
wfields, err := cfg.wordFields(word2.Parts)
if err != nil {
return nil, err
}
for _, field := range wfields {
path, doGlob := cfg.escapedGlobField(field)
var matches []string
if doGlob && cfg.ReadDir != nil {
matches, err = cfg.glob(dir, path)
if err != nil {
return nil, err
}
if len(matches) > 0 {
fields = append(fields, matches...)
continue
}
}
fields = append(fields, cfg.fieldJoin(field))
}
}
}
return fields, nil
} | go | func Fields(cfg *Config, words ...*syntax.Word) ([]string, error) {
cfg = prepareConfig(cfg)
fields := make([]string, 0, len(words))
dir := cfg.envGet("PWD")
for _, word := range words {
afterBraces := []*syntax.Word{word}
if w2 := syntax.SplitBraces(word); w2 != word {
afterBraces = Braces(w2)
}
for _, word2 := range afterBraces {
wfields, err := cfg.wordFields(word2.Parts)
if err != nil {
return nil, err
}
for _, field := range wfields {
path, doGlob := cfg.escapedGlobField(field)
var matches []string
if doGlob && cfg.ReadDir != nil {
matches, err = cfg.glob(dir, path)
if err != nil {
return nil, err
}
if len(matches) > 0 {
fields = append(fields, matches...)
continue
}
}
fields = append(fields, cfg.fieldJoin(field))
}
}
}
return fields, nil
} | [
"func",
"Fields",
"(",
"cfg",
"*",
"Config",
",",
"words",
"...",
"*",
"syntax",
".",
"Word",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"cfg",
"=",
"prepareConfig",
"(",
"cfg",
")",
"\n",
"fields",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"words",
")",
")",
"\n",
"dir",
":=",
"cfg",
".",
"envGet",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"word",
":=",
"range",
"words",
"{",
"afterBraces",
":=",
"[",
"]",
"*",
"syntax",
".",
"Word",
"{",
"word",
"}",
"\n",
"if",
"w2",
":=",
"syntax",
".",
"SplitBraces",
"(",
"word",
")",
";",
"w2",
"!=",
"word",
"{",
"afterBraces",
"=",
"Braces",
"(",
"w2",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"word2",
":=",
"range",
"afterBraces",
"{",
"wfields",
",",
"err",
":=",
"cfg",
".",
"wordFields",
"(",
"word2",
".",
"Parts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"field",
":=",
"range",
"wfields",
"{",
"path",
",",
"doGlob",
":=",
"cfg",
".",
"escapedGlobField",
"(",
"field",
")",
"\n",
"var",
"matches",
"[",
"]",
"string",
"\n",
"if",
"doGlob",
"&&",
"cfg",
".",
"ReadDir",
"!=",
"nil",
"{",
"matches",
",",
"err",
"=",
"cfg",
".",
"glob",
"(",
"dir",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"matches",
")",
">",
"0",
"{",
"fields",
"=",
"append",
"(",
"fields",
",",
"matches",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"fields",
"=",
"append",
"(",
"fields",
",",
"cfg",
".",
"fieldJoin",
"(",
"field",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fields",
",",
"nil",
"\n",
"}"
] | // Fields expands a number of words as if they were arguments in a shell
// command. This includes brace expansion, tilde expansion, parameter expansion,
// command substitution, arithmetic expansion, and quote removal. | [
"Fields",
"expands",
"a",
"number",
"of",
"words",
"as",
"if",
"they",
"were",
"arguments",
"in",
"a",
"shell",
"command",
".",
"This",
"includes",
"brace",
"expansion",
"tilde",
"expansion",
"parameter",
"expansion",
"command",
"substitution",
"arithmetic",
"expansion",
"and",
"quote",
"removal",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L363-L395 | train |
mvdan/sh | expand/expand.go | pathJoin2 | func pathJoin2(elem1, elem2 string) string {
if elem1 == "" {
return elem2
}
if strings.HasSuffix(elem1, string(filepath.Separator)) {
return elem1 + elem2
}
return elem1 + string(filepath.Separator) + elem2
} | go | func pathJoin2(elem1, elem2 string) string {
if elem1 == "" {
return elem2
}
if strings.HasSuffix(elem1, string(filepath.Separator)) {
return elem1 + elem2
}
return elem1 + string(filepath.Separator) + elem2
} | [
"func",
"pathJoin2",
"(",
"elem1",
",",
"elem2",
"string",
")",
"string",
"{",
"if",
"elem1",
"==",
"\"",
"\"",
"{",
"return",
"elem2",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"elem1",
",",
"string",
"(",
"filepath",
".",
"Separator",
")",
")",
"{",
"return",
"elem1",
"+",
"elem2",
"\n",
"}",
"\n",
"return",
"elem1",
"+",
"string",
"(",
"filepath",
".",
"Separator",
")",
"+",
"elem2",
"\n",
"}"
] | // pathJoin2 is a simpler version of filepath.Join without cleaning the result,
// since that's needed for globbing. | [
"pathJoin2",
"is",
"a",
"simpler",
"version",
"of",
"filepath",
".",
"Join",
"without",
"cleaning",
"the",
"result",
"since",
"that",
"s",
"needed",
"for",
"globbing",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L651-L659 | train |
mvdan/sh | expand/expand.go | pathSplit | func pathSplit(path string) []string {
path = filepath.FromSlash(path)
return strings.Split(path, string(filepath.Separator))
} | go | func pathSplit(path string) []string {
path = filepath.FromSlash(path)
return strings.Split(path, string(filepath.Separator))
} | [
"func",
"pathSplit",
"(",
"path",
"string",
")",
"[",
"]",
"string",
"{",
"path",
"=",
"filepath",
".",
"FromSlash",
"(",
"path",
")",
"\n",
"return",
"strings",
".",
"Split",
"(",
"path",
",",
"string",
"(",
"filepath",
".",
"Separator",
")",
")",
"\n",
"}"
] | // pathSplit splits a file path into its elements, retaining empty ones. Before
// splitting, slashes are replaced with filepath.Separator, so that splitting
// Unix paths on Windows works as well. | [
"pathSplit",
"splits",
"a",
"file",
"path",
"into",
"its",
"elements",
"retaining",
"empty",
"ones",
".",
"Before",
"splitting",
"slashes",
"are",
"replaced",
"with",
"filepath",
".",
"Separator",
"so",
"that",
"splitting",
"Unix",
"paths",
"on",
"Windows",
"works",
"as",
"well",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L664-L667 | train |
mvdan/sh | fileutil/file.go | CouldBeScript | func CouldBeScript(info os.FileInfo) ScriptConfidence {
name := info.Name()
switch {
case info.IsDir(), name[0] == '.':
return ConfNotScript
case info.Mode()&os.ModeSymlink != 0:
return ConfNotScript
case extRe.MatchString(name):
return ConfIsScript
case strings.IndexByte(name, '.') > 0:
return ConfNotScript // different extension
case info.Size() < int64(len("#/bin/sh\n")):
return ConfNotScript // cannot possibly hold valid shebang
default:
return ConfIfShebang
}
} | go | func CouldBeScript(info os.FileInfo) ScriptConfidence {
name := info.Name()
switch {
case info.IsDir(), name[0] == '.':
return ConfNotScript
case info.Mode()&os.ModeSymlink != 0:
return ConfNotScript
case extRe.MatchString(name):
return ConfIsScript
case strings.IndexByte(name, '.') > 0:
return ConfNotScript // different extension
case info.Size() < int64(len("#/bin/sh\n")):
return ConfNotScript // cannot possibly hold valid shebang
default:
return ConfIfShebang
}
} | [
"func",
"CouldBeScript",
"(",
"info",
"os",
".",
"FileInfo",
")",
"ScriptConfidence",
"{",
"name",
":=",
"info",
".",
"Name",
"(",
")",
"\n",
"switch",
"{",
"case",
"info",
".",
"IsDir",
"(",
")",
",",
"name",
"[",
"0",
"]",
"==",
"'.'",
":",
"return",
"ConfNotScript",
"\n",
"case",
"info",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"!=",
"0",
":",
"return",
"ConfNotScript",
"\n",
"case",
"extRe",
".",
"MatchString",
"(",
"name",
")",
":",
"return",
"ConfIsScript",
"\n",
"case",
"strings",
".",
"IndexByte",
"(",
"name",
",",
"'.'",
")",
">",
"0",
":",
"return",
"ConfNotScript",
"// different extension",
"\n",
"case",
"info",
".",
"Size",
"(",
")",
"<",
"int64",
"(",
"len",
"(",
"\"",
"\\n",
"\"",
")",
")",
":",
"return",
"ConfNotScript",
"// cannot possibly hold valid shebang",
"\n",
"default",
":",
"return",
"ConfIfShebang",
"\n",
"}",
"\n",
"}"
] | // CouldBeScript reports how likely a file is to be a shell script. It
// discards directories, symlinks, hidden files and files with non-shell
// extensions. | [
"CouldBeScript",
"reports",
"how",
"likely",
"a",
"file",
"is",
"to",
"be",
"a",
"shell",
"script",
".",
"It",
"discards",
"directories",
"symlinks",
"hidden",
"files",
"and",
"files",
"with",
"non",
"-",
"shell",
"extensions",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/fileutil/file.go#L39-L55 | train |
mvdan/sh | expand/arith.go | atoi | func atoi(s string) int {
n, _ := strconv.Atoi(s)
return n
} | go | func atoi(s string) int {
n, _ := strconv.Atoi(s)
return n
} | [
"func",
"atoi",
"(",
"s",
"string",
")",
"int",
"{",
"n",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"return",
"n",
"\n",
"}"
] | // atoi is just a shorthand for strconv.Atoi that ignores the error,
// just like shells do. | [
"atoi",
"is",
"just",
"a",
"shorthand",
"for",
"strconv",
".",
"Atoi",
"that",
"ignores",
"the",
"error",
"just",
"like",
"shells",
"do",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/arith.go#L110-L113 | train |
mvdan/sh | shell/expand.go | Fields | func Fields(s string, env func(string) string) ([]string, error) {
p := syntax.NewParser()
var words []*syntax.Word
err := p.Words(strings.NewReader(s), func(w *syntax.Word) bool {
words = append(words, w)
return true
})
if err != nil {
return nil, err
}
if env == nil {
env = os.Getenv
}
cfg := &expand.Config{Env: expand.FuncEnviron(env)}
return expand.Fields(cfg, words...)
} | go | func Fields(s string, env func(string) string) ([]string, error) {
p := syntax.NewParser()
var words []*syntax.Word
err := p.Words(strings.NewReader(s), func(w *syntax.Word) bool {
words = append(words, w)
return true
})
if err != nil {
return nil, err
}
if env == nil {
env = os.Getenv
}
cfg := &expand.Config{Env: expand.FuncEnviron(env)}
return expand.Fields(cfg, words...)
} | [
"func",
"Fields",
"(",
"s",
"string",
",",
"env",
"func",
"(",
"string",
")",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"p",
":=",
"syntax",
".",
"NewParser",
"(",
")",
"\n",
"var",
"words",
"[",
"]",
"*",
"syntax",
".",
"Word",
"\n",
"err",
":=",
"p",
".",
"Words",
"(",
"strings",
".",
"NewReader",
"(",
"s",
")",
",",
"func",
"(",
"w",
"*",
"syntax",
".",
"Word",
")",
"bool",
"{",
"words",
"=",
"append",
"(",
"words",
",",
"w",
")",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"env",
"==",
"nil",
"{",
"env",
"=",
"os",
".",
"Getenv",
"\n",
"}",
"\n",
"cfg",
":=",
"&",
"expand",
".",
"Config",
"{",
"Env",
":",
"expand",
".",
"FuncEnviron",
"(",
"env",
")",
"}",
"\n",
"return",
"expand",
".",
"Fields",
"(",
"cfg",
",",
"words",
"...",
")",
"\n",
"}"
] | // Fields performs shell expansion on s as if it were a command's arguments,
// using env to resolve variables. It is similar to Expand, but includes brace
// expansion, tilde expansion, and globbing.
//
// If env is nil, the current environment variables are used. Empty variables
// are treated as unset; to support variables which are set but empty, use the
// expand package directly.
//
// An error will be reported if the input string had invalid syntax. | [
"Fields",
"performs",
"shell",
"expansion",
"on",
"s",
"as",
"if",
"it",
"were",
"a",
"command",
"s",
"arguments",
"using",
"env",
"to",
"resolve",
"variables",
".",
"It",
"is",
"similar",
"to",
"Expand",
"but",
"includes",
"brace",
"expansion",
"tilde",
"expansion",
"and",
"globbing",
".",
"If",
"env",
"is",
"nil",
"the",
"current",
"environment",
"variables",
"are",
"used",
".",
"Empty",
"variables",
"are",
"treated",
"as",
"unset",
";",
"to",
"support",
"variables",
"which",
"are",
"set",
"but",
"empty",
"use",
"the",
"expand",
"package",
"directly",
".",
"An",
"error",
"will",
"be",
"reported",
"if",
"the",
"input",
"string",
"had",
"invalid",
"syntax",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/shell/expand.go#L48-L63 | train |
mvdan/sh | syntax/printer.go | KeepPadding | func KeepPadding(p *Printer) {
p.keepPadding = true
p.cols.Writer = p.bufWriter.(*bufio.Writer)
p.bufWriter = &p.cols
} | go | func KeepPadding(p *Printer) {
p.keepPadding = true
p.cols.Writer = p.bufWriter.(*bufio.Writer)
p.bufWriter = &p.cols
} | [
"func",
"KeepPadding",
"(",
"p",
"*",
"Printer",
")",
"{",
"p",
".",
"keepPadding",
"=",
"true",
"\n",
"p",
".",
"cols",
".",
"Writer",
"=",
"p",
".",
"bufWriter",
".",
"(",
"*",
"bufio",
".",
"Writer",
")",
"\n",
"p",
".",
"bufWriter",
"=",
"&",
"p",
".",
"cols",
"\n",
"}"
] | // KeepPadding will keep most nodes and tokens in the same column that
// they were in the original source. This allows the user to decide how
// to align and pad their code with spaces.
//
// Note that this feature is best-effort and will only keep the
// alignment stable, so it may need some human help the first time it is
// run. | [
"KeepPadding",
"will",
"keep",
"most",
"nodes",
"and",
"tokens",
"in",
"the",
"same",
"column",
"that",
"they",
"were",
"in",
"the",
"original",
"source",
".",
"This",
"allows",
"the",
"user",
"to",
"decide",
"how",
"to",
"align",
"and",
"pad",
"their",
"code",
"with",
"spaces",
".",
"Note",
"that",
"this",
"feature",
"is",
"best",
"-",
"effort",
"and",
"will",
"only",
"keep",
"the",
"alignment",
"stable",
"so",
"it",
"may",
"need",
"some",
"human",
"help",
"the",
"first",
"time",
"it",
"is",
"run",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/printer.go#L42-L46 | train |
mvdan/sh | syntax/printer.go | NewPrinter | func NewPrinter(options ...func(*Printer)) *Printer {
p := &Printer{
bufWriter: bufio.NewWriter(nil),
tabsPrinter: new(Printer),
tabWriter: new(tabwriter.Writer),
}
for _, opt := range options {
opt(p)
}
return p
} | go | func NewPrinter(options ...func(*Printer)) *Printer {
p := &Printer{
bufWriter: bufio.NewWriter(nil),
tabsPrinter: new(Printer),
tabWriter: new(tabwriter.Writer),
}
for _, opt := range options {
opt(p)
}
return p
} | [
"func",
"NewPrinter",
"(",
"options",
"...",
"func",
"(",
"*",
"Printer",
")",
")",
"*",
"Printer",
"{",
"p",
":=",
"&",
"Printer",
"{",
"bufWriter",
":",
"bufio",
".",
"NewWriter",
"(",
"nil",
")",
",",
"tabsPrinter",
":",
"new",
"(",
"Printer",
")",
",",
"tabWriter",
":",
"new",
"(",
"tabwriter",
".",
"Writer",
")",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"options",
"{",
"opt",
"(",
"p",
")",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // NewPrinter allocates a new Printer and applies any number of options. | [
"NewPrinter",
"allocates",
"a",
"new",
"Printer",
"and",
"applies",
"any",
"number",
"of",
"options",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/printer.go#L54-L64 | train |
mvdan/sh | interp/module.go | FromModuleContext | func FromModuleContext(ctx context.Context) (ModuleCtx, bool) {
mc, ok := ctx.Value(moduleCtxKey{}).(ModuleCtx)
return mc, ok
} | go | func FromModuleContext(ctx context.Context) (ModuleCtx, bool) {
mc, ok := ctx.Value(moduleCtxKey{}).(ModuleCtx)
return mc, ok
} | [
"func",
"FromModuleContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"ModuleCtx",
",",
"bool",
")",
"{",
"mc",
",",
"ok",
":=",
"ctx",
".",
"Value",
"(",
"moduleCtxKey",
"{",
"}",
")",
".",
"(",
"ModuleCtx",
")",
"\n",
"return",
"mc",
",",
"ok",
"\n",
"}"
] | // FromModuleContext returns the ModuleCtx value stored in ctx, if any. | [
"FromModuleContext",
"returns",
"the",
"ModuleCtx",
"value",
"stored",
"in",
"ctx",
"if",
"any",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/module.go#L21-L24 | train |
mvdan/sh | syntax/walk.go | DebugPrint | func DebugPrint(w io.Writer, node Node) error {
p := debugPrinter{out: w}
p.print(reflect.ValueOf(node))
return p.err
} | go | func DebugPrint(w io.Writer, node Node) error {
p := debugPrinter{out: w}
p.print(reflect.ValueOf(node))
return p.err
} | [
"func",
"DebugPrint",
"(",
"w",
"io",
".",
"Writer",
",",
"node",
"Node",
")",
"error",
"{",
"p",
":=",
"debugPrinter",
"{",
"out",
":",
"w",
"}",
"\n",
"p",
".",
"print",
"(",
"reflect",
".",
"ValueOf",
"(",
"node",
")",
")",
"\n",
"return",
"p",
".",
"err",
"\n",
"}"
] | // DebugPrint prints the provided syntax tree, spanning multiple lines and with
// indentation. Can be useful to investigate the content of a syntax tree. | [
"DebugPrint",
"prints",
"the",
"provided",
"syntax",
"tree",
"spanning",
"multiple",
"lines",
"and",
"with",
"indentation",
".",
"Can",
"be",
"useful",
"to",
"investigate",
"the",
"content",
"of",
"a",
"syntax",
"tree",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/walk.go#L233-L237 | train |
mvdan/sh | syntax/lexer.go | fill | func (p *Parser) fill() {
p.offs += p.bsp
left := len(p.bs) - p.bsp
copy(p.readBuf[:left], p.readBuf[p.bsp:])
readAgain:
n, err := 0, p.readErr
if err == nil {
n, err = p.src.Read(p.readBuf[left:])
p.readErr = err
}
if n == 0 {
if err == nil {
goto readAgain
}
// don't use p.errPass as we don't want to overwrite p.tok
if err != io.EOF {
p.err = err
}
if left > 0 {
p.bs = p.readBuf[:left]
} else {
p.bs = nil
}
} else {
p.bs = p.readBuf[:left+n]
}
p.bsp = 0
} | go | func (p *Parser) fill() {
p.offs += p.bsp
left := len(p.bs) - p.bsp
copy(p.readBuf[:left], p.readBuf[p.bsp:])
readAgain:
n, err := 0, p.readErr
if err == nil {
n, err = p.src.Read(p.readBuf[left:])
p.readErr = err
}
if n == 0 {
if err == nil {
goto readAgain
}
// don't use p.errPass as we don't want to overwrite p.tok
if err != io.EOF {
p.err = err
}
if left > 0 {
p.bs = p.readBuf[:left]
} else {
p.bs = nil
}
} else {
p.bs = p.readBuf[:left+n]
}
p.bsp = 0
} | [
"func",
"(",
"p",
"*",
"Parser",
")",
"fill",
"(",
")",
"{",
"p",
".",
"offs",
"+=",
"p",
".",
"bsp",
"\n",
"left",
":=",
"len",
"(",
"p",
".",
"bs",
")",
"-",
"p",
".",
"bsp",
"\n",
"copy",
"(",
"p",
".",
"readBuf",
"[",
":",
"left",
"]",
",",
"p",
".",
"readBuf",
"[",
"p",
".",
"bsp",
":",
"]",
")",
"\n",
"readAgain",
":",
"n",
",",
"err",
":=",
"0",
",",
"p",
".",
"readErr",
"\n",
"if",
"err",
"==",
"nil",
"{",
"n",
",",
"err",
"=",
"p",
".",
"src",
".",
"Read",
"(",
"p",
".",
"readBuf",
"[",
"left",
":",
"]",
")",
"\n",
"p",
".",
"readErr",
"=",
"err",
"\n",
"}",
"\n",
"if",
"n",
"==",
"0",
"{",
"if",
"err",
"==",
"nil",
"{",
"goto",
"readAgain",
"\n",
"}",
"\n",
"// don't use p.errPass as we don't want to overwrite p.tok",
"if",
"err",
"!=",
"io",
".",
"EOF",
"{",
"p",
".",
"err",
"=",
"err",
"\n",
"}",
"\n",
"if",
"left",
">",
"0",
"{",
"p",
".",
"bs",
"=",
"p",
".",
"readBuf",
"[",
":",
"left",
"]",
"\n",
"}",
"else",
"{",
"p",
".",
"bs",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"else",
"{",
"p",
".",
"bs",
"=",
"p",
".",
"readBuf",
"[",
":",
"left",
"+",
"n",
"]",
"\n",
"}",
"\n",
"p",
".",
"bsp",
"=",
"0",
"\n",
"}"
] | // fill reads more bytes from the input src into readBuf. Any bytes that
// had not yet been used at the end of the buffer are slid into the
// beginning of the buffer. | [
"fill",
"reads",
"more",
"bytes",
"from",
"the",
"input",
"src",
"into",
"readBuf",
".",
"Any",
"bytes",
"that",
"had",
"not",
"yet",
"been",
"used",
"at",
"the",
"end",
"of",
"the",
"buffer",
"are",
"slid",
"into",
"the",
"beginning",
"of",
"the",
"buffer",
"."
] | 5700c68a35dc3882e646a5e41776e31bb2c078e3 | https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/lexer.go#L119-L146 | train |
robertkrimen/otto | file/file.go | AddFile | func (self *FileSet) AddFile(filename, src string) int {
base := self.nextBase()
file := &File{
name: filename,
src: src,
base: base,
}
self.files = append(self.files, file)
self.last = file
return base
} | go | func (self *FileSet) AddFile(filename, src string) int {
base := self.nextBase()
file := &File{
name: filename,
src: src,
base: base,
}
self.files = append(self.files, file)
self.last = file
return base
} | [
"func",
"(",
"self",
"*",
"FileSet",
")",
"AddFile",
"(",
"filename",
",",
"src",
"string",
")",
"int",
"{",
"base",
":=",
"self",
".",
"nextBase",
"(",
")",
"\n",
"file",
":=",
"&",
"File",
"{",
"name",
":",
"filename",
",",
"src",
":",
"src",
",",
"base",
":",
"base",
",",
"}",
"\n",
"self",
".",
"files",
"=",
"append",
"(",
"self",
".",
"files",
",",
"file",
")",
"\n",
"self",
".",
"last",
"=",
"file",
"\n",
"return",
"base",
"\n",
"}"
] | // AddFile adds a new file with the given filename and src.
//
// This an internal method, but exported for cross-package use. | [
"AddFile",
"adds",
"a",
"new",
"file",
"with",
"the",
"given",
"filename",
"and",
"src",
".",
"This",
"an",
"internal",
"method",
"but",
"exported",
"for",
"cross",
"-",
"package",
"use",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/file/file.go#L65-L75 | train |
robertkrimen/otto | global.go | newBoundFunction | func (runtime *_runtime) newBoundFunction(target *_object, this Value, argumentList []Value) *_object {
self := runtime.newBoundFunctionObject(target, this, argumentList)
self.prototype = runtime.global.FunctionPrototype
prototype := runtime.newObject()
self.defineProperty("prototype", toValue_object(prototype), 0100, false)
prototype.defineProperty("constructor", toValue_object(self), 0100, false)
return self
} | go | func (runtime *_runtime) newBoundFunction(target *_object, this Value, argumentList []Value) *_object {
self := runtime.newBoundFunctionObject(target, this, argumentList)
self.prototype = runtime.global.FunctionPrototype
prototype := runtime.newObject()
self.defineProperty("prototype", toValue_object(prototype), 0100, false)
prototype.defineProperty("constructor", toValue_object(self), 0100, false)
return self
} | [
"func",
"(",
"runtime",
"*",
"_runtime",
")",
"newBoundFunction",
"(",
"target",
"*",
"_object",
",",
"this",
"Value",
",",
"argumentList",
"[",
"]",
"Value",
")",
"*",
"_object",
"{",
"self",
":=",
"runtime",
".",
"newBoundFunctionObject",
"(",
"target",
",",
"this",
",",
"argumentList",
")",
"\n",
"self",
".",
"prototype",
"=",
"runtime",
".",
"global",
".",
"FunctionPrototype",
"\n",
"prototype",
":=",
"runtime",
".",
"newObject",
"(",
")",
"\n",
"self",
".",
"defineProperty",
"(",
"\"",
"\"",
",",
"toValue_object",
"(",
"prototype",
")",
",",
"0100",
",",
"false",
")",
"\n",
"prototype",
".",
"defineProperty",
"(",
"\"",
"\"",
",",
"toValue_object",
"(",
"self",
")",
",",
"0100",
",",
"false",
")",
"\n",
"return",
"self",
"\n",
"}"
] | // FIXME Only in one place... | [
"FIXME",
"Only",
"in",
"one",
"place",
"..."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/global.go#L214-L221 | train |
robertkrimen/otto | script.go | CompileWithSourceMap | func (self *Otto) CompileWithSourceMap(filename string, src, sm interface{}) (*Script, error) {
program, err := self.runtime.parse(filename, src, sm)
if err != nil {
return nil, err
}
cmpl_program := cmpl_parse(program)
script := &Script{
version: scriptVersion,
program: cmpl_program,
filename: filename,
src: program.File.Source(),
}
return script, nil
} | go | func (self *Otto) CompileWithSourceMap(filename string, src, sm interface{}) (*Script, error) {
program, err := self.runtime.parse(filename, src, sm)
if err != nil {
return nil, err
}
cmpl_program := cmpl_parse(program)
script := &Script{
version: scriptVersion,
program: cmpl_program,
filename: filename,
src: program.File.Source(),
}
return script, nil
} | [
"func",
"(",
"self",
"*",
"Otto",
")",
"CompileWithSourceMap",
"(",
"filename",
"string",
",",
"src",
",",
"sm",
"interface",
"{",
"}",
")",
"(",
"*",
"Script",
",",
"error",
")",
"{",
"program",
",",
"err",
":=",
"self",
".",
"runtime",
".",
"parse",
"(",
"filename",
",",
"src",
",",
"sm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cmpl_program",
":=",
"cmpl_parse",
"(",
"program",
")",
"\n\n",
"script",
":=",
"&",
"Script",
"{",
"version",
":",
"scriptVersion",
",",
"program",
":",
"cmpl_program",
",",
"filename",
":",
"filename",
",",
"src",
":",
"program",
".",
"File",
".",
"Source",
"(",
")",
",",
"}",
"\n\n",
"return",
"script",
",",
"nil",
"\n",
"}"
] | // CompileWithSourceMap does the same thing as Compile, but with the obvious
// difference of applying a source map. | [
"CompileWithSourceMap",
"does",
"the",
"same",
"thing",
"as",
"Compile",
"but",
"with",
"the",
"obvious",
"difference",
"of",
"applying",
"a",
"source",
"map",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/script.go#L35-L51 | train |
robertkrimen/otto | script.go | marshalBinary | func (self *Script) marshalBinary() ([]byte, error) {
var bfr bytes.Buffer
encoder := gob.NewEncoder(&bfr)
err := encoder.Encode(self.version)
if err != nil {
return nil, err
}
err = encoder.Encode(self.program)
if err != nil {
return nil, err
}
err = encoder.Encode(self.filename)
if err != nil {
return nil, err
}
err = encoder.Encode(self.src)
if err != nil {
return nil, err
}
return bfr.Bytes(), nil
} | go | func (self *Script) marshalBinary() ([]byte, error) {
var bfr bytes.Buffer
encoder := gob.NewEncoder(&bfr)
err := encoder.Encode(self.version)
if err != nil {
return nil, err
}
err = encoder.Encode(self.program)
if err != nil {
return nil, err
}
err = encoder.Encode(self.filename)
if err != nil {
return nil, err
}
err = encoder.Encode(self.src)
if err != nil {
return nil, err
}
return bfr.Bytes(), nil
} | [
"func",
"(",
"self",
"*",
"Script",
")",
"marshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"bfr",
"bytes",
".",
"Buffer",
"\n",
"encoder",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"bfr",
")",
"\n",
"err",
":=",
"encoder",
".",
"Encode",
"(",
"self",
".",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"encoder",
".",
"Encode",
"(",
"self",
".",
"program",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"encoder",
".",
"Encode",
"(",
"self",
".",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"encoder",
".",
"Encode",
"(",
"self",
".",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"bfr",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary will marshal a script into a binary form. A marshalled script
// that is later unmarshalled can be executed on the same version of the otto runtime.
//
// The binary format can change at any time and should be considered unspecified and opaque.
// | [
"MarshalBinary",
"will",
"marshal",
"a",
"script",
"into",
"a",
"binary",
"form",
".",
"A",
"marshalled",
"script",
"that",
"is",
"later",
"unmarshalled",
"can",
"be",
"executed",
"on",
"the",
"same",
"version",
"of",
"the",
"otto",
"runtime",
".",
"The",
"binary",
"format",
"can",
"change",
"at",
"any",
"time",
"and",
"should",
"be",
"considered",
"unspecified",
"and",
"opaque",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/script.go#L62-L82 | train |
robertkrimen/otto | script.go | unmarshalBinary | func (self *Script) unmarshalBinary(data []byte) error {
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&self.version)
if err != nil {
goto error
}
if self.version != scriptVersion {
err = ErrVersion
goto error
}
err = decoder.Decode(&self.program)
if err != nil {
goto error
}
err = decoder.Decode(&self.filename)
if err != nil {
goto error
}
err = decoder.Decode(&self.src)
if err != nil {
goto error
}
return nil
error:
self.version = ""
self.program = nil
self.filename = ""
self.src = ""
return err
} | go | func (self *Script) unmarshalBinary(data []byte) error {
decoder := gob.NewDecoder(bytes.NewReader(data))
err := decoder.Decode(&self.version)
if err != nil {
goto error
}
if self.version != scriptVersion {
err = ErrVersion
goto error
}
err = decoder.Decode(&self.program)
if err != nil {
goto error
}
err = decoder.Decode(&self.filename)
if err != nil {
goto error
}
err = decoder.Decode(&self.src)
if err != nil {
goto error
}
return nil
error:
self.version = ""
self.program = nil
self.filename = ""
self.src = ""
return err
} | [
"func",
"(",
"self",
"*",
"Script",
")",
"unmarshalBinary",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"decoder",
":=",
"gob",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
"\n",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"self",
".",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"goto",
"error",
"\n",
"}",
"\n",
"if",
"self",
".",
"version",
"!=",
"scriptVersion",
"{",
"err",
"=",
"ErrVersion",
"\n",
"goto",
"error",
"\n",
"}",
"\n",
"err",
"=",
"decoder",
".",
"Decode",
"(",
"&",
"self",
".",
"program",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"goto",
"error",
"\n",
"}",
"\n",
"err",
"=",
"decoder",
".",
"Decode",
"(",
"&",
"self",
".",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"goto",
"error",
"\n",
"}",
"\n",
"err",
"=",
"decoder",
".",
"Decode",
"(",
"&",
"self",
".",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"goto",
"error",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"error",
":",
"self",
".",
"version",
"=",
"\"",
"\"",
"\n",
"self",
".",
"program",
"=",
"nil",
"\n",
"self",
".",
"filename",
"=",
"\"",
"\"",
"\n",
"self",
".",
"src",
"=",
"\"",
"\"",
"\n",
"return",
"err",
"\n",
"}"
] | // UnmarshalBinary will vivify a marshalled script into something usable. If the script was
// originally marshalled on a different version of the otto runtime, then this method
// will return an error.
//
// The binary format can change at any time and should be considered unspecified and opaque.
// | [
"UnmarshalBinary",
"will",
"vivify",
"a",
"marshalled",
"script",
"into",
"something",
"usable",
".",
"If",
"the",
"script",
"was",
"originally",
"marshalled",
"on",
"a",
"different",
"version",
"of",
"the",
"otto",
"runtime",
"then",
"this",
"method",
"will",
"return",
"an",
"error",
".",
"The",
"binary",
"format",
"can",
"change",
"at",
"any",
"time",
"and",
"should",
"be",
"considered",
"unspecified",
"and",
"opaque",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/script.go#L90-L119 | train |
robertkrimen/otto | type_function.go | hasInstance | func (self *_object) hasInstance(of Value) bool {
if !self.isCall() {
// We should not have a hasInstance method
panic(self.runtime.panicTypeError())
}
if !of.IsObject() {
return false
}
prototype := self.get("prototype")
if !prototype.IsObject() {
panic(self.runtime.panicTypeError())
}
prototypeObject := prototype._object()
value := of._object().prototype
for value != nil {
if value == prototypeObject {
return true
}
value = value.prototype
}
return false
} | go | func (self *_object) hasInstance(of Value) bool {
if !self.isCall() {
// We should not have a hasInstance method
panic(self.runtime.panicTypeError())
}
if !of.IsObject() {
return false
}
prototype := self.get("prototype")
if !prototype.IsObject() {
panic(self.runtime.panicTypeError())
}
prototypeObject := prototype._object()
value := of._object().prototype
for value != nil {
if value == prototypeObject {
return true
}
value = value.prototype
}
return false
} | [
"func",
"(",
"self",
"*",
"_object",
")",
"hasInstance",
"(",
"of",
"Value",
")",
"bool",
"{",
"if",
"!",
"self",
".",
"isCall",
"(",
")",
"{",
"// We should not have a hasInstance method",
"panic",
"(",
"self",
".",
"runtime",
".",
"panicTypeError",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"of",
".",
"IsObject",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"prototype",
":=",
"self",
".",
"get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"prototype",
".",
"IsObject",
"(",
")",
"{",
"panic",
"(",
"self",
".",
"runtime",
".",
"panicTypeError",
"(",
")",
")",
"\n",
"}",
"\n",
"prototypeObject",
":=",
"prototype",
".",
"_object",
"(",
")",
"\n\n",
"value",
":=",
"of",
".",
"_object",
"(",
")",
".",
"prototype",
"\n",
"for",
"value",
"!=",
"nil",
"{",
"if",
"value",
"==",
"prototypeObject",
"{",
"return",
"true",
"\n",
"}",
"\n",
"value",
"=",
"value",
".",
"prototype",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // 15.3.5.3 | [
"15",
".",
"3",
".",
"5",
".",
"3"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/type_function.go#L259-L281 | train |
robertkrimen/otto | type_function.go | Argument | func (self FunctionCall) Argument(index int) Value {
return valueOfArrayIndex(self.ArgumentList, index)
} | go | func (self FunctionCall) Argument(index int) Value {
return valueOfArrayIndex(self.ArgumentList, index)
} | [
"func",
"(",
"self",
"FunctionCall",
")",
"Argument",
"(",
"index",
"int",
")",
"Value",
"{",
"return",
"valueOfArrayIndex",
"(",
"self",
".",
"ArgumentList",
",",
"index",
")",
"\n",
"}"
] | // Argument will return the value of the argument at the given index.
//
// If no such argument exists, undefined is returned. | [
"Argument",
"will",
"return",
"the",
"value",
"of",
"the",
"argument",
"at",
"the",
"given",
"index",
".",
"If",
"no",
"such",
"argument",
"exists",
"undefined",
"is",
"returned",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/type_function.go#L301-L303 | train |
robertkrimen/otto | otto_.go | valueToRangeIndex | func valueToRangeIndex(indexValue Value, length int64, negativeIsZero bool) int64 {
index := indexValue.number().int64
if negativeIsZero {
if index < 0 {
index = 0
}
// minimum(index, length)
if index >= length {
index = length
}
return index
}
if index < 0 {
index += length
if index < 0 {
index = 0
}
} else {
if index > length {
index = length
}
}
return index
} | go | func valueToRangeIndex(indexValue Value, length int64, negativeIsZero bool) int64 {
index := indexValue.number().int64
if negativeIsZero {
if index < 0 {
index = 0
}
// minimum(index, length)
if index >= length {
index = length
}
return index
}
if index < 0 {
index += length
if index < 0 {
index = 0
}
} else {
if index > length {
index = length
}
}
return index
} | [
"func",
"valueToRangeIndex",
"(",
"indexValue",
"Value",
",",
"length",
"int64",
",",
"negativeIsZero",
"bool",
")",
"int64",
"{",
"index",
":=",
"indexValue",
".",
"number",
"(",
")",
".",
"int64",
"\n",
"if",
"negativeIsZero",
"{",
"if",
"index",
"<",
"0",
"{",
"index",
"=",
"0",
"\n",
"}",
"\n",
"// minimum(index, length)",
"if",
"index",
">=",
"length",
"{",
"index",
"=",
"length",
"\n",
"}",
"\n",
"return",
"index",
"\n",
"}",
"\n\n",
"if",
"index",
"<",
"0",
"{",
"index",
"+=",
"length",
"\n",
"if",
"index",
"<",
"0",
"{",
"index",
"=",
"0",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"index",
">",
"length",
"{",
"index",
"=",
"length",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"index",
"\n",
"}"
] | // A range index can be anything from 0 up to length. It is NOT safe to use as an index
// to an array, but is useful for slicing and in some ECMA algorithms. | [
"A",
"range",
"index",
"can",
"be",
"anything",
"from",
"0",
"up",
"to",
"length",
".",
"It",
"is",
"NOT",
"safe",
"to",
"use",
"as",
"an",
"index",
"to",
"an",
"array",
"but",
"is",
"useful",
"for",
"slicing",
"and",
"in",
"some",
"ECMA",
"algorithms",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/otto_.go#L75-L99 | train |
robertkrimen/otto | parser/error.go | Error | func (self Error) Error() string {
filename := self.Position.Filename
if filename == "" {
filename = "(anonymous)"
}
return fmt.Sprintf("%s: Line %d:%d %s",
filename,
self.Position.Line,
self.Position.Column,
self.Message,
)
} | go | func (self Error) Error() string {
filename := self.Position.Filename
if filename == "" {
filename = "(anonymous)"
}
return fmt.Sprintf("%s: Line %d:%d %s",
filename,
self.Position.Line,
self.Position.Column,
self.Message,
)
} | [
"func",
"(",
"self",
"Error",
")",
"Error",
"(",
")",
"string",
"{",
"filename",
":=",
"self",
".",
"Position",
".",
"Filename",
"\n",
"if",
"filename",
"==",
"\"",
"\"",
"{",
"filename",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"filename",
",",
"self",
".",
"Position",
".",
"Line",
",",
"self",
".",
"Position",
".",
"Column",
",",
"self",
".",
"Message",
",",
")",
"\n",
"}"
] | // FIXME Should this be "SyntaxError"? | [
"FIXME",
"Should",
"this",
"be",
"SyntaxError",
"?"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/parser/error.go#L59-L70 | train |
robertkrimen/otto | parser/error.go | Add | func (self *ErrorList) Add(position file.Position, msg string) {
*self = append(*self, &Error{position, msg})
} | go | func (self *ErrorList) Add(position file.Position, msg string) {
*self = append(*self, &Error{position, msg})
} | [
"func",
"(",
"self",
"*",
"ErrorList",
")",
"Add",
"(",
"position",
"file",
".",
"Position",
",",
"msg",
"string",
")",
"{",
"*",
"self",
"=",
"append",
"(",
"*",
"self",
",",
"&",
"Error",
"{",
"position",
",",
"msg",
"}",
")",
"\n",
"}"
] | // Add adds an Error with given position and message to an ErrorList. | [
"Add",
"adds",
"an",
"Error",
"with",
"given",
"position",
"and",
"message",
"to",
"an",
"ErrorList",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/parser/error.go#L127-L129 | train |
robertkrimen/otto | object.go | getOwnProperty | func (self *_object) getOwnProperty(name string) *_property {
return self.objectClass.getOwnProperty(self, name)
} | go | func (self *_object) getOwnProperty(name string) *_property {
return self.objectClass.getOwnProperty(self, name)
} | [
"func",
"(",
"self",
"*",
"_object",
")",
"getOwnProperty",
"(",
"name",
"string",
")",
"*",
"_property",
"{",
"return",
"self",
".",
"objectClass",
".",
"getOwnProperty",
"(",
"self",
",",
"name",
")",
"\n",
"}"
] | // 8.12
// 8.12.1 | [
"8",
".",
"12",
"8",
".",
"12",
".",
"1"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/object.go#L31-L33 | train |
robertkrimen/otto | object.go | DefaultValue | func (self *_object) DefaultValue(hint _defaultValueHint) Value {
if hint == defaultValueNoHint {
if self.class == "Date" {
// Date exception
hint = defaultValueHintString
} else {
hint = defaultValueHintNumber
}
}
methodSequence := []string{"valueOf", "toString"}
if hint == defaultValueHintString {
methodSequence = []string{"toString", "valueOf"}
}
for _, methodName := range methodSequence {
method := self.get(methodName)
// FIXME This is redundant...
if method.isCallable() {
result := method._object().call(toValue_object(self), nil, false, nativeFrame)
if result.IsPrimitive() {
return result
}
}
}
panic(self.runtime.panicTypeError())
} | go | func (self *_object) DefaultValue(hint _defaultValueHint) Value {
if hint == defaultValueNoHint {
if self.class == "Date" {
// Date exception
hint = defaultValueHintString
} else {
hint = defaultValueHintNumber
}
}
methodSequence := []string{"valueOf", "toString"}
if hint == defaultValueHintString {
methodSequence = []string{"toString", "valueOf"}
}
for _, methodName := range methodSequence {
method := self.get(methodName)
// FIXME This is redundant...
if method.isCallable() {
result := method._object().call(toValue_object(self), nil, false, nativeFrame)
if result.IsPrimitive() {
return result
}
}
}
panic(self.runtime.panicTypeError())
} | [
"func",
"(",
"self",
"*",
"_object",
")",
"DefaultValue",
"(",
"hint",
"_defaultValueHint",
")",
"Value",
"{",
"if",
"hint",
"==",
"defaultValueNoHint",
"{",
"if",
"self",
".",
"class",
"==",
"\"",
"\"",
"{",
"// Date exception",
"hint",
"=",
"defaultValueHintString",
"\n",
"}",
"else",
"{",
"hint",
"=",
"defaultValueHintNumber",
"\n",
"}",
"\n",
"}",
"\n",
"methodSequence",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"if",
"hint",
"==",
"defaultValueHintString",
"{",
"methodSequence",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"methodName",
":=",
"range",
"methodSequence",
"{",
"method",
":=",
"self",
".",
"get",
"(",
"methodName",
")",
"\n",
"// FIXME This is redundant...",
"if",
"method",
".",
"isCallable",
"(",
")",
"{",
"result",
":=",
"method",
".",
"_object",
"(",
")",
".",
"call",
"(",
"toValue_object",
"(",
"self",
")",
",",
"nil",
",",
"false",
",",
"nativeFrame",
")",
"\n",
"if",
"result",
".",
"IsPrimitive",
"(",
")",
"{",
"return",
"result",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"panic",
"(",
"self",
".",
"runtime",
".",
"panicTypeError",
"(",
")",
")",
"\n",
"}"
] | // 8.12.8 | [
"8",
".",
"12",
".",
"8"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/object.go#L73-L98 | train |
robertkrimen/otto | terst/terst.go | decorate | func decorate(call _entry, s string) string {
file, line := call.File, call.Line
if call.PC > 0 {
// Truncate file name at last file name separator.
if index := strings.LastIndex(file, "/"); index >= 0 {
file = file[index+1:]
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
file = file[index+1:]
}
} else {
file = "???"
line = 1
}
buf := new(bytes.Buffer)
// Every line is indented at least one tab.
buf.WriteByte('\t')
fmt.Fprintf(buf, "%s:%d: ", file, line)
lines := strings.Split(s, "\n")
if l := len(lines); l > 1 && lines[l-1] == "" {
lines = lines[:l-1]
}
for i, line := range lines {
if i > 0 {
// Second and subsequent lines are indented an extra tab.
buf.WriteString("\n\t\t")
}
buf.WriteString(line)
}
buf.WriteByte('\n')
return buf.String()
} | go | func decorate(call _entry, s string) string {
file, line := call.File, call.Line
if call.PC > 0 {
// Truncate file name at last file name separator.
if index := strings.LastIndex(file, "/"); index >= 0 {
file = file[index+1:]
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
file = file[index+1:]
}
} else {
file = "???"
line = 1
}
buf := new(bytes.Buffer)
// Every line is indented at least one tab.
buf.WriteByte('\t')
fmt.Fprintf(buf, "%s:%d: ", file, line)
lines := strings.Split(s, "\n")
if l := len(lines); l > 1 && lines[l-1] == "" {
lines = lines[:l-1]
}
for i, line := range lines {
if i > 0 {
// Second and subsequent lines are indented an extra tab.
buf.WriteString("\n\t\t")
}
buf.WriteString(line)
}
buf.WriteByte('\n')
return buf.String()
} | [
"func",
"decorate",
"(",
"call",
"_entry",
",",
"s",
"string",
")",
"string",
"{",
"file",
",",
"line",
":=",
"call",
".",
"File",
",",
"call",
".",
"Line",
"\n",
"if",
"call",
".",
"PC",
">",
"0",
"{",
"// Truncate file name at last file name separator.",
"if",
"index",
":=",
"strings",
".",
"LastIndex",
"(",
"file",
",",
"\"",
"\"",
")",
";",
"index",
">=",
"0",
"{",
"file",
"=",
"file",
"[",
"index",
"+",
"1",
":",
"]",
"\n",
"}",
"else",
"if",
"index",
"=",
"strings",
".",
"LastIndex",
"(",
"file",
",",
"\"",
"\\\\",
"\"",
")",
";",
"index",
">=",
"0",
"{",
"file",
"=",
"file",
"[",
"index",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"}",
"else",
"{",
"file",
"=",
"\"",
"\"",
"\n",
"line",
"=",
"1",
"\n",
"}",
"\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"// Every line is indented at least one tab.",
"buf",
".",
"WriteByte",
"(",
"'\\t'",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"buf",
",",
"\"",
"\"",
",",
"file",
",",
"line",
")",
"\n",
"lines",
":=",
"strings",
".",
"Split",
"(",
"s",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"l",
":=",
"len",
"(",
"lines",
")",
";",
"l",
">",
"1",
"&&",
"lines",
"[",
"l",
"-",
"1",
"]",
"==",
"\"",
"\"",
"{",
"lines",
"=",
"lines",
"[",
":",
"l",
"-",
"1",
"]",
"\n",
"}",
"\n",
"for",
"i",
",",
"line",
":=",
"range",
"lines",
"{",
"if",
"i",
">",
"0",
"{",
"// Second and subsequent lines are indented an extra tab.",
"buf",
".",
"WriteString",
"(",
"\"",
"\\n",
"\\t",
"\\t",
"\"",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"line",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteByte",
"(",
"'\\n'",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // decorate prefixes the string with the file and line of the call site
// and inserts the final newline if needed and indentation tabs for formascing. | [
"decorate",
"prefixes",
"the",
"string",
"with",
"the",
"file",
"and",
"line",
"of",
"the",
"call",
"site",
"and",
"inserts",
"the",
"final",
"newline",
"if",
"needed",
"and",
"indentation",
"tabs",
"for",
"formascing",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L502-L533 | train |
robertkrimen/otto | terst/terst.go | Caller | func Caller() *Call {
scope, entry := findScope()
if scope == nil {
return nil
}
return &Call{
scope: scope,
entry: entry,
}
} | go | func Caller() *Call {
scope, entry := findScope()
if scope == nil {
return nil
}
return &Call{
scope: scope,
entry: entry,
}
} | [
"func",
"Caller",
"(",
")",
"*",
"Call",
"{",
"scope",
",",
"entry",
":=",
"findScope",
"(",
")",
"\n",
"if",
"scope",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"Call",
"{",
"scope",
":",
"scope",
",",
"entry",
":",
"entry",
",",
"}",
"\n",
"}"
] | // Caller will search the stack, looking for a Terst testing scope. If a scope
// is found, then Caller returns a Call for logging errors, accessing testing.T, etc.
// If no scope is found, Caller returns nil. | [
"Caller",
"will",
"search",
"the",
"stack",
"looking",
"for",
"a",
"Terst",
"testing",
"scope",
".",
"If",
"a",
"scope",
"is",
"found",
"then",
"Caller",
"returns",
"a",
"Call",
"for",
"logging",
"errors",
"accessing",
"testing",
".",
"T",
"etc",
".",
"If",
"no",
"scope",
"is",
"found",
"Caller",
"returns",
"nil",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L567-L576 | train |
robertkrimen/otto | terst/terst.go | Log | func (cl *Call) Log(arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
} | go | func (cl *Call) Log(arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
} | [
"func",
"(",
"cl",
"*",
"Call",
")",
"Log",
"(",
"arguments",
"...",
"interface",
"{",
"}",
")",
"{",
"cl",
".",
"scope",
".",
"log",
"(",
"cl",
".",
"entry",
",",
"fmt",
".",
"Sprintln",
"(",
"arguments",
"...",
")",
")",
"\n",
"}"
] | // Log is the terst version of `testing.T.Log` | [
"Log",
"is",
"the",
"terst",
"version",
"of",
"testing",
".",
"T",
".",
"Log"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L590-L592 | train |
robertkrimen/otto | terst/terst.go | Logf | func (cl *Call) Logf(format string, arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
} | go | func (cl *Call) Logf(format string, arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
} | [
"func",
"(",
"cl",
"*",
"Call",
")",
"Logf",
"(",
"format",
"string",
",",
"arguments",
"...",
"interface",
"{",
"}",
")",
"{",
"cl",
".",
"scope",
".",
"log",
"(",
"cl",
".",
"entry",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"arguments",
"...",
")",
")",
"\n",
"}"
] | // Logf is the terst version of `testing.T.Logf` | [
"Logf",
"is",
"the",
"terst",
"version",
"of",
"testing",
".",
"T",
".",
"Logf"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L595-L597 | train |
robertkrimen/otto | terst/terst.go | Error | func (cl *Call) Error(arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
cl.scope.t.Fail()
} | go | func (cl *Call) Error(arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
cl.scope.t.Fail()
} | [
"func",
"(",
"cl",
"*",
"Call",
")",
"Error",
"(",
"arguments",
"...",
"interface",
"{",
"}",
")",
"{",
"cl",
".",
"scope",
".",
"log",
"(",
"cl",
".",
"entry",
",",
"fmt",
".",
"Sprintln",
"(",
"arguments",
"...",
")",
")",
"\n",
"cl",
".",
"scope",
".",
"t",
".",
"Fail",
"(",
")",
"\n",
"}"
] | // Error is the terst version of `testing.T.Error` | [
"Error",
"is",
"the",
"terst",
"version",
"of",
"testing",
".",
"T",
".",
"Error"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L600-L603 | train |
robertkrimen/otto | terst/terst.go | Errorf | func (cl *Call) Errorf(format string, arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
cl.scope.t.Fail()
} | go | func (cl *Call) Errorf(format string, arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
cl.scope.t.Fail()
} | [
"func",
"(",
"cl",
"*",
"Call",
")",
"Errorf",
"(",
"format",
"string",
",",
"arguments",
"...",
"interface",
"{",
"}",
")",
"{",
"cl",
".",
"scope",
".",
"log",
"(",
"cl",
".",
"entry",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"arguments",
"...",
")",
")",
"\n",
"cl",
".",
"scope",
".",
"t",
".",
"Fail",
"(",
")",
"\n",
"}"
] | // Errorf is the terst version of `testing.T.Errorf` | [
"Errorf",
"is",
"the",
"terst",
"version",
"of",
"testing",
".",
"T",
".",
"Errorf"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L606-L609 | train |
robertkrimen/otto | terst/terst.go | Skip | func (cl *Call) Skip(arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
cl.scope.t.SkipNow()
} | go | func (cl *Call) Skip(arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
cl.scope.t.SkipNow()
} | [
"func",
"(",
"cl",
"*",
"Call",
")",
"Skip",
"(",
"arguments",
"...",
"interface",
"{",
"}",
")",
"{",
"cl",
".",
"scope",
".",
"log",
"(",
"cl",
".",
"entry",
",",
"fmt",
".",
"Sprintln",
"(",
"arguments",
"...",
")",
")",
"\n",
"cl",
".",
"scope",
".",
"t",
".",
"SkipNow",
"(",
")",
"\n",
"}"
] | // Skip is the terst version of `testing.T.Skip` | [
"Skip",
"is",
"the",
"terst",
"version",
"of",
"testing",
".",
"T",
".",
"Skip"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L612-L615 | train |
robertkrimen/otto | terst/terst.go | Skipf | func (cl *Call) Skipf(format string, arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
cl.scope.t.SkipNow()
} | go | func (cl *Call) Skipf(format string, arguments ...interface{}) {
cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
cl.scope.t.SkipNow()
} | [
"func",
"(",
"cl",
"*",
"Call",
")",
"Skipf",
"(",
"format",
"string",
",",
"arguments",
"...",
"interface",
"{",
"}",
")",
"{",
"cl",
".",
"scope",
".",
"log",
"(",
"cl",
".",
"entry",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"arguments",
"...",
")",
")",
"\n",
"cl",
".",
"scope",
".",
"t",
".",
"SkipNow",
"(",
")",
"\n",
"}"
] | // Skipf is the terst version of `testing.T.Skipf` | [
"Skipf",
"is",
"the",
"terst",
"version",
"of",
"testing",
".",
"T",
".",
"Skipf"
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/terst/terst.go#L618-L621 | train |
robertkrimen/otto | value.go | IsFunction | func (value Value) IsFunction() bool {
if value.kind != valueObject {
return false
}
return value.value.(*_object).class == "Function"
} | go | func (value Value) IsFunction() bool {
if value.kind != valueObject {
return false
}
return value.value.(*_object).class == "Function"
} | [
"func",
"(",
"value",
"Value",
")",
"IsFunction",
"(",
")",
"bool",
"{",
"if",
"value",
".",
"kind",
"!=",
"valueObject",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"value",
".",
"value",
".",
"(",
"*",
"_object",
")",
".",
"class",
"==",
"\"",
"\"",
"\n",
"}"
] | // IsFunction will return true if value is a function. | [
"IsFunction",
"will",
"return",
"true",
"if",
"value",
"is",
"a",
"function",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/value.go#L192-L197 | train |
robertkrimen/otto | value.go | String | func (value Value) String() string {
result := ""
catchPanic(func() {
result = value.string()
})
return result
} | go | func (value Value) String() string {
result := ""
catchPanic(func() {
result = value.string()
})
return result
} | [
"func",
"(",
"value",
"Value",
")",
"String",
"(",
")",
"string",
"{",
"result",
":=",
"\"",
"\"",
"\n",
"catchPanic",
"(",
"func",
"(",
")",
"{",
"result",
"=",
"value",
".",
"string",
"(",
")",
"\n",
"}",
")",
"\n",
"return",
"result",
"\n",
"}"
] | // String will return the value as a string.
//
// This method will make return the empty string if there is an error. | [
"String",
"will",
"return",
"the",
"value",
"as",
"a",
"string",
".",
"This",
"method",
"will",
"make",
"return",
"the",
"empty",
"string",
"if",
"there",
"is",
"an",
"error",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/value.go#L384-L390 | train |
robertkrimen/otto | value.go | Object | func (value Value) Object() *Object {
switch object := value.value.(type) {
case *_object:
return _newObject(object, value)
}
return nil
} | go | func (value Value) Object() *Object {
switch object := value.value.(type) {
case *_object:
return _newObject(object, value)
}
return nil
} | [
"func",
"(",
"value",
"Value",
")",
"Object",
"(",
")",
"*",
"Object",
"{",
"switch",
"object",
":=",
"value",
".",
"value",
".",
"(",
"type",
")",
"{",
"case",
"*",
"_object",
":",
"return",
"_newObject",
"(",
"object",
",",
"value",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Object will return the object of the value, or nil if value is not an object.
//
// This method will not do any implicit conversion. For example, calling this method on a string primitive value will not return a String object. | [
"Object",
"will",
"return",
"the",
"object",
"of",
"the",
"value",
"or",
"nil",
"if",
"value",
"is",
"not",
"an",
"object",
".",
"This",
"method",
"will",
"not",
"do",
"any",
"implicit",
"conversion",
".",
"For",
"example",
"calling",
"this",
"method",
"on",
"a",
"string",
"primitive",
"value",
"will",
"not",
"return",
"a",
"String",
"object",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/value.go#L474-L480 | train |
robertkrimen/otto | repl/repl.go | DebuggerHandler | func DebuggerHandler(vm *otto.Otto) {
i := atomic.AddUint32(&counter, 1)
// purposefully ignoring the error here - we can't do anything useful with
// it except panicking, and that'd be pretty rude. it'd be easy enough for a
// consumer to define an equivalent function that _does_ panic if desired.
_ = RunWithPrompt(vm, fmt.Sprintf("DEBUGGER[%d]> ", i))
} | go | func DebuggerHandler(vm *otto.Otto) {
i := atomic.AddUint32(&counter, 1)
// purposefully ignoring the error here - we can't do anything useful with
// it except panicking, and that'd be pretty rude. it'd be easy enough for a
// consumer to define an equivalent function that _does_ panic if desired.
_ = RunWithPrompt(vm, fmt.Sprintf("DEBUGGER[%d]> ", i))
} | [
"func",
"DebuggerHandler",
"(",
"vm",
"*",
"otto",
".",
"Otto",
")",
"{",
"i",
":=",
"atomic",
".",
"AddUint32",
"(",
"&",
"counter",
",",
"1",
")",
"\n\n",
"// purposefully ignoring the error here - we can't do anything useful with",
"// it except panicking, and that'd be pretty rude. it'd be easy enough for a",
"// consumer to define an equivalent function that _does_ panic if desired.",
"_",
"=",
"RunWithPrompt",
"(",
"vm",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
")",
"\n",
"}"
] | // DebuggerHandler implements otto's debugger handler signature, providing a
// simple drop-in debugger implementation. | [
"DebuggerHandler",
"implements",
"otto",
"s",
"debugger",
"handler",
"signature",
"providing",
"a",
"simple",
"drop",
"-",
"in",
"debugger",
"implementation",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/repl/repl.go#L18-L25 | train |
robertkrimen/otto | repl/repl.go | RunWithPrompt | func RunWithPrompt(vm *otto.Otto, prompt string) error {
return RunWithOptions(vm, Options{
Prompt: prompt,
})
} | go | func RunWithPrompt(vm *otto.Otto, prompt string) error {
return RunWithOptions(vm, Options{
Prompt: prompt,
})
} | [
"func",
"RunWithPrompt",
"(",
"vm",
"*",
"otto",
".",
"Otto",
",",
"prompt",
"string",
")",
"error",
"{",
"return",
"RunWithOptions",
"(",
"vm",
",",
"Options",
"{",
"Prompt",
":",
"prompt",
",",
"}",
")",
"\n",
"}"
] | // RunWithPrompt runs a REPL with the given prompt and no prelude. | [
"RunWithPrompt",
"runs",
"a",
"REPL",
"with",
"the",
"given",
"prompt",
"and",
"no",
"prelude",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/repl/repl.go#L33-L37 | train |
robertkrimen/otto | repl/repl.go | RunWithPrelude | func RunWithPrelude(vm *otto.Otto, prelude string) error {
return RunWithOptions(vm, Options{
Prelude: prelude,
})
} | go | func RunWithPrelude(vm *otto.Otto, prelude string) error {
return RunWithOptions(vm, Options{
Prelude: prelude,
})
} | [
"func",
"RunWithPrelude",
"(",
"vm",
"*",
"otto",
".",
"Otto",
",",
"prelude",
"string",
")",
"error",
"{",
"return",
"RunWithOptions",
"(",
"vm",
",",
"Options",
"{",
"Prelude",
":",
"prelude",
",",
"}",
")",
"\n",
"}"
] | // RunWithPrelude runs a REPL with the default prompt and the given prelude. | [
"RunWithPrelude",
"runs",
"a",
"REPL",
"with",
"the",
"default",
"prompt",
"and",
"the",
"given",
"prelude",
"."
] | 15f95af6e78dcd2030d8195a138bd88d4f403546 | https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/repl/repl.go#L40-L44 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.