本文整理汇总了Golang中github.com/gopherjs/gopherjs/compiler.Compile函数的典型用法代码示例。如果您正苦于以下问题:Golang Compile函数的具体用法?Golang Compile怎么用?Golang Compile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Compile函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Build
// Build creates a build and returns the first error happening. All errors are typed.
func (b *builder) Build() error {
if b.target == nil {
return ErrorMissingTarget{}
}
fileSet := token.NewFileSet()
files := []*ast.File{}
for name, reader := range b.files {
if reader == nil {
return ErrorParsing{name, "reader must not be nil"}
}
f, err := parser.ParseFile(fileSet, name, reader, 0)
if err != nil {
return ErrorParsing{name, err.Error()}
}
files = append(files, f)
}
s := build.NewSession(b.options)
archive, err := compiler.Compile(b.pkgName, files, fileSet, s.ImportContext, b.options.Minify)
if err != nil {
return ErrorCompiling(err.Error())
}
deps, err := compiler.ImportDependencies(archive, s.ImportContext.Import)
if err != nil {
return ErrorImportingDependencies(err.Error())
}
return compiler.WriteProgramCode(deps, &compiler.SourceMapFilter{Writer: b.target})
}
开发者ID:rexposadas,项目名称:gx,代码行数:34,代码来源:gopherjslib.go
示例2: Compile
func Compile(ctx context.Context, source []byte, mapping bool) ([]byte, error) {
vos := vosctx.FromContext(ctx)
options := &build.Options{
GOROOT: vos.Getenv("GOROOT"),
GOPATH: vos.Getenv("GOPATH"),
CreateMapFile: mapping,
}
s := build.NewSession(options)
packages := make(map[string]*compiler.Archive)
importContext := &compiler.ImportContext{
Packages: s.Types,
Import: s.BuildImportPath,
}
fileSet := token.NewFileSet()
file, err := parser.ParseFile(fileSet, "prog.go", source, parser.ParseComments)
if err != nil {
return nil, kerr.Wrap("NCYFEKGCWX", err)
}
mainPkg, err := compiler.Compile("main", []*ast.File{file}, fileSet, importContext, false)
if err != nil {
return nil, kerr.Wrap("KPHUKOLTBX", err)
}
packages["main"] = mainPkg
bufCode := bytes.NewBuffer(nil)
filter := &compiler.SourceMapFilter{Writer: bufCode}
allPkgs, err := compiler.ImportDependencies(mainPkg, importContext.Import)
if err != nil {
return nil, kerr.Wrap("TIMQHFQTWL", err)
}
if mapping {
bufMap := bytes.NewBuffer(nil)
smap := &sourcemap.Map{File: "script.js"}
filter.MappingCallback = build.NewMappingCallback(smap, options.GOROOT, options.GOPATH, false)
if err := compiler.WriteProgramCode(allPkgs, filter); err != nil {
return nil, kerr.Wrap("YKQEKRKBPL", err)
}
if err := smap.WriteTo(bufMap); err != nil {
return nil, kerr.Wrap("VYQGYAAADG", err)
}
return bufMap.Bytes(), nil
}
if err := compiler.WriteProgramCode(allPkgs, filter); err != nil {
return nil, kerr.Wrap("DPPVHCOTBQ", err)
}
if _, err := bufCode.WriteString("//# sourceMappingURL=script.js.map\n"); err != nil {
return nil, kerr.Wrap("CXXKWQVGUI", err)
}
return bufCode.Bytes(), nil
}
开发者ID:kego,项目名称:ke,代码行数:57,代码来源:compiler.go
示例3: main
//.........这里部分代码省略.........
}
tempfile, err := ioutil.TempFile(currentDirectory, filepath.Base(args[0])+".")
if err != nil && strings.HasPrefix(currentDirectory, runtime.GOROOT()) {
tempfile, err = ioutil.TempFile("", filepath.Base(args[0])+".")
}
if err != nil {
return err
}
defer func() {
tempfile.Close()
os.Remove(tempfile.Name())
os.Remove(tempfile.Name() + ".map")
}()
s := gbuild.NewSession(options)
if err := s.BuildFiles(args[:lastSourceArg], tempfile.Name(), currentDirectory); err != nil {
return err
}
if err := runNode(tempfile.Name(), args[lastSourceArg:], "", options.Quiet); err != nil {
return err
}
return nil
}, options, nil))
}
cmdTest := &cobra.Command{
Use: "test [packages]",
Short: "test packages",
}
bench := cmdTest.Flags().String("bench", "", "Run benchmarks matching the regular expression. By default, no benchmarks run. To run all benchmarks, use '--bench=.'.")
run := cmdTest.Flags().String("run", "", "Run only those tests and examples matching the regular expression.")
short := cmdTest.Flags().Bool("short", false, "Tell long-running tests to shorten their run time.")
verbose := cmdTest.Flags().BoolP("verbose", "v", false, "Log all tests as they are run. Also print all text from Log and Logf calls even if the test succeeds.")
compileOnly := cmdTest.Flags().BoolP("compileonly", "c", false, "Compile the test binary to pkg.test.js but do not run it (where pkg is the last element of the package's import path). The file name can be changed with the -o flag.")
outputFilename := cmdTest.Flags().StringP("output", "o", "", "Compile the test binary to the named file. The test still runs (unless -c is specified).")
cmdTest.Flags().AddFlag(flagMinify)
cmdTest.Flags().AddFlag(flagColor)
cmdTest.Run = func(cmd *cobra.Command, args []string) {
os.Exit(handleError(func() error {
pkgs := make([]*gbuild.PackageData, len(args))
for i, pkgPath := range args {
pkgPath = filepath.ToSlash(pkgPath)
var err error
pkgs[i], err = gbuild.Import(pkgPath, 0, "", nil)
if err != nil {
return err
}
}
if len(pkgs) == 0 {
firstGopathWorkspace := filepath.SplitList(build.Default.GOPATH)[0]
srcDir, err := filepath.EvalSymlinks(filepath.Join(firstGopathWorkspace, "src"))
if err != nil {
return err
}
var pkg *gbuild.PackageData
if strings.HasPrefix(currentDirectory, srcDir) {
pkgPath, err := filepath.Rel(srcDir, currentDirectory)
if err != nil {
return err
}
if pkg, err = gbuild.Import(pkgPath, 0, "", nil); err != nil {
return err
}
}
if pkg == nil {
if pkg, err = gbuild.ImportDir(currentDirectory, 0); err != nil {
开发者ID:pombredanne,项目名称:camlistore,代码行数:67,代码来源:tool.go
示例4: BuildPackage
func (s *Session) BuildPackage(pkg *PackageData) error {
s.Packages[pkg.ImportPath] = pkg
if pkg.ImportPath == "unsafe" {
return nil
}
if pkg.PkgObj != "" {
var fileInfo os.FileInfo
gopherjsBinary, err := osext.Executable()
if err == nil {
fileInfo, err = os.Stat(gopherjsBinary)
if err == nil {
pkg.SrcModTime = fileInfo.ModTime()
}
}
if err != nil {
os.Stderr.WriteString("Could not get GopherJS binary's modification timestamp. Please report issue.\n")
pkg.SrcModTime = time.Now()
}
for _, importedPkgPath := range pkg.Imports {
ignored := true
for _, pos := range pkg.ImportPos[importedPkgPath] {
importFile := filepath.Base(pos.Filename)
for _, file := range pkg.GoFiles {
if importFile == file {
ignored = false
break
}
}
if !ignored {
break
}
}
if importedPkgPath == "unsafe" || ignored {
continue
}
_, err := s.BuildImportPath(importedPkgPath)
if err != nil {
return err
}
impModeTime := s.Packages[importedPkgPath].SrcModTime
if impModeTime.After(pkg.SrcModTime) {
pkg.SrcModTime = impModeTime
}
}
for _, name := range append(pkg.GoFiles, pkg.JSFiles...) {
fileInfo, err := os.Stat(filepath.Join(pkg.Dir, name))
if err != nil {
return err
}
if fileInfo.ModTime().After(pkg.SrcModTime) {
pkg.SrcModTime = fileInfo.ModTime()
}
}
pkgObjFileInfo, err := os.Stat(pkg.PkgObj)
if err == nil && !pkg.SrcModTime.After(pkgObjFileInfo.ModTime()) {
// package object is up to date, load from disk if library
pkg.UpToDate = true
if pkg.IsCommand() {
return nil
}
objFile, err := os.Open(pkg.PkgObj)
if err != nil {
return err
}
defer objFile.Close()
pkg.Archive, err = compiler.ReadArchive(pkg.PkgObj, pkg.ImportPath, objFile, s.Types)
if err != nil {
return err
}
return nil
}
}
fileSet := token.NewFileSet()
files, err := parse(pkg.Package, pkg.IsTest, fileSet)
if err != nil {
return err
}
importContext := &compiler.ImportContext{
Packages: s.Types,
Import: func(path string) (*compiler.Archive, error) {
return s.buildImportPathWithSrcDir(path, pkg.Dir)
},
}
pkg.Archive, err = compiler.Compile(pkg.ImportPath, files, fileSet, importContext, s.options.Minify)
if err != nil {
return err
}
for _, jsFile := range pkg.JSFiles {
code, err := ioutil.ReadFile(filepath.Join(pkg.Dir, jsFile))
if err != nil {
//.........这里部分代码省略.........
开发者ID:flying99999,项目名称:gopherjs,代码行数:101,代码来源:build.go
示例5: main
//.........这里部分代码省略.........
}
tests.NeedTest = collectTests(pkg, "_test")
if len(pkg.XTestGoFiles) != 0 {
testPkg := &gbuild.PackageData{Package: &build.Package{
ImportPath: pkg.ImportPath + "_test",
Dir: pkg.Dir,
GoFiles: pkg.XTestGoFiles,
}}
if err := s.BuildPackage(testPkg); err != nil {
return err
}
tests.NeedXtest = collectTests(testPkg, "_xtest")
}
buf := bytes.NewBuffer(nil)
err := testmainTmpl.Execute(buf, tests)
if err != nil {
return err
}
fset := token.NewFileSet()
mainFile, err := parser.ParseFile(fset, "_testmain.go", buf, 0)
if err != nil {
return err
}
mainPkg := &gbuild.PackageData{
Package: &build.Package{
Name: "main",
ImportPath: "main",
},
}
mainPkg.Archive, err = compiler.Compile("main", []*ast.File{mainFile}, fset, s.ImportContext, options.Minify)
if err != nil {
return err
}
tempfile, err := ioutil.TempFile("", "test.")
if err != nil {
return err
}
defer func() {
tempfile.Close()
os.Remove(tempfile.Name())
}()
if err := s.WriteCommandPackage(mainPkg, tempfile.Name()); err != nil {
return err
}
var args []string
if *verbose {
args = append(args, "-test.v")
}
if *short {
args = append(args, "-test.short")
}
status := "ok "
start := time.Now()
if err := runNode(tempfile.Name(), args, buildPkg.Dir); err != nil {
if _, ok := err.(*exec.ExitError); !ok {
return err
}
exitErr = err
status = "FAIL"
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:67,代码来源:tool.go
示例6: main
//.........这里部分代码省略.........
Dir: pkg.Dir,
GoFiles: append(pkg.GoFiles, pkg.TestGoFiles...),
Imports: append(pkg.Imports, pkg.TestImports...),
}, "_test", &tests.NeedTest); err != nil {
return err
}
if err := collectTests(&build.Package{
ImportPath: pkg.ImportPath + "_test",
Dir: pkg.Dir,
GoFiles: pkg.XTestGoFiles,
Imports: pkg.XTestImports,
}, "_xtest", &tests.NeedXtest); err != nil {
return err
}
buf := bytes.NewBuffer(nil)
if err := testmainTmpl.Execute(buf, tests); err != nil {
return err
}
fset := token.NewFileSet()
mainFile, err := parser.ParseFile(fset, "_testmain.go", buf, 0)
if err != nil {
return err
}
mainPkg := &gbuild.PackageData{
Package: &build.Package{
Name: "main",
ImportPath: "main",
},
}
mainPkg.Archive, err = compiler.Compile("main", []*ast.File{mainFile}, fset, s.ImportContext, options.Minify)
if err != nil {
return err
}
tempfile, err := ioutil.TempFile("", "test.")
if err != nil {
return err
}
defer func() {
tempfile.Close()
os.Remove(tempfile.Name())
os.Remove(tempfile.Name() + ".map")
}()
if err := s.WriteCommandPackage(mainPkg, tempfile.Name()); err != nil {
return err
}
var args []string
if *bench != "" {
args = append(args, "-test.bench", *bench)
}
if *run != "" {
args = append(args, "-test.run", *run)
}
if *short {
args = append(args, "-test.short")
}
if *verbose {
args = append(args, "-test.v")
}
status := "ok "
开发者ID:wmydz1,项目名称:gopherjs,代码行数:67,代码来源:tool.go
示例7: BuildPackage
func (s *Session) BuildPackage(pkg *PackageData) error {
s.Packages[pkg.ImportPath] = pkg
if pkg.ImportPath == "unsafe" {
return nil
}
if pkg.PkgObj != "" {
var fileInfo os.FileInfo
gopherjsBinary, err := osext.Executable()
if err == nil {
fileInfo, err = os.Stat(gopherjsBinary)
if err == nil {
pkg.SrcModTime = fileInfo.ModTime()
}
}
if err != nil {
os.Stderr.WriteString("Could not get GopherJS binary's modification timestamp. Please report issue.\n")
pkg.SrcModTime = time.Now()
}
for _, importedPkgPath := range pkg.Imports {
ignored := true
for _, pos := range pkg.ImportPos[importedPkgPath] {
importFile := filepath.Base(pos.Filename)
for _, file := range pkg.GoFiles {
if importFile == file {
ignored = false
break
}
}
if !ignored {
break
}
}
if importedPkgPath == "unsafe" || ignored {
continue
}
_, err := s.ImportPackage(importedPkgPath)
if err != nil {
return err
}
impModeTime := s.Packages[importedPkgPath].SrcModTime
if impModeTime.After(pkg.SrcModTime) {
pkg.SrcModTime = impModeTime
}
}
for _, name := range pkg.GoFiles {
fileInfo, err := os.Stat(filepath.Join(pkg.Dir, name))
if err != nil {
return err
}
if fileInfo.ModTime().After(pkg.SrcModTime) {
pkg.SrcModTime = fileInfo.ModTime()
}
}
pkgObjFileInfo, err := os.Stat(pkg.PkgObj)
if err == nil && !pkg.SrcModTime.After(pkgObjFileInfo.ModTime()) {
// package object is up to date, load from disk if library
pkg.UpToDate = true
if pkg.IsCommand() {
return nil
}
objFile, err := ioutil.ReadFile(pkg.PkgObj)
if err != nil {
return err
}
pkg.Archive, err = compiler.UnmarshalArchive(pkg.PkgObj, pkg.ImportPath, objFile, s.ImportContext)
if err != nil {
return err
}
return nil
}
}
fileSet := token.NewFileSet()
files, err := Parse(pkg.Package, fileSet)
if err != nil {
return err
}
pkg.Archive, err = compiler.Compile(pkg.ImportPath, files, fileSet, s.ImportContext, s.options.Minify)
if err != nil {
return err
}
if s.options.Verbose {
fmt.Println(pkg.ImportPath)
}
if pkg.PkgObj == "" || pkg.IsCommand() {
return nil
}
if err := s.writeLibraryPackage(pkg, pkg.PkgObj); err != nil {
if strings.HasPrefix(pkg.PkgObj, s.options.GOROOT) {
// fall back to GOPATH
//.........这里部分代码省略.........
开发者ID:phaikawl,项目名称:gopherjs,代码行数:101,代码来源:build.go
示例8: main
//.........这里部分代码省略.........
location.Hash = ""
start := codeArea.Prop("selectionStart").Int()
end := codeArea.Prop("selectionEnd").Int()
code := scope.Get("code").String()
scope.Apply(func() {
scope.Set("code", code[:start]+toInsert+code[end:])
})
codeArea.SetProp("selectionStart", start+len(toInsert))
codeArea.SetProp("selectionEnd", start+len(toInsert))
e.PreventDefault()
}
})
var run func(bool)
run = func(loadOnly bool) {
output = nil
scope.Set("output", output)
pkgsToLoad = make(map[string]struct{})
file, err := parser.ParseFile(fileSet, "prog.go", []byte(scope.Get("code").String()), parser.ParseComments)
if err != nil {
if list, ok := err.(scanner.ErrorList); ok {
for _, entry := range list {
output = append(output, Line{"type": "err", "content": entry.Error()})
}
scope.Set("output", output)
return
}
scope.Set("output", []Line{Line{"type": "err", "content": err.Error()}})
return
}
mainPkg, err := compiler.Compile("main", []*ast.File{file}, fileSet, importContext, false)
packages["main"] = mainPkg
if err != nil && len(pkgsToLoad) == 0 {
if list, ok := err.(compiler.ErrorList); ok {
var output []Line
for _, entry := range list {
output = append(output, Line{"type": "err", "content": entry.Error()})
}
scope.Set("output", output)
return
}
scope.Set("output", []Line{Line{"type": "err", "content": err.Error()}})
return
}
var allPkgs []*compiler.Archive
if len(pkgsToLoad) == 0 {
allPkgs, _ = compiler.ImportDependencies(mainPkg, importContext.Import)
}
if len(pkgsToLoad) != 0 {
pkgsReceived = 0
for path := range pkgsToLoad {
req := xhr.NewRequest("GET", "pkg/"+path+".a.js")
req.ResponseType = xhr.ArrayBuffer
go func(path string) {
err := req.Send(nil)
if err != nil || req.Status != 200 {
scope.Apply(func() {
scope.Set("output", []Line{Line{"type": "err", "content": `failed to load package "` + path + `"`}})
})
return
}
开发者ID:gbbr,项目名称:gopherjs.github.io,代码行数:67,代码来源:playground.go
示例9: control
func control(scope *angularjs.Scope) {
scope.Set("code", initCode)
// scope.Set("showGenerated", false)
// scope.Set("generated", `(generated code will be shown here after clicking "Run")`)
packages := make(map[string]*compiler.Archive)
var pkgsToLoad []string
importContext := compiler.NewImportContext(
func(path string) (*compiler.Archive, error) {
if pkg, found := packages[path]; found {
return pkg, nil
}
pkgsToLoad = append(pkgsToLoad, path)
return &compiler.Archive{}, nil
},
)
fileSet := token.NewFileSet()
pkgsReceived := 0
setupEnvironment(scope)
var run func(bool)
run = func(loadOnly bool) {
output = nil
scope.Set("output", output)
pkgsToLoad = nil
file, err := parser.ParseFile(fileSet, "prog.go",
getCode(), parser.ParseComments,
)
if err != nil {
if list, ok := err.(scanner.ErrorList); ok {
for _, entry := range list {
output = append(output, errErrLine(entry))
}
scope.Set("output", output)
return
}
scope.Set("output", []Line{errErrLine(err)})
return
}
mainPkg, err := compiler.Compile("main",
[]*ast.File{file}, fileSet,
importContext, false,
)
packages["main"] = mainPkg
if err != nil && len(pkgsToLoad) == 0 {
if list, ok := err.(compiler.ErrorList); ok {
output := make([]Line, 0)
for _, entry := range list {
output = append(output, errErrLine(entry))
}
scope.Set("output", output)
return
}
scope.Set("output", []Line{errErrLine(err)})
return
}
var allPkgs []*compiler.Archive
if len(pkgsToLoad) == 0 {
for _, depPath := range mainPkg.Dependencies {
dep, _ := importContext.Import(string(depPath))
allPkgs = append(allPkgs, dep)
}
allPkgs = append(allPkgs, mainPkg)
}
if len(pkgsToLoad) != 0 {
pkgsReceived = 0
for _, p := range pkgsToLoad {
path := p
req := js.Global.Get("XMLHttpRequest").New()
req.Call("open", "GET", "pkg/"+path+".a", true)
req.Set("responseType", "arraybuffer")
req.Set("onload", func() {
if req.Get("status").Int() != 200 {
f := func() {
emsg := fmt.Sprintf("cannot load package \"%s\"", path)
scope.Set("output", []Line{errLine(emsg)})
}
scope.Apply(f)
return
}
data := js.Global.Get("Uint8Array").New(req.Get("response")).Interface().([]byte)
packages[path], err = compiler.UnmarshalArchive(
path+".a", path, []byte(data), importContext,
)
if err != nil {
scope.Apply(func() {
scope.Set("output", []Line{errErrLine(err)})
})
return
}
pkgsReceived++
if pkgsReceived == len(pkgsToLoad) {
//.........这里部分代码省略.........
开发者ID:h8liu,项目名称:h8liu.github.io,代码行数:101,代码来源:playground.go
注:本文中的github.com/gopherjs/gopherjs/compiler.Compile函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论