//! The native back end (`backend = "native"`): the generated package calls a //! BAML program compiled with `baml pack --native --shared` through its //! `baml_lib_*` C functions, using the runtime package //! `github.com/boundaryml/baml-go/bamllib`. //! //! Everything that does not depend on how calls are made is shared with the //! default back end: names, packages, the Go types (`types.go`), option //! types, docs, and the skip logic. This module adds, for the root package: //! //! - `native_functions.go`: one body per BAML function the library can run //! (encode the arguments, call, turn the status into a result or an error, //! decode), with the same signature as the default back end, plus //! straight-line encode and decode functions for every type those //! functions reach, in the byte format of `bex2_boundary/README.md`; //! - `native/native.go`: the manifest (function, type and union-site names //! the runtime resolves to the library's ids when it loads) and `Load`. //! //! Union members: the library writes a union as a member index in an order //! of its own, which can differ between two places the same union appears. //! Each place the library writes a union is a *site*; the generated code //! names a site's members by key ([`member_key`]) and the runtime learns the //! library's order from `describe` when the library loads. use std::{ collections::{BTreeSet, HashMap}, fmt::Write as _, }; use baml_base::Name as BaseName; use baml_sdkgen_types::{ClassCrossing, Name, Symbol, SymbolPool, Ty}; use crate::{ BAML_GO_MODULE, BANNER, DynamicDocContext, GeneratedFunction, TypeImportContext, TypeVarScope, add_function_surface_imports, docstring_with_generated_notes, dynamic_union_doc_notes, expanded_return_slots, function_go_type, function_return_go_type, function_returns_only_error, names::{BamlFqn, GoNameKind, GoNames, GoPackageName, GoVisibility}, packages::GoPackages, render_go_doc_comment, render_go_literal_value, render_projected_go_type, rendering::{GeneratorIdent, GoImports}, types::{GoCallbackReturn, GoFunctionKey, GoLiteral, GoTy, GoTypeProjection}, }; /// Whether unions inside self-describing values the host sends (a host /// function's reply, the arguments of a call through a function value) name /// their member with tag 16. The library takes tag 16 in typed positions /// only for now; until it takes it there too, those unions are sent plain /// and the library picks the member. const MEMBER_FORM_IN_SELF_DESCRIBING: bool = true; /// Import path of the runtime package of the native back end. pub(crate) const BAMLLIB_MODULE: &str = "github.com/boundaryml/baml-go/bamllib"; /// Import aliases. Generated names never start with `_`, so these cannot /// collide with projected BAML names. const LIB: &str = "_bamllib"; const NATIVE: &str = "_bamlnative"; /// Placeholders for the writer and reader variables. Helpers name them `w` /// and `r`; a function body names them `_bamlW_` and `_bamlR_`, because a /// BAML parameter may be called `w` or `r`. const WRITER: &str = "\u{1}w"; const READER: &str = "\u{1}r"; /// Why the native library cannot run `routed`, or `None` when it can. pub(crate) fn skip_reason( routed: &GeneratedFunction<'_>, pool: &SymbolPool, projection: &GoTypeProjection<'_>, ) -> Option { let function = routed.function; if let Some(owner) = routed.owner_name { // Methods of the project's classes are exported as `Class.method`. if owner.package().as_str() != "user" { return Some(format!( "the native library exports the project's own functions only, not those of package `{}`", owner.package() )); } if let Symbol::Class(class) = &pool[owner] && !class.generic_params.is_empty() { return Some( "methods of generic classes need type arguments, which the native library does not take yet" .to_string(), ); } if let Some(receiver) = &routed.receiver { let mut visiting = BTreeSet::new(); if let Err(reason) = supported( &projection.project(&receiver.ty()), pool, projection, &mut visiting, ) { return Some(format!("receiver: {reason}")); } } } else { let wire = routed.go_name.wire().to_string(); if !wire.starts_with("user.") { let package = wire.split('.').next().unwrap_or_default(); return Some(format!( "the native library exports the project's own functions only, not those of package `{package}`" )); } } if function.name.as_str().contains('@') { return Some("LLM spec and stream companions do not compile natively yet".to_string()); } if function.arguments.iter().any(|argument| argument.injected) { return Some("LLM functions do not compile natively yet".to_string()); } if !function.generic_params.is_empty() { return Some( "generic functions need type arguments, which the native library does not take yet" .to_string(), ); } let mut visiting = BTreeSet::new(); for argument in &function.arguments { if let Err(reason) = supported_whole( &projection.project(&argument.ty), pool, projection, &mut visiting, ) { return Some(format!("parameter `{}`: {reason}", argument.name)); } } if !matches!(function.return_type, Ty::Never) && !function.return_type.is_unit() { if let Err(reason) = supported_whole( &projection.project(&function.return_type), pool, projection, &mut visiting, ) { return Some(format!("return type: {reason}")); } } None } /// Whether a whole parameter or result of type `ty` can cross: a function /// type is allowed there (a Go function passed to BAML, or a function value /// BAML returns), not nested in another value. fn supported_whole( ty: &GoTy, pool: &SymbolPool, projection: &GoTypeProjection<'_>, visiting: &mut BTreeSet, ) -> Result<(), String> { let GoTy::Function(key) = ty else { return supported(ty, pool, projection, visiting); }; if key.has_optional_params() { return Err( "a function type with optional parameters does not compile natively".to_string(), ); } if key.component_tys().any(mentions_type_var) { return Err( "a function type that mentions a type parameter needs type arguments, which the native library does not take yet" .to_string(), ); } for param in key.required_params() { supported(param.ty(), pool, projection, visiting) .map_err(|reason| format!("function type parameter: {reason}"))?; } if let Some(ret) = key.ret() { supported(ret, pool, projection, visiting) .map_err(|reason| format!("function type result: {reason}"))?; } if let Some(thrown) = key.throws().thrown() { supported(thrown, pool, projection, visiting) .map_err(|reason| format!("function type throws: {reason}"))?; } Ok(()) } fn mentions_type_var(ty: &GoTy) -> bool { match ty { GoTy::TypeVar(_) => true, GoTy::List(inner) | GoTy::Optional(inner) => mentions_type_var(inner), GoTy::Map { key, value } => mentions_type_var(key) || mentions_type_var(value), GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => { key.members().iter().any(mentions_type_var) } GoTy::Tuple(key) => key.slots().iter().any(mentions_type_var), GoTy::Class(_, arguments) | GoTy::Opaque(_, arguments) => { arguments.iter().any(mentions_type_var) } GoTy::Function(key) => key.component_tys().any(mentions_type_var), _ => false, } } /// Whether values of `ty` can cross the native library as bytes. fn supported( ty: &GoTy, pool: &SymbolPool, projection: &GoTypeProjection<'_>, visiting: &mut BTreeSet, ) -> Result<(), String> { match ty { GoTy::String | GoTy::Int | GoTy::Bigint | GoTy::Float | GoTy::Bool | GoTy::Null | GoTy::Uint8Array | GoTy::Literal(_) | GoTy::Enum(_) | GoTy::EnumVariant(..) => Ok(()), // `json` is a recursive alias: its self-reference is an erased type, // and `baml pack --native --shared` leaves out every function whose // signature reaches one (bex2_boundary README, "erased"). GoTy::Json => Err( "`baml.json.json` is a recursive alias, and the native library leaves out functions that reach one" .to_string(), ), GoTy::Media(_) => Err("media values do not compile natively yet".to_string()), GoTy::ReflectedType => Err( "`type` values need handles, which the native library does not support yet".to_string(), ), GoTy::HostValue => Ok(()), GoTy::Prompt(_) | GoTy::FunctionSpec { .. } | GoTy::Stream { .. } => { Err("LLM values do not compile natively yet".to_string()) } GoTy::Opaque(name, arguments) => { if arguments.is_empty() { Ok(()) } else { Err(format!( "generic class `{name}` needs type arguments, which the native library does not take yet" )) } } GoTy::Function(_) => Err( "a function value nested in another value can be released, not called, natively" .to_string(), ), GoTy::TypeVar(_) => Err( "type parameters need type arguments, which the native library does not take yet" .to_string(), ), GoTy::Unsupported => Err("the type has no Go representation".to_string()), GoTy::Class(name, arguments) => { if !arguments.is_empty() { return Err(format!( "generic class `{name}` crosses with `unknown` fields, which the native back end does not convert yet" )); } if !visiting.insert(name.clone()) { return Ok(()); } let Symbol::Class(class) = &pool[name] else { return Err(format!("`{name}` is not a class")); }; if class.crossing != ClassCrossing::Fields { return Err(format!("`{name}` does not cross by its fields")); } // The library treats a class with a private field as opaque: it // will cross as a handle (bex2_boundary README, "Typed form"). if let Some(field) = class .properties .iter() .find(|property| property.name.as_str().starts_with('_')) { return Err(format!( "`{name}` has the private field `{}`, so it crosses as a handle, which the native library does not support yet", field.name )); } for property in &class.properties { supported( &projection.project(&property.ty), pool, projection, visiting, ) .map_err(|reason| format!("field `{name}.{}`: {reason}", property.name))?; } Ok(()) } GoTy::List(inner) | GoTy::Optional(inner) => supported(inner, pool, projection, visiting), GoTy::Map { key, value } => { supported(key, pool, projection, visiting)?; supported(value, pool, projection, visiting) } GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => { // Members the library carries alike (an enum and its variants, // and containers of them) are one // member there, or the whole union when nothing else is left: // the generated code tells them apart by value, which it can do // through lists, maps and optionals but not through tuples or // unions. for group in alike_groups(key.members()) { if group.len() > 1 && let Some(member) = group .iter() .find(|&&index| !pickable(&key.members()[index])) { return Err(format!( "union members that the native library carries as one type ({}) can only be told apart by value through lists, maps and optionals", type_key(&key.members()[*member]) )); } } for member in key.members() { supported(member, pool, projection, visiting)?; } Ok(()) } GoTy::Tuple(key) => { if !key.is_named() { return Err("tuples of type parameters are not supported natively".to_string()); } for slot in key.slots() { supported(slot, pool, projection, visiting)?; } Ok(()) } } } /// The name `describe` gives a function or type: the program's own items /// without their package (`throws_test.MyError`), others with it /// (`baml.json.ParseError`). fn describe_name(name: &Name) -> String { name.render_dotted(true) } /// The key of a union member, matched against the runtime's /// `TypeNode.key` (bamllib/describe.go). Nested unions list their member /// keys sorted, because the library's order is its own there too. fn member_key(ty: &GoTy) -> String { match ty { GoTy::String => "string".to_string(), GoTy::Int => "int".to_string(), GoTy::Float => "float".to_string(), GoTy::Bool => "bool".to_string(), GoTy::Null => "null".to_string(), GoTy::Uint8Array => "bytes".to_string(), GoTy::Bigint => "bigint".to_string(), // A bigint literal is a type of its own since format 4 (a union // member of its own, `describe`: `{"kind": "literal", "bigint": true}`). GoTy::Literal(GoLiteral::Bigint(value)) => format!("lit:n:{value}"), GoTy::Literal(GoLiteral::String(value)) => format!("lit:s:{value}"), GoTy::Literal(GoLiteral::Int(value)) => format!("lit:i:{value}"), GoTy::Literal(GoLiteral::Bool(value)) => format!("lit:b:{value}"), GoTy::Literal(GoLiteral::Float(value)) => { let bits = value.parse::().map(f64::to_bits).unwrap_or_default(); format!("lit:f:{bits:x}") } GoTy::Enum(name) | GoTy::EnumVariant(name, _) => format!("enum:{}", describe_name(name)), GoTy::Class(name, _) | GoTy::Opaque(name, _) => format!("class:{}", describe_name(name)), GoTy::List(inner) => format!("list({})", member_key(inner)), GoTy::Optional(inner) => format!("opt({})", member_key(inner)), GoTy::Map { key, value } => format!("map({},{})", member_key(key), member_key(value)), GoTy::Tuple(key) => format!( "tuple({})", key.slots() .iter() .map(member_key) .collect::>() .join(",") ), GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => { let mut keys = key.members().iter().map(member_key).collect::>(); keys.sort(); let union = format!("union({})", keys.join(",")); if matches!(ty, GoTy::DynamicUnion { nullable: true, .. }) { format!("opt({union})") } else { union } } GoTy::Json => "unknown".to_string(), GoTy::HostValue => "host_value".to_string(), // A function type written in full (a whole parameter or result): // its parameters and result, as `describe` gives them. GoTy::Function(key) => { let params = key .required_params() .map(|param| type_key(param.ty())) .collect::>() .join(","); let ret = match key.returns() { GoCallbackReturn::Value(ret) => type_key(ret), GoCallbackReturn::Null => "null".to_string(), GoCallbackReturn::Never => "never".to_string(), }; format!("fn({params})->{ret}") } _ => "unsupported".to_string(), } } /// The library's type JSON for `json`: a recursive alias expanded one level, /// its inner references read as `unknown`, in the canonical form of /// [`type_key`]. const JSON_KEY: &str = "opt(union(bigint,bool,float,int,list(unknown),map(string,unknown),string))"; /// The canonical key of the type the library describes for a value of `ty`, /// compared at load with the key the runtime computes from `describe` /// (`canonicalKey` in bamllib/describe.go). Unions are flattened the way the /// library flattens them ([`flat_member_keys`]), sorted and deduplicated, and /// a nullable one is `opt(union(...))`; members the library carries alike /// (enum variants are their enum) meet. fn type_key(ty: &GoTy) -> String { match ty { GoTy::Optional(inner) => { let inner = type_key(inner); if inner.starts_with("opt(") { inner } else { format!("opt({inner})") } } GoTy::List(inner) => format!("list({})", type_key(inner)), GoTy::Map { key, value } => format!("map({},{})", type_key(key), type_key(value)), GoTy::Tuple(key) => format!( "tuple({})", key.slots() .iter() .map(type_key) .collect::>() .join(",") ), GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => { let mut nullable = matches!(ty, GoTy::DynamicUnion { nullable: true, .. }); let mut keys = Vec::new(); flat_member_keys(key.members(), &mut nullable, &mut keys); keys.sort(); keys.dedup(); let base = match keys.len() { 0 => return "null".to_string(), 1 => keys.pop().unwrap_or_default(), _ => format!("union({})", keys.join(",")), }; if nullable { format!("opt({base})") } else { base } } GoTy::Json => JSON_KEY.to_string(), GoTy::EnumVariant(name, _) => format!("enum:{}", describe_name(name)), other => member_key(other), } } /// The keys of a union's members, flat as the library describes them /// (`bex2_boundary` README, "Unions and optionals"): a union member contributes /// its members, an optional member null and its inner type, and null only /// makes the whole union nullable. fn flat_member_keys(members: &[GoTy], nullable: &mut bool, out: &mut Vec) { for member in members { match member { GoTy::Null => *nullable = true, GoTy::Optional(inner) => { *nullable = true; flat_member_keys(std::slice::from_ref(inner.as_ref()), nullable, out); } GoTy::TypedUnion(key) => flat_member_keys(key.members(), nullable, out), GoTy::DynamicUnion { key, nullable: n } => { *nullable |= *n; flat_member_keys(key.members(), nullable, out); } GoTy::Json => { // `json` is a nullable union itself. *nullable = true; let members = JSON_KEY .strip_prefix("opt(union(") .and_then(|k| k.strip_suffix("))")) .unwrap_or_default(); out.extend(split_top_level(members)); } other => out.push(type_key(other)), } } } /// Splits a comma-separated key list at depth zero. fn split_top_level(keys: &str) -> Vec { let mut out = Vec::new(); let (mut depth, mut start) = (0usize, 0usize); for (index, c) in keys.char_indices() { match c { '(' => depth += 1, ')' => depth = depth.saturating_sub(1), ',' if depth == 0 => { out.push(keys[start..index].to_string()); start = index + 1; } _ => {} } } if start < keys.len() { out.push(keys[start..].to_string()); } out } /// The indices of `members` grouped by [`type_key`], in order of first /// appearance: each group is one member of the library's union (the library /// carries enum variants as their enum, and removes duplicates). fn alike_groups(members: &[GoTy]) -> Vec> { let mut groups: Vec<(String, Vec)> = Vec::new(); for (index, member) in members.iter().enumerate() { let key = type_key(member); match groups.iter_mut().find(|(k, _)| *k == key) { Some((_, group)) => group.push(index), None => groups.push((key, vec![index])), } } groups.into_iter().map(|(_, group)| group).collect() } /// Whether the library writes a union of `members` as one plain type, with /// no member index (its members all carry alike). fn collapses(members: &[GoTy]) -> bool { members.len() > 1 && alike_groups(members).len() == 1 } /// The type the library carries for `ty`: enum variants are their enum, /// also inside lists, maps and optionals. Its Go type is the same as `ty`'s. fn erased(ty: &GoTy) -> GoTy { match ty { GoTy::EnumVariant(name, _) => GoTy::Enum(name.clone()), GoTy::List(inner) => GoTy::List(Box::new(erased(inner))), GoTy::Optional(inner) => GoTy::Optional(Box::new(erased(inner))), GoTy::Map { key, value } => GoTy::Map { key: Box::new(erased(key)), value: Box::new(erased(value)), }, other => other.clone(), } } /// Whether a value of `ty` can be told from the other members of its /// group by looking at it (see [`erased`]). fn pickable(ty: &GoTy) -> bool { match ty { GoTy::List(inner) | GoTy::Optional(inner) => pickable(inner), GoTy::Map { key, value } => pickable(key) && pickable(value), GoTy::Tuple(_) | GoTy::TypedUnion(_) | GoTy::DynamicUnion { .. } | GoTy::Json => false, _ => true, } } /// Whether `ty` holds an enum variant, whose values a check must look at. fn narrower_than_erased(ty: &GoTy) -> bool { match ty { GoTy::EnumVariant(..) => true, GoTy::List(inner) | GoTy::Optional(inner) => narrower_than_erased(inner), GoTy::Map { key, value } => narrower_than_erased(key) || narrower_than_erased(value), _ => false, } } /// Where a union site's path starts. #[derive(Clone, Copy)] enum SiteRoot { /// The result of function `index` (manifest order). Func(usize), /// Parameter `param` of function `index` (an encode site). Param(usize, usize), /// Field `field` of type `index` (manifest order). Field(usize, usize), /// Inside union site `index`. Site(usize), } /// The context a decoder is generated in: where its value sits, so union /// sites inside it get their path. #[derive(Clone)] struct Place { root: SiteRoot, path: Vec, } impl Place { fn step(&self, step: impl Into) -> Self { let mut path = self.path.clone(); path.push(step.into()); Self { root: self.root, path, } } } struct SiteOut { root: SiteRoot, path: Vec, members: Option>, } enum TypeOut { Class { name: String, fields: Vec, field_types: Vec, }, Enum { name: String, variants: Vec, }, /// An opaque class: it crosses as a handle. Opaque { name: String, }, } /// One function of the manifest. struct FuncOut { name: String, /// The class of a method (its describe name): `describe` lists methods /// as `Class.method` with the class's id. owner: Option, /// The [`type_key`] of each parameter and of the result. params: Vec, returns: String, /// Type slots the function's values reach (a mismatch fails only them). types: Vec, /// Parameter names and whether each has a default: arguments go by /// position, so a reordered library must be refused. param_names: Vec, defaulted: Vec, } /// Renders the root package's native file and the manifest. pub(crate) struct NativeRenderer<'a> { pool: &'a SymbolPool, names: &'a GoNames, packages: &'a GoPackages, projection: &'a GoTypeProjection<'a>, cyclic_edges: &'a BTreeSet<(Name, Name)>, sdk_import_path: &'a str, root_go: &'a GoPackageName, root_baml: BaseName, imports: GoImports, /// Package-level helpers (codecs). helpers: String, /// Function bodies and option setters. body: String, /// Registrations for the program (run in `init`). registrations: String, funcs: Vec, types: Vec, type_index: HashMap, sites: Vec, /// Typed encoders, by (type, owner package). encoders: HashMap<(GoTy, BaseName), String>, /// Self-describing encoders. dyn_encoders: HashMap<(GoTy, BaseName), String>, /// Value checks of union members the library carries alike. fits: HashMap<(GoTy, BaseName), String>, /// Decoders of values with no union inside (site-independent). decoders: HashMap<(GoTy, BaseName), String>, /// Self-describing decoders (host-call arguments, function value /// results). dyn_decoders: HashMap<(GoTy, BaseName), String>, class_decoders: HashMap, class_encoders: HashMap, enum_codecs: HashMap, counter: usize, } impl<'a> NativeRenderer<'a> { #[allow(clippy::too_many_arguments)] pub(crate) fn new( pool: &'a SymbolPool, names: &'a GoNames, packages: &'a GoPackages, projection: &'a GoTypeProjection<'a>, cyclic_edges: &'a BTreeSet<(Name, Name)>, sdk_import_path: &'a str, root_go: &'a GoPackageName, ) -> Self { Self { pool, names, packages, projection, cyclic_edges, sdk_import_path, root_go, root_baml: BaseName::new("user"), imports: GoImports::default(), helpers: String::new(), body: String::new(), registrations: String::new(), funcs: Vec::new(), types: Vec::new(), type_index: HashMap::new(), sites: Vec::new(), encoders: HashMap::new(), dyn_encoders: HashMap::new(), fits: HashMap::new(), decoders: HashMap::new(), dyn_decoders: HashMap::new(), class_decoders: HashMap::new(), class_encoders: HashMap::new(), enum_codecs: HashMap::new(), counter: 0, } } fn fresh(&mut self, stem: &str) -> String { self.counter += 1; format!("_bamlNative{stem}{}", self.counter) } fn lib_import(&mut self) { self.imports .add_package(&GoPackageName::new(LIB), BAMLLIB_MODULE); } fn runtime_import(&mut self) { self.imports .add_generator(GeneratorIdent::RuntimePackage, BAML_GO_MODULE); } fn native_import(&mut self) { let path = format!("{}/native", self.sdk_import_path); self.imports.add_package(&GoPackageName::new(NATIVE), &path); } /// The Go type of `ty` as written in the root package, for a value whose /// unions and tuples belong to `owner`; adds the imports it needs. fn go_type(&mut self, ty: &GoTy, owner: &BaseName) -> String { let context = TypeImportContext { current_package: self.root_go, pool: self.pool, packages: self.packages, sdk_import_path: self.sdk_import_path, projection: self.projection, }; add_function_surface_imports(ty, owner, &context, &mut self.imports); self.add_nested_imports(ty, owner); render_projected_go_type(ty, owner, self.root_go, self.names, TypeVarScope::default()) } /// Imports for the members of unions and slots of tuples, which the /// codecs spell out (the surface type alone does not). fn add_nested_imports(&mut self, ty: &GoTy, owner: &BaseName) { match ty { GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => { for member in key.members() { let context = TypeImportContext { current_package: self.root_go, pool: self.pool, packages: self.packages, sdk_import_path: self.sdk_import_path, projection: self.projection, }; add_function_surface_imports(member, owner, &context, &mut self.imports); self.add_nested_imports(member, owner); } } GoTy::Tuple(key) => { for slot in key.slots() { let context = TypeImportContext { current_package: self.root_go, pool: self.pool, packages: self.packages, sdk_import_path: self.sdk_import_path, projection: self.projection, }; add_function_surface_imports(slot, owner, &context, &mut self.imports); self.add_nested_imports(slot, owner); } } GoTy::List(inner) | GoTy::Optional(inner) => self.add_nested_imports(inner, owner), GoTy::Map { key, value } => { self.add_nested_imports(key, owner); self.add_nested_imports(value, owner); } GoTy::Function(key) => { for ty in key.component_tys() { let context = TypeImportContext { current_package: self.root_go, pool: self.pool, packages: self.packages, sdk_import_path: self.sdk_import_path, projection: self.projection, }; add_function_surface_imports(ty, owner, &context, &mut self.imports); self.add_nested_imports(ty, owner); } } _ => {} } } /// Imports the Go package that declares the unions and tuples of `owner`. fn use_owner_package(&mut self, owner: &BaseName) { let target = self.packages.get(owner); if target.go_name() != self.root_go { self.imports .add_package(target.go_name(), &target.import_path(self.sdk_import_path)); } } fn class_fields(&self, name: &Name) -> Vec<(String, String, GoTy, bool)> { let Symbol::Class(class) = &self.pool[name] else { unreachable!("a class codec is generated only for a class") }; let fqn = BamlFqn::symbol(name); // A field name is relative to the package that declares the class // (`v.Nanoseconds`, not `v.baml.Nanoseconds`). let owner_go = self.packages.get(name.package()).go_name(); class .properties .iter() .map(|property| { let go = self .names .project( &fqn.member(&property.name), GoNameKind::Field, GoVisibility::Exported, ) .identifier(owner_go) .to_string(); let ty = self.projection.project(&property.ty); let pointer = matches!(&ty, GoTy::Class(target, _) if self.cyclic_edges.contains(&(name.clone(), target.clone()))); (property.name.to_string(), go, ty, pointer) }) .collect() } /// The type slots of the classes and enums values of `ty` reach. fn reach(&mut self, ty: &GoTy, visited: &mut BTreeSet, out: &mut Vec) { match ty { GoTy::Class(name, _) => { if !visited.insert(name.clone()) { return; } out.push(self.type_slot(name)); for (_, _, field, _) in self.class_fields(name) { self.reach(&field, visited, out); } } GoTy::Enum(name) | GoTy::EnumVariant(name, _) | GoTy::Opaque(name, _) => { if visited.insert(name.clone()) { out.push(self.type_slot(name)); } } GoTy::List(inner) | GoTy::Optional(inner) => self.reach(inner, visited, out), GoTy::Map { key, value } => { self.reach(key, visited, out); self.reach(value, visited, out); } GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => { for member in key.members() { self.reach(member, visited, out); } } GoTy::Tuple(key) => { for slot in key.slots() { self.reach(slot, visited, out); } } GoTy::Function(key) => { // Its parameters and result: the library lists what an // exported signature carries, not a function type's throws // (thrown values are read generically). for param in key.required_params() { self.reach(param.ty(), visited, out); } if let Some(ret) = key.ret() { self.reach(ret, visited, out); } } _ => {} } } fn type_slot(&mut self, name: &Name) -> usize { if let Some(&index) = self.type_index.get(name) { return index; } let index = self.types.len(); let out = match &self.pool[name] { Symbol::Class(class) if class.crossing == ClassCrossing::Opaque => TypeOut::Opaque { name: describe_name(name), }, Symbol::Class(class) => TypeOut::Class { name: describe_name(name), fields: class .properties .iter() .map(|p| p.name.to_string()) .collect(), field_types: class .properties .iter() .map(|p| type_key(&self.projection.project(&p.ty))) .collect(), }, Symbol::Enum(enum_) => TypeOut::Enum { name: describe_name(name), variants: enum_.variants.iter().map(|v| v.name.to_string()).collect(), }, _ => unreachable!("only classes and enums have type slots"), }; self.types.push(out); self.type_index.insert(name.clone(), index); index } fn new_site(&mut self, place: &Place, members: Option>) -> usize { let index = self.sites.len(); self.sites.push(SiteOut { root: place.root, path: place.path.clone(), members, }); index } // ------------------------------------------------------------ enums /// (index function, decode function) of an enum. /// The Go constant of enum variant `variant` of `name`. fn variant_ident(&self, name: &Name, variant: &BaseName) -> String { self.names .project( &BamlFqn::symbol(name).member(variant), GoNameKind::EnumVariant, GoVisibility::Exported, ) .identifier(self.root_go) .to_string() } /// A function that reports whether a Go value of the erased type of /// `ty` (see [`erased`]) is a value of `ty`: the variant, the literal, /// every element. Only for types [`narrower_than_erased`]. fn fits_fn(&mut self, ty: &GoTy, owner: &BaseName) -> String { let key = (ty.clone(), owner.clone()); if let Some(function) = self.fits.get(&key) { return function.clone(); } let function = self.fresh("Fits"); self.fits.insert(key, function.clone()); let go = self.go_type(ty, owner); let body = match ty { GoTy::EnumVariant(name, variant) => { format!("\treturn v == {}\n", self.variant_ident(name, variant)) } GoTy::Optional(inner) => { let inner_fn = self.fits_fn(inner, owner); format!("\treturn v == nil || {inner_fn}(*v)\n") } GoTy::List(inner) => { let inner_fn = self.fits_fn(inner, owner); format!( "\tfor _, e := range v {{\n\t\tif !{inner_fn}(e) {{\n\t\t\treturn false\n\t\t}}\n\t}}\n\treturn true\n" ) } GoTy::Map { key, value } => { let key_fn = narrower_than_erased(key).then(|| self.fits_fn(key, owner)); let value_fn = narrower_than_erased(value).then(|| self.fits_fn(value, owner)); let (header, check) = match (key_fn, value_fn) { (Some(k), Some(e)) => ("k, e", format!("!{k}(k) || !{e}(e)")), (Some(k), None) => ("k", format!("!{k}(k)")), (None, Some(e)) => ("_, e", format!("!{e}(e)")), (None, None) => unreachable!(), }; format!( "\tfor {header} := range v {{\n\t\tif {check} {{\n\t\t\treturn false\n\t\t}}\n\t}}\n\treturn true\n" ) } _ => unreachable!(), }; let _ = write!( self.helpers, "func {function}(v {go}) bool {{\n{body}}}\n\n" ); function } fn enum_codec(&mut self, name: &Name) -> (String, String) { if let Some(codec) = self.enum_codecs.get(name) { return codec.clone(); } self.lib_import(); let slot = self.type_slot(name); let index_fn = self.fresh("EnumIndex"); let decode_fn = self.fresh("DecodeEnum"); self.enum_codecs .insert(name.clone(), (index_fn.clone(), decode_fn.clone())); let ty = self.go_type(&GoTy::Enum(name.clone()), name.package()); let Symbol::Enum(enum_) = &self.pool[name] else { unreachable!() }; let fqn = BamlFqn::symbol(name); let variants = enum_ .variants .iter() .map(|variant| { self.names .project( &fqn.member(&variant.name), GoNameKind::EnumVariant, GoVisibility::Exported, ) .identifier(self.root_go) .to_string() }) .collect::>(); let mut out = String::new(); let _ = writeln!( out, "func {index_fn}(w *{LIB}.Writer, v {ty}) uint32 {{\n\tswitch v {{" ); for (index, variant) in variants.iter().enumerate() { let _ = writeln!(out, "\tcase {variant}:\n\t\treturn {index}"); } // The same text as the default back end's error. let wire = self .names .project( &BamlFqn::symbol(name), GoNameKind::Enum, GoVisibility::Exported, ) .wire() .to_string(); let _ = writeln!( out, "\t}}\n\t\u{1}w.Failf(\"invalid BAML enum %q variant %q\", {wire:?}, string(v))\n\treturn 0\n}}\n" ); let _ = writeln!( out, "func {decode_fn}(r *{LIB}.Reader) {ty} {{\n\tswitch \u{1}r.Variant({}) {{", variants.len() ); for (index, variant) in variants.iter().enumerate() { let _ = writeln!(out, "\tcase {index}:\n\t\treturn {variant}"); } let _ = writeln!(out, "\t}}\n\treturn \"\"\n}}\n"); self.helpers.push_str(&out); self.native_import(); let _ = writeln!( self.registrations, "\t{NATIVE}.Program.RegisterDecoder({slot}, func(r *{LIB}.Reader, d int) any {{ return {decode_fn}(\u{1}r) }})" ); let _ = writeln!( self.registrations, "\t{NATIVE}.Program.RegisterEncoder({ty}(\"\"), func(w *{LIB}.Writer, v any, d int) {{ \u{1}w.U8({LIB}.TagEnum); \u{1}w.U32({NATIVE}.Program.TypeID({slot})); \u{1}w.U32({index_fn}(\u{1}w, v.({ty}))) }})" ); (index_fn, decode_fn) } // ------------------------------------------------------------ classes fn class_encoder(&mut self, name: &Name) -> String { if let Some(encoder) = self.class_encoders.get(name) { return encoder.clone(); } self.lib_import(); self.native_import(); let slot = self.type_slot(name); let function = self.fresh("EncodeClass"); self.class_encoders.insert(name.clone(), function.clone()); let owner = name.package().clone(); let ty = self.go_type(&GoTy::Class(name.clone(), Box::new([])), &owner); let mut out = format!( "func {function}(w *{LIB}.Writer, v {ty}, d int) {{\n\tif d >= {LIB}.MaxDepth {{\n\t\t\u{1}w.Failf(\"value is nested deeper than %d levels\", {LIB}.MaxDepth)\n\t\treturn\n\t}}\n" ); for (index, (baml, go, field_ty, pointer)) in self.class_fields(name).into_iter().enumerate() { let place = Place { root: SiteRoot::Field(slot, index), path: Vec::new(), }; let value = if pointer { let _ = writeln!( out, "\tif v.{go} == nil {{\n\t\t\u{1}w.Failf(\"required field {baml} of {} is nil\")\n\t\treturn\n\t}}", describe_name(name) ); format!("*v.{go}") } else { format!("v.{go}") }; out.push_str(&self.encode_stmt(&field_ty, &owner, &value, "d", 1, Some(&place))); } out.push_str("}\n\n"); self.helpers.push_str(&out); let _ = writeln!( self.registrations, "\t{NATIVE}.Program.RegisterEncoder({ty}{{}}, func(w *{LIB}.Writer, v any, d int) {{ \u{1}w.U8({LIB}.TagInstance); \u{1}w.U32({NATIVE}.Program.TypeID({slot})); {function}(\u{1}w, v.({ty}), d+1) }})" ); function } fn class_decoder(&mut self, name: &Name) -> String { if let Some(decoder) = self.class_decoders.get(name) { return decoder.clone(); } self.lib_import(); self.native_import(); let slot = self.type_slot(name); let function = self.fresh("DecodeClass"); self.class_decoders.insert(name.clone(), function.clone()); let owner = name.package().clone(); let ty = self.go_type(&GoTy::Class(name.clone(), Box::new([])), &owner); let mut out = format!( "func {function}(r *{LIB}.Reader, d int) (v {ty}) {{\n\tif !\u{1}r.Enter(d) {{\n\t\treturn v\n\t}}\n" ); for (index, (_, go, field_ty, pointer)) in self.class_fields(name).into_iter().enumerate() { let place = Place { root: SiteRoot::Field(slot, index), path: Vec::new(), }; let expr = self.decode_expr(&field_ty, &owner, &place, "d+1"); if pointer { let _ = writeln!(out, "\t{{\n\t\tx := {expr}\n\t\tv.{go} = &x\n\t}}"); } else { let _ = writeln!(out, "\tv.{go} = {expr}"); } } out.push_str("\treturn v\n}\n\n"); self.helpers.push_str(&out); let _ = writeln!( self.registrations, "\t{NATIVE}.Program.RegisterDecoder({slot}, func(r *{LIB}.Reader, d int) any {{ return {function}(\u{1}r, d) }})" ); function } // ------------------------------------------------------------ encoding /// Statements that write `value` (of type `ty`) in the typed form. With /// a `place`, unions name their member with tag 16 (an encode site); /// without one (inside a value written for `Writer.Any`), they are /// self-describing and the library picks the member. fn encode_stmt( &mut self, ty: &GoTy, owner: &BaseName, value: &str, depth: &str, indent: usize, place: Option<&Place>, ) -> String { let tabs = "\t".repeat(indent); let line = |text: String| format!("{tabs}{text}\n"); match ty { GoTy::String => line(format!("\u{1}w.String({value})")), GoTy::Int => line(format!("\u{1}w.I64({value})")), GoTy::Float => line(format!("\u{1}w.F64({value})")), GoTy::Bool => line(format!("\u{1}w.Bool({value})")), GoTy::Uint8Array => line(format!("\u{1}w.Bytes({value})")), GoTy::Bigint => line(format!("\u{1}w.Bigint({value})")), // A bigint literal crosses as a bigint; any other value is an // error, as for the other literals. GoTy::Literal(GoLiteral::Bigint(_)) => { let literal = self.literal_value(ty); format!( "{tabs}if {value} == nil || {value}.Cmp({literal}) != 0 {{\n{tabs}\t\u{1}w.FailMismatch(\"%v is not the literal %v\", {value}, {literal})\n{tabs}}}\n{tabs}\u{1}w.Bigint({value})\n" ) } GoTy::Null => String::new(), // A literal takes no bytes; a different Go value is an error, not // the literal. GoTy::Literal(_) => { let literal = self.literal_value(ty); format!( "{tabs}if {value} != {literal} {{\n{tabs}\t\u{1}w.FailMismatch(\"%v is not the literal %v\", {value}, {literal})\n{tabs}}}\n" ) } // `json` and a nullable dynamic union are written as an optional // around a self-describing value (unions cross flat: one presence // byte for the whole nullable union). GoTy::DynamicUnion { nullable: true, key, } if place.is_some() && !collapses(key.members()) => { // One presence byte, then the member named (tag 16). let encoder = self.dyn_union_encoder(key, owner, place.expect("place")); format!( "{tabs}if {value} == nil {{\n{tabs}\t\u{1}w.Present(false)\n{tabs}}} else {{\n{tabs}\t\u{1}w.Present(true)\n{tabs}\t{encoder}(\u{1}w, {value}, {depth})\n{tabs}}}\n" ) } GoTy::Json | GoTy::DynamicUnion { nullable: true, .. } => { self.native_import(); if let GoTy::DynamicUnion { key, .. } = ty { self.register_members(key.members(), owner); } format!( "{tabs}if {value} == nil {{\n{tabs}\t\u{1}w.Present(false)\n{tabs}}} else {{\n{tabs}\t\u{1}w.Present(true)\n{tabs}\t\u{1}w.Any({NATIVE}.Program, {value}, {depth})\n{tabs}}}\n" ) } GoTy::DynamicUnion { key, .. } if collapses(key.members()) => { // The library writes the union as the one type its members // carry as (see `collapses`): the typed form of that type, // once the value is one of the members. let members = key.members(); let general = erased(&members[0]); let go = self.go_type(&general, owner); let mut checks = Vec::new(); let mut any_value = false; for member in members { if narrower_than_erased(member) { checks.push(format!("{}(_bamlU_)", self.fits_fn(member, owner))); } else { any_value = true; } } let check = if any_value { String::new() } else { format!( "{tabs}\tif !({}) {{\n{tabs}\t\t\u{1}w.FailMismatch(\"%v is none of the union's members\", _bamlU_)\n{tabs}\t}}\n", checks.join(" || ") ) }; let stmt = self.encode_stmt(&general, owner, "_bamlU_", depth, indent + 1, None); format!( "{tabs}if _bamlU_, ok := {value}.({go}); ok {{\n{check}{stmt}{tabs}}} else {{\n{tabs}\t\u{1}w.Failf(\"a Go %T is not a {}\", {value})\n{tabs}}}\n", go.replace('"', "") ) } GoTy::DynamicUnion { key, .. } if place.is_some() => { let encoder = self.dyn_union_encoder(key, owner, place.expect("place")); line(format!("{encoder}(\u{1}w, {value}, {depth})")) } GoTy::DynamicUnion { key, .. } => { self.native_import(); self.register_members(key.members(), owner); line(format!("\u{1}w.Any({NATIVE}.Program, {value}, {depth})")) } GoTy::Enum(name) => { let (index_fn, _) = self.enum_codec(name); line(format!("\u{1}w.U32({index_fn}(\u{1}w, {value}))")) } // A variant crosses as its enum; another variant is an error, as // for literals. GoTy::EnumVariant(name, variant) => { let (index_fn, _) = self.enum_codec(name); let constant = self.variant_ident(name, variant); format!( "{tabs}if {value} != {constant} {{\n{tabs}\t\u{1}w.FailMismatch(\"%v is not the enum variant %v\", {value}, {constant})\n{tabs}}}\n{tabs}\u{1}w.U32({index_fn}(\u{1}w, {value}))\n" ) } GoTy::Class(name, _) => { let encoder = self.class_encoder(name); line(format!("{encoder}(\u{1}w, {value}, {depth}+1)")) } GoTy::TypedUnion(_) if place.is_some() => { // The member is named (tag 16, the library's index at this // site), then its value in the typed form. let encoder = self.union_encoder(ty, owner, place.expect("place"), false); line(format!("{encoder}(\u{1}w, {value}, {depth})")) } GoTy::TypedUnion(union) if collapses(union.members()) => { // The library writes the union as the one type its members // carry as (an enum and its variants): the typed form of the // arm's value. let encoder = self.collapsed_union_encoder(ty, owner); line(format!("{encoder}(\u{1}w, {value}, {depth})")) } GoTy::TypedUnion(_) => { // Without a site, a union is written self-describing. let encoder = self.dyn_encoder(ty, owner); line(format!("{encoder}(\u{1}w, {value}, {depth})")) } GoTy::HostValue => { self.runtime_import(); format!( "{tabs}if {value} == (baml_go.HostValue{{}}) {{\n{tabs}\t\u{1}w.Failf(\"uninitialized BAML host value\")\n{tabs}}} else {{\n{tabs}\t\u{1}w.HostValue({value}, {value})\n{tabs}}}\n" ) } // An opaque instance: the handle the library issued for it. GoTy::Opaque(..) => { let owner_fn = self.opaque_owner_fn(); line(format!("\u{1}w.Handle({owner_fn}({value}.BAMLInput()))")) } GoTy::Function(key) => match place { Some(place) => { let factory = self.host_fn_factory(key, owner, place); self.native_import(); line(format!( "\u{1}w.HostFn({NATIVE}.Program, {factory}({value}))" )) } None => line("\u{1}w.Failf(\"a function cannot be sent here\")".to_string()), }, GoTy::Optional(inner) => { let inner_place = match inner.as_ref() { GoTy::TypedUnion(_) => place.cloned(), _ => place.map(|place| place.step("o")), }; if matches!(inner.as_ref(), GoTy::Bigint) { format!( "{tabs}\u{1}w.Present({value} != nil)\n{tabs}if {value} != nil {{\n{tabs}\t\u{1}w.Bigint({value})\n{tabs}}}\n" ) } else { // The library counts the optional as a level. let inner_stmt = self.encode_stmt( inner, owner, &format!("(*{value})"), &format!("{depth}+1"), indent + 1, inner_place.as_ref(), ); format!( "{tabs}if {value} == nil {{\n{tabs}\t\u{1}w.Present(false)\n{tabs}}} else {{\n{tabs}\t\u{1}w.Present(true)\n{inner_stmt}{tabs}}}\n" ) } } GoTy::List(_) | GoTy::Map { .. } | GoTy::Tuple(_) => { let encoder = self.container_encoder(ty, owner, place); line(format!("{encoder}(\u{1}w, {value}, {depth})")) } _ => line("\u{1}w.Failf(\"unsupported value\")".to_string()), } } fn container_encoder(&mut self, ty: &GoTy, owner: &BaseName, place: Option<&Place>) -> String { // Unions inside are encode sites of their own place: such an // encoder is not shared. let reusable = place.is_none() || !contains_encode_site(ty); let key = (ty.clone(), owner.clone()); if reusable && let Some(encoder) = self.encoders.get(&key) { return encoder.clone(); } self.lib_import(); let function = self.fresh("Encode"); if reusable { self.encoders.insert(key, function.clone()); } let place = if reusable { None } else { place }; let go = self.go_type(ty, owner); let mut out = format!("func {function}(w *{LIB}.Writer, v {go}, d int) {{\n"); match ty { // Elements that take no bytes (null, literals) need no loop. GoTy::List(inner) => { out.push_str("\t\u{1}w.Len(len(v))\n"); let item = self.encode_stmt( inner, owner, "e", "d+1", 2, place.map(|p| p.step("l")).as_ref(), ); if !item.is_empty() { let _ = write!(out, "\tfor _, e := range v {{\n{item}\t}}\n"); } } GoTy::Map { key, value } => { out.push_str("\t\u{1}w.Len(len(v))\n"); let key_stmt = self.encode_stmt( key, owner, "k", "d+1", 2, place.map(|p| p.step("k")).as_ref(), ); let item = self.encode_stmt( value, owner, "e", "d+1", 2, place.map(|p| p.step("v")).as_ref(), ); let header = match (key_stmt.is_empty(), item.is_empty()) { (true, true) => None, (false, true) => Some("for k := range v"), (true, false) => Some("for _, e := range v"), (false, false) => Some("for k, e := range v"), }; if let Some(header) = header { let _ = write!(out, "\t{header} {{\n{key_stmt}{item}\t}}\n"); } } GoTy::Tuple(tuple) => { for (index, slot) in tuple.slots().iter().enumerate() { out.push_str(&self.encode_stmt( slot, owner, &format!("v.Item{index}"), "d+1", 1, place.map(|p| p.step(format!("t{index}"))).as_ref(), )); } } _ => unreachable!(), } out.push_str("}\n\n"); self.helpers.push_str(&out); function } /// A function that writes a value of `ty` in the self-describing form. fn dyn_encoder(&mut self, ty: &GoTy, owner: &BaseName) -> String { let key = (ty.clone(), owner.clone()); if let Some(encoder) = self.dyn_encoders.get(&key) { return encoder.clone(); } self.lib_import(); let function = self.fresh("EncodeAny"); self.dyn_encoders.insert(key, function.clone()); let go = self.go_type(ty, owner); let mut out = format!("func {function}(w *{LIB}.Writer, v {go}, d int) {{\n"); if let GoTy::TypedUnion(union) = ty { self.use_owner_package(owner); let names: &'a GoNames = self.names; let union_names = names.union(owner, union); let mut clauses = String::new(); let mut uses_value = false; for member in union.members() { let wrapper = union_names .arm(member) .wrapper() .identifier(self.root_go) .to_string(); let _ = writeln!(clauses, "\tcase {wrapper}:"); if matches!(member, GoTy::Literal(_)) { // A literal arm carries no Go value: write the literal. let literal = self.literal_value(member); let stmt = self.dyn_stmt(member, owner, &literal, "d", 2, None); clauses.push_str(&stmt); } else { uses_value = true; let stmt = self.dyn_stmt(member, owner, "a.Value", "d", 2, None); clauses.push_str(&stmt); } } if uses_value { out.push_str("\tswitch a := v.Variant().(type) {\n"); } else { out.push_str("\tswitch v.Variant().(type) {\n"); } out.push_str(&clauses); let _ = writeln!( out, "\tdefault:\n\t\t\u{1}w.Failf(\"zero or invalid {} union value\")\n\t}}\n}}\n", go.rsplit('.').next().unwrap_or(&go) ); self.native_import(); let _ = writeln!( self.registrations, "\t{NATIVE}.Program.RegisterEncoder({go}{{}}, func(w *{LIB}.Writer, v any, d int) {{ {function}(\u{1}w, v.({go}), d) }})" ); } else { out.push_str(&self.dyn_stmt(ty, owner, "v", "d", 1, None)); out.push_str("}\n\n"); if matches!(ty, GoTy::Tuple(tuple) if tuple.is_named()) { // A tuple struct inside `any` (a dynamic union's member). self.native_import(); let _ = writeln!( self.registrations, "\t{NATIVE}.Program.RegisterEncoder({go}{{}}, func(w *{LIB}.Writer, v any, d int) {{ {function}(w, v.({go}), d) }})" ); } } self.helpers.push_str(&out); function } /// Writes a union the library carries as one type (an enum and its /// variants) in that type's typed form. fn collapsed_union_encoder(&mut self, ty: &GoTy, owner: &BaseName) -> String { let key = (ty.clone(), owner.clone()); if let Some(encoder) = self.encoders.get(&key) { return encoder.clone(); } let GoTy::TypedUnion(union) = ty else { unreachable!() }; self.lib_import(); self.use_owner_package(owner); let function = self.fresh("EncodeCollapsedUnion"); self.encoders.insert(key, function.clone()); let go = self.go_type(ty, owner); let names: &'a GoNames = self.names; let union_names = names.union(owner, union); let mut clauses = String::new(); let mut uses_value = false; for member in union.members() { let wrapper = union_names .arm(member) .wrapper() .identifier(self.root_go) .to_string(); // A literal arm writes its literal; any other arm its value in // the member's own typed form, which checks variants. let stmt = if matches!(member, GoTy::Literal(_)) { let literal = self.literal_value(member); self.encode_stmt(&erased(member), owner, &literal, "d", 2, None) } else { uses_value = true; self.encode_stmt(member, owner, "a.Value", "d", 2, None) }; let _ = write!(clauses, "\tcase {wrapper}:\n{stmt}"); } let switch = if uses_value { "switch a := v.Variant().(type)" } else { "switch v.Variant().(type)" }; let _ = writeln!( self.helpers, "func {function}(w *{LIB}.Writer, v {go}, d int) {{\n\t{switch} {{\n{clauses}\tdefault:\n\t\t\u{1}w.Failf(\"zero or invalid {} union value\")\n\t}}\n}}\n", go.rsplit('.').next().unwrap_or(&go) ); function } /// `_bamlNativeOpaqueOwner(input)`: the handle an opaque wrapper holds /// (nil for one the library did not issue, which the writer refuses). fn opaque_owner_fn(&mut self) -> String { let function = "_bamlNativeOpaqueOwner".to_string(); if !self.helpers.contains("func _bamlNativeOpaqueOwner(") { self.lib_import(); self.runtime_import(); let _ = writeln!( self.helpers, "func {function}(in baml_go.Input) *{LIB}.Handle {{\n\towner, _ := baml_go.NativeOpaqueInputOwner(in)\n\th, _ := owner.(*{LIB}.Handle)\n\treturn h\n}}\n" ); } function } /// A function that reads a handle (typed form: a u64) as the generated /// wrapper of opaque class `ty`, which owns it from then on. fn opaque_decoder(&mut self, ty: &GoTy, owner: &BaseName) -> String { let key = (ty.clone(), owner.clone()); if let Some(function) = self.decoders.get(&key) { return function.clone(); } self.lib_import(); self.runtime_import(); let function = self.fresh("DecodeOpaque"); self.decoders.insert(key, function.clone()); let go = self.go_type(ty, owner); let _ = writeln!( self.helpers, "func {function}(r *{LIB}.Reader) (v {go}) {{\n\th := r.Handle()\n\tif h == nil {{\n\t\treturn v\n\t}}\n\tx, err := v.BAMLDecode(baml_go.NativeOpaqueValue(h))\n\tif err != nil {{\n\t\tr.Fail(err)\n\t\treturn v\n\t}}\n\tv, _ = x.({go})\n\treturn v\n}}\n" ); function } /// A function that reads a host value (tag 17 and its token) as the /// `baml_go.HostValue` Go sent. fn host_value_decoder(&mut self) -> String { let function = "_bamlNativeDecodeHostValue".to_string(); if !self.helpers.contains("func _bamlNativeDecodeHostValue(") { self.lib_import(); self.runtime_import(); let _ = writeln!( self.helpers, "func {function}(r *{LIB}.Reader) baml_go.HostValue {{\n\tv, _ := r.HostValue().(baml_go.HostValue)\n\treturn v\n}}\n" ); } function } /// A function that writes a typed union at encode site `place`: tag 16 /// and the library's index of the arm (resolved from `describe` at /// load), then the arm's value in its typed form. Where the library /// carries the union as one type (an enum and its variants), the value /// is written in that type's own form instead (typed, or with `dyn` /// self-describing). fn union_encoder( &mut self, ty: &GoTy, owner: &BaseName, place: &Place, dyn_form: bool, ) -> String { let GoTy::TypedUnion(union) = ty else { unreachable!() }; self.lib_import(); self.native_import(); self.use_owner_package(owner); let members = union.members().to_vec(); let site = self.new_site(place, Some(members.iter().map(type_key).collect())); let child = Place { root: SiteRoot::Site(site), path: Vec::new(), }; let function = self.fresh("EncodeUnion"); let go = self.go_type(ty, owner); let names: &'a GoNames = self.names; let union_names = names.union(owner, union); let wrappers = members .iter() .map(|member| { union_names .arm(member) .wrapper() .identifier(self.root_go) .to_string() }) .collect::>(); let mut out = format!("func {function}(w *{LIB}.Writer, v {go}, d int) {{\n"); if collapses(&members) { // The library carries the whole union as one type. let mut clauses = String::new(); let mut uses_value = false; for (index, member) in members.iter().enumerate() { let stmt = if matches!(member, GoTy::Literal(_)) { let literal = self.literal_value(member); if dyn_form { self.dyn_stmt(member, owner, &literal, "d", 3, None) } else { self.encode_stmt(&erased(member), owner, &literal, "d", 3, None) } } else { uses_value = true; if dyn_form { self.dyn_stmt(member, owner, "a.Value", "d", 3, None) } else { self.encode_stmt(member, owner, "a.Value", "d", 3, None) } }; let _ = write!(clauses, "\t\tcase {}:\n{stmt}", wrappers[index]); } let switch = if uses_value { "switch a := v.Variant().(type)" } else { "switch v.Variant().(type)" }; let _ = write!( out, "\tif \u{1}w.SiteCollapsed({NATIVE}.Program, {site}) {{\n\t\t{switch} {{\n{clauses}\t\tdefault:\n\t\t\t\u{1}w.Failf(\"zero or invalid {} union value\")\n\t\t}}\n\t\treturn\n\t}}\n", go.rsplit('.').next().unwrap_or(&go) ); } let mut clauses = String::new(); let mut uses_value = false; for (index, member) in members.iter().enumerate() { let arm_place = child.step(format!("m{index}")); let stmt = match member { GoTy::Literal(GoLiteral::Bigint(_)) => { let literal = self.literal_value(member); format!("\t\t\u{1}w.Bigint({literal})\n") } GoTy::Literal(_) | GoTy::Null => String::new(), _ => { uses_value = true; self.encode_stmt(member, owner, "a.Value", "d+1", 2, Some(&arm_place)) } }; let _ = write!( clauses, "\tcase {}:\n\t\t\u{1}w.Member({NATIVE}.Program, {site}, {index})\n{stmt}", wrappers[index] ); } let switch = if uses_value { "switch a := v.Variant().(type)" } else { "switch v.Variant().(type)" }; let _ = writeln!( out, "\t{switch} {{\n{clauses}\tdefault:\n\t\t\u{1}w.Failf(\"zero or invalid {} union value\")\n\t}}\n}}\n", go.rsplit('.').next().unwrap_or(&go) ); self.helpers.push_str(&out); function } /// A function that writes a dynamic union (Go `any`) at encode site /// `place`: a type switch over the members' Go types names the member /// (tag 16), then writes its value in the typed form. Members of one Go /// type are told apart by value: literals and enum variants first, then /// the general member. Any other Go value is written self-describing, as /// today, and BAML picks the member or refuses it. fn dyn_union_encoder( &mut self, key: &crate::types::GoUnionKey, owner: &BaseName, place: &Place, ) -> String { self.lib_import(); self.native_import(); let members = key.members().to_vec(); let site = self.new_site(place, Some(members.iter().map(type_key).collect())); let child = Place { root: SiteRoot::Site(site), path: Vec::new(), }; let function = self.fresh("EncodeDynUnion"); // Group by Go type, in member order. let mut groups: Vec<(String, Vec)> = Vec::new(); for (index, member) in members.iter().enumerate() { let go = self.go_type(member, owner); match groups.iter_mut().find(|(g, _)| *g == go) { Some((_, group)) => group.push(index), None => groups.push((go, vec![index])), } } let mut out = format!( "func {function}(w *{LIB}.Writer, v any, d int) {{\n\tswitch x := v.(type) {{\n" ); for (go, group) in &groups { let _ = writeln!(out, "\tcase {go}:\n\t\t_ = x"); let mut narrow = group .iter() .copied() .filter(|&index| matches!(members[index], GoTy::Literal(_) | GoTy::EnumVariant(..))) .collect::>(); narrow.sort_unstable(); let general = group .iter() .copied() .find(|&index| !matches!(members[index], GoTy::Literal(_) | GoTy::EnumVariant(..))); for index in narrow { let check = match &members[index] { GoTy::Literal(GoLiteral::Bigint(_)) => { let literal = self.literal_value(&members[index]); format!("x != nil && x.Cmp({literal}) == 0") } GoTy::Literal(GoLiteral::Int(value)) => format!("x == int64({value})"), GoTy::Literal(_) => { let literal = self.literal_value(&members[index]); format!("x == {literal}") } GoTy::EnumVariant(name, variant) => { format!("x == {}", self.variant_ident(name, variant)) } _ => unreachable!(), }; let stmt = self.encode_stmt( &members[index], owner, "x", "d+1", 3, Some(&child.step(format!("m{index}"))), ); let _ = write!( out, "\t\tif {check} {{\n\t\t\t\u{1}w.Member({NATIVE}.Program, {site}, {index})\n{stmt}\t\t\treturn\n\t\t}}\n" ); } match general { Some(index) => { let stmt = self.encode_stmt( &members[index], owner, "x", "d+1", 2, Some(&child.step(format!("m{index}"))), ); let _ = write!( out, "\t\t\u{1}w.Member({NATIVE}.Program, {site}, {index})\n{stmt}" ); } None => { // As today: BAML checks a value of no member. let _ = writeln!(out, "\t\t\u{1}w.Any({NATIVE}.Program, v, d)"); } } } // Any other Go value (an `int`, a `[]any`, ...) is written plain, as // the default back end does, and BAML picks the member or refuses it. self.register_members(&members, owner); let _ = writeln!( out, "\tdefault:\n\t\t\u{1}w.Any({NATIVE}.Program, v, d)\n\t}}\n}}\n" ); self.helpers.push_str(&out); function } /// A function that turns a Go function of the callback type `key` into /// the host function adapter the library calls: it reads the /// self-describing arguments, calls the Go function with the call's /// context, and writes the result (or what it threw) self-describing, /// naming union members at the sites under `place` (the parameter that /// takes the function: `r` its result, `x` its throws). nil stays nil /// (the argument then fails with "host callable is nil"). fn host_fn_factory(&mut self, key: &GoFunctionKey, owner: &BaseName, place: &Place) -> String { self.lib_import(); self.native_import(); self.runtime_import(); self.imports .add_generator(GeneratorIdent::ContextPackage, "context"); let function = self.fresh("HostFn"); let go = self.callback_go_type(key, owner); let params = key.required_params().collect::>(); let mut body = format!( "func {function}(f {go}) {LIB}.HostFn {{\n\tif f == nil {{\n\t\treturn nil\n\t}}\n\treturn func(ctx context.Context, r *{LIB}.Reader, w *{LIB}.Writer) uint32 {{\n\t\tif !r.Count({}) {{\n\t\t\treturn w.ArgumentError({NATIVE}.Program, r.Err())\n\t\t}}\n", params.len() ); let mut call_args = vec!["ctx".to_string()]; for (index, param) in params.iter().enumerate() { let expr = self.dyn_decode_expr( param.ty(), owner, "1", Some(&place.step(format!("p{index}"))), ); let _ = writeln!(body, "\t\ta{index} := {expr}"); call_args.push(format!("a{index}")); } let _ = writeln!( body, "\t\tif err := r.Err(); err != nil {{\n\t\t\treturn w.ArgumentError({NATIVE}.Program, err)\n\t\t}}" ); let call = format!("f({})", call_args.join(", ")); let returns_error = key.throws().returns_error(); let has_value = key.ret().is_some(); match (has_value, returns_error) { (true, true) => { let _ = writeln!(body, "\t\tresult, err := {call}"); } (true, false) => { let _ = writeln!(body, "\t\tresult := {call}"); } (false, true) => { let _ = writeln!(body, "\t\terr := {call}"); } (false, false) => { let _ = writeln!(body, "\t\t{call}"); } } if returns_error { body.push_str("\t\tif err != nil {\n"); if let Some(thrown) = key.throws().thrown() { // A value thrown with baml_go.Throw as the declared Go type // crosses as the declared throws type. let thrown_go = self.go_type(thrown, owner); let stmt = self.dyn_stmt(thrown, owner, "t.Value", "0", 4, Some(&place.step("x"))); let _ = write!( body, "\t\t\tif t, ok := err.(*baml_go.ThrownValue[{thrown_go}]); ok {{\n{stmt}\t\t\t\tif err := w.Err(); err != nil {{\n\t\t\t\t\treturn w.ContractViolation({NATIVE}.Program, \"the callable's thrown value does not inhabit its declared type: \"+err.Error())\n\t\t\t\t}}\n\t\t\t\treturn {LIB}.ReplyThrew\n\t\t\t}}\n" ); } let _ = writeln!( body, "\t\t\treturn w.Failure({NATIVE}.Program, err)\n\t\t}}" ); } match key.returns() { GoCallbackReturn::Value(ret) => { let stmt = self.dyn_stmt(ret, owner, "result", "0", 2, Some(&place.step("r"))); body.push_str(&stmt); // A result the SDK cannot write broke the declared contract, // as the default back end reports it. let _ = writeln!( body, "\t\tif err := w.Err(); err != nil {{\n\t\t\treturn w.ContractViolation({NATIVE}.Program, \"the callable's result does not inhabit its declared type: \"+err.Error())\n\t\t}}" ); } GoCallbackReturn::Null => { let _ = writeln!(body, "\t\t\u{1}w.U8({LIB}.TagNull)"); } GoCallbackReturn::Never => { let _ = writeln!( body, "\t\treturn w.ContractViolation({NATIVE}.Program, \"BAML host callable declared to return never returned\")" ); } } if !matches!(key.returns(), GoCallbackReturn::Never) { let _ = writeln!(body, "\t\treturn {LIB}.ReplyReturned"); } let _ = writeln!(body, "\t}}\n}}\n"); self.helpers.push_str(&body); function } /// The Go function type of a callback parameter. fn callback_go_type(&mut self, key: &GoFunctionKey, owner: &BaseName) -> String { self.add_nested_imports(&GoTy::Function(key.clone()), owner); for ty in key.component_tys() { self.go_type(ty, owner); } crate::render_callback_go_type( key, owner, self.root_go, self.names, TypeVarScope::default(), ) } /// An expression that wraps a function value BAML returned (its handle, /// read from the result) in today's surface, a /// `baml_go.ReturnedFunction` whose `Call` calls it through the library /// (target kind 1): self-describing arguments, naming union members at /// the sites under `place` (the function's result: `p` its /// parameters), and a self-describing result. A failure is returned when /// the function type's Go surface returns an error, and panics /// otherwise, as the default back end does. fn closure_expr(&mut self, key: &GoFunctionKey, owner: &BaseName, place: &Place) -> String { self.lib_import(); self.native_import(); self.runtime_import(); self.imports .add_generator(GeneratorIdent::ContextPackage, "context"); let function = self.fresh("Closure"); for ty in key.component_tys() { self.go_type(ty, owner); } let returned = crate::render_returned_callback_go_type( key, owner, self.root_go, self.names, TypeVarScope::default(), ); let params = key.required_params().collect::>(); let mut parameters = vec!["ctx context.Context".to_string()]; for (index, param) in params.iter().enumerate() { let go = self.go_type(param.ty(), owner); parameters.push(format!("a{index} {go}")); } parameters.push("options_ ...baml_go.CallOption".to_string()); let returns_error = key.throws().returns_error(); let ret_go = key.ret().map(|ret| self.go_type(ret, owner)); let results = match (&ret_go, returns_error) { (Some(ret), true) => format!(" ({ret}, error)"), (Some(ret), false) => format!(" {ret}"), (None, true) => " error".to_string(), (None, false) => String::new(), }; let fail = |err: &str| match (&ret_go, returns_error) { (Some(_), true) => format!("return zero, {err}"), (None, true) => format!("return {err}"), (_, false) => format!("panic({err})"), }; // Where the function type's throws is in `describe`: a union in a // thrown value can arrive as tag 16. let throws_site = self.new_site(&place.step("x"), None); let mut body = format!( "func {function}(h *{LIB}.Handle) {returned} {{\n\treturn baml_go.NewReturnedFunction(baml_go.Function{{}}, func({}){results} {{\n", parameters.join(", ") ); if let Some(ret) = &ret_go { let _ = writeln!(body, "\t\tvar zero {ret}\n\t\t_ = zero"); } let _ = writeln!( body, "\t\t_, timeout, err := baml_go.NativeArguments(\"\", options_)\n\t\tif err != nil {{\n\t\t\t{}\n\t\t}}\n\t\tc, err := {NATIVE}.Program.BeginValue(ctx, h, timeout)\n\t\tif err != nil {{\n\t\t\t{}\n\t\t}}\n\t\tc.ThrowsAt({throws_site})\n\t\t\u{1}w := c.Writer()\n\t\t\u{1}w.U32({})", fail("err"), fail("err"), params.len() ); for (index, param) in params.iter().enumerate() { let stmt = self.dyn_stmt( param.ty(), owner, &format!("a{index}"), "0", 2, Some(&place.step(format!("p{index}"))), ); body.push_str(&stmt); } let _ = writeln!( body, "\t\t\u{1}r, err := c.Run()\n\t\tif err != nil {{\n\t\t\t{}\n\t\t}}", fail("err") ); match key.ret() { Some(ret) => { let expr = self.dyn_decode_expr(ret, owner, "0", Some(&place.step("r"))); let _ = writeln!(body, "\t\tresult := {expr}"); } None => { let _ = writeln!(body, "\t\t\u{1}r.Tag({LIB}.TagNull)"); } } let _ = writeln!( body, "\t\tif err := c.End(); err != nil {{\n\t\t\t{}\n\t\t}}", fail("err") ); match (key.ret().is_some(), returns_error) { (true, true) => body.push_str("\t\treturn result, nil\n"), (true, false) => body.push_str("\t\treturn result\n"), (false, true) => body.push_str("\t\treturn nil\n"), (false, false) => {} } body.push_str("\t})\n}\n\n"); self.helpers.push_str(&body); format!("{function}(\u{1}r.Handle())") } /// An expression that reads a value of `ty` in the self-describing form /// (a host call's argument, a function value's result) as its Go type. /// A union member is told apart by the value: narrower members (a /// literal, an enum variant) are tried first, then the others in order. fn dyn_decode_expr( &mut self, ty: &GoTy, owner: &BaseName, depth: &str, place: Option<&Place>, ) -> String { let simple = match ty { GoTy::String => Some("\u{1}r.SDString()".to_string()), GoTy::Int => Some("\u{1}r.SDInt()".to_string()), GoTy::Float => Some("\u{1}r.SDFloat()".to_string()), GoTy::Bool => Some("\u{1}r.SDBool()".to_string()), GoTy::Uint8Array => Some("\u{1}r.SDBytes()".to_string()), GoTy::Bigint => Some("\u{1}r.SDBigint()".to_string()), GoTy::Json => Some(format!("\u{1}r.Any({depth})")), GoTy::DynamicUnion { .. } if place.is_none() => Some(format!("\u{1}r.Any({depth})")), _ => None, }; if let Some(expr) = simple { self.lib_import(); return expr; } // With a place, unions inside are sites of their own (tag 16 from // the library names their member): such a decoder is not shared. let reusable = place.is_none() || !contains_site(ty); let place = if reusable { None } else { place }; let key = (ty.clone(), owner.clone()); if reusable && let Some(function) = self.dyn_decoders.get(&key) { return format!("{function}(\u{1}r, {depth})"); } self.lib_import(); let function = self.fresh("DecodeAny"); if reusable { self.dyn_decoders.insert(key, function.clone()); } let go = self.go_type(ty, owner); let mut out = format!( "func {function}(r *{LIB}.Reader, d int) (v {go}) {{\n\tif !\u{1}r.Enter(d) {{\n\t\treturn v\n\t}}\n" ); // At a union position, the member form: tag 16, the library's index // at this site, then the member's typed form. if let (GoTy::TypedUnion(_) | GoTy::DynamicUnion { .. }, Some(place)) = (ty, place) { let site_fn = self.union_site_form(ty, owner, place, false, false); let _ = writeln!( out, "\tif \u{1}r.PeekTag() == {LIB}.TagMember {{\n\t\t\u{1}r.U8()\n\t\treturn {site_fn}(\u{1}r, d)\n\t}}" ); } match ty { GoTy::Null => { self.runtime_import(); let _ = writeln!(out, "\t\u{1}r.Tag({LIB}.TagNull)\n\treturn v\n}}\n"); } GoTy::Literal(literal) => { let (read, value) = match literal { GoLiteral::String(_) => ("\u{1}r.SDString()", self.literal_value(ty)), GoLiteral::Int(value) => ("\u{1}r.SDInt()", format!("int64({value})")), GoLiteral::Bool(_) => ("\u{1}r.SDBool()", self.literal_value(ty)), GoLiteral::Float(_) => ("\u{1}r.SDFloat()", self.literal_value(ty)), GoLiteral::Bigint(_) => ("\u{1}r.SDBigint()", self.literal_value(ty)), }; let check = if matches!(literal, GoLiteral::Bigint(_)) { format!("x == nil || x.Cmp({value}) != 0") } else { format!("x != {value}") }; let _ = writeln!( out, "\tx := {read}\n\tif \u{1}r.Err() == nil && ({check}) {{\n\t\t\u{1}r.Failf(\"%v is not the literal %v\", x, {value})\n\t}}\n\treturn {value}\n}}\n" ); } GoTy::Enum(name) | GoTy::EnumVariant(name, _) => { let (_, decode) = self.enum_codec(name); let slot = self.type_slot(name); let check = match ty { GoTy::EnumVariant(_, variant) => { let constant = self.variant_ident(name, variant); format!( "\tif \u{1}r.Err() == nil && v != {constant} {{\n\t\t\u{1}r.Failf(\"%v is not the enum variant %v\", v, {constant})\n\t}}\n" ) } _ => String::new(), }; let _ = writeln!( out, "\tif \u{1}r.Tag({LIB}.TagEnum) != {LIB}.TagEnum || !\u{1}r.TypeID({slot}) {{\n\t\treturn v\n\t}}\n\tv = {decode}(\u{1}r)\n{check}\treturn v\n}}\n" ); } GoTy::Class(name, _) => { let decoder = self.class_decoder(name); let slot = self.type_slot(name); let _ = writeln!( out, "\tif \u{1}r.Tag({LIB}.TagInstance) != {LIB}.TagInstance || !\u{1}r.TypeID({slot}) {{\n\t\treturn v\n\t}}\n\treturn {decoder}(\u{1}r, d)\n}}\n" ); } GoTy::HostValue => { self.runtime_import(); let _ = writeln!( out, "\tv, _ = \u{1}r.HostValue().(baml_go.HostValue)\n\treturn v\n}}\n" ); } GoTy::Opaque(name, _) => { let slot = self.type_slot(name); let decoder = self.opaque_decoder(ty, owner); let _ = writeln!( out, "\tif \u{1}r.Tag({LIB}.TagInstance) != {LIB}.TagInstance || !\u{1}r.TypeID({slot}) {{\n\t\treturn v\n\t}}\n\treturn {decoder}(\u{1}r)\n}}\n" ); } GoTy::Optional(inner) => { let inner_place = match inner.as_ref() { GoTy::TypedUnion(_) | GoTy::DynamicUnion { .. } => place.cloned(), _ => place.map(|place| place.step("o")), }; let expr = self.dyn_decode_expr(inner, owner, "d+1", inner_place.as_ref()); let tail = if matches!(inner.as_ref(), GoTy::Bigint) { format!("\treturn {expr}\n") } else { format!("\tx := {expr}\n\treturn &x\n") }; let _ = writeln!( out, "\tif \u{1}r.PeekTag() == {LIB}.TagNull {{\n\t\t\u{1}r.U8()\n\t\treturn nil\n\t}}\n{tail}}}\n" ); } GoTy::List(inner) => { let expr = self.dyn_decode_expr(inner, owner, "d+1", place.map(|p| p.step("l")).as_ref()); let _ = writeln!( out, "\tif \u{1}r.Tag({LIB}.TagList) != {LIB}.TagList {{\n\t\treturn v\n\t}}\n\tv = make({go}, \u{1}r.Len())\n\tfor i := range v {{\n\t\tif \u{1}r.Err() != nil {{\n\t\t\tbreak\n\t\t}}\n\t\tv[i] = {expr}\n\t}}\n\treturn v\n}}\n" ); } GoTy::Map { key, value } => { let key_expr = self.dyn_decode_expr(key, owner, "d+1", place.map(|p| p.step("k")).as_ref()); let value_expr = self.dyn_decode_expr(value, owner, "d+1", place.map(|p| p.step("v")).as_ref()); let _ = writeln!( out, "\tif \u{1}r.Tag({LIB}.TagMap) != {LIB}.TagMap {{\n\t\treturn v\n\t}}\n\tn := \u{1}r.Len()\n\tv = make({go}, n)\n\tfor i := 0; i < n && \u{1}r.Err() == nil; i++ {{\n\t\tk := {key_expr}\n\t\tv[k] = {value_expr}\n\t}}\n\treturn v\n}}\n" ); } GoTy::Tuple(tuple) => { let _ = writeln!( out, "\tif \u{1}r.Tag({LIB}.TagTuple) != {LIB}.TagTuple {{\n\t\treturn v\n\t}}\n\tif n := \u{1}r.Len(); \u{1}r.Err() == nil && n != {} {{\n\t\t\u{1}r.Failf(\"a tuple of %d items where %d were expected\", n, {})\n\t\treturn v\n\t}}", tuple.slots().len(), tuple.slots().len() ); for (index, slot) in tuple.slots().iter().enumerate() { let expr = self.dyn_decode_expr( slot, owner, "d+1", place.map(|p| p.step(format!("t{index}"))).as_ref(), ); let _ = writeln!(out, "\tv.Item{index} = {expr}"); } out.push_str("\treturn v\n}\n"); } GoTy::DynamicUnion { .. } => { let _ = writeln!(out, "\treturn \u{1}r.Any(d)\n}}\n"); } GoTy::TypedUnion(union) => { self.use_owner_package(owner); let names: &'a GoNames = self.names; let union_names = names.union(owner, union); let members = union.members().to_vec(); // Narrower members first: a value that fits a literal or an // enum variant is that member. let mut order = (0..members.len()).collect::>(); order.sort_by_key(|&index| { !matches!(members[index], GoTy::Literal(_) | GoTy::EnumVariant(..)) }); out.push_str("\tmark := \u{1}r.Mark()\n"); for index in order { let member = &members[index]; let constructor = union_names .arm(member) .constructor() .identifier(self.root_go) .to_string(); let expr = self.dyn_decode_expr(member, owner, "d+1", None); let value = if matches!(member, GoTy::Literal(_)) { format!("{constructor}()") } else { format!("{constructor}(x)") }; let _ = writeln!( out, "\tif x := {expr}; \u{1}r.Err() == nil {{\n\t\t_ = x\n\t\treturn {value}\n\t}}\n\t\u{1}r.Reset(mark)" ); } let _ = writeln!( out, "\t\u{1}r.Failf(\"the value is none of the union's members\")\n\treturn v\n}}\n" ); } _ => { let _ = writeln!( out, "\t\u{1}r.Failf(\"values of this type cannot cross natively\")\n\treturn v\n}}\n" ); } } self.helpers.push_str(&out); format!("{function}(\u{1}r, {depth})") } /// A dynamic union is written with `Writer.Any`, which finds the /// generated types it can hold through their registered encoders. fn register_members(&mut self, members: &[GoTy], owner: &BaseName) { for member in members { match member { GoTy::Class(name, arguments) if arguments.is_empty() => { self.class_encoder(name); } GoTy::Enum(name) | GoTy::EnumVariant(name, _) => { self.enum_codec(name); } GoTy::TypedUnion(_) => { self.dyn_encoder(member, owner); } GoTy::List(inner) | GoTy::Optional(inner) => { self.register_members(std::slice::from_ref(inner.as_ref()), owner); } GoTy::Map { key, value } => { self.register_members(&[key.as_ref().clone(), value.as_ref().clone()], owner); } GoTy::Tuple(tuple) => { self.register_members(tuple.slots(), owner); if tuple.is_named() { self.dyn_encoder(member, owner); } } _ => {} } } } fn literal_value(&mut self, ty: &GoTy) -> String { let GoTy::Literal(literal) = ty else { unreachable!() }; if matches!(literal, GoLiteral::Bigint(_) | GoLiteral::Float(_)) { self.runtime_import(); } render_go_literal_value(literal, &GeneratorIdent::RuntimePackage.to_string()) } /// Statements that write `value` in the self-describing form (with a /// `place`, unions name their member: tag 16). fn dyn_stmt( &mut self, ty: &GoTy, owner: &BaseName, value: &str, depth: &str, indent: usize, place: Option<&Place>, ) -> String { let tabs = "\t".repeat(indent); let tagged = |tag: &str, write: String| format!("{tabs}\u{1}w.U8({LIB}.{tag})\n{tabs}{write}\n"); match ty { GoTy::Null => format!("{tabs}\u{1}w.U8({LIB}.TagNull)\n"), GoTy::String | GoTy::Literal(GoLiteral::String(_)) => { tagged("TagString", format!("\u{1}w.String({value})")) } GoTy::Int | GoTy::Literal(GoLiteral::Int(_)) => { tagged("TagInt", format!("\u{1}w.I64({value})")) } GoTy::Float | GoTy::Literal(GoLiteral::Float(_)) => { tagged("TagFloat", format!("\u{1}w.F64({value})")) } GoTy::Bool | GoTy::Literal(GoLiteral::Bool(_)) => { tagged("TagBool", format!("\u{1}w.Bool({value})")) } GoTy::Uint8Array => tagged("TagBytes", format!("\u{1}w.Bytes({value})")), GoTy::Bigint | GoTy::Literal(GoLiteral::Bigint(_)) => { tagged("TagBigint", format!("\u{1}w.Bigint({value})")) } GoTy::Json | GoTy::DynamicUnion { .. } => { self.native_import(); format!("{tabs}\u{1}w.Any({NATIVE}.Program, {value}, {depth})\n") } GoTy::Enum(name) | GoTy::EnumVariant(name, _) => { self.native_import(); let (index_fn, _) = self.enum_codec(name); let slot = self.type_slot(name); let check = match ty { GoTy::EnumVariant(_, variant) => { let constant = self.variant_ident(name, variant); format!( "{tabs}if {value} != {constant} {{\n{tabs}\t\u{1}w.FailMismatch(\"%v is not the enum variant %v\", {value}, {constant})\n{tabs}}}\n" ) } _ => String::new(), }; format!( "{check}{tabs}\u{1}w.U8({LIB}.TagEnum)\n{tabs}\u{1}w.U32({NATIVE}.Program.TypeID({slot}))\n{tabs}\u{1}w.U32({index_fn}(\u{1}w, {value}))\n" ) } GoTy::Class(name, _) => { self.native_import(); let encoder = self.class_encoder(name); let slot = self.type_slot(name); format!( "{tabs}\u{1}w.U8({LIB}.TagInstance)\n{tabs}\u{1}w.U32({NATIVE}.Program.TypeID({slot}))\n{tabs}{encoder}(\u{1}w, {value}, {depth}+1)\n" ) } GoTy::HostValue => { self.runtime_import(); format!( "{tabs}if {value} == (baml_go.HostValue{{}}) {{\n{tabs}\t\u{1}w.Failf(\"uninitialized BAML host value\")\n{tabs}}} else {{\n{tabs}\t\u{1}w.HostValue({value}, {value})\n{tabs}}}\n" ) } GoTy::Opaque(name, _) => { self.native_import(); let slot = self.type_slot(name); let owner_fn = self.opaque_owner_fn(); format!( "{tabs}\u{1}w.U8({LIB}.TagInstance)\n{tabs}\u{1}w.U32({NATIVE}.Program.TypeID({slot}))\n{tabs}\u{1}w.Handle({owner_fn}({value}.BAMLInput()))\n" ) } GoTy::Optional(inner) => { let deref = if matches!(inner.as_ref(), GoTy::Bigint) { value.to_string() } else { format!("(*{value})") }; let inner_place = match inner.as_ref() { GoTy::TypedUnion(_) => place.cloned(), _ => place.map(|place| place.step("o")), }; let inner_stmt = self.dyn_stmt( inner, owner, &deref, depth, indent + 1, inner_place.as_ref(), ); format!( "{tabs}if {value} == nil {{\n{tabs}\t\u{1}w.U8({LIB}.TagNull)\n{tabs}}} else {{\n{inner_stmt}{tabs}}}\n" ) } GoTy::TypedUnion(_) if place.is_some() && MEMBER_FORM_IN_SELF_DESCRIBING => { let encoder = self.union_encoder(ty, owner, place.expect("place"), true); format!("{tabs}{encoder}(\u{1}w, {value}, {depth}+1)\n") } GoTy::TypedUnion(_) => { let encoder = self.dyn_encoder(ty, owner); format!("{tabs}{encoder}(\u{1}w, {value}, {depth}+1)\n") } GoTy::List(inner) => { let inner_stmt = self.dyn_stmt( inner, owner, "e", &format!("{depth}+1"), indent + 1, place.map(|p| p.step("l")).as_ref(), ); format!( "{tabs}\u{1}w.U8({LIB}.TagList)\n{tabs}\u{1}w.Len(len({value}))\n{tabs}for _, e := range {value} {{\n{tabs}\t_ = e\n{inner_stmt}{tabs}}}\n" ) } GoTy::Map { key, value: item } => { let key_stmt = self.dyn_stmt( key, owner, "k", &format!("{depth}+1"), indent + 1, place.map(|p| p.step("k")).as_ref(), ); let item_stmt = self.dyn_stmt( item, owner, "e", &format!("{depth}+1"), indent + 1, place.map(|p| p.step("v")).as_ref(), ); format!( "{tabs}\u{1}w.U8({LIB}.TagMap)\n{tabs}\u{1}w.Len(len({value}))\n{tabs}for k, e := range {value} {{\n{tabs}\t_, _ = k, e\n{key_stmt}{item_stmt}{tabs}}}\n" ) } GoTy::Tuple(tuple) => { let mut out = format!( "{tabs}\u{1}w.U8({LIB}.TagTuple)\n{tabs}\u{1}w.Len({})\n", tuple.slots().len() ); for (index, slot) in tuple.slots().iter().enumerate() { out.push_str(&self.dyn_stmt( slot, owner, &format!("{value}.Item{index}"), depth, indent, place.map(|p| p.step(format!("t{index}"))).as_ref(), )); } out } _ => format!("{tabs}\u{1}w.Failf(\"unsupported value\")\n"), } } // ------------------------------------------------------------ decoding /// An expression that reads a value of `ty` (typed form) at `place`. fn decode_expr(&mut self, ty: &GoTy, owner: &BaseName, place: &Place, depth: &str) -> String { match ty { GoTy::String => "\u{1}r.String()".to_string(), GoTy::Int => "\u{1}r.I64()".to_string(), GoTy::Float => "\u{1}r.F64()".to_string(), GoTy::Bool => "\u{1}r.Bool()".to_string(), GoTy::Uint8Array => "\u{1}r.Bytes()".to_string(), GoTy::Bigint => "\u{1}r.Bigint()".to_string(), GoTy::Literal(GoLiteral::Bigint(_)) => { let literal = self.literal_value(ty); format!("\u{1}r.BigintLiteral({literal})") } GoTy::Null => { self.runtime_import(); format!("{}.Null{{}}", GeneratorIdent::RuntimePackage) } // Typed, so `result_ := ...` has the Go type of the surface. GoTy::Literal(GoLiteral::Int(value)) => format!("int64({value})"), GoTy::Literal(_) => self.literal_value(ty), GoTy::Json => { let site = self.new_site(place, None); format!("\u{1}r.Dynamic({site}, {depth})") } GoTy::HostValue => { self.runtime_import(); format!("{}(\u{1}r)", self.host_value_decoder()) } GoTy::Opaque(..) => { let decoder = self.opaque_decoder(ty, owner); format!("{decoder}(\u{1}r)") } GoTy::Function(key) => self.closure_expr(key, owner, place), GoTy::Enum(name) | GoTy::EnumVariant(name, _) => { let (_, decode) = self.enum_codec(name); format!("{decode}(\u{1}r)") } GoTy::Class(name, _) => { let decoder = self.class_decoder(name); format!("{decoder}(\u{1}r, {depth})") } GoTy::TypedUnion(_) | GoTy::DynamicUnion { .. } => { let function = self.union_site(ty, owner, place, false); format!("{function}(\u{1}r, {depth})") } GoTy::Optional(inner) if matches!( inner.as_ref(), GoTy::TypedUnion(_) | GoTy::DynamicUnion { .. } ) => { let function = self.union_site(inner, owner, place, true); format!("{function}(\u{1}r, {depth})") } GoTy::Optional(_) | GoTy::List(_) | GoTy::Map { .. } | GoTy::Tuple(_) => { let function = self.container_decoder(ty, owner, place); format!("{function}(\u{1}r, {depth})") } _ => "nil /* unsupported */".to_string(), } } fn container_decoder(&mut self, ty: &GoTy, owner: &BaseName, place: &Place) -> String { let reusable = !contains_site(ty); let key = (ty.clone(), owner.clone()); if reusable && let Some(decoder) = self.decoders.get(&key) { return decoder.clone(); } self.lib_import(); let function = self.fresh("Decode"); if reusable { self.decoders.insert(key, function.clone()); } let go = self.go_type(ty, owner); let mut out = format!( "func {function}(r *{LIB}.Reader, d int) (v {go}) {{\n\tif !\u{1}r.Enter(d) {{\n\t\treturn v\n\t}}\n" ); match ty { GoTy::Optional(inner) => { let expr = self.decode_expr(inner, owner, &place.step("o"), "d+1"); if matches!(inner.as_ref(), GoTy::Bigint) { let _ = writeln!( out, "\tif !\u{1}r.Present() {{\n\t\treturn nil\n\t}}\n\treturn {expr}\n}}\n" ); } else { let _ = writeln!( out, "\tif !\u{1}r.Present() {{\n\t\treturn nil\n\t}}\n\tx := {expr}\n\treturn &x\n}}\n" ); } } GoTy::List(inner) => { let expr = self.decode_expr(inner, owner, &place.step("l"), "d+1"); let _ = writeln!( out, "\tv = make({go}, \u{1}r.Len())\n\tfor i := range v {{\n\t\tif \u{1}r.Err() != nil {{\n\t\t\tbreak\n\t\t}}\n\t\tv[i] = {expr}\n\t}}\n\treturn v\n}}\n" ); } GoTy::Map { key, value } => { let key_expr = self.decode_expr(key, owner, &place.step("k"), "d+1"); let value_expr = self.decode_expr(value, owner, &place.step("v"), "d+1"); let _ = writeln!( out, "\tn := \u{1}r.Len()\n\tv = make({go}, n)\n\tfor i := 0; i < n && \u{1}r.Err() == nil; i++ {{\n\t\tk := {key_expr}\n\t\tv[k] = {value_expr}\n\t}}\n\treturn v\n}}\n" ); } GoTy::Tuple(tuple) => { for (index, slot) in tuple.slots().iter().enumerate() { let expr = self.decode_expr(slot, owner, &place.step(format!("t{index}")), "d+1"); let _ = writeln!(out, "\tv.Item{index} = {expr}"); } out.push_str("\treturn v\n}\n"); } _ => unreachable!(), } out.push('\n'); self.helpers.push_str(&out); function } /// A function that reads the union of type `ty` at `place`. With /// `nullable`, the Go value is a pointer (nil for null); a dynamic union /// is `any` either way (nil for null). fn union_site(&mut self, ty: &GoTy, owner: &BaseName, place: &Place, nullable: bool) -> String { self.union_site_form(ty, owner, place, nullable, true) } /// `union_site`, with `presence` false for the member form after tag 16 /// in a self-describing value: no presence byte (null is tag 0 there). fn union_site_form( &mut self, ty: &GoTy, owner: &BaseName, place: &Place, nullable: bool, presence: bool, ) -> String { self.lib_import(); let members = match ty { GoTy::TypedUnion(key) | GoTy::DynamicUnion { key, .. } => key.members().to_vec(), _ => unreachable!(), }; let site = self.new_site(place, Some(members.iter().map(type_key).collect())); let function = self.fresh("DecodeUnion"); let go = self.go_type(ty, owner); let typed = matches!(ty, GoTy::TypedUnion(_)); let result = if typed && nullable { format!("*{go}") } else { go }; let child = Place { root: SiteRoot::Site(site), path: Vec::new(), }; let mut out = format!( "func {function}(r *{LIB}.Reader, d int) (v {result}) {{\n\tif !\u{1}r.Enter(d) {{\n\t\treturn v\n\t}}\n" ); if presence { let _ = writeln!( out, "\tif \u{1}r.SiteOptional({site}) && !\u{1}r.Present() {{" ); if typed && !nullable { out.push_str("\t\t\u{1}r.Failf(\"null where a value is required\")\n"); } out.push_str("\t\treturn v\n\t}\n"); } let names: &'a GoNames = self.names; let union_names = if let GoTy::TypedUnion(key) = ty { self.use_owner_package(owner); Some(names.union(owner, key)) } else { None }; let root_go = self.root_go; // The value of arm `index` holding `expr`, returned. let ret = |index: usize, expr: &str, tabs: &str| { let member = &members[index]; let value = match union_names { Some(names) => { let constructor = names .arm(member) .constructor() .identifier(root_go) .to_string(); if matches!(member, GoTy::Literal(_)) { format!("{constructor}()") } else { format!("{constructor}({expr})") } } None => expr.to_string(), }; if typed && nullable { format!("{tabs}x := {value}\n{tabs}return &x\n") } else { format!("{tabs}return {value}\n") } }; // Members the library carries alike are one library member (or the // whole union, written as that one type with no index): read the // value once and pick the arm by value, narrower arms first. let groups = alike_groups(&members); let pick = |this: &mut Self, group: &[usize], tabs: &str| { let general = erased(&members[group[0]]); let expr = this.decode_expr( &general, owner, &child.step(format!("m{}", group[0])), "d+1", ); let mut out = format!("{tabs}u := {expr}\n"); let mut fallback = None; for &index in group { if narrower_than_erased(&members[index]) { let check = this.fits_fn(&members[index], owner); let _ = writeln!(out, "{tabs}if {check}(u) {{"); out.push_str(&ret(index, "u", &format!("{tabs}\t"))); let _ = writeln!(out, "{tabs}}}"); } else if fallback.is_none() { fallback = Some(index); } } match fallback { Some(index) => out.push_str(&ret(index, "u", tabs)), None => { let _ = writeln!( out, "{tabs}\u{1}r.Failf(\"%v is none of the union's members\", u)\n{tabs}return v" ); } } out }; if groups.len() == 1 && members.len() > 1 { let _ = writeln!(out, "\tif \u{1}r.SiteCollapsed({site}) {{"); let block = pick(self, &groups[0], "\t\t"); out.push_str(&block); out.push_str("\t}\n"); } // Null is the presence byte above (unions cross flat): an index // always names a member. let _ = writeln!(out, "\tswitch \u{1}r.Arm({site}) {{"); for group in &groups { let list = group .iter() .map(ToString::to_string) .collect::>() .join(", "); let _ = writeln!(out, "\tcase {list}:"); if let [index] = group.as_slice() && !narrower_than_erased(&members[*index]) { let member = &members[*index]; let expr = self.decode_expr(member, owner, &child.step(format!("m{index}")), "d+1"); if matches!(member, GoTy::Literal(GoLiteral::Bigint(_))) { // A bigint literal takes the bytes of a bigint (format // 4); its arm has no Go value, so read and check them. let _ = writeln!(out, "\t\t_ = {expr}"); } out.push_str(&ret(*index, &expr, "\t\t")); } else { let block = pick(self, group, "\t\t"); out.push_str(&block); } } out.push_str("\t}\n\treturn v\n}\n\n"); self.helpers.push_str(&out); function } // ------------------------------------------------------------ functions /// Renders one function: its option setters and its body. pub(crate) fn render_function(&mut self, routed: &GeneratedFunction<'_>) { let function = routed.function; let root = self.root_baml.clone(); let index = self.funcs.len(); let wire = routed.go_name.wire().to_string(); // A method is `.` in `describe`; an instance method's // first parameter is `self`, in its typed form. let describe = match routed.owner_name { Some(owner) => format!("{}.{}", describe_name(owner), function.name), None => wire.strip_prefix("user.").unwrap_or(&wire).to_string(), }; let self_ty = routed .receiver .as_ref() .map(|receiver| self.projection.project(&receiver.ty())); let mut reached = Vec::new(); let mut visited = BTreeSet::new(); let mut params = Vec::new(); if let Some(ty) = &self_ty { self.reach(ty, &mut visited, &mut reached); params.push(type_key(ty)); } for argument in &function.arguments { let ty = self.projection.project(&argument.ty); self.reach(&ty, &mut visited, &mut reached); params.push(type_key(&ty)); } let returns = if matches!(function.return_type, Ty::Never) { "never".to_string() } else if function.return_type.is_unit() { "null".to_string() } else { let ty = self.projection.project(&function.return_type); self.reach(&ty, &mut visited, &mut reached); type_key(&ty) }; reached.sort_unstable(); self.funcs.push(FuncOut { owner: routed.owner_name.map(describe_name), name: describe, params, returns, types: reached, param_names: self_ty .iter() .map(|_| "self".to_string()) .chain( function .arguments .iter() .map(|argument| argument.name.to_string()), ) .collect(), defaulted: self_ty .iter() .map(|_| false) .chain( function .arguments .iter() .map(|argument| argument.default.is_some()), ) .collect(), }); self.lib_import(); self.native_import(); self.runtime_import(); self.imports .add_generator(GeneratorIdent::ContextPackage, "context"); let go_name = routed.go_name.identifier(self.root_go).to_string(); let scope = TypeVarScope { callback: None, helper: None, callable: Some(&routed.fqn), class: None, }; // Option type and setters: the same names as the default back end. let option_type = routed .option_type .as_ref() .map(|name| name.identifier(self.root_go).to_string()); if let Some(option_type) = &option_type { let _ = writeln!(self.body, "\ntype {option_type} = baml_go.CallOption"); for argument in routed .arguments .iter() .filter(|a| a.argument.default.is_some()) { let setter = argument .option_setter .as_ref() .expect("defaulted argument must have an option setter"); let surface = self.signature_type(&argument.argument.ty, scope); let _ = writeln!( self.body, "\nfunc {}(value_ {surface}) {option_type} {{\n\treturn baml_go.NativeArgument({wire:?}, {:?}, value_)\n}}", setter.identifier(self.root_go), setter.wire().to_string() ); } } // Signature. let mut signature = vec!["ctx_ context.Context".to_string()]; for argument in routed .arguments .iter() .filter(|a| a.argument.default.is_none()) { let surface = self.signature_type(&argument.argument.ty, scope); signature.push(format!( "{} {surface}", argument.go_name.identifier(self.root_go) )); } signature.push(format!( "options_ ...{}", option_type .clone() .unwrap_or_else(|| "baml_go.CallOption".to_string()) )); let only_error = function_returns_only_error(&function.return_type); let expanded = expanded_return_slots(&function.return_type, self.projection); let return_types: Vec = if only_error { Vec::new() } else if let Some(slots) = &expanded { slots .slots() .iter() .map(|slot| self.go_type(slot, &root)) .collect() } else { let context = TypeImportContext { current_package: self.root_go, pool: self.pool, packages: self.packages, sdk_import_path: self.sdk_import_path, projection: self.projection, }; add_function_surface_imports( &self.projection.project(&function.return_type), &root, &context, &mut self.imports, ); vec![function_return_go_type( &function.return_type, &root, self.root_go, self.names, self.projection, scope, )] }; // Named zero values, not `*new(T)`: a parameter may be called `new`. let zeros = (0..return_types.len()) .map(|index| format!("_bamlZero{index}_")) .collect::>(); let fail = |err: &str| { if zeros.is_empty() { format!("return {err}") } else { format!("return {}, {err}", zeros.join(", ")) } }; // Docs: the same as the default back end. let mut notes = Vec::new(); for argument in &routed.arguments { notes.extend(dynamic_union_doc_notes( &self.projection.project(&argument.argument.ty), &format!("Parameter {}", argument.go_name.identifier(self.root_go)), &root, self.root_go, self.names, DynamicDocContext::Argument, scope, )); } notes.extend(dynamic_union_doc_notes( &self.projection.project(&function.return_type), "The return value", &root, self.root_go, self.names, DynamicDocContext::Return, scope, )); if function.throws.is_some() || matches!(function.return_type, Ty::Never) { notes.push( "BAML failures are returned as *baml_go.BamlError values; the native library sends no BAML trace yet." .to_string(), ); } notes.push( "A context deadline or cancellation returns ctx.Err(): at once while the call waits, and when the call ends if it never waits; BAML code that only computes is not interrupted." .to_string(), ); let docstring = docstring_with_generated_notes(function.docstring.as_deref(), ¬es); self.body.push('\n'); render_go_doc_comment(&mut self.body, &go_name, docstring.as_deref()); let returns = if only_error { "error".to_string() } else { format!("({}, error)", return_types.join(", ")) }; let receiver = match (&routed.receiver, &self_ty) { (Some(_), Some(ty)) => format!("(_bamlSelf_ {}) ", self.go_type(ty, &root)), _ => String::new(), }; let mut out = format!( "func {receiver}{go_name}({}) {returns} {{\n", signature.join(", ") ); for (zero, ty) in zeros.iter().zip(&return_types) { let _ = writeln!(out, "\tvar {zero} {ty}"); } let has_options = routed .arguments .iter() .any(|a| a.argument.default.is_some()); let opts = if has_options { "_bamlOpts_" } else { "_" }; let _ = writeln!( out, "\t{opts}, _bamlTimeout_, err_ := baml_go.NativeArguments({wire:?}, options_)\n\tif err_ != nil {{\n\t\t{}\n\t}}", fail("err_") ); let _ = writeln!( out, "\t_bamlCall_, err_ := {NATIVE}.Program.Begin(ctx_, {index}, _bamlTimeout_)\n\tif err_ != nil {{\n\t\t{}\n\t}}", fail("err_") ); if !routed.arguments.is_empty() || self_ty.is_some() { out.push_str("\t\u{1}w := _bamlCall_.Writer()\n"); } let first_param = usize::from(self_ty.is_some()); if let Some(ty) = &self_ty { let place = Place { root: SiteRoot::Param(index, 0), path: Vec::new(), }; out.push_str("\t\u{1}w.Arg(\"self\")\n\t\u{1}w.Present(true)\n"); out.push_str(&self.encode_stmt(ty, &root, "_bamlSelf_", "0", 1, Some(&place))); } for (position, argument) in routed.arguments.iter().enumerate() { let ty = self.projection.project(&argument.argument.ty); let place = Place { root: SiteRoot::Param(index, first_param + position), path: Vec::new(), }; let _ = writeln!(out, "\t\u{1}w.Arg({:?})", argument.argument.name.as_str()); if argument.argument.default.is_some() { let surface = self.signature_type(&argument.argument.ty, scope); let stmt = self.encode_stmt(&ty, &root, "_bamlV_", "0", 2, Some(&place)); let param = argument .option_setter .as_ref() .expect("setter") .wire() .to_string(); // The setter stores the parameter's Go type; another // function's setter for a parameter of the same name may not. let assert = if surface == "any" { "\t\t_bamlV_ := _bamlAny_\n".to_string() } else { format!( "\t\t_bamlV_, _bamlTyped_ := _bamlAny_.({surface})\n\t\tif !_bamlTyped_ {{\n\t\t\t{}\n\t\t}}\n", fail(&format!( "baml_go.NativeArgumentTypeError({wire:?}, {param:?}, _bamlAny_)" )) ) }; let _ = writeln!( out, "\tif _bamlAny_, _bamlOk_ := _bamlOpts_[{param:?}]; _bamlOk_ {{\n{assert}\t\t_ = _bamlV_\n\t\t\u{1}w.Present(true)\n{stmt}\t}} else {{\n\t\t\u{1}w.Present(false)\n\t}}" ); } else { let value = argument.go_name.identifier(self.root_go).to_string(); out.push_str("\t\u{1}w.Present(true)\n"); out.push_str(&self.encode_stmt(&ty, &root, &value, "0", 1, Some(&place))); } } let place = Place { root: SiteRoot::Func(index), path: Vec::new(), }; // The decoding statements first, so the reader is bound only when // they use it. let mut tail = String::new(); if function.return_type.is_unit() { tail.push_str("\treturn _bamlCall_.End()\n}\n"); } else if matches!(function.return_type, Ty::Never) { let _ = writeln!( tail, "\tif err_ := _bamlCall_.End(); err_ != nil {{\n\t\treturn err_\n\t}}\n\treturn baml_go.UnexpectedNeverReturn({:?})\n}}", routed.go_name.wire().to_string() ); } else if let Some(slots) = &expanded { let mut results = Vec::new(); for (slot_index, slot) in slots.slots().iter().enumerate() { let expr = self.decode_expr(slot, &root, &place.step(format!("t{slot_index}")), "0"); let _ = writeln!(tail, "\t_bamlSlot{slot_index}_ := {expr}"); results.push(format!("_bamlSlot{slot_index}_")); } let _ = writeln!( tail, "\tif err_ := _bamlCall_.End(); err_ != nil {{\n\t\t{}\n\t}}\n\treturn {}, nil\n}}", fail("err_"), results.join(", ") ); } else { let ty = self.projection.project(&function.return_type); let expr = self.decode_expr(&ty, &root, &place, "0"); let _ = writeln!( tail, "\tresult_ := {expr}\n\tif err_ := _bamlCall_.End(); err_ != nil {{\n\t\t{}\n\t}}\n\treturn result_, nil\n}}", fail("err_") ); } let run = if uses_reader(&tail) { "\u{1}r, err_ := _bamlCall_.Run()" } else { "_, err_ = _bamlCall_.Run()" }; let _ = writeln!( out, "\t{run}\n\tif err_ != nil {{\n\t\t{}\n\t}}", fail("err_") ); out.push_str(&tail); self.body.push_str(&out); } fn signature_type(&mut self, ty: &Ty, scope: TypeVarScope<'_>) -> String { let root = self.root_baml.clone(); let context = TypeImportContext { current_package: self.root_go, pool: self.pool, packages: self.packages, sdk_import_path: self.sdk_import_path, projection: self.projection, }; add_function_surface_imports( &self.projection.project(ty), &root, &context, &mut self.imports, ); function_go_type(ty, &root, self.root_go, self.names, self.projection, scope) } /// The root package's `native_functions.go`. pub(crate) fn render_file(&mut self) -> String { let local = |code: &str| code.replace(WRITER, "w").replace(READER, "r"); let mut code = String::new(); if !self.registrations.is_empty() { let _ = writeln!(code, "func init() {{\n{}}}\n", local(&self.registrations)); } code.push_str(&local(&self.helpers)); code.push_str( &self .body .replace(WRITER, "_bamlW_") .replace(READER, "_bamlR_"), ); let mut out = String::from(BANNER); let _ = writeln!(out, "package {}\n", self.root_go.as_str()); out.push_str(&used_imports(&self.imports.render(), &code)); out.push_str(&code); out } /// `native/native.go`: the manifest and `Load`. pub(crate) fn render_manifest(&self, default_library: &str) -> String { let mut out = String::from(BANNER); out.push_str( "// Package native holds what the generated package knows about its BAML\n\ // library (built with `baml pack --native --shared`): the names of its\n\ // functions and types, and the places where it writes unions. The runtime\n\ // resolves them to the library's ids when the library loads.\n", ); let _ = writeln!( out, "package native\n\nimport (\n\tbaml_go {BAML_GO_MODULE:?}\n\t{LIB} {BAMLLIB_MODULE:?}\n)\n" ); out.push_str( "// Load loads the BAML library from path. Call it before the first BAML call;\n\ // otherwise the first call loads $BAML_LIBRARY, or else the library named\n\ // after the package next to the executable (see Program.DefaultPath).\n\ func Load(path string) error { return Program.Load(path) }\n\n", ); out.push_str("// Program is the generated package's view of its library.\n"); let _ = writeln!(out, "var Program = {LIB}.NewProgram({LIB}.Manifest{{"); let _ = writeln!(out, "\tDefaultLibrary: {default_library:?},"); out.push_str("\tFunctions: []_bamllib.FuncSpec{\n"); for function in &self.funcs { let types = function .types .iter() .map(ToString::to_string) .collect::>() .join(", "); let defaulted = function .defaulted .iter() .map(ToString::to_string) .collect::>() .join(", "); let owner = function .owner .as_ref() .map(|owner| format!("Owner: {owner:?}, ")) .unwrap_or_default(); let _ = writeln!( out, "\t\t{{Name: {:?}, {owner}Params: []string{{{}}}, Returns: {:?}, Types: []int{{{types}}}, ParamNames: []string{{{}}}, Defaulted: []bool{{{defaulted}}}}},", function.name, quoted(&function.params), function.returns, quoted(&function.param_names) ); } out.push_str("\t},\n\tTypes: []_bamllib.TypeSpec{\n"); for ty in &self.types { match ty { TypeOut::Class { name, fields, field_types, } => { let _ = writeln!( out, "\t\t{{Name: {name:?}, Fields: []string{{{}}}, FieldTypes: []string{{{}}}}},", quoted(fields), quoted(field_types) ); } TypeOut::Enum { name, variants } => { let _ = writeln!( out, "\t\t{{Name: {name:?}, Enum: true, Variants: []string{{{}}}}},", quoted(variants) ); } TypeOut::Opaque { name } => { let _ = writeln!(out, "\t\t{{Name: {name:?}, Opaque: true}},"); } } } out.push_str("\t},\n\tSites: []_bamllib.SiteSpec{\n"); for site in &self.sites { // Rendered as Go integer literals; -1 means "none". let (func, ty, field, parent, arg) = match site.root { SiteRoot::Func(index) => { (index.to_string(), "-1".to_string(), 0, "-1".to_string(), 0) } SiteRoot::Param(index, param) => ( index.to_string(), "-1".to_string(), 0, "-1".to_string(), param + 1, ), SiteRoot::Field(ty, field) => { ("-1".to_string(), ty.to_string(), field, "-1".to_string(), 0) } SiteRoot::Site(parent) => { ("-1".to_string(), "-1".to_string(), 0, parent.to_string(), 0) } }; let members = match &site.members { Some(members) => format!("[]string{{{}}}", quoted(members)), None => "nil".to_string(), }; let _ = writeln!( out, "\t\t{{Func: {func}, Arg: {arg}, Type: {ty}, Field: {field}, Parent: {parent}, Path: []string{{{}}}, Members: {members}}},", quoted(&site.path) ); } out.push_str("\t},\n"); out.push_str( "\tNewError: func(kind, className, message string, value any, payload []byte, held any) error {\n\ \t\treturn baml_go.NewNativeBamlError(kind, className, message, value, payload, held)\n\ \t},\n\ \tClassify: func(err error) _bamllib.Failure {\n\ \t\tif payload, held, kind, ok := baml_go.NativeErrorPayload(err); ok {\n\ \t\t\treturn _bamllib.Failure{Kind: _bamllib.FailForward, Payload: payload, Held: held, Panic: kind == \"panic\"}\n\ \t\t}\n\ \t\tif goType, ok := baml_go.NativeThrownType(err); ok {\n\ \t\t\treturn _bamllib.Failure{Kind: _bamllib.FailThrown, GoType: goType}\n\ \t\t}\n\ \t\treturn _bamllib.Failure{}\n\ \t},\n})\n", ); out } } /// The import block without the imports `code` does not use. Imports are /// collected generously while rendering (a type's package, `math/big` for a /// bigint anywhere in it); Go rejects an unused one, so the final text /// decides. fn used_imports(block: &str, code: &str) -> String { // Only references count: not a doc comment that mentions `big.`, not a // string such as "user.big.Thing". let code = without_comments_and_strings(code); let mut kept = Vec::new(); for line in block.lines().filter(|line| !line.trim().is_empty()) { let trimmed = line.trim(); let Some(path_start) = trimmed.find('"') else { kept.push(line.to_string()); continue; }; let path = trimmed[path_start..].trim_matches('"'); // An import without an alias is named by its package clause, which // is the last path segment except for the runtime module. let alias = match trimmed[..path_start].trim() { "" if path == BAML_GO_MODULE => GeneratorIdent::RuntimePackage.as_str(), "" => path.rsplit('/').next().unwrap_or(path), explicit => explicit, }; if references(&code, alias) { kept.push(line.to_string()); } } if kept.len() <= 2 { // Only `import (` and `)` are left. return String::new(); } let mut out = kept.join("\n"); out.push_str("\n\n"); out } /// Whether `code` names `alias.` as a qualified identifier (not as the tail /// of a longer identifier such as `_bamlbig.`). fn references(code: &str, alias: &str) -> bool { let needle = format!("{alias}."); code.match_indices(&needle).any(|(at, _)| { code[..at] .chars() .next_back() .is_none_or(|before| !(before.is_alphanumeric() || before == '_')) }) } /// Go source with comments and string, rune and raw-string literals blanked /// out, so that import usage is decided from code alone. fn without_comments_and_strings(code: &str) -> String { let mut out = String::with_capacity(code.len()); let mut chars = code.chars().peekable(); while let Some(c) = chars.next() { match c { '/' if chars.peek() == Some(&'/') => { for next in chars.by_ref() { if next == '\n' { out.push('\n'); break; } } } '/' if chars.peek() == Some(&'*') => { chars.next(); let mut previous = ' '; for next in chars.by_ref() { if previous == '*' && next == '/' { break; } previous = next; } out.push(' '); } '"' | '\'' => { let mut escaped = false; for next in chars.by_ref() { if escaped { escaped = false; } else if next == '\\' { escaped = true; } else if next == c || next == '\n' { break; } } out.push_str("\"\""); } '`' => { for next in chars.by_ref() { if next == '`' { break; } } out.push_str("\"\""); } other => out.push(other), } } out } /// Whether generated statements read from the reader `r`. fn uses_reader(code: &str) -> bool { code.contains(READER) } fn quoted(items: &[String]) -> String { items .iter() .map(|item| format!("{item:?}")) .collect::>() .join(", ") } /// Whether encoding `ty` reaches a typed union (an encode site) or a /// function directly (not through a class, whose encoder owns its sites). fn contains_encode_site(ty: &GoTy) -> bool { match ty { GoTy::TypedUnion(_) | GoTy::Function(_) => true, GoTy::List(inner) | GoTy::Optional(inner) => contains_encode_site(inner), GoTy::Map { key, value } => contains_encode_site(key) || contains_encode_site(value), GoTy::Tuple(key) => key.slots().iter().any(contains_encode_site), _ => false, } } /// Whether decoding `ty` reaches a union or `json` value directly (not /// through a class, whose decoder owns its own sites). fn contains_site(ty: &GoTy) -> bool { match ty { GoTy::TypedUnion(_) | GoTy::DynamicUnion { .. } | GoTy::Json => true, GoTy::List(inner) | GoTy::Optional(inner) => contains_site(inner), GoTy::Map { key, value } => contains_site(key) || contains_site(value), GoTy::Tuple(key) => key.slots().iter().any(contains_site), _ => false, } } #[cfg(test)] mod tests { use std::path::PathBuf; use baml_base::Name as BaseName; use baml_sdkgen_types::{ Class, ClassProperty, Freshness, Function, FunctionArgument, FunctionArgumentDefault, Name, NamingConvention, Origin, SkipWarning, Symbol, SymbolPool, Ty, }; use crate::{ Backend, DEFAULT_MAX_TYPED_UNION_ARITY, DEFAULT_PACKAGE_NAME, Generated, GoGenOptions, try_to_source_code_with_backend, try_to_source_code_with_bytecode_and_options, }; const IMPORT: &str = "example.com/project/baml_sdk"; fn options() -> GoGenOptions<'static> { GoGenOptions { naming_convention: NamingConvention::Language, sdk_import_path: IMPORT, package_name: DEFAULT_PACKAGE_NAME, max_typed_union_arity: DEFAULT_MAX_TYPED_UNION_ARITY, } } fn native(pool: &SymbolPool) -> Generated { try_to_source_code_with_backend(pool, &[], None, &options(), Backend::Native, None) .expect("native generation") } fn origin() -> Origin { Origin { source_file_path: "main.baml".to_string(), span_start: 0, } } fn user(name: &str) -> Name { Name::new(BaseName::new("user"), vec![], BaseName::new(name)) } fn argument(name: &str, ty: Ty) -> FunctionArgument { FunctionArgument { injected: false, name: BaseName::new(name), docstring: None, ty, default: None, } } fn function(name: &Name, arguments: Vec, return_type: Ty) -> (Name, Symbol) { ( name.clone(), Symbol::Function(Function { name: name.name().clone(), generic_params: vec![], docstring: None, arguments, return_type, throws: None, watchers: vec![], origin: origin(), }), ) } fn class(name: &Name, fields: Vec<(&str, Ty)>) -> (Name, Symbol) { ( name.clone(), Symbol::Class(Class { crossing: baml_sdkgen_types::ClassCrossing::Fields, name: name.clone(), generic_params: vec![], docstring: None, properties: fields .into_iter() .map(|(field, ty)| ClassProperty { name: BaseName::new(field), docstring: None, ty, json_fallback: false, json_flatten: false, json_rename: None, }) .collect(), static_methods: vec![], instance_methods: vec![], origin: origin(), json_omit_nulls: false, }), ) } fn file<'a>(generated: &'a Generated, path: &str) -> &'a str { generated .files .get(&PathBuf::from(path)) .unwrap_or_else(|| panic!("missing {path}")) } fn person_pool() -> SymbolPool { let person = user("Person"); SymbolPool::from([ class(&person, vec![("name", Ty::String), ("age", Ty::Int)]), function( &user("round_trip_person"), vec![argument("person", Ty::Class(person.clone(), vec![].into()))], Ty::Class(person, vec![].into()), ), function( &user("round_trip_int"), vec![argument("value", Ty::Int)], Ty::Int, ), ]) } #[test] fn default_backend_output_is_unchanged() { let pool = person_pool(); let before = try_to_source_code_with_bytecode_and_options(&pool, &[1, 2], &options()) .expect("bridge generation"); let after = try_to_source_code_with_backend( &pool, &[1, 2], None, &options(), Backend::Bridge, None, ) .expect("bridge generation"); assert_eq!(before.files, after.files); assert_eq!(before.warnings, after.warnings); } #[test] fn native_backend_keeps_signatures_and_calls_the_library() { let pool = person_pool(); let bridge = try_to_source_code_with_bytecode_and_options(&pool, &[1, 2], &options()) .expect("bridge generation"); let generated = native(&pool); let functions = file(&generated, "native_functions.go"); for signature in [ "func RoundTripPerson(ctx_ context.Context, person Person, options_ ...baml_go.CallOption) (Person, error) {", "func RoundTripInt(ctx_ context.Context, value int64, options_ ...baml_go.CallOption) (int64, error) {", ] { assert!( file(&bridge, "functions.go").contains(signature), "{signature}" ); assert!(functions.contains(signature), "{signature}\n{functions}"); } assert!(functions.contains("_bamlnative.Program.Begin(ctx_, ")); assert!(functions.contains("_bamlW_.I64(value)")); assert!(functions.contains("_bamlR_.I64()")); // Straight-line class codecs. assert!(functions.contains("w.String(v.Name)")); assert!(functions.contains("v.Age = r.I64()")); // No embedded engine, no bridge function bodies. assert!( !generated .files .contains_key(&PathBuf::from("internal/bootstrap/bootstrap.go")) ); assert!(!file(&generated, "functions.go").contains("CallWithPreparedOptions")); // The types are those of the default back end. assert_eq!(file(&generated, "types.go"), file(&bridge, "types.go")); let manifest = file(&generated, "native/native.go"); assert!( manifest.contains(r#"{Name: "round_trip_person", Params: []string{"class:Person"}, Returns: "class:Person", Types: []int{0}, ParamNames: []string{"person"}, Defaulted: []bool{false}}"#), "{manifest}" ); assert!( manifest.contains(r#"{Name: "Person", Fields: []string{"name", "age"}, FieldTypes: []string{"string", "int"}}"#), "{manifest}" ); assert!(manifest.contains(r#"DefaultLibrary: "baml_sdk""#)); } #[test] fn optional_arguments_use_native_call_options() { let name = user("probe"); let mut defaulted = argument("opt", Ty::Union(vec![Ty::Int, Ty::Null].into())); defaulted.default = Some(FunctionArgumentDefault::Null); let pool = SymbolPool::from([function( &name, vec![argument("arg0", Ty::Int), defaulted], Ty::Int, )]); let generated = native(&pool); let functions = file(&generated, "native_functions.go"); assert!( functions.contains("type ProbeOption = baml_go.CallOption"), "{functions}" ); assert!( functions.contains(r#"return baml_go.NativeArgument("user.probe", "opt", value_)"#), "{functions}" ); assert!(functions.contains(r#"_bamlOpts_["opt"]"#)); assert!(functions.contains("_bamlW_.Present(false)")); } #[test] fn unions_are_sites_resolved_by_member_keys() { let pool = SymbolPool::from([function( &user("pick"), vec![argument( "value", Ty::Union(vec![Ty::Int, Ty::String].into()), )], Ty::Union(vec![Ty::Int, Ty::String].into()), )]); let generated = native(&pool); let functions = file(&generated, "native_functions.go"); let manifest = file(&generated, "native/native.go"); assert!(functions.contains("r.Arm(1)"), "{functions}"); assert!( manifest.contains(r#"Members: []string{"string", "int"}"#) || manifest.contains(r#"Members: []string{"int", "string"}"#), "{manifest}" ); // Host to library, a typed union names its member (tag 16) at an // encode site of the parameter, resolved from `describe` at load. assert!( functions.contains("w.Member(_bamlnative.Program, 0, "), "{functions}" ); assert!(manifest.contains("{Func: 0, Arg: 1,"), "{manifest}"); assert!(!functions.contains("_bamllib.TagInt"), "{functions}"); } #[test] fn nested_nullable_unions_cross_flat() { // `(int | bool)? | bool`: the library describes it as // optional(union[int, bool]) (format 3). The site lists the flat // members, null is the presence byte, and an argument is one // presence byte and the self-describing value. let nested = || { Ty::Union( vec![ Ty::Union(vec![Ty::Int, Ty::Bool, Ty::Null].into()), Ty::Bool, ] .into(), ) }; let pool = SymbolPool::from([function( &user("flat"), vec![argument("value", nested())], nested(), )]); let generated = native(&pool); let functions = file(&generated, "native_functions.go"); let manifest = file(&generated, "native/native.go"); assert!( manifest.contains(r#"Members: []string{"int", "bool"}"#) || manifest.contains(r#"Members: []string{"bool", "int"}"#), "{manifest}" ); assert!(!manifest.contains("Encode"), "{manifest}"); assert!( functions.contains("r.SiteOptional(1) && !r.Present()"), "{functions}" ); assert!(!functions.contains("case -1"), "{functions}"); assert!(functions.contains("_bamlW_.Present(false)"), "{functions}"); } #[test] fn unions_the_library_writes_as_one_type_pick_the_arm_by_value() { // `E0 | E0.A`: the library carries the variant as its enum and // writes the union as plain `E0`, with no member index. The decoder // reads the enum when the site is collapsed and picks the variant // arm when the value is that variant; arguments use the typed form. let e0 = user("E0"); let enum_ = Symbol::Enum(baml_sdkgen_types::Enum { name: e0.clone(), docstring: None, variants: ["A", "B"] .iter() .map(|variant| baml_sdkgen_types::EnumVariant { name: BaseName::new(*variant), docstring: None, value: (*variant).to_string(), json_rename: None, }) .collect(), origin: origin(), }); let union = || { Ty::Union( vec![ Ty::Enum(e0.clone()), Ty::EnumVariant(e0.clone(), BaseName::new("A")), ] .into(), ) }; let two = Ty::Union( vec![ Ty::EnumVariant(e0.clone(), BaseName::new("A")), Ty::EnumVariant(e0.clone(), BaseName::new("B")), ] .into(), ); let pool = SymbolPool::from([ (e0.clone(), enum_), function(&user("pick"), vec![argument("value", union())], union()), function(&user("two"), vec![argument("value", two.clone())], two), ]); let generated = native(&pool); assert!(generated.warnings.is_empty(), "{:?}", generated.warnings); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("if r.SiteCollapsed(1) {"), "{functions}"); assert!(functions.contains("\tcase 0, 1:\n\t\tu := "), "{functions}"); assert!(functions.contains("return v == E0A"), "{functions}"); // An argument: the one type's own form where the library collapses // the union, the member named otherwise. assert!( functions.contains("if w.SiteCollapsed(_bamlnative.Program, 0) {"), "{functions}" ); assert!(functions.contains("is not the enum variant"), "{functions}"); assert!(!functions.contains("EncodeAny"), "{functions}"); } #[test] fn functions_the_library_cannot_run_are_skipped_with_a_reason() { let mut llm = function( &user("extract"), vec![argument("text", Ty::String)], Ty::String, ); if let Symbol::Function(function) = &mut llm.1 { function.arguments.push(FunctionArgument { injected: true, ..argument("on_event", Ty::Null) }); } let media = function( &user("describe_image"), vec![argument("img", Ty::Media(baml_base::MediaKind::Image))], Ty::String, ); let literal = function( &user("hello"), vec![], Ty::Literal( baml_base::Literal::String("hi".to_string()), Freshness::Regular, ), ); let json = function( &user("parse"), vec![argument("s", Ty::String)], Ty::TypeAlias(Name::new( BaseName::new("baml"), vec![BaseName::new("json")], BaseName::new("json"), )), ); let pool = SymbolPool::from([llm, media, literal, json]); let generated = native(&pool); let reason = |fqn: &str| -> Option<&SkipWarning> { generated.warnings.iter().find(|warning| warning.fqn == fqn) }; assert!(reason("user.extract").is_some_and(|w| w.reason.contains("LLM functions"))); assert!( reason("user.describe_image").is_some_and(|w| w.reason.contains("media")), "{:?}", generated.warnings ); assert!(reason("user.hello").is_none()); assert!( reason("user.parse").is_some_and(|w| w.reason.contains("recursive alias")), "{:?}", generated.warnings ); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("func Hello(")); assert!(!functions.contains("func Extract(")); assert!(!functions.contains("func DescribeImage(")); } /// Review C1: a package of primitive functions has no codec helper, so /// it must not import the runtime package it does not name. #[test] fn primitive_only_package_imports_only_what_it_uses() { let pool = SymbolPool::from([function( &user("add"), vec![argument("a", Ty::Int), argument("b", Ty::Int)], Ty::Int, )]); let generated = native(&pool); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("func Add("), "{functions}"); // Used through `baml_go.NativeArguments`, imported without an alias. assert!( functions.contains("\"github.com/boundaryml/baml-go\""), "{functions}" ); assert!(!functions.contains("_bamllib \""), "{functions}"); for line in functions .lines() .filter(|line| line.starts_with('\t') && line.ends_with('"')) { let alias = line.split_whitespace().next().unwrap_or_default(); let alias = match alias { "\"github.com/boundaryml/baml-go\"" => "baml_go", quoted if quoted.starts_with('"') => quoted .trim_matches('"') .rsplit('/') .next() .unwrap_or_default(), explicit => explicit, }; assert!( functions.contains(&format!("{alias}.")), "unused import {line}\n{functions}" ); } } /// Review C2: a class of another package is read and written with field /// names relative to its own package. #[test] fn class_of_another_package_uses_its_own_field_names() { let duration = Name::new( BaseName::new("baml"), vec![BaseName::new("time")], BaseName::new("Duration"), ); let pool = SymbolPool::from([ class(&duration, vec![("nanoseconds", Ty::Int)]), function( &user("dur"), vec![argument("d", Ty::Class(duration.clone(), vec![].into()))], Ty::Class(duration, vec![].into()), ), ]); let generated = native(&pool); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("v.Nanoseconds"), "{functions}"); assert!(!functions.contains("v.baml."), "{functions}"); } /// Review C3: the library treats a class with a private field as opaque, /// so functions that reach one are skipped, and the others still work. #[test] fn class_with_a_private_field_is_skipped() { let secret = user("Secret"); let pool = SymbolPool::from([ class(&secret, vec![("name", Ty::String), ("_token", Ty::String)]), function( &user("mk"), vec![argument("n", Ty::String)], Ty::Class(secret, vec![].into()), ), function( &user("add"), vec![argument("a", Ty::Int), argument("b", Ty::Int)], Ty::Int, ), ]); let generated = native(&pool); let warning = generated .warnings .iter() .find(|warning| warning.fqn == "user.mk") .expect("mk is skipped"); assert!( warning.reason.contains("private field"), "{}", warning.reason ); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("func Add(")); assert!(!functions.contains("func Mk(")); assert!(!file(&generated, "native/native.go").contains("Secret")); } /// Review N3: a doc comment that mentions `big.` must not keep the /// `math/big` import, which the code itself does not use. #[test] fn imports_are_decided_by_references_not_comments() { let mut documented = function( &user("ib"), vec![argument("x", Ty::Union(vec![Ty::Int, Ty::Bigint].into()))], Ty::Union(vec![Ty::Int, Ty::Bigint].into()), ); if let Symbol::Function(function) = &mut documented.1 { function.docstring = Some("Returns a big.Int or an int; see big.NewInt.".to_string()); } let generated = native(&SymbolPool::from([documented])); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("// Ib Returns a big.Int"), "{functions}"); let code = super::without_comments_and_strings(functions); assert_eq!( functions.contains("\"math/big\""), super::references(&code, "big"), "{functions}" ); assert!(!super::references("x := _bamlbig.Y", "big")); assert!(super::references("x := big.NewInt(1)", "big")); assert!(!super::references( &super::without_comments_and_strings("s := \"user.big.Thing\""), "big" )); } /// Review N4: a bigint literal parameter is checked like the other /// literals, and a bigint literal result too. #[test] fn bigint_literals_are_checked() { let five = Ty::Literal( baml_base::Literal::Bigint(num_bigint::BigInt::from(5)), Freshness::Regular, ); let generated = native(&SymbolPool::from([function( &user("lit_big"), vec![argument("x", five.clone())], five, )])); let functions = file(&generated, "native_functions.go"); assert!( functions.contains("x.Cmp(baml_go.MustBigIntLiteral(\"5\")) != 0"), "{functions}" ); assert!( functions.contains("BigintLiteral(baml_go.MustBigIntLiteral(\"5\"))"), "{functions}" ); } /// Format 4: each bigint literal is a union member of its own (keyed by /// its value), so `1n | 2n` is an ordinary union site, not one type. #[test] fn bigint_literal_unions_have_a_member_index() { let big = |n: i64| { Ty::Literal( baml_base::Literal::Bigint(num_bigint::BigInt::from(n)), Freshness::Regular, ) }; let union = Ty::Union(vec![big(1), big(2)].into()); let generated = native(&SymbolPool::from([function( &user("lit_bigs"), vec![argument("x", union.clone())], union, )])); assert!(generated.warnings.is_empty(), "{:?}", generated.warnings); let manifest = file(&generated, "native/native.go"); assert!( manifest.contains(r#"Members: []string{"lit:n:1", "lit:n:2"}"#), "{manifest}" ); assert!( manifest.contains(r#"Returns: "union(lit:n:1,lit:n:2)""#), "{manifest}" ); let functions = file(&generated, "native_functions.go"); assert!(!functions.contains("SiteCollapsed"), "{functions}"); } /// Review N1: parameter names and defaults are in the manifest, so a /// library whose parameters were reordered is refused at load. #[test] fn manifest_names_parameters_and_defaults() { let mut b = argument("b", Ty::Int); b.default = Some(FunctionArgumentDefault::Null); let generated = native(&SymbolPool::from([function( &user("sub"), vec![argument("a", Ty::Int), b], Ty::Int, )])); let manifest = file(&generated, "native/native.go"); assert!( manifest.contains(r#"ParamNames: []string{"a", "b"}, Defaulted: []bool{false, true}"#), "{manifest}" ); } /// Verification review 2, C1: a parameter named `new` must not shadow /// what the body uses (no `*new(T)`). #[test] fn a_parameter_named_new_does_not_break_the_body() { let generated = native(&SymbolPool::from([function( &user("f"), vec![argument("new", Ty::Int)], Ty::List(Box::new(Ty::Int)), )])); let functions = file(&generated, "native_functions.go"); assert!(!functions.contains("new("), "{functions}"); assert!(functions.contains("var _bamlZero0_ []int64"), "{functions}"); } /// A union with two list members is sent with its member named (tag /// 16), so the library never has to pick between them. #[test] fn unions_of_two_lists_name_their_member() { let ambiguous = || Ty::Union(vec![Ty::List(Box::new(Ty::Int)), Ty::List(Box::new(Ty::String))].into()); let generated = native(&SymbolPool::from([ function(&user("takes"), vec![argument("x", ambiguous())], Ty::Int), function(&user("gives"), vec![argument("n", Ty::Int)], ambiguous()), ])); assert!(generated.warnings.is_empty(), "{:?}", generated.warnings); let functions = file(&generated, "native_functions.go"); assert!(functions.contains("func Takes("), "{functions}"); assert!(functions.contains("func Gives("), "{functions}"); assert!( functions.contains("w.Member(_bamlnative.Program, 1, 0)"), "{functions}" ); assert!( functions.contains("w.Member(_bamlnative.Program, 1, 1)"), "{functions}" ); } fn callable(params: Vec<(Option<&str>, Ty)>, ret: Ty, throws: Ty) -> Ty { Ty::Function { params: params .into_iter() .map(|(name, ty)| baml_sdkgen_types::CallableParam { name: name.map(BaseName::new), ty, mode: baml_sdkgen_types::CodegenFunctionParamMode::Required, }) .collect(), ret: Box::new(ret), throws: Box::new(throws), } } fn method(name: &str, arguments: Vec, return_type: Ty) -> Function { let (_, Symbol::Function(function)) = function(&user(name), arguments, return_type) else { unreachable!() }; function } /// Methods are exported as `Class.method`: an instance method is a Go /// method whose receiver is sent first (`self`), a static one a package /// helper; both are found by their class at load. #[test] fn methods_are_exported_by_their_class() { let counter = user("Counter"); let (name, mut symbol) = class(&counter, vec![("n", Ty::Int)]); if let Symbol::Class(class) = &mut symbol { class.instance_methods.push(method( "bump", vec![argument("by", Ty::Int)], Ty::Class(counter.clone(), Box::new([])), )); class .static_methods .push(method("zero", vec![], Ty::Class(counter, Box::new([])))); } let generated = native(&SymbolPool::from([(name, symbol)])); assert!(generated.warnings.is_empty(), "{:?}", generated.warnings); let functions = file(&generated, "native_functions.go"); assert!( functions.contains("func (_bamlSelf_ Counter) Bump(ctx_ context.Context, by int64"), "{functions}" ); assert!( functions.contains("func CounterZero(ctx_ context.Context"), "{functions}" ); assert!(functions.contains("_bamlW_.Arg(\"self\")"), "{functions}"); let manifest = file(&generated, "native/native.go"); assert!( manifest.contains(r#"{Name: "Counter.bump", Owner: "Counter", Params: []string{"class:Counter", "int"}"#), "{manifest}" ); assert!( manifest.contains(r#"ParamNames: []string{"self", "by"}"#), "{manifest}" ); assert!( manifest.contains(r#"{Name: "Counter.zero", Owner: "Counter","#), "{manifest}" ); } /// A Go function passed to BAML becomes a host function adapter; a /// function value BAML returns becomes a `baml_go.ReturnedFunction` /// calling its handle; host values cross as tag 17 tokens. #[test] fn callbacks_function_values_and_host_values() { let int_to_int = || callable(vec![(None, Ty::Int)], Ty::Int, Ty::Never); let host_value = Ty::Class( Name::new( BaseName::new("baml"), vec![BaseName::new("host")], BaseName::new("Value"), ), Box::new([]), ); let generated = native(&SymbolPool::from([ function( &user("apply"), vec![argument("f", int_to_int()), argument("x", Ty::Int)], Ty::Int, ), function( &user("make_adder"), vec![argument("n", Ty::Int)], callable(vec![(Some("x"), Ty::Int)], Ty::Int, Ty::Never), ), function( &user("echo_host"), vec![argument("v", host_value.clone())], host_value, ), ])); let skipped = generated .warnings .iter() .map(|warning| format!("{}: {}", warning.fqn, warning.reason)) .collect::>(); let functions = file(&generated, "native_functions.go"); let manifest = file(&generated, "native/native.go"); assert!( functions.contains("_bamlW_.HostFn(_bamlnative.Program, _bamlNativeHostFn"), "{functions}" ); assert!(functions.contains("if !r.Count(1) {"), "{functions}"); assert!( manifest.contains(r#"Params: []string{"fn(int)->int", "int"}"#), "{manifest}" ); assert!( functions.contains("baml_go.NewReturnedFunction(baml_go.Function{}"), "{functions}" ); assert!( functions.contains("_bamlnative.Program.BeginValue(ctx, h, timeout)"), "{functions}" ); if skipped .iter() .any(|warning| warning.starts_with("user.echo_host")) { // `baml.host.Value` is not in this hand-built pool's projection. return; } assert!(functions.contains("HostValue("), "{functions}\n{skipped:?}"); } /// A function type nested in another value, or one with optional /// parameters, stays unavailable, with the reason. #[test] fn function_types_the_library_cannot_take_are_skipped() { let nested = Ty::List(Box::new(callable( vec![(None, Ty::Int)], Ty::Int, Ty::Never, ))); let optional = Ty::Function { params: vec![baml_sdkgen_types::CallableParam { name: Some(BaseName::new("y")), ty: Ty::Int, mode: baml_sdkgen_types::CodegenFunctionParamMode::Optional, }] .into_iter() .collect(), ret: Box::new(Ty::Int), throws: Box::new(Ty::Never), }; let generated = native(&SymbolPool::from([ function(&user("hof"), vec![argument("fs", nested)], Ty::Int), function(&user("opt"), vec![argument("f", optional)], Ty::Int), ])); let reason = |fqn: &str| { generated .warnings .iter() .find(|warning| warning.fqn == fqn) .map(|warning| warning.reason.clone()) .unwrap_or_default() }; // The default back end's own rules already refuse a list of // functions; the native rule covers what they let through. assert!(!reason("user.hof").is_empty(), "hof is generated"); assert!( reason("user.opt").contains("optional parameters"), "{}", reason("user.opt") ); } }