package bamllib import ( "context" "errors" "fmt" "os" "path/filepath" "reflect" "runtime" "slices" "strconv" "strings" "sync" "time" ) // Manifest is what a generated package knows about the program it was // generated from. Function ids and type ids are positions in the library's // description, stable for one build only, so the generated code names // functions and types and looks the ids up when the library loads. type Manifest struct { // DefaultLibrary is the file name (without lib prefix or extension) the // library is looked for next to the executable. DefaultLibrary string Functions []FuncSpec Types []TypeSpec Sites []SiteSpec // NewError builds the Go error for a thrown or panicking BAML value // (kind is "error" or "panic"), so it is the same error the package's // other back end returns. payload is the value as the library sent it // (self-describing) and held the host values it carries: a callback // that returns the error throws that value on. NewError func(kind, className, message string, value any, payload []byte, held any) error // Classify tells a callback's error apart (see Failure). Classify func(err error) Failure } // FuncSpec names one function as `describe` lists it, with the canonical // key (canonicalKey) of each parameter's type and of the result's, and the // type indices its values reach. type FuncSpec struct { Name string // Owner is the class of a method (its describe name): `describe` lists // a method as `Class.method` with the class's id in method_of. Owner string Params []string Returns string Types []int // ParamNames and Defaulted name each parameter and say whether it has a // default: arguments go by position, so a library whose parameters were // reordered (or lost a default) must be refused, not called. ParamNames []string Defaulted []bool } // TypeSpec names one class (with its field names in declaration order and // the canonical key of each field's type) or one enum (with its variants). type TypeSpec struct { Name string Enum bool Opaque bool // an opaque class: crosses as a handle Fields []string FieldTypes []string Variants []string } // DescribeFormat is the version of `describe` (and of the byte format) this // runtime reads. A library that reports another one is refused. const DescribeFormat = 5 // SiteSpec is one place where the library writes a union (or a value the // generated code decodes from the description, Members == nil). The site is // found from its root (a function's result, or a class field) by Path, a // list of steps: "o" (the inside of an optional), "l" (list element), "k" / // "v" (map key / value), "t" (tuple item i), "m" (member i, in the // generated order, of the union site Parent). type SiteSpec struct { Func int // function index whose result (or parameter, see Arg) holds the site, or -1 // Arg is 0 for the function's result, k+1 for its parameter k (an // encode site: arguments name their union members with tag 16). Arg int Type int // type index whose field holds the site, when Func is -1 Field int Parent int // site the path starts from, or -1 Path []string // Members are the keys of the union's members in the order the // generated code numbers its arms (see TypeNode.canonicalKey). nil: the site is // decoded from the description (Reader.Dynamic). Members []string } // Program is a generated package's view of its library: the manifest, the // loaded library, and the ids and union orders resolved from its description. type Program struct { m Manifest mu sync.Mutex loaded bool path string cfg Config lib *Library err error funcs []funcSlot typeIDs []uint32 // type index → library type id sites []site decoders map[uint32]func(*Reader, int) any // library type id → decoder of a generated type encoders map[uint32]int // library type id → type index pendingDecoders map[int]func(*Reader, int) any // type index → decoder, until load anyEncoders map[reflect.Type]func(*Writer, any, int) } type funcSlot struct { id uint32 mayWait bool err error } type site struct { node *TypeNode arms []int // library member index → generated arm libIndex []int // generated arm → library member index (encode sites) leaves []*TypeNode // generated arm → the library's type of that member optional bool // the library writes the union inside an optional collapsed bool // the library writes one member type, not a union err error } // NewProgram wraps a manifest. Nothing is loaded until the first call or Load. func NewProgram(m Manifest) *Program { return &Program{m: m} } // RegisterDecoder tells the program how to build the generated Go value of // type index t, for values the library sends self-describing (a thrown // class, a class inside `unknown`). Called from generated init code. func (p *Program) RegisterDecoder(t int, decode func(*Reader, int) any) { p.mu.Lock() defer p.mu.Unlock() if p.pendingDecoders == nil { p.pendingDecoders = map[int]func(*Reader, int) any{} } p.pendingDecoders[t] = decode } // SetConfig sets how the library is started. Call it before the first call. func (p *Program) SetConfig(cfg Config) { p.mu.Lock() defer p.mu.Unlock() p.cfg = cfg } // Load loads the library at path. Without it, the first call loads the file // named by $BAML_LIBRARY, or else lib. next to // the executable. A library that fails to open (missing file, wrong // platform) leaves the program unloaded, so Load can be retried. func (p *Program) Load(path string) error { p.mu.Lock() defer p.mu.Unlock() if p.loaded { if p.path == path { return p.err } return fmt.Errorf("a BAML library is already loaded (%s)", p.path) } return p.load(path) } // DefaultPath is where the library is looked for when Load is not called. func (p *Program) DefaultPath() string { if env := os.Getenv("BAML_LIBRARY"); env != "" { return env } ext := ".so" switch runtime.GOOS { case "darwin": ext = ".dylib" case "windows": ext = ".dll" } name := "lib" + p.m.DefaultLibrary + ext exe, err := os.Executable() if err != nil { return name } return filepath.Join(filepath.Dir(exe), name) } func (p *Program) ensure() error { p.mu.Lock() defer p.mu.Unlock() if !p.loaded { if err := p.load(p.DefaultPath()); err != nil { return err } } return p.err } // Library is the loaded library (nil before the first call or Load). func (p *Program) Library() *Library { p.mu.Lock() defer p.mu.Unlock() return p.lib } // load opens the library and checks it against the manifest. An error // opening it is returned and leaves the program unloaded. A library that // opens but does not match fails, at call time, the functions the mismatch // concerns (or every call, for an unknown describe format). func (p *Program) load(path string) error { if os.Getenv("BAML_LIBRARY_ASYNC_ONLY") == "1" { // For measurements: every call through baml_lib_call. p.cfg.AsyncOnly = true } lib, err := Open(path, p.cfg) if err != nil { return err } p.loaded = true p.path = path p.lib = lib lib.mu.Lock() lib.progs = append(lib.progs, p) lib.mu.Unlock() // The event reader runs from the start: failures nobody awaited arrive // as events, also in a program that only makes direct calls. _ = lib.startPump() d := &lib.desc if d.Format != DescribeFormat { p.err = fmt.Errorf("BAML library %s has describe format %d; this runtime reads format %d (update baml-go or repack the library)", path, d.Format, DescribeFormat) return p.err } p.funcs = make([]funcSlot, len(p.m.Functions)) for i, spec := range p.m.Functions { p.funcs[i] = p.checkFunc(spec) } p.typeIDs = make([]uint32, len(p.m.Types)) p.encoders = map[uint32]int{} typeErr := make([]error, len(p.m.Types)) for i, spec := range p.m.Types { p.typeIDs[i] = ^uint32(0) t, ok := d.typeByName(spec.Name) if !ok { typeErr[i] = mismatch("type %s is not in the library", spec.Name) continue } p.typeIDs[i] = t.ID typeErr[i] = p.checkType(spec, t) if typeErr[i] == nil { p.encoders[t.ID] = i } } p.sites = make([]site, len(p.m.Sites)) for i := range p.m.Sites { p.resolveSite(i, typeErr) } // A site that cannot be resolved fails what holds it: its function, or // the class whose field it is in. for i := range p.m.Sites { if p.sites[i].err == nil { continue } root := p.siteRoot(i) spec := p.m.Sites[root] if spec.Func >= 0 && spec.Func < len(p.funcs) { if p.funcs[spec.Func].err == nil { p.funcs[spec.Func].err = p.sites[i].err } } else if spec.Type >= 0 && spec.Type < len(typeErr) && typeErr[spec.Type] == nil { typeErr[spec.Type] = p.sites[i].err } } // A mismatched type fails only the functions whose values reach it. for i, spec := range p.m.Functions { if p.funcs[i].err != nil { continue } for _, t := range spec.Types { if t < len(typeErr) && typeErr[t] != nil { p.funcs[i].err = typeErr[t] break } } } p.decoders = map[uint32]func(*Reader, int) any{} for t, decode := range p.pendingDecoders { if t < len(p.typeIDs) && typeErr[t] == nil { p.decoders[p.typeIDs[t]] = decode } } return nil } // checkFunc finds a function and compares its signature with the manifest. func (p *Program) checkFunc(spec FuncSpec) funcSlot { var f *FuncDesc ok := false if spec.Owner != "" { f, ok = p.lib.desc.methodByName(spec.Owner, spec.Name[strings.LastIndexByte(spec.Name, '.')+1:]) } else { f, ok = p.lib.desc.funcByName(spec.Name) } if !ok { return funcSlot{err: mismatch("function %s is not in the library", spec.Name)} } if len(f.Params) != len(spec.Params) { return funcSlot{err: mismatch("function %s takes %d parameters in the library, %d here", spec.Name, len(f.Params), len(spec.Params))} } for i, want := range spec.Params { if i < len(spec.ParamNames) && f.Params[i].Name != spec.ParamNames[i] { return funcSlot{err: mismatch("parameter %d of %s is %s in the library, %s here", i+1, spec.Name, f.Params[i].Name, spec.ParamNames[i])} } if i < len(spec.Defaulted) && f.Params[i].HasDefault != spec.Defaulted[i] { return funcSlot{err: mismatch("parameter %s of %s has a default in one of the library and the package, not the other", f.Params[i].Name, spec.Name)} } if got := f.Params[i].Type.canonicalKey(p); got != want { return funcSlot{err: mismatch("parameter %s of %s is %s in the library, %s here", f.Params[i].Name, spec.Name, got, want)} } } if got := f.Returns.canonicalKey(p); got != spec.Returns { return funcSlot{err: mismatch("%s returns %s in the library, %s here", spec.Name, got, spec.Returns)} } return funcSlot{id: f.ID, mayWait: f.MayWait} } // checkType compares a class's fields, or an enum's variants, with the manifest. func (p *Program) checkType(spec TypeSpec, t *TypeDesc) error { if spec.Opaque { if t.Kind != "opaque" { return mismatch("%s is a %s in the library, an opaque class here", spec.Name, t.Kind) } return nil } if spec.Enum { if t.Kind != "enum" || strings.Join(t.Variants, ",") != strings.Join(spec.Variants, ",") { return mismatch("enum %s has variants %v in the library, %v here", spec.Name, t.Variants, spec.Variants) } return nil } if t.Kind != "class" { return mismatch("%s is a %s in the library, a class here", spec.Name, t.Kind) } names := make([]string, len(t.Fields)) for j, f := range t.Fields { names[j] = f.Name } if strings.Join(names, ",") != strings.Join(spec.Fields, ",") { return mismatch("class %s has fields %v in the library, %v here", spec.Name, names, spec.Fields) } for j, want := range spec.FieldTypes { if got := t.Fields[j].Type.canonicalKey(p); got != want { return mismatch("field %s of %s is %s in the library, %s here", t.Fields[j].Name, spec.Name, got, want) } } return nil } // siteRoot follows a site's parents to the site whose path starts at a // function result or a class field. func (p *Program) siteRoot(i int) int { for n := 0; n < len(p.m.Sites) && p.m.Sites[i].Parent >= 0; n++ { i = p.m.Sites[i].Parent } return i } func (p *Program) resolveSite(i int, typeErr []error) { spec := p.m.Sites[i] s := &p.sites[i] d := &p.lib.desc var node *TypeNode where := "" switch { case spec.Parent >= 0: parent := &p.sites[spec.Parent] if parent.err != nil { s.err = parent.err return } node = parent.node where = fmt.Sprintf("inside site %d", spec.Parent) case spec.Func >= 0: slot := p.funcs[spec.Func] if slot.err != nil { s.err = slot.err return } f := &d.Functions[slot.id] if spec.Arg > 0 { if spec.Arg > len(f.Params) { s.err = mismatch("%s has no parameter %d", f.QualifiedName, spec.Arg) return } node = f.Params[spec.Arg-1].Type where = "parameter " + f.Params[spec.Arg-1].Name + " of " + f.QualifiedName } else { node = f.Returns where = "the result of " + f.QualifiedName } default: if spec.Type < 0 || spec.Type >= len(typeErr) { s.err = mismatch("site %d has no root", i) return } if typeErr[spec.Type] != nil { s.err = typeErr[spec.Type] return } id := p.typeIDs[spec.Type] if int(id) >= len(d.Types) || spec.Field >= len(d.Types[id].Fields) { s.err = mismatch("type %s has no field %d", p.m.Types[spec.Type].Name, spec.Field) return } t := &d.Types[id] node = t.Fields[spec.Field].Type where = "field " + t.Fields[spec.Field].Name + " of " + t.QualifiedName } for _, step := range spec.Path { if node == nil { break } switch { case step == "o" && node.Kind == "optional": node = node.Of case step == "l" && node.Kind == "list": node = node.Of case step == "k" && node.Kind == "map": node = node.Key case step == "v" && node.Kind == "map": node = node.MapValue() case strings.HasPrefix(step, "t") && node.Kind == "tuple": k, _ := strconv.Atoi(step[1:]) if k < len(node.Items) { node = node.Items[k] } else { node = nil } case step == "r" && node.Kind == "function": node = node.Returns case step == "x" && node.Kind == "function": node = node.Throws case strings.HasPrefix(step, "p") && node.Kind == "function": k, _ := strconv.Atoi(step[1:]) if k < len(node.Params) { node = node.Params[k] } else { node = nil } case strings.HasPrefix(step, "m") && spec.Parent >= 0: // Member k of the parent union. k, _ := strconv.Atoi(step[1:]) parent := &p.sites[spec.Parent] if k < len(parent.leaves) { node = parent.leaves[k] } else { node = nil } default: node = nil } } if node == nil { s.err = mismatch("%s does not have the shape the generated code expects (path %v)", where, spec.Path) return } s.node = node if spec.Members == nil { return } // Unions cross flat (format 3): a nullable union is one optional around // one union of the remaining members, which are never unions or // optionals themselves. if node.Kind == "optional" { s.optional = true node = node.Of s.node = node } if node != nil && node.Kind != "union" { // The library writes a union whose members it carries alike (an // enum and its variants, bigint and bigint literals) as that one // type, with no member index: the generated code then reads the // type and picks the member by value. Only when every generated // member has that key. key := node.canonicalKey(p) collapsed := len(spec.Members) > 0 for _, want := range spec.Members { collapsed = collapsed && want == key } if collapsed { s.collapsed = true return } } if node == nil || node.Kind != "union" { s.err = mismatch("%s is %s in the library, a union here", where, node.String()) return } s.arms = make([]int, len(node.Members)) s.libIndex = make([]int, len(spec.Members)) s.leaves = make([]*TypeNode, len(spec.Members)) for libIndex, member := range node.Members { // Generated arms the library carries alike (two variants of one // enum) share a key and the library's one member. key := member.canonicalKey(p) arm := slices.Index(spec.Members, key) if arm < 0 { s.err = mismatch("%s: union member %s of the library is not one of %v here", where, key, spec.Members) return } s.arms[libIndex] = arm for k, want := range spec.Members { if want == key { s.leaves[k] = member s.libIndex[k] = libIndex } } } for k, leaf := range s.leaves { if leaf == nil { s.err = mismatch("%s: union member %s is not in the library's union", where, spec.Members[k]) return } } } // discardFor is how a result nobody waits for is read, so the handles it // holds are released; nil when its type cannot hold any. func (p *Program) discardFor(kind uint32, target uint64) func(uint32, []byte) { if kind == targetCallable { return func(status uint32, data []byte) { if status == StatusReturned { r := Reader{B: data, prog: p} r.Any(0) } } } d := &p.lib.desc if target >= uint64(len(d.Functions)) { return nil } returns := d.Functions[target].Returns if !returns.holdsHandles(p, nil) { return nil } return func(status uint32, data []byte) { if status == StatusReturned { r := Reader{B: data, prog: p} r.Node(returns, 0) } } } // TypeID is the library's id of type index t, for self-describing values. func (p *Program) TypeID(t int) uint32 { return p.typeIDs[t] } // Call is one call in progress. Generated code gets it from Begin (or // BeginValue), writes the arguments into Writer, calls Run, reads the // result from the Reader Run returns, and calls End. All of its memory comes // from a pool of heap buffers and goes back there at End (or when Run // fails). type Call struct { callBuf p *Program kind uint32 target uint64 mayWait bool timeoutMs uint64 ctx context.Context cancel context.CancelFunc value *Handle // the function value a BeginValue call calls throws *TypeNode // the declared throws type of a function value read epochRead reading bool } var callPool = sync.Pool{New: func() any { return newCall() }} //go:noinline func newCall() *Call { c := new(Call) c.args.B = make([]byte, 0, 256) c.out = make([]byte, initialOut) c.wt.ch = make(chan event, 1) return c } // Begin starts a call of function index fn. It loads the library on first // use. A positive timeout (from WithOptions) bounds the call like a context // deadline; the earlier of it and the context's deadline goes to the // library, which ends the call TimedOut where it waits. func (p *Program) Begin(ctx context.Context, fn int, timeout time.Duration) (*Call, error) { if ctx == nil { return nil, errors.New("BAML call: nil context") } if err := ctx.Err(); err != nil { return nil, err } if !p.ready() { if err := p.ensure(); err != nil { return nil, err } } slot := &p.funcs[fn] if slot.err != nil { return nil, slot.err } c := p.newCall(ctx, timeout) c.kind, c.target, c.mayWait = targetExport, uint64(slot.id), slot.mayWait return c, nil } // BeginValue starts a call of a function value BAML returned. Its // arguments are a u32 count, then each value self-describing; its result is // one self-describing value. It goes through baml_lib_call (it may wait). func (p *Program) BeginValue(ctx context.Context, h *Handle, timeout time.Duration) (*Call, error) { if ctx == nil { return nil, errors.New("BAML call: nil context") } if err := ctx.Err(); err != nil { return nil, err } if h == nil || !h.pin() { return nil, errors.New("call BAML function: invalid or released function handle") } c := p.newCall(ctx, timeout) c.kind, c.target, c.mayWait = targetCallable, h.id, true c.value = h return c, nil } func (p *Program) newCall(ctx context.Context, timeout time.Duration) *Call { c := callPool.Get().(*Call) c.p = p c.args.lib = p.lib if timeout > 0 { c.ctx, c.cancel = context.WithTimeout(ctx, timeout) } else { c.ctx = ctx } c.timeoutMs = 0 if deadline, ok := c.ctx.Deadline(); ok { left := time.Until(deadline) ms := (left + time.Millisecond - 1) / time.Millisecond if ms < 1 { ms = 1 } c.timeoutMs = uint64(ms) } return c } func (p *Program) ready() bool { p.mu.Lock() ok := p.loaded && p.err == nil p.mu.Unlock() return ok } // ThrowsAt tells a function value call where its declared throws type is // (a site decoded from the description): a union in a thrown value can then // arrive as tag 16. func (c *Call) ThrowsAt(site int) { if site >= 0 && site < len(c.p.sites) && c.p.sites[site].err == nil { c.throws = c.p.sites[site].node } } // Writer is where the arguments go: per parameter a presence byte, then the // value in its typed form (for BeginValue: a count, then self-describing // values). func (c *Call) Writer() *Writer { return &c.args } // Run sends the call and waits for it. On success it returns the reader of // the result; otherwise the call is over (no End) and the error says why. func (c *Call) Run() (*Reader, error) { if err := c.args.err; err != nil { newError := c.p.m.NewError c.args.rollback() c.release() var mismatch *MismatchError if errors.As(err, &mismatch) && newError != nil { message := err.Error() return nil, newError("error", "baml.errors.TypeMismatch", message, map[string]any{"message": message}, nil, nil) } return nil, err } // The context may have ended while the arguments were encoded: do not // start a call nobody waits for. if err := c.ctx.Err(); err != nil { c.args.rollback() c.release() return nil, err } lib := c.p.lib c.read = lib.hv.beginRead() c.reading = true if c.mayWait || !lib.syncPath { c.discard = c.p.discardFor(c.kind, c.target) } status, data, err := lib.call(c.ctx, c.kind, c.target, c.mayWait, c.timeoutMs, &c.callBuf) if err != nil { c.release() return nil, err } if status == StatusReturned { c.reader = Reader{B: data, prog: c.p} return &c.reader, nil } // A thrown value under a declared union throws type names its member // (tag 16): read it against that type (a function value's, or the // exported function's). throws := c.throws if throws == nil && c.kind == targetExport { if d := &c.p.lib.desc; c.target < uint64(len(d.Functions)) { throws = d.Functions[c.target].Throws } } err = c.p.statusErrorAt(c.ctx, status, data, throws) c.release() return nil, err } // End checks the result was read completely and gives the buffers back. func (c *Call) End() error { err := c.reader.Done() c.release() return err } func (c *Call) release() { if c.reading { c.p.lib.hv.endRead(c.read) c.reading = false } if c.value != nil { c.value.unpin() c.value = nil } c.args.reset() c.reply.reset() c.reader = Reader{} c.discard = nil c.throws = nil if c.cancel != nil { c.cancel() c.cancel = nil } c.p, c.ctx = nil, nil if cap(c.out) > 1<<20 { c.out = make([]byte, initialOut) } if cap(c.args.B) > 1<<20 { c.args.B = make([]byte, 0, 256) } callPool.Put(c) }