Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
parse.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 parse.c
12 * @brief VM opcode snippet for parsing a JSON string into a Fun Value.
13 *
14 * Implements the OP_JSON_PARSE instruction. Expects a string (or any value
15 * convertible to string) on the stack, parses it with json-c, converts the
16 * resulting json_object to a Fun Value and pushes it.
17 *
18 * Build gating: compiled only when FUN_WITH_JSON is enabled. Otherwise the
19 * opcode consumes its argument and pushes Nil.
20 *
21 * Stack effect (with FUN_WITH_JSON):
22 * - Pops: text (any; converted to string)
23 * - Pushes: Value converted from JSON, or Nil on error
24 *
25 * Errors and edge cases:
26 * - If allocation fails, tokenization fails, or the text is not valid JSON,
27 * the opcode pushes Nil.
28 * - The temporary json-c objects are released after conversion; ownership of
29 * the pushed Fun Value follows normal VM semantics.
30 */
31
32/* JSON_PARSE */
34#ifdef FUN_WITH_JSON
35 Value text = pop_value(vm);
38 if (!s) {
39 push_value(vm, make_nil());
40 break;
41 }
42 struct json_tokener *tok = json_tokener_new();
43 json_object *root = json_tokener_parse_ex(tok, s, (int)strlen(s));
44 enum json_tokener_error jerr = json_tokener_get_error(tok);
47 if (jerr != json_tokener_success) {
48 push_value(vm, make_nil());
49 } else {
53 }
54#else
55 /* Fallback when JSON is disabled: consume arg, push Nil */
56 Value drop = pop_value(vm);
57 free_value(drop);
58 push_value(vm, make_nil());
59#endif
60 break;
61}
@ OP_JSON_PARSE
Definition bytecode.h:167
Value v
Definition cast.c:22
json_object * root
Definition from_file.c:44
enum json_tokener_error jerr
Definition parse.c:44
free(s)
struct json_tokener * tok
Definition parse.c:42
free_value(text)
json_tokener_free(tok)
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
uint32_t s
Definition rol.c:31
Tagged union representing a Fun value.
Definition value.h:68
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
char * text
Definition parse.c:44