Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
hello_args_return.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2026 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
10/**
11 * @file hello_args_return.c
12 * @brief Implements the OP_RUST_HELLO_ARGS_RETURN opcode (conditional build).
13 *
14 * Demonstrates round-tripping a string value through Rust. Pops a value,
15 * converts it to a C string, passes it to Rust, and pushes back the string
16 * returned by Rust. If Rust returns NULL or Rust support is disabled, Nil is
17 * pushed.
18 *
19 * OP_RUST_HELLO_ARGS_RETURN: (msg:any) -> string | Nil
20 *
21 * Behavior (FUN_WITH_RUST=ON):
22 * - Pops one value from the stack and converts it to a newly allocated C
23 * string via value_to_string_alloc().
24 * - Calls fun_rust_echo_string(msg) which returns an owned C string pointer
25 * that must be released via fun_rust_string_free().
26 * - Pushes the returned string as VAL_STRING on success; pushes Nil if Rust
27 * returns NULL.
28 *
29 * Behavior (FUN_WITH_RUST=OFF):
30 * - Pops and frees one value to preserve stack discipline.
31 * - Raises a runtime error indicating missing Rust support.
32 * - Pushes Nil.
33 */
34
36#ifdef FUN_WITH_RUST
37 Value vmsg = pop_value(vm);
38 char *msg = value_to_string_alloc(&vmsg);
40 if (msg) {
41 char *ret = fun_rust_echo_string(msg);
42 free(msg);
43 if (ret) {
44 push_value(vm, make_string(ret));
46 } else {
47 push_value(vm, make_nil());
48 }
49 } else {
50 char *ret = fun_rust_echo_string("");
51 if (ret) {
52 push_value(vm, make_string(ret));
54 } else {
55 push_value(vm, make_nil());
56 }
57 }
58#else
59 /* Still pop and free the arg to keep stack sane */
60 Value vmsg = pop_value(vm);
61 free_value(vmsg);
62 vm_raise_error(vm, "RUST_HELLO_ARGS_RETURN requires FUN_WITH_RUST=ON at build time");
63 push_value(vm, make_nil());
64#endif
65 break;
66}
@ OP_RUST_HELLO_ARGS_RETURN
Definition bytecode.h:280
char * msg
Definition hello_args.c:35
free_value(vmsg)
free(vals)
Tagged union representing a Fun value.
Definition value.h:68
Value make_nil(void)
Construct a nil Value.
Definition value.c:126
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition value.c:95
char * value_to_string_alloc(const Value *v)
Allocate a printable C string for a Value.
Definition value.c:641
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
void vm_raise_error(VM *vm, const char *msg)
Raise a runtime error inside the VM, honoring try/catch/finally.
Definition vm.c:248
static void push_value(VM *vm, Value v)
Push a Value onto the VM operand stack.
Definition vm.c:564
void fun_rust_string_free(char *ptr)
char * fun_rust_echo_string(const char *input)