Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
to_string.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 2025 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 to_string.c
12 * @brief Implements the OP_TO_STRING opcode for converting values to strings in the VM.
13 *
14 * This file handles the OP_TO_STRING instruction, which converts a value of any type
15 * into its string representation and pushes the result onto the stack.
16 *
17 * Behavior:
18 * - Pops a value from the stack.
19 * - Converts the value to a string based on its type:
20 * - Integers: Convert to decimal string (e.g., 42 → "42")
21 * - Strings: Return a copy of the string
22 * - Arrays: Convert to "[array n=<length>]"
23 * - Maps: Convert to "{map n=<length>}"
24 * - Functions: Convert to "<function@<address>>"
25 * - Nil: Convert to "nil"
26 * - Pushes the resulting string onto the stack.
27 *
28 * Error Handling:
29 * - Exits with an error if memory allocation fails during string creation.
30 *
31 * Example:
32 * - Bytecode: OP_TO_STRING
33 * - Stack before: [42]
34 * - Stack after: ["42"]
35 */
36
38 Value v = pop_value(vm);
40 Value out = make_string(s ? s : "");
41 if (s) free(s);
43 push_value(vm, out);
44 break;
45}
Value out
Definition apop.c:38
@ OP_TO_STRING
Definition bytecode.h:94
Value v
Definition cast.c:22
free(vals)
uint32_t s
Definition rol.c:31
Tagged union representing a Fun value.
Definition value.h:68
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition value.c:95
void free_value(Value v)
Free dynamic storage owned by a Value.
Definition value.c:517
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
static void push_value(VM *vm, Value v)
Push a Value onto the VM operand stack.
Definition vm.c:564