Example #1
0
func newBinder(bindPkg *build.Package) (*binder, error) {
	if bindPkg.Name == "main" {
		return nil, fmt.Errorf("package %q: can only bind a library package", bindPkg.Name)
	}

	fset := token.NewFileSet()

	hasErr := false
	var files []*ast.File
	for _, filename := range bindPkg.GoFiles {
		p := filepath.Join(bindPkg.Dir, filename)
		file, err := parser.ParseFile(fset, p, nil, parser.AllErrors)
		if err != nil {
			hasErr = true
			if list, _ := err.(scanner.ErrorList); len(list) > 0 {
				for _, err := range list {
					fmt.Fprintln(os.Stderr, err)
				}
			} else {
				fmt.Fprintln(os.Stderr, err)
			}
		}
		files = append(files, file)
	}

	if hasErr {
		return nil, errors.New("package parsing failed.")
	}

	conf := loader.Config{
		Fset:        fset,
		AllowErrors: true,
	}
	conf.TypeChecker.IgnoreFuncBodies = true
	conf.TypeChecker.FakeImportC = true
	conf.TypeChecker.DisableUnusedImportCheck = true
	var tcErrs []error
	conf.TypeChecker.Error = func(err error) {
		tcErrs = append(tcErrs, err)
	}

	conf.CreateFromFiles(bindPkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		for _, err := range tcErrs {
			fmt.Fprintln(os.Stderr, err)
		}
		return nil, err
	}
	b := &binder{
		files: files,
		fset:  fset,
		pkg:   program.Created[0].Pkg,
	}
	return b, nil
}
Example #2
0
func genPkg(pkg *build.Package) {
	files := parseFiles(pkg.Dir, pkg.GoFiles)
	if len(files) == 0 {
		return // some error has been reported
	}

	conf := loader.Config{
		Fset:        fset,
		AllowErrors: true,
	}
	conf.TypeChecker.IgnoreFuncBodies = true
	conf.TypeChecker.FakeImportC = true
	conf.TypeChecker.DisableUnusedImportCheck = true
	var tcErrs []error
	conf.TypeChecker.Error = func(err error) {
		tcErrs = append(tcErrs, err)
	}
	conf.CreateFromFiles(pkg.ImportPath, files...)
	program, err := conf.Load()
	if err != nil {
		for _, err := range tcErrs {
			errorf("%v", err)
		}
		errorf("%v", err)
		return
	}
	p := program.Created[0].Pkg

	fname := defaultFileName(*lang, p)
	switch *lang {
	case "java":
		w, closer := writer(fname, p)
		processErr(bind.GenJava(w, fset, p, *javaPkg))
		closer()
	case "go":
		w, closer := writer(fname, p)
		processErr(bind.GenGo(w, fset, p))
		closer()
	case "objc":
		if fname == "" {
			processErr(bind.GenObjc(os.Stdout, fset, p, *prefix, true))
			processErr(bind.GenObjc(os.Stdout, fset, p, *prefix, false))
		} else {
			hname := fname[:len(fname)-2] + ".h"
			w, closer := writer(hname, p)
			processErr(bind.GenObjc(w, fset, p, *prefix, true))
			closer()
			w, closer = writer(fname, p)
			processErr(bind.GenObjc(w, fset, p, *prefix, false))
			closer()
		}
	default:
		errorf("unknown target language: %q", *lang)
	}
}