Ejemplo n.º 1
0
Archivo: main.go Proyecto: 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)
}
Ejemplo n.º 2
0
// MemHome coverts the snapshot into a mem home for building
func (s *Snapshot) MemHome() *builds.MemHome {
	home := pl.MakeMemHome(pl.Lang(false))
	for pkg, files := range s.Pkgs {
		// TODO: should not use main as package name here.
		pkgName := strings.TrimPrefix(pkg, "/")
		if pkgName == "" {
			pkgName = "main"
		}

		var fileNames []string
		if strings.HasPrefix(pkgName, "asm/") || pkgName == "asm" {
			for f := range files {
				if strings.HasSuffix(f, ".s") {
					fileNames = append(fileNames, f)
				}
			}
		} else {
			for f := range files {
				if strings.HasSuffix(f, ".g") {
					fileNames = append(fileNames, f)
				}
			}
		}

		if len(fileNames) > 0 {
			p := home.NewPkg(pkgName)
			for _, f := range fileNames {
				bs := files[f]
				fpath := path.Join(pkg, f)
				p.AddFile(fpath, f, string(bs))
			}
		}
	}

	return home
}