diff --git a/compiler/compiler.go b/compiler/compiler.go index 0da00b40..a6355cb2 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -34,6 +34,7 @@ type Config struct { DumpSSA bool // dump Go SSA, for compiler debugging Debug bool // add debug symbols for gdb RootDir string // GOROOT for TinyGo + GOPATH string // GOPATH, like `go env GOPATH` BuildTags []string // build tags for TinyGo (empty means {runtime.GOOS/runtime.GOARCH}) } @@ -151,6 +152,15 @@ func (c *Compiler) Module() llvm.Module { func (c *Compiler) Compile(mainPath string) error { tripleSplit := strings.Split(c.Triple, "-") + // Prefix the GOPATH with the system GOROOT, as GOROOT is already set to + // the TinyGo root. + gopath := c.GOPATH + if gopath == "" { + gopath = runtime.GOROOT() + } else { + gopath = runtime.GOROOT() + string(filepath.ListSeparator) + gopath + } + config := loader.Config{ TypeChecker: types.Config{ Sizes: &StdSizes{ @@ -163,7 +173,7 @@ func (c *Compiler) Compile(mainPath string) error { GOARCH: tripleSplit[0], GOOS: tripleSplit[2], GOROOT: c.RootDir, - GOPATH: runtime.GOROOT(), + GOPATH: gopath, CgoEnabled: true, UseAllFiles: false, Compiler: "gc", // must be one of the recognized compilers diff --git a/main.go b/main.go index 43f09f7a..9137bc3f 100644 --- a/main.go +++ b/main.go @@ -22,6 +22,7 @@ func Compile(pkgName, outpath string, spec *TargetSpec, printIR, dumpSSA, debug Debug: debug, DumpSSA: dumpSSA, RootDir: sourceDir(), + GOPATH: getGopath(), BuildTags: spec.BuildTags, } c, err := compiler.NewCompiler(pkgName, config) @@ -198,6 +199,7 @@ func Flash(pkgName, target, port string, printIR, dumpSSA, debug bool, printSize func Run(pkgName string) error { config := compiler.Config{ RootDir: sourceDir(), + GOPATH: getGopath(), } c, err := compiler.NewCompiler(pkgName, config) if err != nil { diff --git a/target.go b/target.go index 43a9700d..8f7a44cc 100644 --- a/target.go +++ b/target.go @@ -58,3 +58,24 @@ func sourceDir() string { _, path, _, _ := runtime.Caller(0) return filepath.Dir(path) } + +func getGopath() string { + gopath := os.Getenv("GOPATH") + if gopath != "" { + return gopath + } + + // fallback + var home string + if runtime.GOOS == "windows" { + home = os.Getenv("USERPROFILE") + } else { + home = os.Getenv("HOME") + } + if home == "" { + // This is very unlikely, so panic here. + // Not the nicest solution, however. + panic("no $HOME or %USERPROFILE% found") + } + return filepath.Join(home, "go") +}