// TODO(sbarzowski) this function takes far too many arguments - build interpreter in vm instead
359413
func evaluate(node ast.Node, ext vmExtMap, tla vmExtMap, nativeFuncs map[string]*NativeFunction,
	maxStack int, importer Importer, stringOutputMode bool) (string, error) {

	i, err := buildInterpreter(ext, nativeFuncs, maxStack, importer)
	if err != nil {
		return "", err
	}

	result, manifestationTrace, err := evaluateAux(i, node, tla)
	if err != nil {
		return "", err
	}

	var buf bytes.Buffer
	if stringOutputMode {
		err = i.manifestString(&buf, manifestationTrace, result)
	} else {
		err = i.manifestAndSerializeJSON(&buf, manifestationTrace, result, true, "")
	}
	if err != nil {
		return "", err
	}
	buf.WriteString("\n")
	return buf.String(), nil
}
150192
func MakeVM() *VM {
	return &VM{
		MaxStack:       500,
		ext:            make(vmExtMap),
		tla:            make(vmExtMap),
		nativeFuncs:    make(map[string]*NativeFunction),
		ErrorFormatter: &termErrorFormatter{pretty: false, maxStackTraceSize: 20},
		importer:       &FileImporter{},
	}
}
493705
func main() {
	app := cli.NewApp()
	app.Name = "puppeth"
	app.Usage = "assemble and maintain private Ethereum networks"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "network",
			Usage: "name of the network to administer (no spaces or hyphens, please)",
		},
		cli.IntFlag{
			Name:  "loglevel",
			Value: 3,
			Usage: "log level to emit to the screen",
		},
	}
	app.Before = func(c *cli.Context) error {
		// Set up the logger to print everything and the random generator
		log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(c.Int("loglevel")), log.StreamHandler(os.Stdout, log.TerminalFormat(true))))
		rand.Seed(time.Now().UnixNano())

		return nil
	}
	app.Action = runWizard
	app.Run(os.Args)
}
450598
func (intr *Interpreter) execBuiltin() *starlark.Builtin {
	return starlark.NewBuiltin("exec", func(th *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
		var module starlark.String
		if err := starlark.UnpackArgs("exec", args, kwargs, "module", &module); err != nil {
			return nil, err
		}
		mod := module.GoString()

		// Only threads started via 'exec' (or equivalently ExecModule) can exec
		// other scripts. Modules that are loaded via load(...), or custom callbacks
		// from native code aren't allowed to call exec, since exec's impurity may
		// lead to unexpected results.
		if GetThreadKind(th) != ThreadExecing {
			return nil, fmt.Errorf("exec %s: forbidden in this context, only exec'ed scripts can exec other scripts", mod)
		}

		// See also th.Load in runModule.
		key, err := makeModuleKey(mod, th)
		if err != nil {
			return nil, err
		}
		dict, err := intr.ExecModule(Context(th), key.pkg, key.path)
		if err != nil {
			// Starlark stringifies errors using Error(). For EvalError, Error()
			// string is just a root cause, it does not include the backtrace where
			// the execution failed. Preserve it explicitly by sticking the backtrace
			// into the error message.
			//
			// Note that returning 'err' as is will preserve the backtrace inside
			// the execed module, but we'll lose the backtrace of the 'exec' call
			// itself, since EvalError object will just bubble to the top of the Go
			// call stack unmodified.
			if evalErr, ok := err.(*starlark.EvalError); ok {
				return nil, fmt.Errorf("exec %s failed: %s", mod, evalErr.Backtrace())
			}
			return nil, fmt.Errorf("cannot exec %s: %s", mod, err)
		}

		return starlarkstruct.FromStringDict(starlark.String("execed"), dict), nil
	})
}
1004563
func evalBuildline(buildline string) (int64, error) {
	matches := buildlineRE.FindStringSubmatch(buildline)

	// +1 to make it more obvious that the whole string containing the info is also returned as matches[0].
	if len(matches) < 1+1 {
		return 0, fmt.Errorf("too few matches found in buildline: %s", buildline)
	}

	if len(matches) > 1+1 {
		return 0, fmt.Errorf("too many matches found in buildline: %s", buildline)
	}

	syncedSize, err := strconv.ParseInt(matches[1], 10, 64)

	if err != nil {
		return 0, fmt.Errorf("%s in buildline: %s", err, buildline)
	}

	return syncedSize, nil
}
363627
func (vm *VM) NativeFunction(f *NativeFunction) {
	vm.nativeFuncs[f.Name] = f
}
1290644
func (env *Zlisp) FunctionCallNameTypeCheck(f *SexpFunction, nargs *int) error {
	if f.inputTypes != nil {
		Q("FunctionCallNameTypeCheck sees inputTypes: '%v'", f.inputTypes.SexpString(nil))
	} else {
		return nil // no type checking requested
	}
	if f.varargs {
		return nil // name/type checking for vargarg not currently implemented.
	}

	// our call arguments prepared -- will be pushed to the datastack
	finalArgs := make([]Sexp, f.inputTypes.NumKeys)

	// pop everything off the stack, will push finalArgs later
	exprs, err := env.datastack.PopExpressions(*nargs)
	if err != nil {
		return err
	}

	// map the named submitted args, for fast lookup by name
	submittedByName := make(map[string]Sexp)

	// prep submittedByName
	for i := 0; i < *nargs; i++ {
		switch sym := exprs[i].(type) {
		case *SexpSymbol:
			if sym.colonTail {
				Q("in env.CallFunction, have symbol.colonTail: exprs[%v]='%#v'", i, sym)
				typ, err := f.inputTypes.HashGet(env, sym)
				if err != nil {
					return fmt.Errorf("%s takes no argument '%s'", f.name, sym.name)
				}
				if i == (*nargs)-1 {
					return fmt.Errorf("named parameter '%s' not followed by value", sym.name)
				}
				val := exprs[i+1]
				i++
				_, already := submittedByName[sym.name]
				if already {
					return fmt.Errorf("duplicate named parameter '%s'", sym.name)
				}

				submittedByName[sym.name] = val
				valtyp := val.Type()
				if typ != nil && typ != valtyp {
					return fmt.Errorf("type mismatch for parameter '%s': expected '%s', got '%s'",
						sym.name, typ.SexpString(nil), valtyp.SexpString(nil))
				}
			} else {
				Q("in env.CallFunction, exprs[%v]='%v'/type=%T", i, exprs[i].SexpString(nil), exprs[i])
			}
		default:
			Q("in env.CallFunction, exprs[%v]='%v'/type=%T", i, exprs[i].SexpString(nil), exprs[i])
		}
	}

	// simplify name matching for now with this rule: all by name, or none.
	haveByName := len(submittedByName)
	if haveByName > 0 {
		if haveByName != f.inputTypes.NumKeys {
			return fmt.Errorf("named arguments count %v != expected %v", haveByName, f.inputTypes.NumKeys)
		}

		// prep finalArgs in the order dictated
		for i, key := range f.inputTypes.KeyOrder {
			switch sy := key.(type) {
			case *SexpSymbol:
				// search for sy.name in our submittedByName args
				a, found := submittedByName[sy.name]
				if found {
					Q("%s call: matching %v-th argument named '%s': passing value '%s'",
						f.name, i, sy.name, a.SexpString(nil))
					finalArgs[i] = a
				}
			default:
				return fmt.Errorf("unsupported argument-name type %T", key)
			}

		}
	} else {
		// not using named parameters, restore the arguments to the stack as they were.
		finalArgs = exprs
	}
	*nargs = len(finalArgs)
	return env.datastack.PushExpressions(finalArgs)
}
47633
func Convert_v1_BuildSource_To_build_BuildSource(in *v1.BuildSource, out *build.BuildSource, s conversion.Scope) error {
	return autoConvert_v1_BuildSource_To_build_BuildSource(in, out, s)
}
1073740
func main() {
	cmd.RootCmd.DisableAutoGenTag = true
	identity := func(s string) string {
		return fmt.Sprintf(`{{< relref "docs/%s" >}}`, s)
	}
	emptyStr := func(s string) string { return "" }
	doc.GenMarkdownTreeCustom(cmd.RootCmd, "./", emptyStr, identity)
}
30202
func main() {
	args := os.Args

	assocData := bytes.Repeat([]byte{'B'}, 32)

	if len(args) == 1 {
		fmt.Printf("Usage: %s (generate|decode) <private-keys>\n", args[0])
	} else if args[1] == "generate" {
		var path sphinx.PaymentPath
		for i, hexKey := range args[2:] {
			binKey, err := hex.DecodeString(hexKey)
			if err != nil || len(binKey) != 33 {
				log.Fatalf("%s is not a valid hex pubkey %s", hexKey, err)
			}

			pubkey, err := btcec.ParsePubKey(binKey, btcec.S256())
			if err != nil {
				panic(err)
			}

			path[i] = sphinx.OnionHop{
				NodePub: *pubkey,
				HopData: sphinx.HopData{
					Realm:         [1]byte{0x00},
					ForwardAmount: uint64(i),
					OutgoingCltv:  uint32(i),
				},
			}
			copy(path[i].HopData.NextAddress[:], bytes.Repeat([]byte{byte(i)}, 8))

			fmt.Fprintf(os.Stderr, "Node %d pubkey %x\n", i, pubkey.SerializeCompressed())
		}

		sessionKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), bytes.Repeat([]byte{'A'}, 32))

		msg, err := sphinx.NewOnionPacket(&path, sessionKey, assocData)
		if err != nil {
			log.Fatalf("Error creating message: %v", err)
		}

		w := bytes.NewBuffer([]byte{})
		err = msg.Encode(w)

		if err != nil {
			log.Fatalf("Error serializing message: %v", err)
		}

		fmt.Printf("%x\n", w.Bytes())
	} else if args[1] == "decode" {
		binKey, err := hex.DecodeString(args[2])
		if len(binKey) != 32 || err != nil {
			log.Fatalf("Argument not a valid hex private key")
		}

		hexBytes, _ := ioutil.ReadAll(os.Stdin)
		binMsg, err := hex.DecodeString(strings.TrimSpace(string(hexBytes)))
		if err != nil {
			log.Fatalf("Error decoding message: %s", err)
		}

		privkey, _ := btcec.PrivKeyFromBytes(btcec.S256(), binKey)
		s := sphinx.NewRouter(privkey, &chaincfg.TestNet3Params,
			sphinx.NewMemoryReplayLog())

		var packet sphinx.OnionPacket
		err = packet.Decode(bytes.NewBuffer(binMsg))

		if err != nil {
			log.Fatalf("Error parsing message: %v", err)
		}
		p, err := s.ProcessOnionPacket(&packet, assocData, 10)
		if err != nil {
			log.Fatalf("Failed to decode message: %s", err)
		}

		w := bytes.NewBuffer([]byte{})
		err = p.NextPacket.Encode(w)

		if err != nil {
			log.Fatalf("Error serializing message: %v", err)
		}
		fmt.Printf("%x\n", w.Bytes())
	}
}
607458
func main() {
	// env represents one interpreter:
	// It will have one parsing and one execution goroutine.
	env = NewGlisp()

	// cfg configures the env
	cfg := &GlsipConfig{
		// some of the options:
		ExitOnFailure: false, // action to take on error
		Sandboxed:     false, // restrict scripts to sandobox?
		Quiet:         false, // display startup banner?
		Trace:         false, // for debugging, print actions step-by-step
	}

	// start a repl
	Repl(env, cfg)
}
955766
func (r *resp) buildArgumentsPart(args []interface{}) []byte {
	buildValuesPart := func(vs valuer) []byte {
		tmp := []byte{}
		for _, value := range vs.Values() {
			tmp = append(tmp, r.buildValuePart(value)...)
		}
		return tmp
	}
	buildHashPart := func(h Hash) []byte {
		tmp := []byte{}
		for key, value := range h {
			tmp = append(tmp, r.buildValuePart(key)...)
			tmp = append(tmp, r.buildValuePart(value)...)
		}
		return tmp
	}
	tmp := []byte{}
	part := []byte{}
	for _, arg := range args {
		switch typedArg := arg.(type) {
		case valuer:
			part = buildValuesPart(typedArg)
		case Hash:
			part = buildHashPart(typedArg)
		case Hashable:
			part = buildHashPart(typedArg.GetHash())
		default:
			part = r.buildValuePart(arg)
		}
		tmp = append(tmp, part...)
	}
	return tmp
}
50921
func interpolationFuncSlice() ast.Function {
	return ast.Function{
		ArgTypes: []ast.Type{
			ast.TypeList, // inputList
			ast.TypeInt,  // from
			ast.TypeInt,  // to
		},
		ReturnType: ast.TypeList,
		Variadic:   false,
		Callback: func(args []interface{}) (interface{}, error) {
			inputList := args[0].([]ast.Variable)
			from := args[1].(int)
			to := args[2].(int)

			if from < 0 {
				return nil, fmt.Errorf("from index must be >= 0")
			}
			if to > len(inputList) {
				return nil, fmt.Errorf("to index must be <= length of the input list")
			}
			if from > to {
				return nil, fmt.Errorf("from index must be <= to index")
			}

			var outputList []ast.Variable
			for i, val := range inputList {
				if i >= from && i < to {
					outputList = append(outputList, val)
				}
			}
			return outputList, nil
		},
	}
}
1030925
func main() {
	flag.Parse()
	if len(flag.Args()) == 0 {
		panic(fmt.Errorf("arch is required"))
	}

	for _, arch := range flag.Args() {
		wd, err := os.Getwd()
		if err != nil {
			panic(err)
		}
		f, err := os.Open(filepath.Join(wd, arch))
		if err != nil {
			panic(err)
		}
		defer f.Close()
		buf := &bytes.Buffer{}

		gz, err := gzip.NewWriterLevel(newHexStringWriter(buf), gzip.BestCompression)
		if err != nil {
			panic(err)
		}
		if _, err = io.Copy(gz, f); err != nil {
			panic(err)
		}
		if err := gz.Close(); err != nil {
			panic(err)
		}

		fn := filepath.Join(wd, arch+"_binary.go")
		dest, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			panic(err)
		}
		if err := tmpl.Execute(dest, struct{ Arch, Package, Data string }{Arch: arch, Package: "binfmt_misc", Data: buf.String()}); err != nil {
			panic(err)
		}
		dest.Close()
	}

}
113613
func runtimeArchitecture() (string, error) {
	cmd := exec.Command("/usr/bin/uname", "-m")
	machine, err := cmd.Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(machine)), nil
}
466200
func main() {
	env, err := plugins.NewEnvironment()
	env.RespondAndExitIfError(err)

	var stats *statistics.DocumentStatistics

	for _, model := range env.Request.Models {
		switch model.TypeUrl {
		case "openapi.v2.Document":
			documentv2 := &openapiv2.Document{}
			err = proto.Unmarshal(model.Value, documentv2)
			if err == nil {
				// Analyze the API document.
				stats = statistics.NewDocumentStatistics(env.Request.SourceName, documentv2)
			}
		case "openapi.v3.Document":
			documentv3 := &openapiv3.Document{}
			err = proto.Unmarshal(model.Value, documentv3)
			if err == nil {
				// Analyze the API document.
				stats = statistics.NewDocumentStatisticsV3(env.Request.SourceName, documentv3)
			}
		}
	}

	if stats != nil {
		// Return the analysis results with an appropriate filename.
		// Results are in files named "summary.json" in the same relative
		// locations as the description source files.
		file := &plugins.File{}
		file.Name = strings.Replace(stats.Name, path.Base(stats.Name), "summary.json", -1)
		file.Data, err = json.MarshalIndent(stats, "", "  ")
		file.Data = append(file.Data, []byte("\n")...)
		env.RespondAndExitIfError(err)
		env.Response.Files = append(env.Response.Files, file)
	}

	env.RespondAndExit()
}
1206165
func (f InterpreterFunc) Execute(s string, ctx *Context) (interface{}, error) {
	return f(s, ctx)
}