Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
from_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 from_file.c
12 * @brief VM opcode snippet for loading a JSON document from a file.
13 *
14 * This snippet is included by vm.c and implements the OP_JSON_FROM_FILE
15 * instruction. It expects a path on the VM stack, reads the file using
16 * json-c, converts the resulting json_object tree into a Fun Value, and
17 * pushes that Value back on the VM stack.
18 *
19 * Build gating: compiled only when FUN_WITH_JSON is enabled (json-c
20 * available). When disabled, the opcode consumes its argument (if any)
21 * and pushes Nil.
22 *
23 * Stack effect (with FUN_WITH_JSON):
24 * - Pops: path (any; converted to string)
25 * - Pushes: Value converted from JSON, or Nil on error
26 *
27 * Errors and edge cases:
28 * - If the path cannot be converted to a C string or json_object_from_file
29 * fails (e.g., missing file, invalid JSON), the opcode pushes Nil.
30 * - The created json_object is released after conversion; ownership of the
31 * pushed Fun Value follows normal VM semantics.
32 */
33
34/* JSON_FROM_FILE */
36#ifdef FUN_WITH_JSON
37 Value vpath = pop_value(vm);
40 if (!path) {
41 push_value(vm, make_nil());
42 break;
43 }
44 json_object *root = json_object_from_file(path);
46 if (!root) {
47 push_value(vm, make_nil());
48 break;
49 }
53#else
54 Value vpath = pop_value(vm);
56 push_value(vm, make_nil());
57#endif
58 break;
59}
@ OP_JSON_FROM_FILE
Definition bytecode.h:169
Value v
Definition cast.c:22
char * path
Definition download.c:43
free_value(vpath)
free(path)
json_object * root
Definition from_file.c:44
json_object_put(root)
push_value(vm, v)
static Value json_to_fun(json_object *j)
Convert a json-c object into a Fun Value.
Definition json.c:46
Tagged union representing a Fun value.
Definition value.h:68
void vpath
Definition stubs.c:23
Value make_nil(void)
Construct a nil Value.
Definition value.c:126
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