Example #1
0
File: main.go Project: e8vm/shanhu
// Build builds a set of packages.
func Build(
	input string, pkgs []string, runTests bool, logln func(s string),
) string {
	s := new(fs.Snapshot)
	if err := json.Unmarshal([]byte(input), s); err != nil {
		return jsonStr(&result{FatalErr: err.Error()})
	}

	opt := &builds.Options{
		LogLine:    logln,
		RunTests:   runTests,
		TestCycles: 1e6,
		Verbose:    true,
	}
	img, errs := s.Build(pkgs, opt)
	if errs != nil {
		return jsonStr(&result{Errs: makeResErrors(errs)})
	}

	if img == nil {
		return jsonStr(&result{NoRun: true})
	}

	outBuf := new(bytes.Buffer)
	m := arch.NewMachine(&arch.Config{
		Output: outBuf,
	})
	if err := m.LoadImage(bytes.NewReader(img)); err != nil {
		return jsonStr(newErrorRes(err))
	}

	const ncycle = 1e6
	ret, exp := m.Run(ncycle)

	res := &result{
		Output: outBuf.String(),
		Ncycle: ret,
	}
	if exp != nil {
		stackTrace := new(bytes.Buffer)
		if !arch.IsHalt(exp) {
			arch.FprintStack(stackTrace, m, exp)
		}

		res.ExcepCore = exp.Core
		res.ExcepCode = exp.Code
		res.ExcepMsg = exp.Error()
		res.StackTrace = stackTrace.String()
	}

	return jsonStr(res)
}
Example #2
0
File: main.go Project: e8vm/shanhu
// Compile compiles and runs the code and returns the output of running
// in a json string.
func Compile(file, code string) string {
	home := pl.MakeMemHome(pl.Lang(false))
	const pkgName = "toys"
	pkg := home.NewPkg(pkgName)
	pkg.AddFile("toys/"+file, file, code)

	b := builds.NewBuilder(home, home)
	b.RunTests = true
	b.TestCycles = 1000000

	if errs := b.BuildAll(); errs != nil {
		res := &result{Errs: makeResErrors(errs)}
		return jsonStr(res)
	}

	image := home.BinBytes(pkgName)
	if image == nil {
		err := errors.New("missing main() function")
		return jsonStr(newErrorRes(err))
	}

	outBuf := new(bytes.Buffer)
	m := arch.NewMachine(&arch.Config{
		Output: outBuf,
	})
	if err := m.LoadImage(bytes.NewReader(image)); err != nil {
		return jsonStr(newErrorRes(err))
	}

	res := new(result)
	ret, exp := m.Run(1000000)
	res.Output = outBuf.String()
	res.Ncycle = ret
	if exp != nil {
		res.ExcepCore = exp.Core
		res.ExcepCode = exp.Code
		res.ExcepMsg = exp.Error()
	}

	return jsonStr(res)
}