Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
to_file.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_file.c
12 * @brief VM opcode snippet for writing a Fun Value as JSON to a file.
13 *
14 * Implements the OP_JSON_TO_FILE instruction. Expects a pretty-print flag,
15 * a Value to serialize, and a path. Serializes the Value via json-c and
16 * writes it to the specified file path.
17 *
18 * Build gating: compiled only when FUN_WITH_JSON is enabled. Otherwise the
19 * opcode consumes three arguments and pushes 0 (failure).
20 *
21 * Stack effect (with FUN_WITH_JSON):
22 * - Pops: pretty (bool/int), value (any), path (any; converted to string)
23 * - Pushes: int (1 on success, 0 on failure)
24 *
25 * Errors and edge cases:
26 * - If the path cannot be converted to a C string or file writing fails,
27 * the opcode pushes 0.
28 * - Pretty printing selects JSON_C_TO_STRING_PRETTY; otherwise plain output.
29 */
30
31/* JSON_TO_FILE */
33#ifdef FUN_WITH_JSON
34 Value vpretty = pop_value(vm);
38 int pretty = (vpretty.type == VAL_BOOL || vpretty.type == VAL_INT) ? (vpretty.i != 0) : 0;
39 free_value(vpretty);
41 if (!path) {
43 push_value(vm, make_int(0));
44 break;
45 }
46 json_object *j = fun_to_json(&any);
47 int flags = pretty ? JSON_C_TO_STRING_PRETTY : JSON_C_TO_STRING_PLAIN;
48 int rc = json_object_to_file_ext(path, j, flags);
52 push_value(vm, make_int(rc == 0 ? 1 : 0));
53#else
54 Value vpretty = pop_value(vm);
55 free_value(vpretty);
56 Value any = pop_value(vm);
58 Value vpath = pop_value(vm);
60 push_value(vm, make_int(0));
61#endif
62 break;
63}
@ OP_JSON_TO_FILE
Definition bytecode.h:170
CURLcode rc
Definition download.c:71
char * path
Definition download.c:43
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
int pretty
Definition stringify.c:36
Value any
Definition stringify.c:35
int flags
Definition stringify.c:38
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
ValueType type
Definition value.h:69
void vpath
Definition stubs.c:23
json_object_put(j)
free(path)
push_value(vm, make_int(rc==0 ? 1 :0))
free_value(vpretty)
char * value_to_string_alloc(const Value *v)
Allocate a printable C string for a Value.
Definition value.c:641
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ 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