github.com/gotranspile/cxgo@v0.3.8-0.20240118201721-29871598a6a2/libs/config.go (about) 1 package libs 2 3 import ( 4 "errors" 5 6 "github.com/gotranspile/cxgo/types" 7 ) 8 9 // NewEnv creates a new environment. It uses GOARCH env to set sensible defaults. 10 func NewEnv(conf types.Config) *Env { 11 return &Env{ 12 Env: types.NewEnv(conf), 13 libs: make(map[string]*Library), 14 imports: map[string]string{ 15 "unsafe": "unsafe", 16 "math": "math", 17 "libc": RuntimeLibc, 18 }, 19 macros: make(map[string]bool), 20 } 21 } 22 23 type Env struct { 24 *types.Env 25 NoLibs bool // completely disable library lookups 26 Map map[string]string // when searching for library name, consult the map first and search that name instead 27 libs map[string]*Library 28 imports map[string]string 29 macros map[string]bool 30 } 31 32 func (c *Env) Clone() *Env { 33 c2 := &Env{Env: c.Env, NoLibs: c.NoLibs} 34 c2.libs = make(map[string]*Library) 35 for k, v := range c.libs { 36 c2.libs[k] = v 37 } 38 c2.imports = make(map[string]string) 39 for k, v := range c.imports { 40 c2.imports[k] = v 41 } 42 c2.macros = make(map[string]bool) 43 for k, v := range c.macros { 44 c2.macros[k] = v 45 } 46 c2.Map = make(map[string]string) 47 for k, v := range c.Map { 48 c2.Map[k] = v 49 } 50 return c2 51 } 52 53 func (c *Env) ResolveImport(name string) string { 54 path := c.imports[name] 55 if path == "" { 56 path = name 57 } 58 return path 59 } 60 61 // LookupLibrary finds an already loaded Library. It is useful to prevent import loops. 62 // 63 // Typically, the GetLibrary function should be used instead, because it will load the library automatically, if needed. 64 func (c *Env) LookupLibrary(name string) *Library { 65 if v, ok := c.Map[name]; ok { 66 name = v 67 } 68 if c.NoLibs && name != BuiltinH { 69 return nil 70 } 71 if v, ok := c.Map[name]; ok { 72 name = v 73 } 74 l, ok := c.libs[name] 75 if !ok { 76 panic(errors.New("cannot find library: " + name)) 77 } 78 return l 79 }