git.delta.rocks / jrsonnet / refs/commits / 921b9905a568

difftreelog

doc(libjsonnet): copy official documentation to doccomments

Yaroslav Bolyukin2022-08-27parent: #b4d71ec.patch.diff
in: master

7 files changed

modifiedbindings/jsonnet/Cargo.tomldiffbeforeafterboth
--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -1,5 +1,5 @@
 [package]
-name = "jsonnet"
+name = "libjsonnet"
 description = "Rust implementation of libjsonnet.so"
 version = "0.4.2"
 authors = ["Yaroslav Bolyukin <iam@lach.pw>"]
@@ -14,9 +14,11 @@
 jrsonnet-gcmodule = { version = "0.3.4" }
 
 [lib]
+name = "jsonnet"
 crate-type = ["cdylib"]
 
 [features]
+# Export additional functions for native integration, i.e ability to set custom trace format
 interop = []
 experimental = ["exp-preserve-order", "exp-destruct"]
 exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
1010
11use std::{11use std::{
12 alloc::Layout,12 alloc::Layout,
13 env,13 borrow::Cow,
14 ffi::{CStr, CString},14 ffi::{CStr, CString, OsStr},
15 os::raw::{c_char, c_double, c_int, c_uint},15 os::raw::{c_char, c_double, c_int, c_uint},
16 path::Path,
16};17};
1718
18use import::NativeImportResolver;
19use jrsonnet_evaluator::{IStr, ManifestFormat, State, Val};19use jrsonnet_evaluator::{
20 trace::PathResolver, FileImportResolver, IStr, ManifestFormat, State, Val,
21};
2022
21/// WASM stub23/// WASM stub
22#[cfg(target_arch = "wasm32")]24#[cfg(target_arch = "wasm32")]
23#[no_mangle]25#[no_mangle]
24pub extern "C" fn _start() {}26pub extern "C" fn _start() {}
2527
28/// Return the version string of the Jsonnet interpreter. Conforms to semantic versioning
29/// http://semver.org/ If this does not match LIB_JSONNET_VERSION then there is a mismatch between
30/// header and compiled library.
26#[no_mangle]31#[no_mangle]
27pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {32pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {
28 b"v0.16.0\0"33 b"v0.16.0\0"
29}34}
3035
36unsafe fn parse_path(input: &CStr) -> Cow<Path> {
37 #[cfg(target_family = "unix")]
38 {
39 use std::os::unix::ffi::OsStrExt;
40 let str = OsStr::from_bytes(input.to_bytes());
41 Cow::Borrowed(Path::new(str))
42 }
43 #[cfg(target_family = "windows")]
44 {
45 use std::os::windows::ffi::OsStringExt;
46 let str = input.to_str().expect("input is not utf8");
47 let wide = str.encode_utf16().collect::<Vec<_>>();
48 let wide = OsString::from_wide(&wide);
49 Cow::Owned(PathBuf::new(wide))
50 }
51 #[cfg(not(any(target_family = "unix", target_family = "windows")))]
52 {
53 compile_error!("unsupported os")
54 }
55}
56
57unsafe fn unparse_path(input: &Path) -> Cow<CStr> {
58 #[cfg(target_family = "unix")]
59 {
60 use std::os::unix::ffi::OsStrExt;
61 let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
62 Cow::Owned(str)
63 }
64 #[cfg(not(any(target_family = "unix", target_family = "windows")))]
65 {
66 compile_error!("unsupported os")
67 }
68}
69
70/// Create a new Jsonnet virtual machine.
31#[no_mangle]71#[no_mangle]
32pub extern "C" fn jsonnet_make() -> *mut State {72pub extern "C" fn jsonnet_make() -> *mut State {
33 let state = State::default();73 let state = State::default();
34 state.settings_mut().import_resolver = Box::new(NativeImportResolver::default());74 state.settings_mut().import_resolver = Box::new(FileImportResolver::default());
35 state.settings_mut().context_initializer =75 state.settings_mut().context_initializer = Box::new(jrsonnet_stdlib::ContextInitializer::new(
36 Box::new(jrsonnet_stdlib::ContextInitializer::new(state.clone()));76 state.clone(),
77 PathResolver::new_cwd_fallback(),
78 ));
37 Box::into_raw(Box::new(state))79 Box::into_raw(Box::new(state))
38}80}
3981
40/// # Safety82/// Complement of `jsonnet_vm_make`
41#[no_mangle]83#[no_mangle]
42#[allow(clippy::boxed_local)]84#[allow(clippy::boxed_local)]
43pub unsafe extern "C" fn jsonnet_destroy(vm: *mut State) {85pub extern "C" fn jsonnet_destroy(vm: Box<State>) {
44 drop(Box::from_raw(vm));86 drop(vm);
45}87}
4688
89/// Set the maximum stack depth.
47#[no_mangle]90#[no_mangle]
48pub extern "C" fn jsonnet_max_stack(vm: &State, v: c_uint) {91pub extern "C" fn jsonnet_max_stack(vm: &State, v: c_uint) {
49 vm.settings_mut().max_stack = v as usize;92 vm.settings_mut().max_stack = v as usize;
50}93}
5194
52// jrsonnet currently have no GC, so these functions is no-op95/// Set the number of objects required before a garbage collection cycle is allowed.
96///
97/// No-op for now
53#[no_mangle]98#[no_mangle]
54pub extern "C" fn jsonnet_gc_min_objects(_vm: &State, _v: c_uint) {}99pub extern "C" fn jsonnet_gc_min_objects(_vm: &State, _v: c_uint) {}
100
101/// Run the garbage collector after this amount of growth in the number of objects
102///
103/// No-op for now
55#[no_mangle]104#[no_mangle]
56pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &State, _v: c_double) {}105pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &State, _v: c_double) {}
57106
107/// Expect a string as output and don't JSON encode it.
58#[no_mangle]108#[no_mangle]
59pub extern "C" fn jsonnet_string_output(vm: &State, v: c_int) {109pub extern "C" fn jsonnet_string_output(vm: &State, v: c_int) {
60 match v {110 match v {
68 }118 }
69}119}
70120
121/// Allocate, resize, or free a buffer. This will abort if the memory cannot be allocated. It will
122/// only return NULL if sz was zero.
123///
71/// # Safety124/// # Safety
125///
126/// `buf` should be either previosly allocated by this library, or NULL
72///127///
73/// This function is most definitely broken, but it works somehow, see TODO inside128/// This function is most definitely broken, but it works somehow, see TODO inside
74#[no_mangle]129#[no_mangle]
75pub unsafe extern "C" fn jsonnet_realloc(_vm: &State, buf: *mut u8, sz: usize) -> *mut u8 {130pub unsafe extern "C" fn jsonnet_realloc(_vm: &State, buf: *mut u8, sz: usize) -> *mut u8 {
76 if buf.is_null() {131 if buf.is_null() {
77 assert!(sz != 0);132 if sz == 0 {
133 return std::ptr::null_mut();
134 }
78 return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());135 return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());
79 }136 }
80 // TODO: Somehow store size of allocation, because its real size is probally not 16 :D137 // TODO: Somehow store size of allocation, because its real size is probally not 16 :D
89 std::alloc::realloc(buf, old_layout, sz)146 std::alloc::realloc(buf, old_layout, sz)
90}147}
91148
149/// Clean up a JSON subtree.
92/// # Safety150///
151/// This is useful if you want to abort with an error mid-way through building a complex value.
93#[no_mangle]152#[no_mangle]
94#[allow(clippy::boxed_local)]153#[allow(clippy::boxed_local)]
95pub unsafe extern "C" fn jsonnet_json_destroy(_vm: &State, v: *mut Val) {154pub extern "C" fn jsonnet_json_destroy(_vm: &State, v: Box<Val>) {
96 drop(Box::from_raw(v));155 drop(v);
97}156}
98157
158/// Set the number of lines of stack trace to display (0 for all of them).
99#[no_mangle]159#[no_mangle]
100pub extern "C" fn jsonnet_max_trace(vm: &State, v: c_uint) {160pub extern "C" fn jsonnet_max_trace(vm: &State, v: c_uint) {
101 vm.set_max_trace(v as usize)161 vm.set_max_trace(v as usize)
102}162}
103163
164/// Evaluate a file containing Jsonnet code, return a JSON string.
165///
166/// The returned string should be cleaned up with jsonnet_realloc.
167///
104/// # Safety168/// # Safety
105///169///
106/// This function is safe, if received v is a pointer to normal C string170/// `filename` should be a \0-terminated string
107#[no_mangle]171#[no_mangle]
108pub unsafe extern "C" fn jsonnet_evaluate_file(172pub unsafe extern "C" fn jsonnet_evaluate_file(
109 vm: &State,173 vm: &State,
110 filename: *const c_char,174 filename: *const c_char,
111 error: &mut c_int,175 error: &mut c_int,
112) -> *const c_char {176) -> *const c_char {
113 let filename = CStr::from_ptr(filename);177 let filename = parse_path(CStr::from_ptr(filename));
114 match vm178 match vm
115 .import(179 .import(&filename)
116 &env::current_dir().expect("cwd"),
117 filename.to_str().unwrap(),
118 )
119 .and_then(|v| vm.with_tla(v))180 .and_then(|v| vm.with_tla(v))
120 .and_then(|v| vm.manifest(v))181 .and_then(|v| vm.manifest(v))
131 }192 }
132}193}
133194
195/// Evaluate a string containing Jsonnet code, return a JSON string.
196///
197/// The returned string should be cleaned up with jsonnet_realloc.
198///
134/// # Safety199/// # Safety
135///200///
136/// This function is safe, if received v is a pointer to normal C string201/// `filename`, `snippet` should be a \0-terminated strings
137#[no_mangle]202#[no_mangle]
138pub unsafe extern "C" fn jsonnet_evaluate_snippet(203pub unsafe extern "C" fn jsonnet_evaluate_snippet(
139 vm: &State,204 vm: &State,
144 let filename = CStr::from_ptr(filename);209 let filename = CStr::from_ptr(filename);
145 let snippet = CStr::from_ptr(snippet);210 let snippet = CStr::from_ptr(snippet);
146 match vm211 match vm
147 .evaluate_snippet(filename.to_str().unwrap().into(), snippet.to_str().unwrap())212 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())
148 .and_then(|v| vm.with_tla(v))213 .and_then(|v| vm.with_tla(v))
149 .and_then(|v| vm.manifest(v))214 .and_then(|v| vm.manifest(v))
150 {215 {
184 filename: *const c_char,249 filename: *const c_char,
185 error: &mut c_int,250 error: &mut c_int,
186) -> *const c_char {251) -> *const c_char {
187 let filename = CStr::from_ptr(filename);252 let filename = parse_path(CStr::from_ptr(filename));
188 match vm253 match vm
189 .import(254 .import(&filename)
190 &env::current_dir().expect("cwd"),
191 filename.to_str().unwrap(),
192 )
193 .and_then(|v| vm.with_tla(v))255 .and_then(|v| vm.with_tla(v))
194 .and_then(|v| vm.manifest_multi(v))256 .and_then(|v| vm.manifest_multi(v))
216 let filename = CStr::from_ptr(filename);278 let filename = CStr::from_ptr(filename);
217 let snippet = CStr::from_ptr(snippet);279 let snippet = CStr::from_ptr(snippet);
218 match vm280 match vm
219 .evaluate_snippet(filename.to_str().unwrap().into(), snippet.to_str().unwrap())281 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())
220 .and_then(|v| vm.with_tla(v))282 .and_then(|v| vm.with_tla(v))
221 .and_then(|v| vm.manifest_multi(v))283 .and_then(|v| vm.manifest_multi(v))
222 {284 {
254 filename: *const c_char,316 filename: *const c_char,
255 error: &mut c_int,317 error: &mut c_int,
256) -> *const c_char {318) -> *const c_char {
257 let filename = CStr::from_ptr(filename);319 let filename = parse_path(CStr::from_ptr(filename));
258 match vm320 match vm
259 .import(321 .import(&filename)
260 &env::current_dir().expect("cwd"),
261 filename.to_str().unwrap(),
262 )
263 .and_then(|v| vm.with_tla(v))322 .and_then(|v| vm.with_tla(v))
264 .and_then(|v| vm.manifest_stream(v))323 .and_then(|v| vm.manifest_stream(v))
270 Err(e) => {329 Err(e) => {
271 *error = 1;330 *error = 1;
272 let out = vm.stringify_err(&e);331 let out = vm.stringify_err(&e);
273 CString::new(&out as &str).unwrap().into_raw()332 CString::new(&out as &str)
333 .expect("there should be no \\0 in the error string")
334 .into_raw()
274 }335 }
275 }336 }
286 let filename = CStr::from_ptr(filename);347 let filename = CStr::from_ptr(filename);
287 let snippet = CStr::from_ptr(snippet);348 let snippet = CStr::from_ptr(snippet);
288 match vm349 match vm
289 .evaluate_snippet(filename.to_str().unwrap().into(), snippet.to_str().unwrap())350 .evaluate_snippet(
351 filename.to_str().expect("filename is not utf-8"),
352 snippet.to_str().expect("snippet is not utf-8"),
353 )
290 .and_then(|v| vm.with_tla(v))354 .and_then(|v| vm.with_tla(v))
291 .and_then(|v| vm.manifest_stream(v))355 .and_then(|v| vm.manifest_stream(v))
297 Err(e) => {361 Err(e) => {
298 *error = 1;362 *error = 1;
299 let out = vm.stringify_err(&e);363 let out = vm.stringify_err(&e);
300 CString::new(&out as &str).unwrap().into_raw()364 CString::new(&out as &str)
365 .expect("there should be no \\0 in the error string")
366 .into_raw()
301 }367 }
302 }368 }
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -12,6 +12,15 @@
 };
 use jrsonnet_gcmodule::Cc;
 
+/// The returned JsonnetJsonValue* should be allocated with jsonnet_realloc.  It will be cleaned up
+/// along with the objects rooted at argv by libjsonnet when no-longer needed.  Return a string upon
+/// failure, which will appear in Jsonnet as an error.  The argv pointer is an array whose size
+/// matches the array of parameters supplied when the native callback was originally registered.
+///
+/// - `ctx` User pointer, given in jsonnet_native_callback.
+/// - `argv` Array of arguments from Jsonnet code.
+/// - `param` success Set this byref param to 1 to indicate success and 0 for failure.
+/// Returns the content of the imported file, or an error message.
 type JsonnetNativeCallback = unsafe extern "C" fn(
 	ctx: *const c_void,
 	argv: *const *const Val,
@@ -44,13 +53,20 @@
 		if success == 1 {
 			Ok(v)
 		} else {
-			let e = IStr::from_untyped(v, s).expect("error msg");
+			let e = IStr::from_untyped(v, s).expect("error msg should be a string");
 			Err(Error::RuntimeError(e).into())
 		}
 	}
 }
 
+/// Callback to provide native extensions to Jsonnet.
+///
 /// # Safety
+///
+/// `vm` should be a vm allocated by `jsonnet_make`
+/// `cb` should be a correct function pointer
+/// `raw_params` should point to a NULL-terminated string array
+/// `name`, `raw_params` elements should be a \0-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_native_callback(
 	vm: &State,
@@ -59,13 +75,18 @@
 	ctx: *const c_void,
 	mut raw_params: *const *const c_char,
 ) {
-	let name = CStr::from_ptr(name).to_str().expect("utf8 name").into();
+	let name = CStr::from_ptr(name)
+		.to_str()
+		.expect("name is not utf-8")
+		.into();
 	let mut params = Vec::new();
 	loop {
 		if (*raw_params).is_null() {
 			break;
 		}
-		let param = CStr::from_ptr(*raw_params).to_str().expect("not utf8");
+		let param = CStr::from_ptr(*raw_params)
+			.to_str()
+			.expect("param name is not utf-8");
 		params.push(BuiltinParam {
 			name: param.into(),
 			has_default: false,
modifiedbindings/jsonnet/src/val_extract.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_extract.rs
+++ b/bindings/jsonnet/src/val_extract.rs
@@ -7,6 +7,7 @@
 
 use jrsonnet_evaluator::{State, Val};
 
+/// If the value is a string, return it as UTF8 otherwise return NULL.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_string(_vm: &State, v: &Val) -> *mut c_char {
 	match v {
@@ -14,6 +15,8 @@
 		_ => std::ptr::null_mut(),
 	}
 }
+
+/// If the value is a number, return 1 and store the number in out, otherwise return 0.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_number(_vm: &State, v: &Val, out: &mut c_double) -> c_int {
 	match v {
@@ -24,6 +27,8 @@
 		_ => 0,
 	}
 }
+
+/// Return 0 if the value is false, 1 if it is true, and 2 if it is not a bool.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_bool(_vm: &State, v: &Val) -> c_int {
 	match v {
@@ -32,6 +37,8 @@
 		_ => 2,
 	}
 }
+
+/// Return 1 if the value is null, else 0.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_extract_null(_vm: &State, v: &Val) -> c_int {
 	match v {
modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -8,37 +8,46 @@
 use jrsonnet_evaluator::{val::ArrValue, ObjValue, State, Val};
 use jrsonnet_gcmodule::Cc;
 
+/// Convert the given UTF8 string to a JsonnetJsonValue.
+///
 /// # Safety
 ///
-/// This function is safe, if received v is a pointer to normal C string
+/// `v` should be a \0-terminated string
 #[no_mangle]
-pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &State, v: *const c_char) -> *mut Val {
-	let cstr = CStr::from_ptr(v);
-	let str = cstr.to_str().unwrap();
-	Box::into_raw(Box::new(Val::Str(str.into())))
+pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &State, val: *const c_char) -> *mut Val {
+	let val = CStr::from_ptr(val);
+	let val = val.to_str().expect("string is not utf-8");
+	Box::into_raw(Box::new(Val::Str(val.into())))
 }
 
+/// Convert the given double to a JsonnetJsonValue.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_number(_vm: &State, v: c_double) -> *mut Val {
 	Box::into_raw(Box::new(Val::Num(v)))
 }
 
+/// Convert the given bool (1 or 0) to a JsonnetJsonValue.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_bool(_vm: &State, v: c_int) -> *mut Val {
-	assert!(v == 0 || v == 1);
+	assert!(v == 0 || v == 1, "bad boolean value");
 	Box::into_raw(Box::new(Val::Bool(v == 1)))
 }
 
+/// Make a JsonnetJsonValue representing null.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_null(_vm: &State) -> *mut Val {
 	Box::into_raw(Box::new(Val::Null))
 }
 
+/// Make a JsonnetJsonValue representing an array.
+///
+/// Assign elements with jsonnet_json_array_append.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_array(_vm: &State) -> *mut Val {
 	Box::into_raw(Box::new(Val::Arr(ArrValue::Eager(Cc::new(Vec::new())))))
 }
 
+/// Make a JsonnetJsonValue representing an object.
 #[no_mangle]
 pub extern "C" fn jsonnet_json_make_object(_vm: &State) -> *mut Val {
 	Box::into_raw(Box::new(Val::Obj(ObjValue::new_empty())))
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -7,9 +7,12 @@
 use jrsonnet_evaluator::{val::ArrValue, State, Thunk, Val};
 use jrsonnet_gcmodule::Cc;
 
+/// Add value to the end of the array arr
+///
 /// # Safety
 ///
-/// Received arr value should be correct pointer to array allocated by make_array
+/// `arr` should be correct pointer to array value allocated by make_array, or returned by other library call
+/// `val` should be correct pointer to value allocated using this library
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_json_array_append(_vm: &State, arr: &mut Val, val: &Val) {
 	match arr {
@@ -26,9 +29,14 @@
 	}
 }
 
+/// Add the field to the object, bound to value.
+///
+/// This shadows any previous binding of the field.
+///
 /// # Safety
 ///
-/// This function is safe if passed name is ok
+/// `obj` should be pointer to object value allocated by make_object, or returned by other library call
+/// `name` should be \0-terminated string
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_json_object_append(
 	_vm: &State,
modifiedbindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -4,52 +4,84 @@
 
 use jrsonnet_evaluator::State;
 
+/// Bind a Jsonnet external var to the given string.
+///
+/// Argument values are copied so memory should be managed by caller.
+///
 /// # Safety
+///
+/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_ext_var(vm: &State, name: *const c_char, value: *const c_char) {
 	let name = CStr::from_ptr(name);
 	let value = CStr::from_ptr(value);
 
-	let any_resolver = vm.context_initializer();
-	any_resolver
+	let any_initializer = vm.context_initializer();
+	any_initializer
 		.as_any()
 		.downcast_ref::<jrsonnet_stdlib::ContextInitializer>()
 		.expect("only stdlib context initializer supported")
 		.add_ext_str(
-			name.to_str().unwrap().into(),
-			value.to_str().unwrap().into(),
+			name.to_str().expect("name is not utf-8").into(),
+			value.to_str().expect("value is not utf-8").into(),
 		)
 }
 
+/// Bind a Jsonnet external var to the given code.
+///
+/// Argument values are copied so memory should be managed by caller.
+///
 /// # Safety
+///
+/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
 #[no_mangle]
-pub unsafe extern "C" fn jsonnet_ext_code(vm: &State, name: *const c_char, value: *const c_char) {
+pub unsafe extern "C" fn jsonnet_ext_code(vm: &State, name: *const c_char, code: *const c_char) {
 	let name = CStr::from_ptr(name);
-	let value = CStr::from_ptr(value);
+	let code = CStr::from_ptr(code);
 
-	let any_resolver = vm.context_initializer();
-	any_resolver
+	let any_initializer = vm.context_initializer();
+	any_initializer
 		.as_any()
 		.downcast_ref::<jrsonnet_stdlib::ContextInitializer>()
 		.expect("only stdlib context initializer supported")
-		.add_ext_code(name.to_str().unwrap(), value.to_str().unwrap())
-		.unwrap()
+		.add_ext_code(
+			name.to_str().expect("name is not utf-8"),
+			code.to_str().expect("code is not utf-8"),
+		)
+		.expect("can't parse ext code")
 }
+
+/// Bind a string top-level argument for a top-level parameter.
+///
+/// Argument values are copied so memory should be managed by caller.
+///
 /// # Safety
+///
+/// Caller should pass correct pointers as `name` and `value`, they need to be \0-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_tla_var(vm: &State, name: *const c_char, value: *const c_char) {
 	let name = CStr::from_ptr(name);
 	let value = CStr::from_ptr(value);
 	vm.add_tla_str(
-		name.to_str().unwrap().into(),
-		value.to_str().unwrap().into(),
+		name.to_str().expect("name is not utf-8").into(),
+		value.to_str().expect("value is not utf-8").into(),
 	)
 }
+
+/// Bind a code top-level argument for a top-level parameter.
+///
+/// Argument values are copied so memory should be managed by caller.
+///
 /// # Safety
+///
+/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
 #[no_mangle]
-pub unsafe extern "C" fn jsonnet_tla_code(vm: &State, name: *const c_char, value: *const c_char) {
+pub unsafe extern "C" fn jsonnet_tla_code(vm: &State, name: *const c_char, code: *const c_char) {
 	let name = CStr::from_ptr(name);
-	let value = CStr::from_ptr(value);
-	vm.add_tla_code(name.to_str().unwrap().into(), value.to_str().unwrap())
-		.unwrap()
+	let code = CStr::from_ptr(code);
+	vm.add_tla_code(
+		name.to_str().expect("name is not utf-8").into(),
+		code.to_str().expect("code is not utf-8"),
+	)
+	.expect("can't parse tla code")
 }