github.com/gotranspile/cxgo@v0.3.8-0.20240118201721-29871598a6a2/libs/stdlib.go (about)

     1  package libs
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/gotranspile/cxgo/runtime/cmath"
     8  	"github.com/gotranspile/cxgo/runtime/libc"
     9  	"github.com/gotranspile/cxgo/types"
    10  )
    11  
    12  const StdlibH = "stdlib.h"
    13  
    14  // https://pubs.opengroup.org/onlinepubs/9699919799/
    15  
    16  func init() {
    17  	RegisterLibrary(StdlibH, func(c *Env) *Library {
    18  		voidPtr := c.PtrT(nil)
    19  		gstrT := c.Go().String()
    20  		cstrT := c.C().String()
    21  		wstrT := c.C().WString()
    22  		intT := types.IntT(4)
    23  		gintT := c.Go().Int()
    24  		longT := types.IntT(8)
    25  		uintT := types.UintT(4)
    26  		l := &Library{
    27  			Imports: map[string]string{
    28  				"libc":  RuntimeLibc,
    29  				"cmath": RuntimePrefix + "cmath",
    30  			},
    31  			Idents: map[string]*types.Ident{
    32  				"abs":      c.NewIdent("abs", "cmath.Abs", cmath.Abs, c.FuncTT(longT, longT)),
    33  				"_Exit":    c.Go().OsExitFunc(),
    34  				"malloc":   c.C().MallocFunc(),
    35  				"calloc":   c.C().CallocFunc(),
    36  				"realloc":  c.NewIdent("realloc", "libc.Realloc", libc.Realloc, c.FuncTT(voidPtr, voidPtr, gintT)),
    37  				"free":     c.C().FreeFunc(),
    38  				"atoi":     c.NewIdent("atoi", "libc.Atoi", libc.Atoi, c.FuncTT(gintT, gstrT)),
    39  				"atol":     c.NewIdent("atol", "libc.Atoi", libc.Atoi, c.FuncTT(gintT, gstrT)),
    40  				"atof":     c.NewIdent("atof", "libc.Atof", libc.Atof, c.FuncTT(types.FloatT(8), gstrT)),
    41  				"rand":     c.NewIdent("rand", "libc.Rand", libc.Rand, c.FuncTT(intT)),
    42  				"srand":    c.NewIdent("srand", "libc.SeedRand", libc.SeedRand, c.FuncTT(nil, uintT)),
    43  				"qsort":    c.NewIdent("qsort", "libc.Sort", libc.Sort, c.FuncTT(nil, voidPtr, uintT, uintT, c.FuncTT(intT, voidPtr, voidPtr))),
    44  				"bsearch":  c.NewIdent("bsearch", "libc.Search", libc.Search, c.FuncTT(voidPtr, voidPtr, voidPtr, uintT, uintT, c.FuncTT(intT, voidPtr, voidPtr))),
    45  				"mbstowcs": c.NewIdent("mbstowcs", "libc.Mbstowcs", libc.Mbstowcs, c.FuncTT(uintT, wstrT, cstrT, uintT)),
    46  			},
    47  			Header: fmt.Sprintf("#define RAND_MAX %d\n", libc.RandMax),
    48  		}
    49  
    50  		l.Declare(
    51  			c.NewIdent("getenv", "os.Getenv", os.Getenv, c.FuncTT(c.Go().String(), c.Go().String())),
    52  		)
    53  		return l
    54  	})
    55  }