Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
stringify.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 stringify.c
12 * @brief VM opcode snippet for converting a Fun Value to a JSON string.
13 *
14 * Implements the OP_JSON_STRINGIFY instruction. Expects a boolean/integer flag
15 * indicating pretty-printing and a Value to serialize. Uses json-c to build a
16 * json_object from the Value and then renders it to a string, which is pushed
17 * back to the stack.
18 *
19 * Build gating: compiled only when FUN_WITH_JSON is enabled. Otherwise the
20 * opcode consumes its two arguments and pushes the string "null".
21 *
22 * Stack effect (with FUN_WITH_JSON):
23 * - Pops: pretty (bool/int), value (any)
24 * - Pushes: string (JSON representation)
25 *
26 * Errors and edge cases:
27 * - If conversion to json_object fails, an empty string is pushed.
28 * - Pretty printing selects JSON_C_TO_STRING_PRETTY; otherwise plain output.
29 */
30
31/* JSON_STRINGIFY */
33#ifdef FUN_WITH_JSON
34 Value vpretty = pop_value(vm);
36 int pretty = (vpretty.type == VAL_BOOL || vpretty.type == VAL_INT) ? (vpretty.i != 0) : 0;
37 json_object *j = fun_to_json(&any);
38 int flags = pretty ? JSON_C_TO_STRING_PRETTY : JSON_C_TO_STRING_PLAIN;
39 const char *js = json_object_to_json_string_ext(j, flags);
42 free_value(vpretty);
44#else
45 /* Fallback: consume two args, push "null" */
46 Value vpretty = pop_value(vm);
47 free_value(vpretty);
48 Value any = pop_value(vm);
50 push_value(vm, make_string("null"));
51#endif
52 break;
53}
@ OP_JSON_STRINGIFY
Definition bytecode.h:168
static json_object * fun_to_json(const Value *v)
Convert a Fun Value into a json-c object.
Definition json.c:99
json_object * j
Definition stringify.c:37
const char * js
Definition stringify.c:39
json_object_put(j)
int pretty
Definition stringify.c:36
push_value(vm, make_string(js ? js :""))
Value any
Definition stringify.c:35
int flags
Definition stringify.c:38
free_value(vpretty)
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
ValueType type
Definition value.h:69
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition value.c:95
@ VAL_BOOL
Definition value.h:52
@ VAL_INT
Definition value.h:51
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580